1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/compiler.h>
32 #include <string.h> // strcmp()
34 #if defined(SG_WINDOWS)
35 # include <io.h> // isatty()
36 # include <process.h> // _getpid()
38 # define isatty _isatty
40 // for open() and options
41 # include <sys/types.h>
42 # include <sys/stat.h>
48 #include <boost/algorithm/string/compare.hpp>
49 #include <boost/algorithm/string/predicate.hpp>
51 #include <osgViewer/Viewer>
53 #include <simgear/canvas/Canvas.hxx>
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/structure/exception.hxx>
57 #include <simgear/structure/event_mgr.hxx>
58 #include <simgear/structure/SGPerfMon.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/sgstream.hxx>
62 #include <simgear/misc/strutils.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/scene/tsync/terrasync.hxx>
66 #include <simgear/scene/model/modellib.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/material/Effect.hxx>
69 #include <simgear/scene/model/particles.hxx>
70 #include <simgear/scene/tsync/terrasync.hxx>
72 #include <simgear/package/Root.hxx>
73 #include <simgear/package/Package.hxx>
74 #include <simgear/package/Install.hxx>
75 #include <simgear/package/Catalog.hxx>
77 #include <Aircraft/controls.hxx>
78 #include <Aircraft/replay.hxx>
79 #include <Aircraft/FlightHistory.hxx>
80 #include <Airports/runways.hxx>
81 #include <Airports/airport.hxx>
82 #include <Airports/dynamics.hxx>
84 #include <AIModel/AIManager.hxx>
86 #include <ATC/atc_mgr.hxx>
88 #include <Autopilot/route_mgr.hxx>
89 #include <Autopilot/autopilotgroup.hxx>
91 #include <Cockpit/panel.hxx>
92 #include <Cockpit/panel_io.hxx>
94 #include <Canvas/canvas_mgr.hxx>
95 #include <Canvas/gui_mgr.hxx>
96 #include <Canvas/FGCanvasSystemAdapter.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <GUI/MessageBox.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Model/acmodel.hxx>
102 #include <Model/modelmgr.hxx>
103 #include <AIModel/submodel.hxx>
104 #include <AIModel/AIManager.hxx>
105 #include <Navaids/navdb.hxx>
106 #include <Navaids/navlist.hxx>
107 #include <Scenery/scenery.hxx>
108 #include <Scenery/SceneryPager.hxx>
109 #include <Scenery/tilemgr.hxx>
110 #include <Scripting/NasalSys.hxx>
111 #include <Sound/voice.hxx>
112 #include <Sound/soundmanager.hxx>
113 #include <Systems/system_mgr.hxx>
114 #include <Time/light.hxx>
115 #include <Time/TimeManager.hxx>
117 #include <Traffic/TrafficMgr.hxx>
118 #include <MultiPlayer/multiplaymgr.hxx>
119 #include <FDM/fdm_shell.hxx>
120 #include <Environment/ephemeris.hxx>
121 #include <Environment/environment_mgr.hxx>
122 #include <Viewer/renderer.hxx>
123 #include <Viewer/viewmgr.hxx>
124 #include <Viewer/FGEventHandler.hxx>
125 #include <Navaids/NavDataCache.hxx>
126 #include <Instrumentation/HUD/HUD.hxx>
127 #include <Cockpit/cockpitDisplayManager.hxx>
128 #include <Network/HTTPClient.hxx>
129 #include <Network/fgcom.hxx>
130 #include <Network/http/httpd.hxx>
131 #include <Include/version.h>
132 #include <Viewer/splash.hxx>
133 #include <Viewer/CameraGroup.hxx>
135 #include "fg_init.hxx"
137 #include "fg_commands.hxx"
138 #include "fg_props.hxx"
139 #include "FGInterpolator.hxx"
140 #include "options.hxx"
141 #include "globals.hxx"
142 #include "logger.hxx"
144 #include "positioninit.hxx"
146 #include "AircraftDirVisitorBase.hxx"
149 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
157 using namespace boost::algorithm;
158 using namespace simgear::pkg;
160 extern osg::ref_ptr<osgViewer::Viewer> viewer;
162 // Return the current base package version
163 string fgBasePackageVersion(const SGPath& base_path) {
170 sg_gzifstream in( p.str() );
181 class FindAndCacheAircraft : public AircraftDirVistorBase
184 FindAndCacheAircraft(SGPropertyNode* autoSave)
186 _cache = autoSave->getNode("sim/startup/path-cache", true);
191 std::string aircraft = fgGetString( "/sim/aircraft", "");
192 if (aircraft.empty()) {
193 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
194 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
198 _searchAircraft = aircraft + "-set.xml";
199 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
200 if (!aircraftDir.empty()) {
201 // aircraft-dir was set, skip any searching at all, if it's valid
202 simgear::Dir acPath(aircraftDir);
203 SGPath setFile = acPath.file(_searchAircraft);
204 if (setFile.exists()) {
205 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
208 readProperties(setFile.str(), globals->get_props());
209 } catch ( const sg_exception &e ) {
210 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
211 flightgear::fatalMessageBox("Error reading aircraft",
212 "An error occured reading the requested aircraft (" + aircraft + ")",
213 e.getFormattedMessage());
219 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
220 "' not found in specified dir:" << aircraftDir);
221 flightgear::fatalMessageBox("Aircraft not found",
222 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
229 // prepare cache for re-scan
230 SGPropertyNode *n = _cache->getNode("fg-root", true);
231 n->setStringValue(globals->get_fg_root().c_str());
232 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
233 n = _cache->getNode("fg-aircraft", true);
234 n->setStringValue(getAircraftPaths().c_str());
235 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
236 _cache->removeChildren("aircraft");
238 visitAircraftPaths();
241 if (_foundPath.str().empty()) {
242 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
243 flightgear::fatalMessageBox("Aircraft not found",
244 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
249 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
250 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
251 if (!_foundPath.exists()) {
252 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
257 readProperties(_foundPath.str(), globals->get_props());
258 } catch ( const sg_exception &e ) {
259 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
260 flightgear::fatalMessageBox("Error reading aircraft",
261 "An error occured reading the requested aircraft (" + aircraft + ")",
262 e.getFormattedMessage());
270 SGPath getAircraftPaths() {
271 string_list pathList = globals->get_aircraft_paths();
272 SGPath aircraftPaths;
273 string_list::const_iterator it = pathList.begin();
274 if (it != pathList.end()) {
275 aircraftPaths.set(*it);
278 for (; it != pathList.end(); ++it) {
279 aircraftPaths.add(*it);
281 return aircraftPaths;
286 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
287 return false; // cache mismatch
290 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
291 return false; // cache mismatch
294 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
295 for (unsigned int i = 0; i < cache.size(); i++) {
296 const char *name = cache[i]->getStringValue("file", "");
297 if (!boost::equals(_searchAircraft, name, is_iequal())) {
301 SGPath xml(cache[i]->getStringValue("path", ""));
309 } // of aircraft in cache iteration
314 virtual VisitResult visit(const SGPath& p)
319 if (!_cache->getChild("aircraft", i++, false))
323 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
325 std::string fileName(p.file());
326 n = entry->getNode("file", true);
327 n->setStringValue(fileName);
328 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
330 n = entry->getNode("path", true);
331 n->setStringValue(p.dir());
332 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
334 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
339 return VISIT_CONTINUE;
342 std::string _searchAircraft;
344 SGPropertyNode* _cache;
348 static SGPath platformDefaultDataPath()
350 char *envp = ::getenv( "APPDATA" );
351 SGPath config( envp );
352 config.append( "flightgear.org" );
356 #elif defined(SG_MAC)
358 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
361 static SGPath platformDefaultDataPath()
363 return SGPath::home() / ".fgfs";
369 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
370 globals->set_fg_home(dataPath.c_str());
372 simgear::Dir fgHome(dataPath);
373 if (!fgHome.exists()) {
377 if (!fgHome.exists()) {
378 flightgear::fatalMessageBox("Problem setting up user data",
379 "Unable to create the user-data storage folder at: '"
380 + dataPath.str() + "'");
384 if (fgGetBool("/sim/fghome-readonly", false)) {
385 // user / config forced us into readonly mode, fine
386 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
390 // write our PID, and check writeability
391 SGPath pidPath(dataPath, "fgfs.pid");
392 if (pidPath.exists()) {
393 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
394 // set a marker property so terrasync/navcache don't try to write
395 // from secondary instances
396 fgSetBool("/sim/fghome-readonly", true);
402 #if defined(SG_WINDOWS)
403 size_t len = snprintf(buf, 16, "%d", _getpid());
405 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
406 FILE_SHARE_READ, /* sharing */
407 NULL, /* security attributes */
408 CREATE_NEW, /* error if already exists */
409 FILE_FLAG_DELETE_ON_CLOSE,
410 NULL /* template */);
412 result = (f != INVALID_HANDLE_VALUE);
415 WriteFile(f, buf, len, &written, NULL /* overlapped */);
418 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
420 ssize_t len = snprintf(buf, 16, "%d", getpid());
421 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
423 result = ::write(fd, buf, len) == len;
424 if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
429 fgSetBool("/sim/fghome-readonly", false);
432 flightgear::fatalMessageBox("File permissions problem",
433 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
434 "User-data at:" + dataPath.str());
439 // Read in configuration (file and command line)
440 int fgInitConfig ( int argc, char **argv, bool reinit )
442 SGPath dataPath = globals->get_fg_home();
444 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
445 if (!exportDir.exists()) {
446 exportDir.create(0755);
449 // Set /sim/fg-home. Use FG_HOME if necessary.
450 // deliberately not a tied property, for fgValidatePath security
451 // write-protect to avoid accidents
452 SGPropertyNode *home = fgGetNode("/sim", true);
453 home->removeChild("fg-home", 0);
454 home = home->getChild("fg-home", 0, true);
455 home->setStringValue(dataPath.c_str());
456 home->setAttribute(SGPropertyNode::WRITE, false);
459 flightgear::Options* options = flightgear::Options::sharedInstance();
461 options->init(argc, argv, dataPath);
464 bool loadDefaults = options->shouldLoadDefaultConfig();
466 // Read global preferences from $FG_ROOT/preferences.xml
467 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
468 fgLoadProps("preferences.xml", globals->get_props());
469 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
471 // do not load user settings when reset to default is requested, or if
472 // told to explicitly ignore
473 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
475 SG_LOG(SG_GENERAL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
479 globals->loadUserSettings(dataPath);
482 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
483 }// of no-default-config selected
485 return flightgear::FG_OPTIONS_OK;
488 static void initAircraftDirsNasalSecurity()
490 // deliberately not a tied property, for fgValidatePath security
491 // write-protect to avoid accidents
492 SGPropertyNode* sim = fgGetNode("/sim", true);
493 sim->removeChildren("fg-aircraft");
496 string_list const aircraft_paths = globals->get_aircraft_paths();
497 for( string_list::const_iterator it = aircraft_paths.begin();
498 it != aircraft_paths.end();
501 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
502 n->setStringValue(*it);
503 n->setAttribute(SGPropertyNode::WRITE, false);
507 void fgInitAircraftPaths(bool reinit)
509 if (!globals->packageRoot()) {
513 SGSharedPtr<Root> pkgRoot(globals->packageRoot());
514 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
515 aircraftProp->setAttribute(SGPropertyNode::PRESERVE, true);
518 flightgear::Options::sharedInstance()->initPaths();
522 int fgInitAircraft(bool reinit)
525 flightgear::Options::sharedInstance()->initAircraft();
528 SGSharedPtr<Root> pkgRoot(globals->packageRoot());
529 SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
531 string aircraftId(aircraftProp->getStringValue());
532 PackageRef acftPackage = pkgRoot->getPackageById(aircraftId);
534 if (acftPackage->isInstalled()) {
535 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft from package:" << acftPackage->qualifiedId());
537 // set catalog path so intra-package dependencies within the catalog
538 // are resolved correctly.
539 globals->set_catalog_aircraft_path(acftPackage->catalog()->installRoot());
541 // set aircraft-dir to short circuit the search process
542 InstallRef acftInstall = acftPackage->install();
543 fgSetString("/sim/aircraft-dir", acftInstall->path().c_str());
545 // overwrite the fully qualified ID with the aircraft one, so the
546 // code in FindAndCacheAircraft works as normal
547 // note since we may be using a variant, we can't use the package ID
548 size_t lastDot = aircraftId.rfind('.');
549 if (lastDot != std::string::npos) {
550 aircraftId = aircraftId.substr(lastDot + 1);
551 aircraftProp->setStringValue(aircraftId);
554 // run the traditional-code path below
557 // naturally the better option would be to on-demand install it!
558 flightgear::fatalMessageBox("Aircraft not installed",
559 "Requested aircraft is not currently installed.",
562 return flightgear::FG_OPTIONS_ERROR;
567 initAircraftDirsNasalSecurity();
569 FindAndCacheAircraft f(globals->get_props());
570 if (!f.loadAircraft()) {
571 return flightgear::FG_OPTIONS_ERROR;
574 return flightgear::FG_OPTIONS_OK;
578 * Initialize vor/ndb/ils/fix list management and query systems (as
579 * well as simple airport db list)
580 * This is called multiple times in the case of a cache rebuild,
581 * to allow lengthy caching to take place in the background, without
582 * blocking the main/UI thread.
587 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
588 static bool doingRebuild = false;
591 cache = flightgear::NavDataCache::createInstance();
592 doingRebuild = cache->isRebuildRequired();
595 static const char* splashIdentsByRebuildPhase[] = {
604 flightgear::NavDataCache::RebuildPhase phase;
605 phase = cache->rebuild();
606 if (phase != flightgear::NavDataCache::REBUILD_DONE) {
607 // update the splash text based on percentage, phase
609 fgSplashProgress(splashIdentsByRebuildPhase[phase],
610 cache->rebuildPhaseCompletionPercentage());
612 // sleep to give the rebuild thread more time
613 SGTimeStamp::sleepForMSec(50);
618 // depend on when the NavCache was initialised, scenery paths may not
619 // have been setup. This is a safe place to consistently check the value,
620 // and drop the ground-nets if something has changed
621 cache->dropGroundnetsIfRequired();
623 FGTACANList *channellist = new FGTACANList;
624 globals->set_channellist( channellist );
626 SGPath path(globals->get_fg_root());
627 path.append( "Navaids/TACAN_freq.dat" );
628 flightgear::loadTacan(path, channellist);
633 // General house keeping initializations
634 bool fgInitGeneral() {
637 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
638 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
640 root = globals->get_fg_root();
641 if ( ! root.length() ) {
642 // No root path set? Then bail ...
643 SG_LOG( SG_GENERAL, SG_ALERT,
644 "Cannot continue without a path to the base package "
645 << "being defined." );
648 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
650 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
651 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
652 fgSetString("/sim/startup/browser-app", globals->get_browser());
654 simgear::Dir cwd(simgear::Dir::current());
655 SGPropertyNode *curr = fgGetNode("/sim", true);
656 curr->removeChild("fg-current", 0);
657 curr = curr->getChild("fg-current", 0, true);
658 curr->setStringValue(cwd.path().str());
659 curr->setAttribute(SGPropertyNode::WRITE, false);
661 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
662 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
666 // Write various configuraton values out to the logs
667 void fgOutputSettings()
669 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
670 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
672 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
673 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
674 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
676 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
677 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
680 // This is the top level init routine which calls all the other
681 // initialization routines. If you are adding a subsystem to flight
682 // gear, its initialization call should located in this routine.
683 // Returns non-zero if a problem encountered.
684 void fgCreateSubsystems(bool duringReset) {
686 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
687 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
689 ////////////////////////////////////////////////////////////////////
690 // Initialize the sound subsystem.
691 ////////////////////////////////////////////////////////////////////
692 // Sound manager uses an own subsystem group "SOUND" which is the last
693 // to be updated in every loop.
694 // Sound manager is updated last so it can use the CPU while the GPU
695 // is processing the scenery (doubled the frame-rate for me) -EMH-
696 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
698 ////////////////////////////////////////////////////////////////////
699 // Initialize the event manager subsystem.
700 ////////////////////////////////////////////////////////////////////
702 globals->get_event_mgr()->init();
703 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
705 ////////////////////////////////////////////////////////////////////
706 // Initialize the property interpolator subsystem. Put into the INIT
707 // group because the "nasal" subsystem may need it at GENERAL take-down.
708 ////////////////////////////////////////////////////////////////////
709 globals->add_subsystem("prop-interpolator", new FGInterpolator, SGSubsystemMgr::INIT);
712 ////////////////////////////////////////////////////////////////////
713 // Add the FlightGear property utilities.
714 ////////////////////////////////////////////////////////////////////
715 globals->add_subsystem("properties", new FGProperties);
718 ////////////////////////////////////////////////////////////////////
719 // Add the performance monitoring system.
720 ////////////////////////////////////////////////////////////////////
721 globals->add_subsystem("performance-mon",
722 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
723 fgGetNode("/sim/performance-monitor", true)));
725 ////////////////////////////////////////////////////////////////////
726 // Initialize the material property subsystem.
727 ////////////////////////////////////////////////////////////////////
729 SGPath mpath( globals->get_fg_root() );
730 mpath.append( fgGetString("/sim/rendering/materials-file") );
731 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
732 globals->get_props()) ) {
733 throw sg_io_exception("Error loading materials file", mpath);
736 // may exist already due to GUI startup
737 if (!globals->get_subsystem("http")) {
738 globals->add_subsystem( "http", new FGHTTPClient );
741 ////////////////////////////////////////////////////////////////////
742 // Initialize the scenery management subsystem.
743 ////////////////////////////////////////////////////////////////////
745 globals->get_scenery()->get_scene_graph()
746 ->addChild(simgear::Particles::getCommonRoot());
747 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
749 ////////////////////////////////////////////////////////////////////
750 // Initialize the flight model subsystem.
751 ////////////////////////////////////////////////////////////////////
753 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
755 ////////////////////////////////////////////////////////////////////
756 // Initialize the weather subsystem.
757 ////////////////////////////////////////////////////////////////////
759 // Initialize the weather modeling subsystem
760 globals->add_subsystem("environment", new FGEnvironmentMgr);
761 globals->add_subsystem("ephemeris", new Ephemeris);
763 ////////////////////////////////////////////////////////////////////
764 // Initialize the aircraft systems and instrumentation (before the
766 ////////////////////////////////////////////////////////////////////
768 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
769 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
770 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
771 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
773 ////////////////////////////////////////////////////////////////////
774 // Initialize the XML Autopilot subsystem.
775 ////////////////////////////////////////////////////////////////////
777 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
778 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
779 globals->add_subsystem( "route-manager", new FGRouteMgr );
781 ////////////////////////////////////////////////////////////////////
782 // Initialize the Input-Output subsystem
783 ////////////////////////////////////////////////////////////////////
784 globals->add_subsystem( "io", new FGIO );
786 ////////////////////////////////////////////////////////////////////
787 // Create and register the logger.
788 ////////////////////////////////////////////////////////////////////
790 globals->add_subsystem("logger", new FGLogger);
792 ////////////////////////////////////////////////////////////////////
793 // Create and register the XML GUI.
794 ////////////////////////////////////////////////////////////////////
796 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
798 //////////////////////////////////////////////////////////////////////
799 // Initialize the 2D cloud subsystem.
800 ////////////////////////////////////////////////////////////////////
801 fgGetBool("/sim/rendering/bump-mapping", false);
803 ////////////////////////////////////////////////////////////////////
804 // Initialize the canvas 2d drawing subsystem.
805 ////////////////////////////////////////////////////////////////////
806 simgear::canvas::Canvas::setSystemAdapter(
807 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
809 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
810 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
812 ////////////////////////////////////////////////////////////////////
813 // Initialize the ATC subsystem
814 ////////////////////////////////////////////////////////////////////
815 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
817 ////////////////////////////////////////////////////////////////////
818 // Initialize multiplayer subsystem
819 ////////////////////////////////////////////////////////////////////
821 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
823 ////////////////////////////////////////////////////////////////////
824 // Initialise the AI Model Manager
825 ////////////////////////////////////////////////////////////////////
826 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
827 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
828 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
831 // It's probably a good idea to initialize the top level traffic manager
832 // After the AI and ATC systems have been initialized properly.
833 // AI Traffic manager
834 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
836 ////////////////////////////////////////////////////////////////////
837 // Add a new 2D panel.
838 ////////////////////////////////////////////////////////////////////
840 fgSetArchivable("/sim/panel/visibility");
841 fgSetArchivable("/sim/panel/x-offset");
842 fgSetArchivable("/sim/panel/y-offset");
843 fgSetArchivable("/sim/panel/jitter");
845 ////////////////////////////////////////////////////////////////////
846 // Initialize the controls subsystem.
847 ////////////////////////////////////////////////////////////////////
849 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
851 ////////////////////////////////////////////////////////////////////
852 // Initialize the input subsystem.
853 ////////////////////////////////////////////////////////////////////
855 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
858 ////////////////////////////////////////////////////////////////////
859 // Initialize the replay subsystem
860 ////////////////////////////////////////////////////////////////////
861 globals->add_subsystem("replay", new FGReplay);
862 globals->add_subsystem("history", new FGFlightHistory);
864 #ifdef ENABLE_AUDIO_SUPPORT
865 ////////////////////////////////////////////////////////////////////
866 // Initialize the sound-effects subsystem.
867 ////////////////////////////////////////////////////////////////////
868 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
872 ////////////////////////////////////////////////////////////////////
873 // Initialize the FGCom subsystem.
874 ////////////////////////////////////////////////////////////////////
875 globals->add_subsystem("fgcom", new FGCom);
879 SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
881 globals->add_subsystem("httpd", httpd );
884 ////////////////////////////////////////////////////////////////////
885 // Initialize the lighting subsystem.
886 ////////////////////////////////////////////////////////////////////
888 // ordering here is important : Nasal (via events), then models, then views
890 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
891 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
894 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
895 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
897 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
899 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
900 SGSubsystemMgr::DISPLAY);
903 void fgPostInitSubsystems()
908 ////////////////////////////////////////////////////////////////////////
909 // Initialize the Nasal interpreter.
910 // Do this last, so that the loaded scripts see initialized state
911 ////////////////////////////////////////////////////////////////////////
912 FGNasalSys* nasal = new FGNasalSys();
913 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
915 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
917 // initialize methods that depend on other subsystems.
919 globals->get_subsystem_mgr()->postinit();
920 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
922 ////////////////////////////////////////////////////////////////////////
923 // End of subsystem initialization.
924 ////////////////////////////////////////////////////////////////////
926 fgSetBool("/sim/crashed", false);
927 fgSetBool("/sim/initialized", true);
929 SG_LOG( SG_GENERAL, SG_INFO, endl);
932 // re-position is a simplified version of the traditional (legacy)
933 // reset procedure. We only need to poke systems which will be upset by
934 // a sudden change in aircraft position. Since this potentially includes
935 // Nasal, we trigger the 'reinit' signal.
936 void fgStartReposition()
938 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
939 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
941 // ensure we are frozen
942 bool freeze = master_freeze->getBoolValue();
944 master_freeze->setBoolValue(true);
947 // set this signal so Nasal scripts can take action.
948 fgSetBool("/sim/signals/reinit", true);
949 fgSetBool("/sim/crashed", false);
951 FDMShell* fdm = static_cast<FDMShell*>(globals->get_subsystem("flight"));
954 // update our position based on current presets
955 // this will mark position as needed finalized which we'll do in the
957 flightgear::initPosition();
959 simgear::SGTerraSync* terraSync =
960 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
962 terraSync->reposition();
965 // Initialize the FDM
966 globals->get_subsystem("flight")->reinit();
968 // reset replay buffers
969 globals->get_subsystem("replay")->reinit();
971 // ugly: finalizePosition waits for METAR to arrive for the new airport.
972 // we don't re-init the environment manager here, since historically we did
973 // not, and doing so seems to have other issues. All that's needed is to
974 // schedule METAR fetch immediately, so it's available for finalizePosition.
975 // So we manually extract the METAR-fetching component inside the environment
976 // manager, and re-init that.
977 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
979 envMgr->get_subsystem("realwx")->reinit();
982 // need to bind FDMshell again, since we manually unbound it above...
985 // need to reset aircraft (systems/instruments/autopilot)
986 // so they can adapt to current environment
987 globals->get_subsystem("systems")->reinit();
988 globals->get_subsystem("instrumentation")->reinit();
989 globals->get_subsystem("xml-autopilot")->reinit();
991 // setup state to end re-init
992 fgSetBool("/sim/signals/reinit", false);
994 master_freeze->setBoolValue(false);
996 fgSetBool("/sim/sceneryloaded",false);
999 void fgStartNewReset()
1001 SGPropertyNode_ptr preserved(new SGPropertyNode);
1003 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1004 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1006 fgSetBool("/sim/signals/reinit", true);
1007 fgSetBool("/sim/freeze/master", true);
1009 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1010 // Nasal is manually inited in fgPostInit, ensure it's already shutdown
1011 // before other subsystems, so Nasal listeners don't fire during shutdonw
1012 SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
1015 subsystemManger->remove("nasal");
1017 subsystemManger->shutdown();
1018 subsystemManger->unbind();
1020 // remove most subsystems, with a few exceptions.
1021 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1022 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1023 const string_list& names(grp->member_names());
1024 string_list::const_iterator it;
1025 for (it = names.begin(); it != names.end(); ++it) {
1026 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
1027 || (*it == "lighting"))
1033 subsystemManger->remove(it->c_str());
1034 } catch (std::exception& e) {
1035 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1037 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1040 // don't delete here, dropping the ref should be sufficient
1042 } // of top-level groups iteration
1044 FGRenderer* render = globals->get_renderer();
1045 // needed or we crash in multi-threaded OSG mode
1046 render->getViewer()->stopThreading();
1048 // order is important here since tile-manager shutdown needs to
1049 // access the scenery object
1050 globals->set_tile_mgr(NULL);
1051 globals->set_scenery(NULL);
1052 FGScenery::getPagerSingleton()->clearRequests();
1053 flightgear::CameraGroup::setDefault(NULL);
1055 // don't cancel the pager until after shutdown, since AIModels (and
1056 // potentially others) can queue delete requests on the pager.
1057 render->getViewer()->getDatabasePager()->cancel();
1058 render->getViewer()->getDatabasePager()->clear();
1060 osgDB::Registry::instance()->clearObjectCache();
1062 // preserve the event handler; re-creating it would entail fixing the
1064 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1066 globals->set_renderer(NULL);
1067 globals->set_matlib(NULL);
1068 globals->set_chatter_queue(NULL);
1070 simgear::clearEffectCache();
1071 simgear::SGModelLib::resetPropertyRoot();
1073 simgear::GlobalParticleCallback::setSwitch(NULL);
1075 globals->resetPropertyRoot();
1076 // otherwise channels are duplicated
1077 globals->get_channel_options_list()->clear();
1079 fgInitConfig(0, NULL, true);
1080 fgInitGeneral(); // all of this?
1082 flightgear::Options::sharedInstance()->processOptions();
1084 // PRESERVED properties over-write state from options, intentionally
1085 if ( copyProperties(preserved, globals->get_props()) ) {
1086 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1088 SG_LOG( SG_GENERAL, SG_INFO,
1089 "Some errors restoring preserved state (read-only props?)" );
1092 fgGetNode("/sim")->removeChild("aircraft-dir");
1093 fgInitAircraftPaths(true);
1094 fgInitAircraft(true);
1096 render = new FGRenderer;
1097 render->setEventHandler(eventHandler);
1098 eventHandler->reset();
1099 globals->set_renderer(render);
1101 render->setViewer(viewer.get());
1103 viewer->getDatabasePager()->setUpThreads(1, 1);
1105 // must do this before splashinit for Rembrandt
1106 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1107 render->splashinit();
1108 viewer->startThreading();
1110 fgOSResetProperties();
1112 // init some things manually
1113 // which do not follow the regular init pattern
1115 globals->get_event_mgr()->init();
1116 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1118 globals->set_matlib( new SGMaterialLib );
1120 // terra-sync needs the property tree root, pass it back in
1121 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1122 terra_sync->setRoot(globals->get_props());
1124 fgSetBool("/sim/signals/reinit", false);
1125 fgSetBool("/sim/freeze/master", false);
1126 fgSetBool("/sim/sceneryloaded",false);
1129 void fgInitPackageRoot()
1131 if (globals->packageRoot()) {
1135 // there is some debate if we should be using FG_HOME here (hidden
1136 // location) vs a user-visible location inside Documents (especially on
1137 // Windows and Mac). Really this location should be managed by FG, not
1138 // the user, but it can potentially grow large.
1139 SGPath packageAircraftDir = globals->get_fg_home();
1140 packageAircraftDir.append("Aircraft");
1142 SGSharedPtr<Root> pkgRoot(new Root(packageAircraftDir, FLIGHTGEAR_VERSION));
1143 // set the http client later (too early in startup right now)
1144 globals->setPackageRoot(pkgRoot);