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/material/Effect.hxx>
68 #include <simgear/scene/model/particles.hxx>
69 #include <simgear/scene/tsync/terrasync.hxx>
71 #include <Aircraft/controls.hxx>
72 #include <Aircraft/replay.hxx>
73 #include <Aircraft/FlightHistory.hxx>
74 #include <Airports/runways.hxx>
75 #include <Airports/airport.hxx>
76 #include <Airports/dynamics.hxx>
78 #include <AIModel/AIManager.hxx>
80 #include <ATCDCL/ATISmgr.hxx>
81 #include <ATC/atc_mgr.hxx>
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
89 #include <Canvas/canvas_mgr.hxx>
90 #include <Canvas/gui_mgr.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <GUI/MessageBox.hxx>
93 #include <Input/input.hxx>
94 #include <Instrumentation/instrument_mgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Model/modelmgr.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Scenery/scenery.hxx>
102 #include <Scenery/tilemgr.hxx>
103 #include <Scripting/NasalSys.hxx>
104 #include <Sound/voice.hxx>
105 #include <Sound/soundmanager.hxx>
106 #include <Systems/system_mgr.hxx>
107 #include <Time/light.hxx>
108 #include <Time/TimeManager.hxx>
110 #include <Traffic/TrafficMgr.hxx>
111 #include <MultiPlayer/multiplaymgr.hxx>
112 #include <FDM/fdm_shell.hxx>
113 #include <Environment/ephemeris.hxx>
114 #include <Environment/environment_mgr.hxx>
115 #include <Viewer/renderer.hxx>
116 #include <Viewer/viewmgr.hxx>
117 #include <Viewer/FGEventHandler.hxx>
118 #include <Navaids/NavDataCache.hxx>
119 #include <Instrumentation/HUD/HUD.hxx>
120 #include <Cockpit/cockpitDisplayManager.hxx>
121 #include <Network/HTTPClient.hxx>
122 #include <Network/fgcom.hxx>
124 #include <Viewer/CameraGroup.hxx>
126 #include "fg_init.hxx"
128 #include "fg_commands.hxx"
129 #include "fg_props.hxx"
130 #include "FGInterpolator.hxx"
131 #include "options.hxx"
132 #include "globals.hxx"
133 #include "logger.hxx"
135 #include "positioninit.hxx"
137 #include "AircraftDirVisitorBase.hxx"
140 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
143 //#define NEW_RESET 1
149 using namespace boost::algorithm;
151 extern osg::ref_ptr<osgViewer::Viewer> viewer;
153 // Return the current base package version
154 string fgBasePackageVersion() {
155 SGPath base_path( globals->get_fg_root() );
156 base_path.append("version");
157 if (!base_path.exists()) {
161 sg_gzifstream in( base_path.str() );
172 class FindAndCacheAircraft : public AircraftDirVistorBase
175 FindAndCacheAircraft(SGPropertyNode* autoSave)
177 _cache = autoSave->getNode("sim/startup/path-cache", true);
182 std::string aircraft = fgGetString( "/sim/aircraft", "");
183 if (aircraft.empty()) {
184 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
185 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
189 _searchAircraft = aircraft + "-set.xml";
190 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
191 if (!aircraftDir.empty()) {
192 // aircraft-dir was set, skip any searching at all, if it's valid
193 simgear::Dir acPath(aircraftDir);
194 SGPath setFile = acPath.file(_searchAircraft);
195 if (setFile.exists()) {
196 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
199 readProperties(setFile.str(), globals->get_props());
200 } catch ( const sg_exception &e ) {
201 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
202 flightgear::fatalMessageBox("Error reading aircraft",
203 "An error occured reading the requested aircraft (" + aircraft + ")",
204 e.getFormattedMessage());
210 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
211 "' not found in specified dir:" << aircraftDir);
212 flightgear::fatalMessageBox("Aircraft not found",
213 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
220 // prepare cache for re-scan
221 SGPropertyNode *n = _cache->getNode("fg-root", true);
222 n->setStringValue(globals->get_fg_root().c_str());
223 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
224 n = _cache->getNode("fg-aircraft", true);
225 n->setStringValue(getAircraftPaths().c_str());
226 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
227 _cache->removeChildren("aircraft");
229 visitAircraftPaths();
232 if (_foundPath.str().empty()) {
233 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
234 flightgear::fatalMessageBox("Aircraft not found",
235 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
240 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
241 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
242 if (!_foundPath.exists()) {
243 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
248 readProperties(_foundPath.str(), globals->get_props());
249 } catch ( const sg_exception &e ) {
250 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
251 flightgear::fatalMessageBox("Error reading aircraft",
252 "An error occured reading the requested aircraft (" + aircraft + ")",
253 e.getFormattedMessage());
261 SGPath getAircraftPaths() {
262 string_list pathList = globals->get_aircraft_paths();
263 SGPath aircraftPaths;
264 string_list::const_iterator it = pathList.begin();
265 if (it != pathList.end()) {
266 aircraftPaths.set(*it);
269 for (; it != pathList.end(); ++it) {
270 aircraftPaths.add(*it);
272 return aircraftPaths;
277 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
278 return false; // cache mismatch
281 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
282 return false; // cache mismatch
285 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
286 for (unsigned int i = 0; i < cache.size(); i++) {
287 const char *name = cache[i]->getStringValue("file", "");
288 if (!boost::equals(_searchAircraft, name, is_iequal())) {
292 SGPath xml(cache[i]->getStringValue("path", ""));
300 } // of aircraft in cache iteration
305 virtual VisitResult visit(const SGPath& p)
310 if (!_cache->getChild("aircraft", i++, false))
314 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
316 std::string fileName(p.file());
317 n = entry->getNode("file", true);
318 n->setStringValue(fileName);
319 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
321 n = entry->getNode("path", true);
322 n->setStringValue(p.dir());
323 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
325 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
330 return VISIT_CONTINUE;
333 std::string _searchAircraft;
335 SGPropertyNode* _cache;
339 static SGPath platformDefaultDataPath()
341 char *envp = ::getenv( "APPDATA" );
342 SGPath config( envp );
343 config.append( "flightgear.org" );
347 #elif defined(SG_MAC)
349 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
352 static SGPath platformDefaultDataPath()
354 return SGPath::home() / ".fgfs";
360 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
361 globals->set_fg_home(dataPath.c_str());
363 simgear::Dir fgHome(dataPath);
364 if (!fgHome.exists()) {
368 if (!fgHome.exists()) {
369 flightgear::fatalMessageBox("Problem setting up user data",
370 "Unable to create the user-data storage folder at: '"
371 + dataPath.str() + "'");
375 if (fgGetBool("/sim/fghome-readonly", false)) {
376 // user / config forced us into readonly mode, fine
377 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
381 // write our PID, and check writeability
382 SGPath pidPath(dataPath, "fgfs.pid");
383 if (pidPath.exists()) {
384 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
385 // set a marker property so terrasync/navcache don't try to write
386 // from secondary instances
387 fgSetBool("/sim/fghome-readonly", true);
393 #if defined(SG_WINDOWS)
394 size_t len = snprintf(buf, 16, "%d", _getpid());
396 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
397 FILE_SHARE_READ, /* sharing */
398 NULL, /* security attributes */
399 CREATE_NEW, /* error if already exists */
400 FILE_FLAG_DELETE_ON_CLOSE,
401 NULL /* template */);
403 result = (f != INVALID_HANDLE_VALUE);
406 WriteFile(f, buf, len, &written, NULL /* overlapped */);
409 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
411 size_t len = snprintf(buf, 16, "%d", getpid());
412 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
414 ::write(fd, buf, len);
415 ::unlink(pidPath.c_str()); // delete file when app quits
419 fgSetBool("/sim/fghome-readonly", false);
422 flightgear::fatalMessageBox("File permissions problem",
423 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
424 "User-data at:" + dataPath.str());
429 // Read in configuration (file and command line)
430 int fgInitConfig ( int argc, char **argv, bool reinit )
432 SGPath dataPath = globals->get_fg_home();
434 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
435 if (!exportDir.exists()) {
436 exportDir.create(0777);
439 // Set /sim/fg-home and don't allow malign code to override it until
440 // Nasal security is set up. Use FG_HOME if necessary.
441 SGPropertyNode *home = fgGetNode("/sim", true);
442 home->removeChild("fg-home", 0, false);
443 home = home->getChild("fg-home", 0, true);
444 home->setStringValue(dataPath.c_str());
445 home->setAttribute(SGPropertyNode::WRITE, false);
448 flightgear::Options* options = flightgear::Options::sharedInstance();
450 options->init(argc, argv, dataPath);
453 bool loadDefaults = options->shouldLoadDefaultConfig();
455 // Read global preferences from $FG_ROOT/preferences.xml
456 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
457 fgLoadProps("preferences.xml", globals->get_props());
458 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
460 // do not load user settings when reset to default is requested, or if
461 // told to explicitly ignore
462 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
464 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
468 globals->loadUserSettings(dataPath);
471 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
472 }// of no-default-config selected
474 return flightgear::FG_OPTIONS_OK;
477 int fgInitAircraft(bool reinit)
479 // Scan user config files and command line for a specified aircraft.
481 flightgear::Options::sharedInstance()->initAircraft();
484 FindAndCacheAircraft f(globals->get_props());
485 if (!f.loadAircraft()) {
486 return flightgear::FG_OPTIONS_ERROR;
489 return flightgear::FG_OPTIONS_OK;
493 * Initialize vor/ndb/ils/fix list management and query systems (as
494 * well as simple airport db list)
495 * This is called multiple times in the case of a cache rebuild,
496 * to allow lengthy caching to take place in the background, without
497 * blocking the main/UI thread.
502 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
503 static bool doingRebuild = false;
504 if (doingRebuild || cache->isRebuildRequired()) {
506 bool finished = cache->rebuild();
508 // sleep to give the rebuild thread more time
509 SGTimeStamp::sleepForMSec(50);
514 FGTACANList *channellist = new FGTACANList;
515 globals->set_channellist( channellist );
517 SGPath path(globals->get_fg_root());
518 path.append( "Navaids/TACAN_freq.dat" );
519 flightgear::loadTacan(path, channellist);
524 // General house keeping initializations
525 bool fgInitGeneral() {
528 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
529 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
531 root = globals->get_fg_root();
532 if ( ! root.length() ) {
533 // No root path set? Then bail ...
534 SG_LOG( SG_GENERAL, SG_ALERT,
535 "Cannot continue without a path to the base package "
536 << "being defined." );
539 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
541 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
542 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
543 fgSetString("/sim/startup/browser-app", globals->get_browser());
545 simgear::Dir cwd(simgear::Dir::current());
546 SGPropertyNode *curr = fgGetNode("/sim", true);
547 curr->removeChild("fg-current", 0, false);
548 curr = curr->getChild("fg-current", 0, true);
549 curr->setStringValue(cwd.path().str());
550 curr->setAttribute(SGPropertyNode::WRITE, false);
552 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
553 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
557 // Write various configuraton values out to the logs
558 void fgOutputSettings()
560 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
561 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
563 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
564 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
565 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
567 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
568 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
571 // This is the top level init routine which calls all the other
572 // initialization routines. If you are adding a subsystem to flight
573 // gear, its initialization call should located in this routine.
574 // Returns non-zero if a problem encountered.
575 void fgCreateSubsystems(bool duringReset) {
577 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
578 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
580 ////////////////////////////////////////////////////////////////////
581 // Initialize the sound subsystem.
582 ////////////////////////////////////////////////////////////////////
583 // Sound manager uses an own subsystem group "SOUND" which is the last
584 // to be updated in every loop.
585 // Sound manager is updated last so it can use the CPU while the GPU
586 // is processing the scenery (doubled the frame-rate for me) -EMH-
587 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
589 ////////////////////////////////////////////////////////////////////
590 // Initialize the event manager subsystem.
591 ////////////////////////////////////////////////////////////////////
593 globals->get_event_mgr()->init();
594 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
596 ////////////////////////////////////////////////////////////////////
597 // Initialize the property interpolator subsystem. Put into the INIT
598 // group because the "nasal" subsystem may need it at GENERAL take-down.
599 ////////////////////////////////////////////////////////////////////
600 FGInterpolator* interp = new FGInterpolator;
601 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
602 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
603 SGPropertyNode::setInterpolationMgr(interp);
605 ////////////////////////////////////////////////////////////////////
606 // Add the FlightGear property utilities.
607 ////////////////////////////////////////////////////////////////////
608 globals->add_subsystem("properties", new FGProperties);
611 ////////////////////////////////////////////////////////////////////
612 // Add the performance monitoring system.
613 ////////////////////////////////////////////////////////////////////
614 globals->add_subsystem("performance-mon",
615 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
616 fgGetNode("/sim/performance-monitor", true)));
618 ////////////////////////////////////////////////////////////////////
619 // Initialize the material property subsystem.
620 ////////////////////////////////////////////////////////////////////
622 SGPath mpath( globals->get_fg_root() );
623 mpath.append( fgGetString("/sim/rendering/materials-file") );
624 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
625 globals->get_props()) ) {
626 throw sg_io_exception("Error loading materials file", mpath);
629 globals->add_subsystem( "http", new FGHTTPClient );
631 ////////////////////////////////////////////////////////////////////
632 // Initialize the scenery management subsystem.
633 ////////////////////////////////////////////////////////////////////
635 globals->get_scenery()->get_scene_graph()
636 ->addChild(simgear::Particles::getCommonRoot());
637 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
639 ////////////////////////////////////////////////////////////////////
640 // Initialize the flight model subsystem.
641 ////////////////////////////////////////////////////////////////////
643 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
645 ////////////////////////////////////////////////////////////////////
646 // Initialize the weather subsystem.
647 ////////////////////////////////////////////////////////////////////
649 // Initialize the weather modeling subsystem
650 globals->add_subsystem("environment", new FGEnvironmentMgr);
651 globals->add_subsystem("ephemeris", new Ephemeris);
653 ////////////////////////////////////////////////////////////////////
654 // Initialize the aircraft systems and instrumentation (before the
656 ////////////////////////////////////////////////////////////////////
658 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
659 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
660 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
661 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
663 ////////////////////////////////////////////////////////////////////
664 // Initialize the XML Autopilot subsystem.
665 ////////////////////////////////////////////////////////////////////
667 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
668 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
669 globals->add_subsystem( "route-manager", new FGRouteMgr );
671 ////////////////////////////////////////////////////////////////////
672 // Initialize the Input-Output subsystem
673 ////////////////////////////////////////////////////////////////////
674 globals->add_subsystem( "io", new FGIO );
676 ////////////////////////////////////////////////////////////////////
677 // Create and register the logger.
678 ////////////////////////////////////////////////////////////////////
680 globals->add_subsystem("logger", new FGLogger);
682 ////////////////////////////////////////////////////////////////////
683 // Create and register the XML GUI.
684 ////////////////////////////////////////////////////////////////////
686 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
688 //////////////////////////////////////////////////////////////////////
689 // Initialize the 2D cloud subsystem.
690 ////////////////////////////////////////////////////////////////////
691 fgGetBool("/sim/rendering/bump-mapping", false);
693 ////////////////////////////////////////////////////////////////////
694 // Initialize the canvas 2d drawing subsystem.
695 ////////////////////////////////////////////////////////////////////
696 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
697 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
699 ////////////////////////////////////////////////////////////////////
700 // Initialise the ATIS Manager
701 // Note that this is old stuff, but is necessary for the
702 // current ATIS implementation. Therefore, leave it in here
703 // until the ATIS system is ported over to make use of the ATIS
704 // sub system infrastructure.
705 ////////////////////////////////////////////////////////////////////
707 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
709 ////////////////////////////////////////////////////////////////////
710 // Initialize the ATC subsystem
711 ////////////////////////////////////////////////////////////////////
712 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
714 ////////////////////////////////////////////////////////////////////
715 // Initialize multiplayer subsystem
716 ////////////////////////////////////////////////////////////////////
718 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
720 ////////////////////////////////////////////////////////////////////
721 // Initialise the AI Model Manager
722 ////////////////////////////////////////////////////////////////////
723 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
724 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
725 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
728 // It's probably a good idea to initialize the top level traffic manager
729 // After the AI and ATC systems have been initialized properly.
730 // AI Traffic manager
731 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
733 ////////////////////////////////////////////////////////////////////
734 // Add a new 2D panel.
735 ////////////////////////////////////////////////////////////////////
737 fgSetArchivable("/sim/panel/visibility");
738 fgSetArchivable("/sim/panel/x-offset");
739 fgSetArchivable("/sim/panel/y-offset");
740 fgSetArchivable("/sim/panel/jitter");
742 ////////////////////////////////////////////////////////////////////
743 // Initialize the controls subsystem.
744 ////////////////////////////////////////////////////////////////////
746 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
748 ////////////////////////////////////////////////////////////////////
749 // Initialize the input subsystem.
750 ////////////////////////////////////////////////////////////////////
752 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
755 ////////////////////////////////////////////////////////////////////
756 // Initialize the replay subsystem
757 ////////////////////////////////////////////////////////////////////
758 globals->add_subsystem("replay", new FGReplay);
759 globals->add_subsystem("history", new FGFlightHistory);
761 #ifdef ENABLE_AUDIO_SUPPORT
762 ////////////////////////////////////////////////////////////////////
763 // Initialize the sound-effects subsystem.
764 ////////////////////////////////////////////////////////////////////
765 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
769 ////////////////////////////////////////////////////////////////////
770 // Initialize the FGCom subsystem.
771 ////////////////////////////////////////////////////////////////////
772 globals->add_subsystem("fgcom", new FGCom);
775 ////////////////////////////////////////////////////////////////////
776 // Initialize the lighting subsystem.
777 ////////////////////////////////////////////////////////////////////
779 // ordering here is important : Nasal (via events), then models, then views
781 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
782 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
785 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
786 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
788 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
790 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
791 SGSubsystemMgr::DISPLAY);
794 void fgPostInitSubsystems()
799 ////////////////////////////////////////////////////////////////////////
800 // Initialize the Nasal interpreter.
801 // Do this last, so that the loaded scripts see initialized state
802 ////////////////////////////////////////////////////////////////////////
803 FGNasalSys* nasal = new FGNasalSys();
804 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
806 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
808 // Ensure IOrules and path validation are working properly by trying to
809 // access a folder/file which should never be accessible.
810 const char* no_access_path =
816 if( fgValidatePath(no_access_path, true) )
821 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
823 if( fgValidatePath(no_access_path, false) )
828 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
831 // initialize methods that depend on other subsystems.
833 globals->get_subsystem_mgr()->postinit();
834 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
836 ////////////////////////////////////////////////////////////////////////
837 // End of subsystem initialization.
838 ////////////////////////////////////////////////////////////////////
840 fgSetBool("/sim/crashed", false);
841 fgSetBool("/sim/initialized", true);
843 SG_LOG( SG_GENERAL, SG_INFO, endl);
845 // Save the initial state for future
847 globals->saveInitialState();
850 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
851 void fgReInitSubsystems()
858 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
860 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
862 // setup state to begin re-init
863 bool freeze = master_freeze->getBoolValue();
865 master_freeze->setBoolValue(true);
868 fgSetBool("/sim/signals/reinit", true);
869 fgSetBool("/sim/crashed", false);
871 // do actual re-init steps
872 globals->get_subsystem("flight")->unbind();
874 // reset control state, before restoring initial state; -set or config files
875 // may specify values for flaps, trim tabs, magnetos, etc
876 globals->get_controls()->reset_all();
878 globals->restoreInitialState();
880 // update our position based on current presets
881 // this will mark position as needed finalized which we'll do in the
883 flightgear::initPosition();
885 simgear::SGTerraSync* terraSync =
886 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
888 terraSync->reposition();
891 // Force reupdating the positions of the ai 3d models. They are used for
892 // initializing ground level for the FDM.
893 globals->get_subsystem("ai-model")->reinit();
895 // Initialize the FDM
896 globals->get_subsystem("flight")->reinit();
898 // reset replay buffers
899 globals->get_subsystem("replay")->reinit();
901 // reload offsets from config defaults
902 globals->get_viewmgr()->reinit();
904 // ugly: finalizePosition waits for METAR to arrive for the new airport.
905 // we don't re-init the environment manager here, since historically we did
906 // not, and doing so seems to have other issues. All that's needed is to
907 // schedule METAR fetch immediately, so it's available for finalizePosition.
908 // So we manually extract the METAR-fetching component inside the environment
909 // manager, and re-init that.
910 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
912 envMgr->get_subsystem("realwx")->reinit();
915 globals->get_subsystem("time")->reinit();
917 // need to bind FDMshell again, since we manually unbound it above...
918 globals->get_subsystem("flight")->bind();
920 // need to reset aircraft (systems/instruments) so they can adapt to current environment
921 globals->get_subsystem("systems")->reinit();
922 globals->get_subsystem("instrumentation")->reinit();
924 globals->get_subsystem("ATIS")->reinit();
926 // setup state to end re-init
927 fgSetBool("/sim/signals/reinit", false);
929 master_freeze->setBoolValue(false);
931 fgSetBool("/sim/sceneryloaded",false);
934 void fgStartNewReset()
936 globals->saveInitialState();
938 fgSetBool("/sim/signals/reinit", true);
939 fgSetBool("/sim/freeze/master", true);
941 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
942 subsystemManger->shutdown();
943 subsystemManger->unbind();
945 // remove them all (with some exceptions?)
946 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
947 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
948 const string_list& names(grp->member_names());
949 string_list::const_iterator it;
950 for (it = names.begin(); it != names.end(); ++it) {
951 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
952 || (*it == "lighting"))
958 subsystemManger->remove(it->c_str());
959 } catch (std::exception& e) {
960 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
962 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
965 // don't delete here, dropping the ref should be sufficient
967 } // of top-level groups iteration
969 // order is important here since tile-manager shutdown needs to
970 // access the scenery object
971 globals->set_tile_mgr(NULL);
972 globals->set_scenery(NULL);
973 flightgear::CameraGroup::setDefault(NULL);
975 FGRenderer* render = globals->get_renderer();
976 // don't cancel the pager until after shutdown, since AIModels (and
977 // potentially others) can queue delete requests on the pager.
978 render->getViewer()->getDatabasePager()->cancel();
980 osgDB::Registry::instance()->clearObjectCache();
982 // preserve the event handler; re-creating it would entail fixing the
984 osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
986 globals->set_renderer(NULL);
987 globals->set_matlib(NULL);
988 globals->set_chatter_queue(NULL);
990 simgear::clearEffectCache();
991 simgear::SGModelLib::resetPropertyRoot();
993 globals->resetPropertyRoot();
994 globals->restoreInitialState();
996 fgInitConfig(0, NULL, true);
997 fgInitGeneral(); // all of this?
999 fgGetNode("/sim")->removeChild("aircraft-dir");
1000 fgInitAircraft(true);
1001 flightgear::Options::sharedInstance()->processOptions();
1003 render = new FGRenderer;
1004 render->setEventHandler(eventHandler);
1005 globals->set_renderer(render);
1007 render->setViewer(viewer.get());
1008 viewer->getDatabasePager()->setUpThreads(1, 1);
1009 render->splashinit();
1011 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1013 fgOSResetProperties();
1016 // init some things manually
1017 // which do not follow the regular init pattern
1019 globals->get_event_mgr()->init();
1020 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1022 globals->set_matlib( new SGMaterialLib );
1024 // terra-sync needs the property tree root, pass it back in
1025 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1026 terra_sync->setRoot(globals->get_props());
1028 fgSetBool("/sim/signals/reinit", false);
1029 fgSetBool("/sim/freeze/master", false);
1030 fgSetBool("/sim/sceneryloaded",false);