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/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/structure/SGPerfMon.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/sg_dir.hxx>
60 #include <simgear/misc/sgstream.hxx>
61 #include <simgear/misc/strutils.hxx>
62 #include <simgear/props/props_io.hxx>
63 #include <simgear/scene/tsync/terrasync.hxx>
65 #include <simgear/scene/model/modellib.hxx>
66 #include <simgear/scene/material/matlib.hxx>
67 #include <simgear/scene/model/particles.hxx>
68 #include <simgear/scene/tsync/terrasync.hxx>
70 #include <Aircraft/controls.hxx>
71 #include <Aircraft/replay.hxx>
72 #include <Aircraft/FlightHistory.hxx>
73 #include <Airports/runways.hxx>
74 #include <Airports/airport.hxx>
75 #include <Airports/dynamics.hxx>
77 #include <AIModel/AIManager.hxx>
79 #include <ATCDCL/ATISmgr.hxx>
80 #include <ATC/atc_mgr.hxx>
82 #include <Autopilot/route_mgr.hxx>
83 #include <Autopilot/autopilotgroup.hxx>
85 #include <Cockpit/panel.hxx>
86 #include <Cockpit/panel_io.hxx>
88 #include <Canvas/canvas_mgr.hxx>
89 #include <Canvas/gui_mgr.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <GUI/MessageBox.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <AIModel/submodel.hxx>
97 #include <AIModel/AIManager.hxx>
98 #include <Navaids/navdb.hxx>
99 #include <Navaids/navlist.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/tilemgr.hxx>
102 #include <Scripting/NasalSys.hxx>
103 #include <Sound/voice.hxx>
104 #include <Sound/soundmanager.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Time/TimeManager.hxx>
109 #include <Traffic/TrafficMgr.hxx>
110 #include <MultiPlayer/multiplaymgr.hxx>
111 #include <FDM/fdm_shell.hxx>
112 #include <Environment/ephemeris.hxx>
113 #include <Environment/environment_mgr.hxx>
114 #include <Viewer/renderer.hxx>
115 #include <Viewer/viewmgr.hxx>
116 #include <Viewer/FGEventHandler.hxx>
117 #include <Navaids/NavDataCache.hxx>
118 #include <Instrumentation/HUD/HUD.hxx>
119 #include <Cockpit/cockpitDisplayManager.hxx>
120 #include <Network/HTTPClient.hxx>
121 #include <Network/fgcom.hxx>
123 #include <Viewer/CameraGroup.hxx>
125 #include "fg_init.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "FGInterpolator.hxx"
130 #include "options.hxx"
131 #include "globals.hxx"
132 #include "logger.hxx"
134 #include "positioninit.hxx"
136 #include "AircraftDirVisitorBase.hxx"
139 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
142 //#define NEW_RESET 1
148 using namespace boost::algorithm;
150 extern osg::ref_ptr<osgViewer::Viewer> viewer;
152 // Return the current base package version
153 string fgBasePackageVersion() {
154 SGPath base_path( globals->get_fg_root() );
155 base_path.append("version");
156 if (!base_path.exists()) {
160 sg_gzifstream in( base_path.str() );
171 class FindAndCacheAircraft : public AircraftDirVistorBase
174 FindAndCacheAircraft(SGPropertyNode* autoSave)
176 _cache = autoSave->getNode("sim/startup/path-cache", true);
181 std::string aircraft = fgGetString( "/sim/aircraft", "");
182 if (aircraft.empty()) {
183 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
184 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
188 _searchAircraft = aircraft + "-set.xml";
189 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
190 if (!aircraftDir.empty()) {
191 // aircraft-dir was set, skip any searching at all, if it's valid
192 simgear::Dir acPath(aircraftDir);
193 SGPath setFile = acPath.file(_searchAircraft);
194 if (setFile.exists()) {
195 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
198 readProperties(setFile.str(), globals->get_props());
199 } catch ( const sg_exception &e ) {
200 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
201 flightgear::fatalMessageBox("Error reading aircraft",
202 "An error occured reading the requested aircraft (" + aircraft + ")",
203 e.getFormattedMessage());
209 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
210 "' not found in specified dir:" << aircraftDir);
211 flightgear::fatalMessageBox("Aircraft not found",
212 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
219 // prepare cache for re-scan
220 SGPropertyNode *n = _cache->getNode("fg-root", true);
221 n->setStringValue(globals->get_fg_root().c_str());
222 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
223 n = _cache->getNode("fg-aircraft", true);
224 n->setStringValue(getAircraftPaths().c_str());
225 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
226 _cache->removeChildren("aircraft");
228 visitAircraftPaths();
231 if (_foundPath.str().empty()) {
232 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
233 flightgear::fatalMessageBox("Aircraft not found",
234 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
239 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
240 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
241 if (!_foundPath.exists()) {
242 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
247 readProperties(_foundPath.str(), globals->get_props());
248 } catch ( const sg_exception &e ) {
249 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
250 flightgear::fatalMessageBox("Error reading aircraft",
251 "An error occured reading the requested aircraft (" + aircraft + ")",
252 e.getFormattedMessage());
260 SGPath getAircraftPaths() {
261 string_list pathList = globals->get_aircraft_paths();
262 SGPath aircraftPaths;
263 string_list::const_iterator it = pathList.begin();
264 if (it != pathList.end()) {
265 aircraftPaths.set(*it);
268 for (; it != pathList.end(); ++it) {
269 aircraftPaths.add(*it);
271 return aircraftPaths;
276 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
277 return false; // cache mismatch
280 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
281 return false; // cache mismatch
284 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
285 for (unsigned int i = 0; i < cache.size(); i++) {
286 const char *name = cache[i]->getStringValue("file", "");
287 if (!boost::equals(_searchAircraft, name, is_iequal())) {
291 SGPath xml(cache[i]->getStringValue("path", ""));
299 } // of aircraft in cache iteration
304 virtual VisitResult visit(const SGPath& p)
309 if (!_cache->getChild("aircraft", i++, false))
313 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
315 std::string fileName(p.file());
316 n = entry->getNode("file", true);
317 n->setStringValue(fileName);
318 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
320 n = entry->getNode("path", true);
321 n->setStringValue(p.dir());
322 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
324 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
329 return VISIT_CONTINUE;
332 std::string _searchAircraft;
334 SGPropertyNode* _cache;
338 static SGPath platformDefaultDataPath()
340 char *envp = ::getenv( "APPDATA" );
341 SGPath config( envp );
342 config.append( "flightgear.org" );
346 #elif defined(SG_MAC)
348 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
351 static SGPath platformDefaultDataPath()
353 return SGPath::home() / ".fgfs";
359 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
360 globals->set_fg_home(dataPath.c_str());
362 simgear::Dir fgHome(dataPath);
363 if (!fgHome.exists()) {
367 if (!fgHome.exists()) {
368 flightgear::fatalMessageBox("Problem setting up user data",
369 "Unable to create the user-data storage folder at: '"
370 + dataPath.str() + "'");
374 if (fgGetBool("/sim/fghome-readonly", false)) {
375 // user / config forced us into readonly mode, fine
376 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
380 // write our PID, and check writeability
381 SGPath pidPath(dataPath, "fgfs.pid");
382 if (pidPath.exists()) {
383 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
384 // set a marker property so terrasync/navcache don't try to write
385 // from secondary instances
386 fgSetBool("/sim/fghome-readonly", true);
392 #if defined(SG_WINDOWS)
393 size_t len = snprintf(buf, 16, "%d", _getpid());
395 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
396 FILE_SHARE_READ, /* sharing */
397 NULL, /* security attributes */
398 CREATE_NEW, /* error if already exists */
399 FILE_FLAG_DELETE_ON_CLOSE,
400 NULL /* template */);
402 result = (f != INVALID_HANDLE_VALUE);
405 WriteFile(f, buf, len, &written, NULL /* overlapped */);
408 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
410 size_t len = snprintf(buf, 16, "%d", getpid());
411 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
413 ::write(fd, buf, len);
414 ::unlink(pidPath.c_str()); // delete file when app quits
418 fgSetBool("/sim/fghome-readonly", false);
421 flightgear::fatalMessageBox("File permissions problem",
422 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
423 "User-data at:" + dataPath.str());
428 // Read in configuration (file and command line)
429 int fgInitConfig ( int argc, char **argv, bool reinit )
431 SGPath dataPath = globals->get_fg_home();
433 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
434 if (!exportDir.exists()) {
435 exportDir.create(0777);
438 // Set /sim/fg-home and don't allow malign code to override it until
439 // Nasal security is set up. Use FG_HOME if necessary.
440 SGPropertyNode *home = fgGetNode("/sim", true);
441 home->removeChild("fg-home", 0, false);
442 home = home->getChild("fg-home", 0, true);
443 home->setStringValue(dataPath.c_str());
444 home->setAttribute(SGPropertyNode::WRITE, false);
447 flightgear::Options* options = flightgear::Options::sharedInstance();
449 options->init(argc, argv, dataPath);
452 bool loadDefaults = flightgear::Options::sharedInstance()->shouldLoadDefaultConfig();
454 // Read global preferences from $FG_ROOT/preferences.xml
455 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
456 fgLoadProps("preferences.xml", globals->get_props());
457 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
459 // do not load user settings when reset to default is requested, or if
460 // told to explicitly ignore
461 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
463 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
467 globals->loadUserSettings(dataPath);
470 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
471 }// of no-default-config selected
473 // Scan user config files and command line for a specified aircraft.
474 options->initAircraft();
476 FindAndCacheAircraft f(globals->get_props());
477 if (!f.loadAircraft()) {
478 return flightgear::FG_OPTIONS_ERROR;
481 // parse options after loading aircraft to ensure any user
482 // overrides of defaults are honored.
483 return options->processOptions();
489 * Initialize vor/ndb/ils/fix list management and query systems (as
490 * well as simple airport db list)
491 * This is called multiple times in the case of a cache rebuild,
492 * to allow lengthy caching to take place in the background, without
493 * blocking the main/UI thread.
498 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
499 static bool doingRebuild = false;
500 if (doingRebuild || cache->isRebuildRequired()) {
502 bool finished = cache->rebuild();
504 // sleep to give the rebuild thread more time
505 SGTimeStamp::sleepForMSec(50);
510 FGTACANList *channellist = new FGTACANList;
511 globals->set_channellist( channellist );
513 SGPath path(globals->get_fg_root());
514 path.append( "Navaids/TACAN_freq.dat" );
515 flightgear::loadTacan(path, channellist);
520 // General house keeping initializations
521 bool fgInitGeneral() {
524 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
525 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
527 root = globals->get_fg_root();
528 if ( ! root.length() ) {
529 // No root path set? Then bail ...
530 SG_LOG( SG_GENERAL, SG_ALERT,
531 "Cannot continue without a path to the base package "
532 << "being defined." );
535 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
537 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
538 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
539 fgSetString("/sim/startup/browser-app", globals->get_browser());
541 simgear::Dir cwd(simgear::Dir::current());
542 SGPropertyNode *curr = fgGetNode("/sim", true);
543 curr->removeChild("fg-current", 0, false);
544 curr = curr->getChild("fg-current", 0, true);
545 curr->setStringValue(cwd.path().str());
546 curr->setAttribute(SGPropertyNode::WRITE, false);
548 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
549 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
553 // Write various configuraton values out to the logs
554 void fgOutputSettings()
556 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
557 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
559 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
560 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
561 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
563 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
564 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
567 // This is the top level init routine which calls all the other
568 // initialization routines. If you are adding a subsystem to flight
569 // gear, its initialization call should located in this routine.
570 // Returns non-zero if a problem encountered.
571 void fgCreateSubsystems(bool duringReset) {
573 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
574 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
576 ////////////////////////////////////////////////////////////////////
577 // Initialize the sound subsystem.
578 ////////////////////////////////////////////////////////////////////
579 // Sound manager uses an own subsystem group "SOUND" which is the last
580 // to be updated in every loop.
581 // Sound manager is updated last so it can use the CPU while the GPU
582 // is processing the scenery (doubled the frame-rate for me) -EMH-
583 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
585 ////////////////////////////////////////////////////////////////////
586 // Initialize the event manager subsystem.
587 ////////////////////////////////////////////////////////////////////
589 globals->get_event_mgr()->init();
590 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
592 ////////////////////////////////////////////////////////////////////
593 // Initialize the property interpolator subsystem. Put into the INIT
594 // group because the "nasal" subsystem may need it at GENERAL take-down.
595 ////////////////////////////////////////////////////////////////////
596 FGInterpolator* interp = new FGInterpolator;
597 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
598 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
599 SGPropertyNode::setInterpolationMgr(interp);
601 ////////////////////////////////////////////////////////////////////
602 // Add the FlightGear property utilities.
603 ////////////////////////////////////////////////////////////////////
604 globals->add_subsystem("properties", new FGProperties);
607 ////////////////////////////////////////////////////////////////////
608 // Add the performance monitoring system.
609 ////////////////////////////////////////////////////////////////////
610 globals->add_subsystem("performance-mon",
611 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
612 fgGetNode("/sim/performance-monitor", true)));
614 ////////////////////////////////////////////////////////////////////
615 // Initialize the material property subsystem.
616 ////////////////////////////////////////////////////////////////////
619 SGPath mpath( globals->get_fg_root() );
620 mpath.append( fgGetString("/sim/rendering/materials-file") );
621 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
622 globals->get_props()) ) {
623 throw sg_io_exception("Error loading materials file", mpath);
627 globals->add_subsystem( "http", new FGHTTPClient );
629 ////////////////////////////////////////////////////////////////////
630 // Initialize the scenery management subsystem.
631 ////////////////////////////////////////////////////////////////////
633 globals->get_scenery()->get_scene_graph()
634 ->addChild(simgear::Particles::getCommonRoot());
635 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
637 ////////////////////////////////////////////////////////////////////
638 // Initialize the flight model subsystem.
639 ////////////////////////////////////////////////////////////////////
641 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
643 ////////////////////////////////////////////////////////////////////
644 // Initialize the weather subsystem.
645 ////////////////////////////////////////////////////////////////////
647 // Initialize the weather modeling subsystem
648 globals->add_subsystem("environment", new FGEnvironmentMgr);
649 globals->add_subsystem("ephemeris", new Ephemeris);
651 ////////////////////////////////////////////////////////////////////
652 // Initialize the aircraft systems and instrumentation (before the
654 ////////////////////////////////////////////////////////////////////
656 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
657 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
658 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
659 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
661 ////////////////////////////////////////////////////////////////////
662 // Initialize the XML Autopilot subsystem.
663 ////////////////////////////////////////////////////////////////////
665 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
666 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
667 globals->add_subsystem( "route-manager", new FGRouteMgr );
669 ////////////////////////////////////////////////////////////////////
670 // Initialize the Input-Output subsystem
671 ////////////////////////////////////////////////////////////////////
672 globals->add_subsystem( "io", new FGIO );
674 ////////////////////////////////////////////////////////////////////
675 // Create and register the logger.
676 ////////////////////////////////////////////////////////////////////
678 globals->add_subsystem("logger", new FGLogger);
680 ////////////////////////////////////////////////////////////////////
681 // Create and register the XML GUI.
682 ////////////////////////////////////////////////////////////////////
684 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
686 //////////////////////////////////////////////////////////////////////
687 // Initialize the 2D cloud subsystem.
688 ////////////////////////////////////////////////////////////////////
689 fgGetBool("/sim/rendering/bump-mapping", false);
691 ////////////////////////////////////////////////////////////////////
692 // Initialize the canvas 2d drawing subsystem.
693 ////////////////////////////////////////////////////////////////////
694 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
695 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
697 ////////////////////////////////////////////////////////////////////
698 // Initialise the ATIS Manager
699 // Note that this is old stuff, but is necessary for the
700 // current ATIS implementation. Therefore, leave it in here
701 // until the ATIS system is ported over to make use of the ATIS
702 // sub system infrastructure.
703 ////////////////////////////////////////////////////////////////////
705 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
707 ////////////////////////////////////////////////////////////////////
708 // Initialize the ATC subsystem
709 ////////////////////////////////////////////////////////////////////
710 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
712 ////////////////////////////////////////////////////////////////////
713 // Initialize multiplayer subsystem
714 ////////////////////////////////////////////////////////////////////
716 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
718 ////////////////////////////////////////////////////////////////////
719 // Initialise the AI Model Manager
720 ////////////////////////////////////////////////////////////////////
721 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
722 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
723 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
726 // It's probably a good idea to initialize the top level traffic manager
727 // After the AI and ATC systems have been initialized properly.
728 // AI Traffic manager
729 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
731 ////////////////////////////////////////////////////////////////////
732 // Add a new 2D panel.
733 ////////////////////////////////////////////////////////////////////
735 fgSetArchivable("/sim/panel/visibility");
736 fgSetArchivable("/sim/panel/x-offset");
737 fgSetArchivable("/sim/panel/y-offset");
738 fgSetArchivable("/sim/panel/jitter");
740 ////////////////////////////////////////////////////////////////////
741 // Initialize the controls subsystem.
742 ////////////////////////////////////////////////////////////////////
744 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
746 ////////////////////////////////////////////////////////////////////
747 // Initialize the input subsystem.
748 ////////////////////////////////////////////////////////////////////
750 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
753 ////////////////////////////////////////////////////////////////////
754 // Initialize the replay subsystem
755 ////////////////////////////////////////////////////////////////////
756 globals->add_subsystem("replay", new FGReplay);
757 globals->add_subsystem("history", new FGFlightHistory);
759 #ifdef ENABLE_AUDIO_SUPPORT
760 ////////////////////////////////////////////////////////////////////
761 // Initialize the sound-effects subsystem.
762 ////////////////////////////////////////////////////////////////////
763 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
767 ////////////////////////////////////////////////////////////////////
768 // Initialize the FGCom subsystem.
769 ////////////////////////////////////////////////////////////////////
770 globals->add_subsystem("fgcom", new FGCom);
773 ////////////////////////////////////////////////////////////////////
774 // Initialize the lighting subsystem.
775 ////////////////////////////////////////////////////////////////////
777 // ordering here is important : Nasal (via events), then models, then views
779 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
780 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
783 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
784 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
786 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
788 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
789 SGSubsystemMgr::DISPLAY);
792 void fgPostInitSubsystems()
797 ////////////////////////////////////////////////////////////////////////
798 // Initialize the Nasal interpreter.
799 // Do this last, so that the loaded scripts see initialized state
800 ////////////////////////////////////////////////////////////////////////
801 FGNasalSys* nasal = new FGNasalSys();
802 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
804 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
806 // Ensure IOrules and path validation are working properly by trying to
807 // access a folder/file which should never be accessible.
808 const char* no_access_path =
814 if( fgValidatePath(no_access_path, true) )
819 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
821 if( fgValidatePath(no_access_path, false) )
826 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
829 // initialize methods that depend on other subsystems.
831 globals->get_subsystem_mgr()->postinit();
832 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
834 ////////////////////////////////////////////////////////////////////////
835 // End of subsystem initialization.
836 ////////////////////////////////////////////////////////////////////
838 fgSetBool("/sim/crashed", false);
839 fgSetBool("/sim/initialized", true);
841 SG_LOG( SG_GENERAL, SG_INFO, endl);
843 // Save the initial state for future
845 globals->saveInitialState();
848 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
849 void fgReInitSubsystems()
856 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
858 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
860 // setup state to begin re-init
861 bool freeze = master_freeze->getBoolValue();
863 master_freeze->setBoolValue(true);
866 fgSetBool("/sim/signals/reinit", true);
867 fgSetBool("/sim/crashed", false);
869 // do actual re-init steps
870 globals->get_subsystem("flight")->unbind();
872 // reset control state, before restoring initial state; -set or config files
873 // may specify values for flaps, trim tabs, magnetos, etc
874 globals->get_controls()->reset_all();
876 globals->restoreInitialState();
878 // update our position based on current presets
879 // this will mark position as needed finalized which we'll do in the
881 flightgear::initPosition();
883 simgear::SGTerraSync* terraSync =
884 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
886 terraSync->reposition();
889 // Force reupdating the positions of the ai 3d models. They are used for
890 // initializing ground level for the FDM.
891 globals->get_subsystem("ai-model")->reinit();
893 // Initialize the FDM
894 globals->get_subsystem("flight")->reinit();
896 // reset replay buffers
897 globals->get_subsystem("replay")->reinit();
899 // reload offsets from config defaults
900 globals->get_viewmgr()->reinit();
902 // ugly: finalizePosition waits for METAR to arrive for the new airport.
903 // we don't re-init the environment manager here, since historically we did
904 // not, and doing so seems to have other issues. All that's needed is to
905 // schedule METAR fetch immediately, so it's available for finalizePosition.
906 // So we manually extract the METAR-fetching component inside the environment
907 // manager, and re-init that.
908 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
910 envMgr->get_subsystem("realwx")->reinit();
913 globals->get_subsystem("time")->reinit();
915 // need to bind FDMshell again, since we manually unbound it above...
916 globals->get_subsystem("flight")->bind();
918 // need to reset aircraft (systems/instruments) so they can adapt to current environment
919 globals->get_subsystem("systems")->reinit();
920 globals->get_subsystem("instrumentation")->reinit();
922 globals->get_subsystem("ATIS")->reinit();
924 // setup state to end re-init
925 fgSetBool("/sim/signals/reinit", false);
927 master_freeze->setBoolValue(false);
929 fgSetBool("/sim/sceneryloaded",false);
932 void fgStartNewReset()
934 globals->saveInitialState();
936 fgSetBool("/sim/signals/reinit", true);
937 fgSetBool("/sim/freeze/master", true);
939 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
940 subsystemManger->shutdown();
941 subsystemManger->unbind();
943 // remove them all (with some exceptions?)
944 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
945 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
946 const string_list& names(grp->member_names());
947 string_list::const_iterator it;
948 for (it = names.begin(); it != names.end(); ++it) {
949 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
950 || (*it == "lighting"))
956 subsystemManger->remove(it->c_str());
957 } catch (std::exception& e) {
958 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
960 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
963 // don't delete here, dropping the ref should be sufficient
965 } // of top-level groups iteration
967 // order is important here since tile-manager shutdown needs to
968 // access the scenery object
969 globals->set_tile_mgr(NULL);
970 globals->set_scenery(NULL);
971 flightgear::CameraGroup::setDefault(NULL);
973 FGRenderer* render = globals->get_renderer();
974 // don't cancel the pager until after shutdown, since AIModels (and
975 // potentially others) can queue delete requests on the pager.
976 render->getViewer()->getDatabasePager()->cancel();
978 // preserve the event handler; re-creating it would entail fixing the
980 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
982 globals->set_renderer(NULL);
983 simgear::SGModelLib::resetPropertyRoot();
985 globals->resetPropertyRoot();
986 globals->restoreInitialState();
988 render = new FGRenderer;
989 render->setEventHandler(eventHandler);
990 globals->set_renderer(render);
992 render->setViewer(viewer.get());
993 viewer->getDatabasePager()->setUpThreads(1, 1);
994 render->splashinit();
996 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
998 fgOSResetProperties();
999 fgInitConfig(0, NULL, true);
1001 // init some things manually
1002 // which do not follow the regular init pattern
1004 globals->get_event_mgr()->init();
1005 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1007 // terra-sync needs the property tree root, pass it back in
1008 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1009 terra_sync->setRoot(globals->get_props());
1011 fgSetBool("/sim/signals/reinit", false);
1012 fgSetBool("/sim/freeze/master", false);
1013 fgSetBool("/sim/sceneryloaded",false);