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.
30 #include <string.h> // strcmp()
33 # include <io.h> // isatty()
34 # define isatty _isatty
37 #include <simgear/compiler.h>
40 #include <boost/algorithm/string/compare.hpp>
41 #include <boost/algorithm/string/predicate.hpp>
43 #include <simgear/constants.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/structure/exception.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/structure/SGPerfMon.hxx>
48 #include <simgear/misc/sg_path.hxx>
49 #include <simgear/misc/sg_dir.hxx>
50 #include <simgear/misc/sgstream.hxx>
51 #include <simgear/misc/strutils.hxx>
52 #include <simgear/props/props_io.hxx>
54 #include <simgear/scene/material/matlib.hxx>
55 #include <simgear/scene/model/particles.hxx>
57 #include <Aircraft/controls.hxx>
58 #include <Aircraft/replay.hxx>
59 #include <Aircraft/FlightHistory.hxx>
60 #include <Airports/runways.hxx>
61 #include <Airports/airport.hxx>
62 #include <Airports/dynamics.hxx>
64 #include <AIModel/AIManager.hxx>
66 #include <ATCDCL/ATISmgr.hxx>
67 #include <ATC/atc_mgr.hxx>
69 #include <Autopilot/route_mgr.hxx>
70 #include <Autopilot/autopilotgroup.hxx>
72 #include <Cockpit/panel.hxx>
73 #include <Cockpit/panel_io.hxx>
75 #include <Canvas/canvas_mgr.hxx>
76 #include <Canvas/gui_mgr.hxx>
77 #include <GUI/new_gui.hxx>
78 #include <Input/input.hxx>
79 #include <Instrumentation/instrument_mgr.hxx>
80 #include <Model/acmodel.hxx>
81 #include <Model/modelmgr.hxx>
82 #include <AIModel/submodel.hxx>
83 #include <AIModel/AIManager.hxx>
84 #include <Navaids/navdb.hxx>
85 #include <Navaids/navlist.hxx>
86 #include <Scenery/scenery.hxx>
87 #include <Scenery/tilemgr.hxx>
88 #include <Scripting/NasalSys.hxx>
89 #include <Sound/voice.hxx>
90 #include <Sound/soundmanager.hxx>
91 #include <Systems/system_mgr.hxx>
92 #include <Time/light.hxx>
93 #include <Traffic/TrafficMgr.hxx>
94 #include <MultiPlayer/multiplaymgr.hxx>
95 #include <FDM/fdm_shell.hxx>
96 #include <Environment/ephemeris.hxx>
97 #include <Environment/environment_mgr.hxx>
98 #include <Viewer/renderer.hxx>
99 #include <Viewer/viewmgr.hxx>
100 #include <Navaids/NavDataCache.hxx>
101 #include <Instrumentation/HUD/HUD.hxx>
102 #include <Cockpit/cockpitDisplayManager.hxx>
103 #include <Network/HTTPClient.hxx>
105 #include "fg_init.hxx"
107 #include "fg_commands.hxx"
108 #include "fg_props.hxx"
109 #include "FGInterpolator.hxx"
110 #include "options.hxx"
111 #include "globals.hxx"
112 #include "logger.hxx"
114 #include "positioninit.hxx"
121 using namespace boost::algorithm;
124 // Return the current base package version
125 string fgBasePackageVersion() {
126 SGPath base_path( globals->get_fg_root() );
127 base_path.append("version");
129 sg_gzifstream in( base_path.str() );
130 if ( !in.is_open() ) {
131 SGPath old_path( globals->get_fg_root() );
132 old_path.append( "Thanks" );
133 sg_gzifstream old( old_path.str() );
134 if ( !old.is_open() ) {
137 return "[old version]";
149 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
151 if (!dirPath.exists()) {
152 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
157 simgear::Dir dir(dirPath);
158 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
159 simgear::PathList::iterator p;
160 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
161 // check file name ends with -set.xml
163 // if we found a -set.xml at this level, don't recurse any deeper
166 bool done = (obj->*pred)(*p);
170 } // of -set.xml iteration
176 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
177 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
178 if (p->file() == "CVS") {
182 if (fgFindAircraftInDir(*p, obj, pred)) {
185 } // of subdirs iteration
191 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
193 const string_list& paths(globals->get_aircraft_paths());
194 string_list::const_iterator it = paths.begin();
195 for (; it != paths.end(); ++it) {
196 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
200 } // of aircraft paths iteration
202 // if we reach this point, search the default location (always last)
203 SGPath rootAircraft(globals->get_fg_root());
204 rootAircraft.append("Aircraft");
205 fgFindAircraftInDir(rootAircraft, obj, pred);
208 class FindAndCacheAircraft
211 FindAndCacheAircraft(SGPropertyNode* autoSave)
213 _cache = autoSave->getNode("sim/startup/path-cache", true);
218 std::string aircraft = fgGetString( "/sim/aircraft", "");
219 if (aircraft.empty()) {
220 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
224 _searchAircraft = aircraft + "-set.xml";
225 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
226 if (!aircraftDir.empty()) {
227 // aircraft-dir was set, skip any searching at all, if it's valid
228 simgear::Dir acPath(aircraftDir);
229 SGPath setFile = acPath.file(_searchAircraft);
230 if (setFile.exists()) {
231 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
234 readProperties(setFile.str(), globals->get_props());
235 } catch ( const sg_exception &e ) {
236 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
242 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
243 "' not found in specified dir:" << aircraftDir);
249 // prepare cache for re-scan
250 SGPropertyNode *n = _cache->getNode("fg-root", true);
251 n->setStringValue(globals->get_fg_root().c_str());
252 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
253 n = _cache->getNode("fg-aircraft", true);
254 n->setStringValue(getAircraftPaths().c_str());
255 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
256 _cache->removeChildren("aircraft");
258 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
261 if (_foundPath.str().empty()) {
262 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
266 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
267 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
268 if (!_foundPath.exists()) {
269 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
274 readProperties(_foundPath.str(), globals->get_props());
275 } catch ( const sg_exception &e ) {
276 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
284 SGPath getAircraftPaths() {
285 string_list pathList = globals->get_aircraft_paths();
286 SGPath aircraftPaths;
287 string_list::const_iterator it = pathList.begin();
288 if (it != pathList.end()) {
289 aircraftPaths.set(*it);
292 for (; it != pathList.end(); ++it) {
293 aircraftPaths.add(*it);
295 return aircraftPaths;
300 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
301 return false; // cache mismatch
304 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
305 return false; // cache mismatch
308 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
309 for (unsigned int i = 0; i < cache.size(); i++) {
310 const char *name = cache[i]->getStringValue("file", "");
311 if (!boost::equals(_searchAircraft, name, is_iequal())) {
315 SGPath xml(cache[i]->getStringValue("path", ""));
323 } // of aircraft in cache iteration
328 bool checkAircraft(const SGPath& p)
333 if (!_cache->getChild("aircraft", i++, false))
337 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
339 std::string fileName(p.file());
340 n = entry->getNode("file", true);
341 n->setStringValue(fileName);
342 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
344 n = entry->getNode("path", true);
345 n->setStringValue(p.dir());
346 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
348 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
356 std::string _searchAircraft;
358 SGPropertyNode* _cache;
362 static SGPath platformDefaultDataPath()
364 char *envp = ::getenv( "APPDATA" );
365 SGPath config( envp );
366 config.append( "flightgear.org" );
370 SGPath platformDesktopPath()
373 typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPWSTR, int, BOOL);
374 static GetSpecialFolderPath SHGetSpecialFolderPath = NULL;
376 // lazy open+resolve of shell32
377 if (!SHGetSpecialFolderPath) {
378 HINSTANCE shellDll = ::LoadLibrary("shell32");
379 SHGetSpecialFolderPath = (GetSpecialFolderPath) GetProcAddress(shellDll, "SHGetSpecialFolderPathA");
382 if (!SHGetSpecialFolderPath)
386 if (SHGetSpecialFolderPath(0, path, CSIDL_DESKTOPDIRECTORY, false)) {
393 // TODO real implementation and move to SGPath
394 return SGPath(fgGetString("/sim/fg-current"));
399 #include <CoreServices/CoreServices.h>
401 static SGPath platformDefaultDataPath()
404 OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
409 unsigned char path[1024];
410 if (FSRefMakePath(&ref, path, 1024) != noErr) {
415 appData.set((const char*) path);
416 appData.append("FlightGear");
420 static SGPath platformDefaultDataPath()
422 return SGPath::home() / ".fgfs";
425 SGPath platformDesktopPath()
427 return SGPath::desktop();
433 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
434 globals->set_fg_home(dataPath.c_str());
436 simgear::Dir fgHome(dataPath);
437 if (!fgHome.exists()) {
442 // Read in configuration (file and command line)
443 bool fgInitConfig ( int argc, char **argv )
445 SGPath dataPath = globals->get_fg_home();
447 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
448 if (!exportDir.exists()) {
449 exportDir.create(0777);
452 // Set /sim/fg-home and don't allow malign code to override it until
453 // Nasal security is set up. Use FG_HOME if necessary.
454 SGPropertyNode *home = fgGetNode("/sim", true);
455 home->removeChild("fg-home", 0, false);
456 home = home->getChild("fg-home", 0, true);
457 home->setStringValue(dataPath.c_str());
458 home->setAttribute(SGPropertyNode::WRITE, false);
460 flightgear::Options* options = flightgear::Options::sharedInstance();
461 options->init(argc, argv, dataPath);
462 bool loadDefaults = flightgear::Options::sharedInstance()->shouldLoadDefaultConfig();
464 // Read global preferences from $FG_ROOT/preferences.xml
465 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
466 fgLoadProps("preferences.xml", globals->get_props());
467 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
469 // do not load user settings when reset to default is requested
470 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
472 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
476 globals->loadUserSettings(dataPath);
479 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
480 }// of no-default-config selected
482 // Scan user config files and command line for a specified aircraft.
483 options->initAircraft();
485 FindAndCacheAircraft f(globals->get_props());
486 if (!f.loadAircraft()) {
490 // parse options after loading aircraft to ensure any user
491 // overrides of defaults are honored.
492 options->processOptions();
500 * Initialize vor/ndb/ils/fix list management and query systems (as
501 * well as simple airport db list)
502 * This is called multiple times in the case of a cache rebuild,
503 * to allow length caching to take place in the background, without
504 * blocking the main/UI thread.
509 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
510 static bool doingRebuild = false;
511 if (doingRebuild || cache->isRebuildRequired()) {
513 bool finished = cache->rebuild();
515 // sleep to give the rebuild thread more time
516 SGTimeStamp::sleepForMSec(50);
521 FGTACANList *channellist = new FGTACANList;
522 globals->set_channellist( channellist );
524 SGPath path(globals->get_fg_root());
525 path.append( "Navaids/TACAN_freq.dat" );
526 flightgear::loadTacan(path, channellist);
531 // General house keeping initializations
532 bool fgInitGeneral() {
535 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
536 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
538 root = globals->get_fg_root();
539 if ( ! root.length() ) {
540 // No root path set? Then bail ...
541 SG_LOG( SG_GENERAL, SG_ALERT,
542 "Cannot continue without a path to the base package "
543 << "being defined." );
546 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
548 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
549 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
550 fgSetString("/sim/startup/browser-app", globals->get_browser());
552 simgear::Dir cwd(simgear::Dir::current());
553 SGPropertyNode *curr = fgGetNode("/sim", true);
554 curr->removeChild("fg-current", 0, false);
555 curr = curr->getChild("fg-current", 0, true);
556 curr->setStringValue(cwd.path().str());
557 curr->setAttribute(SGPropertyNode::WRITE, false);
559 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
560 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
564 // Write various configuraton values out to the logs
565 void fgOutputSettings()
567 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
568 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
570 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
571 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
572 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
574 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
575 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
578 // This is the top level init routine which calls all the other
579 // initialization routines. If you are adding a subsystem to flight
580 // gear, its initialization call should located in this routine.
581 // Returns non-zero if a problem encountered.
582 void fgCreateSubsystems() {
584 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
585 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
587 ////////////////////////////////////////////////////////////////////
588 // Initialize the sound subsystem.
589 ////////////////////////////////////////////////////////////////////
590 // Sound manager uses an own subsystem group "SOUND" which is the last
591 // to be updated in every loop.
592 // Sound manager is updated last so it can use the CPU while the GPU
593 // is processing the scenery (doubled the frame-rate for me) -EMH-
594 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
596 ////////////////////////////////////////////////////////////////////
597 // Initialize the event manager subsystem.
598 ////////////////////////////////////////////////////////////////////
600 globals->get_event_mgr()->init();
601 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
603 ////////////////////////////////////////////////////////////////////
604 // Initialize the property interpolator subsystem. Put into the INIT
605 // group because the "nasal" subsystem may need it at GENERAL take-down.
606 ////////////////////////////////////////////////////////////////////
607 FGInterpolator* interp = new FGInterpolator;
608 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
609 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
610 SGPropertyNode::setInterpolationMgr(interp);
612 ////////////////////////////////////////////////////////////////////
613 // Add the FlightGear property utilities.
614 ////////////////////////////////////////////////////////////////////
615 globals->add_subsystem("properties", new FGProperties);
618 ////////////////////////////////////////////////////////////////////
619 // Add the performance monitoring system.
620 ////////////////////////////////////////////////////////////////////
621 globals->add_subsystem("performance-mon",
622 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
623 fgGetNode("/sim/performance-monitor", true)));
625 ////////////////////////////////////////////////////////////////////
626 // Initialize the material property subsystem.
627 ////////////////////////////////////////////////////////////////////
629 SGPath mpath( globals->get_fg_root() );
630 mpath.append( fgGetString("/sim/rendering/materials-file") );
631 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
632 globals->get_props()) ) {
633 SG_LOG( SG_GENERAL, SG_ALERT,
634 "Error loading materials file " << mpath.str() );
638 globals->add_subsystem( "http", new FGHTTPClient );
640 ////////////////////////////////////////////////////////////////////
641 // Initialize the scenery management subsystem.
642 ////////////////////////////////////////////////////////////////////
644 globals->get_scenery()->get_scene_graph()
645 ->addChild(simgear::Particles::getCommonRoot());
646 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
648 ////////////////////////////////////////////////////////////////////
649 // Initialize the flight model subsystem.
650 ////////////////////////////////////////////////////////////////////
652 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
654 ////////////////////////////////////////////////////////////////////
655 // Initialize the weather subsystem.
656 ////////////////////////////////////////////////////////////////////
658 // Initialize the weather modeling subsystem
659 globals->add_subsystem("environment", new FGEnvironmentMgr);
660 globals->add_subsystem("ephemeris", new Ephemeris);
662 ////////////////////////////////////////////////////////////////////
663 // Initialize the aircraft systems and instrumentation (before the
665 ////////////////////////////////////////////////////////////////////
667 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
668 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
669 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
670 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
672 ////////////////////////////////////////////////////////////////////
673 // Initialize the XML Autopilot subsystem.
674 ////////////////////////////////////////////////////////////////////
676 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
677 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
678 globals->add_subsystem( "route-manager", new FGRouteMgr );
680 ////////////////////////////////////////////////////////////////////
681 // Initialize the Input-Output subsystem
682 ////////////////////////////////////////////////////////////////////
683 globals->add_subsystem( "io", new FGIO );
685 ////////////////////////////////////////////////////////////////////
686 // Create and register the logger.
687 ////////////////////////////////////////////////////////////////////
689 globals->add_subsystem("logger", new FGLogger);
691 ////////////////////////////////////////////////////////////////////
692 // Create and register the XML GUI.
693 ////////////////////////////////////////////////////////////////////
695 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
697 //////////////////////////////////////////////////////////////////////
698 // Initialize the 2D cloud subsystem.
699 ////////////////////////////////////////////////////////////////////
700 fgGetBool("/sim/rendering/bump-mapping", false);
702 ////////////////////////////////////////////////////////////////////
703 // Initialize the canvas 2d drawing subsystem.
704 ////////////////////////////////////////////////////////////////////
705 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
706 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
708 ////////////////////////////////////////////////////////////////////
709 // Initialise the ATIS Manager
710 // Note that this is old stuff, but is necessary for the
711 // current ATIS implementation. Therefore, leave it in here
712 // until the ATIS system is ported over to make use of the ATIS
713 // sub system infrastructure.
714 ////////////////////////////////////////////////////////////////////
716 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
718 ////////////////////////////////////////////////////////////////////
719 // Initialize the ATC subsystem
720 ////////////////////////////////////////////////////////////////////
721 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
723 ////////////////////////////////////////////////////////////////////
724 // Initialize multiplayer subsystem
725 ////////////////////////////////////////////////////////////////////
727 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
729 ////////////////////////////////////////////////////////////////////
730 // Initialise the AI Model Manager
731 ////////////////////////////////////////////////////////////////////
732 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
733 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
734 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
737 // It's probably a good idea to initialize the top level traffic manager
738 // After the AI and ATC systems have been initialized properly.
739 // AI Traffic manager
740 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
742 ////////////////////////////////////////////////////////////////////
743 // Add a new 2D panel.
744 ////////////////////////////////////////////////////////////////////
746 fgSetArchivable("/sim/panel/visibility");
747 fgSetArchivable("/sim/panel/x-offset");
748 fgSetArchivable("/sim/panel/y-offset");
749 fgSetArchivable("/sim/panel/jitter");
751 ////////////////////////////////////////////////////////////////////
752 // Initialize the controls subsystem.
753 ////////////////////////////////////////////////////////////////////
755 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
757 ////////////////////////////////////////////////////////////////////
758 // Initialize the input subsystem.
759 ////////////////////////////////////////////////////////////////////
761 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
764 ////////////////////////////////////////////////////////////////////
765 // Initialize the replay subsystem
766 ////////////////////////////////////////////////////////////////////
767 globals->add_subsystem("replay", new FGReplay);
768 globals->add_subsystem("history", new FGFlightHistory);
770 #ifdef ENABLE_AUDIO_SUPPORT
771 ////////////////////////////////////////////////////////////////////
772 // Initialize the sound-effects subsystem.
773 ////////////////////////////////////////////////////////////////////
774 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
777 ////////////////////////////////////////////////////////////////////
778 // Initialize the lighting subsystem.
779 ////////////////////////////////////////////////////////////////////
781 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
783 // ordering here is important : Nasal (via events), then models, then views
784 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
786 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
787 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
789 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
791 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
792 SGSubsystemMgr::DISPLAY);
795 void fgPostInitSubsystems()
800 ////////////////////////////////////////////////////////////////////////
801 // Initialize the Nasal interpreter.
802 // Do this last, so that the loaded scripts see initialized state
803 ////////////////////////////////////////////////////////////////////////
804 FGNasalSys* nasal = new FGNasalSys();
805 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
807 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
809 // Ensure IOrules and path validation are working properly by trying to
810 // access a folder/file which should never be accessible.
811 const char* no_access_path =
817 if( fgValidatePath(no_access_path, true) )
822 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
824 if( fgValidatePath(no_access_path, false) )
829 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
832 // initialize methods that depend on other subsystems.
834 globals->get_subsystem_mgr()->postinit();
835 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
837 ////////////////////////////////////////////////////////////////////////
838 // End of subsystem initialization.
839 ////////////////////////////////////////////////////////////////////
841 fgSetBool("/sim/crashed", false);
842 fgSetBool("/sim/initialized", true);
844 SG_LOG( SG_GENERAL, SG_INFO, endl);
846 // Save the initial state for future
848 globals->saveInitialState();
851 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
852 void fgReInitSubsystems()
854 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
856 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
858 // setup state to begin re-init
859 bool freeze = master_freeze->getBoolValue();
861 master_freeze->setBoolValue(true);
864 fgSetBool("/sim/signals/reinit", true);
865 fgSetBool("/sim/crashed", false);
867 // do actual re-init steps
868 globals->get_subsystem("flight")->unbind();
870 // reset control state, before restoring initial state; -set or config files
871 // may specify values for flaps, trim tabs, magnetos, etc
872 globals->get_controls()->reset_all();
874 globals->restoreInitialState();
876 // update our position based on current presets
877 // this will mark position as needed finalized which we'll do in the
879 flightgear::initPosition();
881 // Force reupdating the positions of the ai 3d models. They are used for
882 // initializing ground level for the FDM.
883 globals->get_subsystem("ai-model")->reinit();
885 // Initialize the FDM
886 globals->get_subsystem("flight")->reinit();
888 // reset replay buffers
889 globals->get_subsystem("replay")->reinit();
891 // reload offsets from config defaults
892 globals->get_viewmgr()->reinit();
894 // ugly: finalizePosition waits for METAR to arrive for the new airport.
895 // we don't re-init the environment manager here, since historically we did
896 // not, and doing so seems to have other issues. All that's needed is to
897 // schedule METAR fetch immediately, so it's available for finalizePosition.
898 // So we manually extract the METAR-fetching component inside the environment
899 // manager, and re-init that.
900 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
902 envMgr->get_subsystem("realwx")->reinit();
905 globals->get_subsystem("time")->reinit();
907 // need to bind FDMshell again, since we manually unbound it above...
908 globals->get_subsystem("flight")->bind();
910 // need to reset aircraft (systems/instruments) so they can adapt to current environment
911 globals->get_subsystem("systems")->reinit();
912 globals->get_subsystem("instrumentation")->reinit();
914 globals->get_subsystem("ATIS")->reinit();
916 // setup state to end re-init
917 fgSetBool("/sim/signals/reinit", false);
919 master_freeze->setBoolValue(false);
921 fgSetBool("/sim/sceneryloaded",false);
925 ///////////////////////////////////////////////////////////////////////////////
926 // helper object to implement the --show-aircraft command.
927 // resides here so we can share the fgFindAircraftInDir template above,
928 // and hence ensure this command lists exectly the same aircraft as the normal
935 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
939 void show(const SGPath& path)
941 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
943 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
944 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
945 cout << "Available aircraft:" << endl;
946 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
947 cout << _aircraft[i] << endl;
952 bool processAircraft(const SGPath& path)
956 readProperties(path.str(), &root);
957 } catch (sg_exception& ) {
963 descStr += path.file();
964 // trim common suffix from file names
965 int nPos = descStr.rfind("-set.xml");
966 if (nPos == (int)(descStr.size() - 8)) {
967 descStr.resize(nPos);
970 SGPropertyNode *node = root.getNode("sim");
972 SGPropertyNode* desc = node->getNode("description");
973 // if a status tag is found, read it in
974 if (node->hasValue("status")) {
975 maturity = getNumMaturity(node->getStringValue("status"));
979 if (descStr.size() <= 27+3) {
980 descStr.append(29+3-descStr.size(), ' ');
983 descStr.append( 32, ' ');
985 descStr += desc->getStringValue();
987 } // of have 'sim' node
989 if (maturity < _minStatus) {
993 _aircraft.push_back(descStr);
998 int getNumMaturity(const char * str)
1000 // changes should also be reflected in $FG_ROOT/data/options.xml &
1001 // $FG_ROOT/data/Translations/string-default.xml
1002 const char* levels[] = {"alpha","beta","early-production","production"};
1004 if (!strcmp(str, "all")) {
1008 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1009 if (strcmp(str,levels[i])==0)
1015 // recommended in Meyers, Effective STL when internationalization and embedded
1016 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1017 struct ciLessLibC : public std::binary_function<string, string, bool>
1019 bool operator()(const std::string &lhs, const std::string &rhs) const
1021 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1026 string_list _aircraft;
1029 void fgShowAircraft(const SGPath &path)
1035 cout << "Hit a key to continue..." << endl;