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 <Aircraft/controls.hxx>
73 #include <Aircraft/replay.hxx>
74 #include <Aircraft/FlightHistory.hxx>
75 #include <Airports/runways.hxx>
76 #include <Airports/airport.hxx>
77 #include <Airports/dynamics.hxx>
79 #include <AIModel/AIManager.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 <Canvas/FGCanvasSystemAdapter.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <GUI/MessageBox.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Model/modelmgr.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Scenery/scenery.hxx>
103 #include <Scenery/tilemgr.hxx>
104 #include <Scripting/NasalSys.hxx>
105 #include <Sound/voice.hxx>
106 #include <Sound/soundmanager.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/TimeManager.hxx>
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <FDM/fdm_shell.hxx>
114 #include <Environment/ephemeris.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Viewer/renderer.hxx>
117 #include <Viewer/viewmgr.hxx>
118 #include <Viewer/FGEventHandler.hxx>
119 #include <Navaids/NavDataCache.hxx>
120 #include <Instrumentation/HUD/HUD.hxx>
121 #include <Cockpit/cockpitDisplayManager.hxx>
122 #include <Network/HTTPClient.hxx>
123 #include <Network/fgcom.hxx>
124 #include <Network/http/httpd.hxx>
126 #include <Viewer/CameraGroup.hxx>
128 #include "fg_init.hxx"
130 #include "fg_commands.hxx"
131 #include "fg_props.hxx"
132 #include "FGInterpolator.hxx"
133 #include "options.hxx"
134 #include "globals.hxx"
135 #include "logger.hxx"
137 #include "positioninit.hxx"
139 #include "AircraftDirVisitorBase.hxx"
142 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
145 //#define NEW_RESET 1
151 using namespace boost::algorithm;
153 extern osg::ref_ptr<osgViewer::Viewer> viewer;
155 // Return the current base package version
156 string fgBasePackageVersion() {
157 SGPath base_path( globals->get_fg_root() );
158 base_path.append("version");
159 if (!base_path.exists()) {
163 sg_gzifstream in( base_path.str() );
174 class FindAndCacheAircraft : public AircraftDirVistorBase
177 FindAndCacheAircraft(SGPropertyNode* autoSave)
179 _cache = autoSave->getNode("sim/startup/path-cache", true);
184 std::string aircraft = fgGetString( "/sim/aircraft", "");
185 if (aircraft.empty()) {
186 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
187 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
191 _searchAircraft = aircraft + "-set.xml";
192 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
193 if (!aircraftDir.empty()) {
194 // aircraft-dir was set, skip any searching at all, if it's valid
195 simgear::Dir acPath(aircraftDir);
196 SGPath setFile = acPath.file(_searchAircraft);
197 if (setFile.exists()) {
198 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
201 readProperties(setFile.str(), globals->get_props());
202 } catch ( const sg_exception &e ) {
203 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
204 flightgear::fatalMessageBox("Error reading aircraft",
205 "An error occured reading the requested aircraft (" + aircraft + ")",
206 e.getFormattedMessage());
212 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
213 "' not found in specified dir:" << aircraftDir);
214 flightgear::fatalMessageBox("Aircraft not found",
215 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
222 // prepare cache for re-scan
223 SGPropertyNode *n = _cache->getNode("fg-root", true);
224 n->setStringValue(globals->get_fg_root().c_str());
225 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
226 n = _cache->getNode("fg-aircraft", true);
227 n->setStringValue(getAircraftPaths().c_str());
228 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
229 _cache->removeChildren("aircraft");
231 visitAircraftPaths();
234 if (_foundPath.str().empty()) {
235 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
236 flightgear::fatalMessageBox("Aircraft not found",
237 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
242 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
243 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
244 if (!_foundPath.exists()) {
245 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
250 readProperties(_foundPath.str(), globals->get_props());
251 } catch ( const sg_exception &e ) {
252 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
253 flightgear::fatalMessageBox("Error reading aircraft",
254 "An error occured reading the requested aircraft (" + aircraft + ")",
255 e.getFormattedMessage());
263 SGPath getAircraftPaths() {
264 string_list pathList = globals->get_aircraft_paths();
265 SGPath aircraftPaths;
266 string_list::const_iterator it = pathList.begin();
267 if (it != pathList.end()) {
268 aircraftPaths.set(*it);
271 for (; it != pathList.end(); ++it) {
272 aircraftPaths.add(*it);
274 return aircraftPaths;
279 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
280 return false; // cache mismatch
283 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
284 return false; // cache mismatch
287 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
288 for (unsigned int i = 0; i < cache.size(); i++) {
289 const char *name = cache[i]->getStringValue("file", "");
290 if (!boost::equals(_searchAircraft, name, is_iequal())) {
294 SGPath xml(cache[i]->getStringValue("path", ""));
302 } // of aircraft in cache iteration
307 virtual VisitResult visit(const SGPath& p)
312 if (!_cache->getChild("aircraft", i++, false))
316 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
318 std::string fileName(p.file());
319 n = entry->getNode("file", true);
320 n->setStringValue(fileName);
321 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
323 n = entry->getNode("path", true);
324 n->setStringValue(p.dir());
325 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
327 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
332 return VISIT_CONTINUE;
335 std::string _searchAircraft;
337 SGPropertyNode* _cache;
341 static SGPath platformDefaultDataPath()
343 char *envp = ::getenv( "APPDATA" );
344 SGPath config( envp );
345 config.append( "flightgear.org" );
349 #elif defined(SG_MAC)
351 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
354 static SGPath platformDefaultDataPath()
356 return SGPath::home() / ".fgfs";
362 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
363 globals->set_fg_home(dataPath.c_str());
365 simgear::Dir fgHome(dataPath);
366 if (!fgHome.exists()) {
370 if (!fgHome.exists()) {
371 flightgear::fatalMessageBox("Problem setting up user data",
372 "Unable to create the user-data storage folder at: '"
373 + dataPath.str() + "'");
377 if (fgGetBool("/sim/fghome-readonly", false)) {
378 // user / config forced us into readonly mode, fine
379 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
383 // write our PID, and check writeability
384 SGPath pidPath(dataPath, "fgfs.pid");
385 if (pidPath.exists()) {
386 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
387 // set a marker property so terrasync/navcache don't try to write
388 // from secondary instances
389 fgSetBool("/sim/fghome-readonly", true);
395 #if defined(SG_WINDOWS)
396 size_t len = snprintf(buf, 16, "%d", _getpid());
398 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
399 FILE_SHARE_READ, /* sharing */
400 NULL, /* security attributes */
401 CREATE_NEW, /* error if already exists */
402 FILE_FLAG_DELETE_ON_CLOSE,
403 NULL /* template */);
405 result = (f != INVALID_HANDLE_VALUE);
408 WriteFile(f, buf, len, &written, NULL /* overlapped */);
411 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
413 ssize_t len = snprintf(buf, 16, "%d", getpid());
414 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
416 result = ::write(fd, buf, len) == len;
417 if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
422 fgSetBool("/sim/fghome-readonly", false);
425 flightgear::fatalMessageBox("File permissions problem",
426 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
427 "User-data at:" + dataPath.str());
432 // Read in configuration (file and command line)
433 int fgInitConfig ( int argc, char **argv, bool reinit )
435 SGPath dataPath = globals->get_fg_home();
437 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
438 if (!exportDir.exists()) {
439 exportDir.create(0755);
442 // Set /sim/fg-home and don't allow malign code to override it until
443 // Nasal security is set up. Use FG_HOME if necessary.
444 SGPropertyNode *home = fgGetNode("/sim", true);
445 home->removeChild("fg-home", 0);
446 home = home->getChild("fg-home", 0, true);
447 home->setStringValue(dataPath.c_str());
448 home->setAttribute(SGPropertyNode::WRITE, false);
451 flightgear::Options* options = flightgear::Options::sharedInstance();
453 options->init(argc, argv, dataPath);
456 bool loadDefaults = options->shouldLoadDefaultConfig();
458 // Read global preferences from $FG_ROOT/preferences.xml
459 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
460 fgLoadProps("preferences.xml", globals->get_props());
461 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
463 // do not load user settings when reset to default is requested, or if
464 // told to explicitly ignore
465 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
467 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
471 globals->loadUserSettings(dataPath);
474 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
475 }// of no-default-config selected
477 return flightgear::FG_OPTIONS_OK;
480 int fgInitAircraft(bool reinit)
482 // Scan user config files and command line for a specified aircraft.
484 flightgear::Options::sharedInstance()->initAircraft();
487 FindAndCacheAircraft f(globals->get_props());
488 if (!f.loadAircraft()) {
489 return flightgear::FG_OPTIONS_ERROR;
492 return flightgear::FG_OPTIONS_OK;
496 * Initialize vor/ndb/ils/fix list management and query systems (as
497 * well as simple airport db list)
498 * This is called multiple times in the case of a cache rebuild,
499 * to allow lengthy caching to take place in the background, without
500 * blocking the main/UI thread.
505 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
506 static bool doingRebuild = false;
507 if (doingRebuild || cache->isRebuildRequired()) {
509 bool finished = cache->rebuild();
511 // sleep to give the rebuild thread more time
512 SGTimeStamp::sleepForMSec(50);
517 FGTACANList *channellist = new FGTACANList;
518 globals->set_channellist( channellist );
520 SGPath path(globals->get_fg_root());
521 path.append( "Navaids/TACAN_freq.dat" );
522 flightgear::loadTacan(path, channellist);
527 // General house keeping initializations
528 bool fgInitGeneral() {
531 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
532 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
534 root = globals->get_fg_root();
535 if ( ! root.length() ) {
536 // No root path set? Then bail ...
537 SG_LOG( SG_GENERAL, SG_ALERT,
538 "Cannot continue without a path to the base package "
539 << "being defined." );
542 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
544 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
545 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
546 fgSetString("/sim/startup/browser-app", globals->get_browser());
548 simgear::Dir cwd(simgear::Dir::current());
549 SGPropertyNode *curr = fgGetNode("/sim", true);
550 curr->removeChild("fg-current", 0);
551 curr = curr->getChild("fg-current", 0, true);
552 curr->setStringValue(cwd.path().str());
553 curr->setAttribute(SGPropertyNode::WRITE, false);
555 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
556 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
560 // Write various configuraton values out to the logs
561 void fgOutputSettings()
563 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
564 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
566 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
567 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
568 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
570 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
571 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
574 // This is the top level init routine which calls all the other
575 // initialization routines. If you are adding a subsystem to flight
576 // gear, its initialization call should located in this routine.
577 // Returns non-zero if a problem encountered.
578 void fgCreateSubsystems(bool duringReset) {
580 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
581 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
583 ////////////////////////////////////////////////////////////////////
584 // Initialize the sound subsystem.
585 ////////////////////////////////////////////////////////////////////
586 // Sound manager uses an own subsystem group "SOUND" which is the last
587 // to be updated in every loop.
588 // Sound manager is updated last so it can use the CPU while the GPU
589 // is processing the scenery (doubled the frame-rate for me) -EMH-
590 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
592 ////////////////////////////////////////////////////////////////////
593 // Initialize the event manager subsystem.
594 ////////////////////////////////////////////////////////////////////
596 globals->get_event_mgr()->init();
597 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
599 ////////////////////////////////////////////////////////////////////
600 // Initialize the property interpolator subsystem. Put into the INIT
601 // group because the "nasal" subsystem may need it at GENERAL take-down.
602 ////////////////////////////////////////////////////////////////////
603 FGInterpolator* interp = new FGInterpolator;
604 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
605 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
606 SGPropertyNode::setInterpolationMgr(interp);
608 ////////////////////////////////////////////////////////////////////
609 // Add the FlightGear property utilities.
610 ////////////////////////////////////////////////////////////////////
611 globals->add_subsystem("properties", new FGProperties);
614 ////////////////////////////////////////////////////////////////////
615 // Add the performance monitoring system.
616 ////////////////////////////////////////////////////////////////////
617 globals->add_subsystem("performance-mon",
618 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
619 fgGetNode("/sim/performance-monitor", true)));
621 ////////////////////////////////////////////////////////////////////
622 // Initialize the material property subsystem.
623 ////////////////////////////////////////////////////////////////////
625 SGPath mpath( globals->get_fg_root() );
626 mpath.append( fgGetString("/sim/rendering/materials-file") );
627 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
628 globals->get_props()) ) {
629 throw sg_io_exception("Error loading materials file", mpath);
632 globals->add_subsystem( "http", new FGHTTPClient );
634 ////////////////////////////////////////////////////////////////////
635 // Initialize the scenery management subsystem.
636 ////////////////////////////////////////////////////////////////////
638 globals->get_scenery()->get_scene_graph()
639 ->addChild(simgear::Particles::getCommonRoot());
640 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
642 ////////////////////////////////////////////////////////////////////
643 // Initialize the flight model subsystem.
644 ////////////////////////////////////////////////////////////////////
646 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
648 ////////////////////////////////////////////////////////////////////
649 // Initialize the weather subsystem.
650 ////////////////////////////////////////////////////////////////////
652 // Initialize the weather modeling subsystem
653 globals->add_subsystem("environment", new FGEnvironmentMgr);
654 globals->add_subsystem("ephemeris", new Ephemeris);
656 ////////////////////////////////////////////////////////////////////
657 // Initialize the aircraft systems and instrumentation (before the
659 ////////////////////////////////////////////////////////////////////
661 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
662 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
663 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
664 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
666 ////////////////////////////////////////////////////////////////////
667 // Initialize the XML Autopilot subsystem.
668 ////////////////////////////////////////////////////////////////////
670 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
671 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
672 globals->add_subsystem( "route-manager", new FGRouteMgr );
674 ////////////////////////////////////////////////////////////////////
675 // Initialize the Input-Output subsystem
676 ////////////////////////////////////////////////////////////////////
677 globals->add_subsystem( "io", new FGIO );
679 ////////////////////////////////////////////////////////////////////
680 // Create and register the logger.
681 ////////////////////////////////////////////////////////////////////
683 globals->add_subsystem("logger", new FGLogger);
685 ////////////////////////////////////////////////////////////////////
686 // Create and register the XML GUI.
687 ////////////////////////////////////////////////////////////////////
689 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
691 //////////////////////////////////////////////////////////////////////
692 // Initialize the 2D cloud subsystem.
693 ////////////////////////////////////////////////////////////////////
694 fgGetBool("/sim/rendering/bump-mapping", false);
696 ////////////////////////////////////////////////////////////////////
697 // Initialize the canvas 2d drawing subsystem.
698 ////////////////////////////////////////////////////////////////////
699 simgear::canvas::Canvas::setSystemAdapter(
700 simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
702 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
703 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
705 ////////////////////////////////////////////////////////////////////
706 // Initialize the ATC subsystem
707 ////////////////////////////////////////////////////////////////////
708 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
710 ////////////////////////////////////////////////////////////////////
711 // Initialize multiplayer subsystem
712 ////////////////////////////////////////////////////////////////////
714 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
716 ////////////////////////////////////////////////////////////////////
717 // Initialise the AI Model Manager
718 ////////////////////////////////////////////////////////////////////
719 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
720 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
721 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
724 // It's probably a good idea to initialize the top level traffic manager
725 // After the AI and ATC systems have been initialized properly.
726 // AI Traffic manager
727 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
729 ////////////////////////////////////////////////////////////////////
730 // Add a new 2D panel.
731 ////////////////////////////////////////////////////////////////////
733 fgSetArchivable("/sim/panel/visibility");
734 fgSetArchivable("/sim/panel/x-offset");
735 fgSetArchivable("/sim/panel/y-offset");
736 fgSetArchivable("/sim/panel/jitter");
738 ////////////////////////////////////////////////////////////////////
739 // Initialize the controls subsystem.
740 ////////////////////////////////////////////////////////////////////
742 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
744 ////////////////////////////////////////////////////////////////////
745 // Initialize the input subsystem.
746 ////////////////////////////////////////////////////////////////////
748 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
751 ////////////////////////////////////////////////////////////////////
752 // Initialize the replay subsystem
753 ////////////////////////////////////////////////////////////////////
754 globals->add_subsystem("replay", new FGReplay);
755 globals->add_subsystem("history", new FGFlightHistory);
757 #ifdef ENABLE_AUDIO_SUPPORT
758 ////////////////////////////////////////////////////////////////////
759 // Initialize the sound-effects subsystem.
760 ////////////////////////////////////////////////////////////////////
761 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
765 ////////////////////////////////////////////////////////////////////
766 // Initialize the FGCom subsystem.
767 ////////////////////////////////////////////////////////////////////
768 globals->add_subsystem("fgcom", new FGCom);
772 SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
774 globals->add_subsystem("httpd", httpd );
777 ////////////////////////////////////////////////////////////////////
778 // Initialize the lighting subsystem.
779 ////////////////////////////////////////////////////////////////////
781 // ordering here is important : Nasal (via events), then models, then views
783 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
784 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
787 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
788 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
790 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
792 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
793 SGSubsystemMgr::DISPLAY);
796 void fgPostInitSubsystems()
801 ////////////////////////////////////////////////////////////////////////
802 // Initialize the Nasal interpreter.
803 // Do this last, so that the loaded scripts see initialized state
804 ////////////////////////////////////////////////////////////////////////
805 FGNasalSys* nasal = new FGNasalSys();
806 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
808 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
810 // Ensure IOrules and path validation are working properly by trying to
811 // access a folder/file which should never be accessible.
812 const char* no_access_path =
818 if( fgValidatePath(no_access_path, true) )
823 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
825 if( fgValidatePath(no_access_path, false) )
830 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
833 // initialize methods that depend on other subsystems.
835 globals->get_subsystem_mgr()->postinit();
836 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
838 ////////////////////////////////////////////////////////////////////////
839 // End of subsystem initialization.
840 ////////////////////////////////////////////////////////////////////
842 fgSetBool("/sim/crashed", false);
843 fgSetBool("/sim/initialized", true);
845 SG_LOG( SG_GENERAL, SG_INFO, endl);
847 // Save the initial state for future
849 globals->saveInitialState();
852 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
853 void fgReInitSubsystems()
860 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
862 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
864 // setup state to begin re-init
865 bool freeze = master_freeze->getBoolValue();
867 master_freeze->setBoolValue(true);
870 fgSetBool("/sim/signals/reinit", true);
871 fgSetBool("/sim/crashed", false);
873 // do actual re-init steps
874 globals->get_subsystem("flight")->unbind();
876 // reset control state, before restoring initial state; -set or config files
877 // may specify values for flaps, trim tabs, magnetos, etc
878 globals->get_controls()->reset_all();
880 globals->restoreInitialState();
882 // update our position based on current presets
883 // this will mark position as needed finalized which we'll do in the
885 flightgear::initPosition();
887 simgear::SGTerraSync* terraSync =
888 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
890 terraSync->reposition();
893 // Force reupdating the positions of the ai 3d models. They are used for
894 // initializing ground level for the FDM.
895 globals->get_subsystem("ai-model")->reinit();
897 // Initialize the FDM
898 globals->get_subsystem("flight")->reinit();
900 // reset replay buffers
901 globals->get_subsystem("replay")->reinit();
903 // reload offsets from config defaults
904 globals->get_viewmgr()->reinit();
906 // ugly: finalizePosition waits for METAR to arrive for the new airport.
907 // we don't re-init the environment manager here, since historically we did
908 // not, and doing so seems to have other issues. All that's needed is to
909 // schedule METAR fetch immediately, so it's available for finalizePosition.
910 // So we manually extract the METAR-fetching component inside the environment
911 // manager, and re-init that.
912 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
914 envMgr->get_subsystem("realwx")->reinit();
917 globals->get_subsystem("time")->reinit();
919 // need to bind FDMshell again, since we manually unbound it above...
920 globals->get_subsystem("flight")->bind();
922 // need to reset aircraft (systems/instruments) so they can adapt to current environment
923 globals->get_subsystem("systems")->reinit();
924 globals->get_subsystem("instrumentation")->reinit();
926 // setup state to end re-init
927 fgSetBool("/sim/signals/reinit", false);
929 master_freeze->setBoolValue(false);
931 fgSetBool("/sim/sceneryloaded",false);
935 // re-position is a simplified version of the traditional (legacy)
936 // reset procedure. We only need to poke systems which will be upset by
937 // a sudden change in aircraft position. Since this potentially includes
938 // Nasal, we trigger the 'reinit' signal.
939 void fgStartReposition()
941 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
942 SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
944 // ensure we are frozen
945 bool freeze = master_freeze->getBoolValue();
947 master_freeze->setBoolValue(true);
950 // set this signal so Nasal scripts can take action.
951 fgSetBool("/sim/signals/reinit", true);
952 fgSetBool("/sim/crashed", false);
954 globals->get_subsystem("flight")->unbind();
956 // update our position based on current presets
957 // this will mark position as needed finalized which we'll do in the
959 flightgear::initPosition();
961 simgear::SGTerraSync* terraSync =
962 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
964 terraSync->reposition();
967 // Force reupdating the positions of the ai 3d models. They are used for
968 // initializing ground level for the FDM.
969 //globals->get_subsystem("ai-model")->reinit();
971 // Initialize the FDM
972 globals->get_subsystem("flight")->reinit();
974 // reset replay buffers
975 globals->get_subsystem("replay")->reinit();
977 // ugly: finalizePosition waits for METAR to arrive for the new airport.
978 // we don't re-init the environment manager here, since historically we did
979 // not, and doing so seems to have other issues. All that's needed is to
980 // schedule METAR fetch immediately, so it's available for finalizePosition.
981 // So we manually extract the METAR-fetching component inside the environment
982 // manager, and re-init that.
983 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
985 envMgr->get_subsystem("realwx")->reinit();
988 // need to bind FDMshell again, since we manually unbound it above...
989 globals->get_subsystem("flight")->bind();
991 // need to reset aircraft (systems/instruments) so they can adapt to current environment
992 globals->get_subsystem("systems")->reinit();
993 globals->get_subsystem("instrumentation")->reinit();
995 // setup state to end re-init
996 fgSetBool("/sim/signals/reinit", false);
998 master_freeze->setBoolValue(false);
1000 fgSetBool("/sim/sceneryloaded",false);
1003 void fgStartNewReset()
1005 SGPropertyNode_ptr preserved(new SGPropertyNode);
1007 if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1008 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1010 fgSetBool("/sim/signals/reinit", true);
1011 fgSetBool("/sim/freeze/master", true);
1013 SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1014 // Nasal is manually inited in fgPostInit, ensure it's already shutdown
1015 // before other subsystems, so Nasal listeners don't fire during shutdonw
1016 SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
1019 subsystemManger->remove("nasal");
1021 subsystemManger->shutdown();
1022 subsystemManger->unbind();
1024 // remove most subsystems, with a few exceptions.
1025 for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1026 SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1027 const string_list& names(grp->member_names());
1028 string_list::const_iterator it;
1029 for (it = names.begin(); it != names.end(); ++it) {
1030 if ((*it == "time") || (*it == "terrasync") || (*it == "events")
1031 || (*it == "lighting"))
1037 subsystemManger->remove(it->c_str());
1038 } catch (std::exception& e) {
1039 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1041 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1044 // don't delete here, dropping the ref should be sufficient
1046 } // of top-level groups iteration
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 flightgear::CameraGroup::setDefault(NULL);
1054 FGRenderer* render = globals->get_renderer();
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 fgInitConfig(0, NULL, true);
1077 fgInitGeneral(); // all of this?
1079 if ( copyProperties(preserved, globals->get_props()) ) {
1080 SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1082 SG_LOG( SG_GENERAL, SG_INFO,
1083 "Some errors restoring preserved state (read-only props?)" );
1086 fgGetNode("/sim")->removeChild("aircraft-dir");
1087 fgInitAircraft(true);
1088 flightgear::Options::sharedInstance()->processOptions();
1090 render = new FGRenderer;
1091 render->setEventHandler(eventHandler);
1092 globals->set_renderer(render);
1094 render->setViewer(viewer.get());
1096 viewer->getDatabasePager()->setUpThreads(1, 1);
1098 // must do this before splashinit for Rembrandt
1099 flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1100 render->splashinit();
1102 fgOSResetProperties();
1104 // init some things manually
1105 // which do not follow the regular init pattern
1107 globals->get_event_mgr()->init();
1108 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1110 globals->set_matlib( new SGMaterialLib );
1112 // terra-sync needs the property tree root, pass it back in
1113 simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1114 terra_sync->setRoot(globals->get_props());
1116 fgSetBool("/sim/signals/reinit", false);
1117 fgSetBool("/sim/freeze/master", false);
1118 fgSetBool("/sim/sceneryloaded",false);