]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Replace SGInterpolator with new advanced interpolation system.
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>             // strcmp()
31
32 #ifdef _WIN32
33 #  include <io.h>               // isatty()
34 #  define isatty _isatty
35 #endif
36
37 #include <simgear/compiler.h>
38
39 #include <string>
40 #include <boost/algorithm/string/compare.hpp>
41 #include <boost/algorithm/string/predicate.hpp>
42
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>
53
54 #include <simgear/scene/material/matlib.hxx>
55 #include <simgear/scene/model/particles.hxx>
56
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>
63
64 #include <AIModel/AIManager.hxx>
65
66 #include <ATCDCL/ATISmgr.hxx>
67 #include <ATC/atc_mgr.hxx>
68
69 #include <Autopilot/route_mgr.hxx>
70 #include <Autopilot/autopilotgroup.hxx>
71
72 #include <Cockpit/panel.hxx>
73 #include <Cockpit/panel_io.hxx>
74
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>
104
105 #include "fg_init.hxx"
106 #include "fg_io.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"
113 #include "main.hxx"
114 #include "positioninit.hxx"
115
116 using std::string;
117 using std::endl;
118 using std::cerr;
119 using std::cout;
120 using namespace boost::algorithm;
121
122
123 // Return the current base package version
124 string fgBasePackageVersion() {
125     SGPath base_path( globals->get_fg_root() );
126     base_path.append("version");
127
128     sg_gzifstream in( base_path.str() );
129     if ( !in.is_open() ) {
130         SGPath old_path( globals->get_fg_root() );
131         old_path.append( "Thanks" );
132         sg_gzifstream old( old_path.str() );
133         if ( !old.is_open() ) {
134             return "[none]";
135         } else {
136             return "[old version]";
137         }
138     }
139
140     string version;
141     in >> version;
142
143     return version;
144 }
145
146
147 template <class T>
148 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
149 {
150   if (!dirPath.exists()) {
151     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
152     return false;
153   }
154     
155   bool recurse = true;
156   simgear::Dir dir(dirPath);
157   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
158   simgear::PathList::iterator p;
159   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
160     // check file name ends with -set.xml
161     
162     // if we found a -set.xml at this level, don't recurse any deeper
163     recurse = false;
164     
165     bool done = (obj->*pred)(*p);
166     if (done) {
167       return true;
168     }
169   } // of -set.xml iteration
170   
171   if (!recurse) {
172     return false;
173   }
174   
175   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
176   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
177     if (p->file() == "CVS") {
178       continue;
179     }
180     
181     if (fgFindAircraftInDir(*p, obj, pred)) {
182       return true;
183     }
184   } // of subdirs iteration
185   
186   return false;
187 }
188
189 template <class T>
190 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
191 {
192   const string_list& paths(globals->get_aircraft_paths());
193   string_list::const_iterator it = paths.begin();
194   for (; it != paths.end(); ++it) {
195     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
196     if (done) {
197       return;
198     }
199   } // of aircraft paths iteration
200   
201   // if we reach this point, search the default location (always last)
202   SGPath rootAircraft(globals->get_fg_root());
203   rootAircraft.append("Aircraft");
204   fgFindAircraftInDir(rootAircraft, obj, pred);
205 }
206
207 class FindAndCacheAircraft
208 {
209 public:
210   FindAndCacheAircraft(SGPropertyNode* autoSave)
211   {
212     _cache = autoSave->getNode("sim/startup/path-cache", true);
213   }
214   
215   bool loadAircraft()
216   {
217     std::string aircraft = fgGetString( "/sim/aircraft", "");
218     if (aircraft.empty()) {
219       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
220       return false;
221     }
222     
223     _searchAircraft = aircraft + "-set.xml";
224     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
225     if (!aircraftDir.empty()) {
226       // aircraft-dir was set, skip any searching at all, if it's valid
227       simgear::Dir acPath(aircraftDir);
228       SGPath setFile = acPath.file(_searchAircraft);
229       if (setFile.exists()) {
230         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
231         
232         try {
233           readProperties(setFile.str(), globals->get_props());
234         } catch ( const sg_exception &e ) {
235           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
236           return false;
237         }
238         
239         return true;
240       } else {
241         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
242                "' not found in specified dir:" << aircraftDir);
243         return false;
244       }
245     }
246     
247     if (!checkCache()) {
248       // prepare cache for re-scan
249       SGPropertyNode *n = _cache->getNode("fg-root", true);
250       n->setStringValue(globals->get_fg_root().c_str());
251       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
252       n = _cache->getNode("fg-aircraft", true);
253       n->setStringValue(getAircraftPaths().c_str());
254       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
255       _cache->removeChildren("aircraft");
256   
257       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
258     }
259     
260     if (_foundPath.str().empty()) {
261       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
262       return false;
263     }
264     
265     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
266     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
267     if (!_foundPath.exists()) {
268       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
269       return false;
270     }
271     
272     try {
273       readProperties(_foundPath.str(), globals->get_props());
274     } catch ( const sg_exception &e ) {
275       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
276       return false;
277     }
278     
279     return true;
280   }
281   
282 private:
283   SGPath getAircraftPaths() {
284     string_list pathList = globals->get_aircraft_paths();
285     SGPath aircraftPaths;
286     string_list::const_iterator it = pathList.begin();
287     if (it != pathList.end()) {
288         aircraftPaths.set(*it);
289         it++;
290     }
291     for (; it != pathList.end(); ++it) {
292         aircraftPaths.add(*it);
293     }
294     return aircraftPaths;
295   }
296   
297   bool checkCache()
298   {
299     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
300       return false; // cache mismatch
301     }
302
303     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
304       return false; // cache mismatch
305     }
306     
307     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
308     for (unsigned int i = 0; i < cache.size(); i++) {
309       const char *name = cache[i]->getStringValue("file", "");
310       if (!boost::equals(_searchAircraft, name, is_iequal())) {
311         continue;
312       }
313       
314       SGPath xml(cache[i]->getStringValue("path", ""));
315       xml.append(name);
316       if (xml.exists()) {
317         _foundPath = xml;
318         return true;
319       } 
320       
321       return false;
322     } // of aircraft in cache iteration
323     
324     return false;
325   }
326   
327   bool checkAircraft(const SGPath& p)
328   {
329     // create cache node
330     int i = 0;
331     while (1) {
332         if (!_cache->getChild("aircraft", i++, false))
333             break;
334     }
335     
336     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
337
338     std::string fileName(p.file());
339     n = entry->getNode("file", true);
340     n->setStringValue(fileName);
341     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
342
343     n = entry->getNode("path", true);
344     n->setStringValue(p.dir());
345     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
346
347     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
348         _foundPath = p;
349         return true;
350     }
351
352     return false;
353   }
354   
355   std::string _searchAircraft;
356   SGPath _foundPath;
357   SGPropertyNode* _cache;
358 };
359
360 #ifdef _WIN32
361 static SGPath platformDefaultDataPath()
362 {
363   char *envp = ::getenv( "APPDATA" );
364   SGPath config( envp );
365   config.append( "flightgear.org" );
366   return config;
367 }
368 #elif __APPLE__
369
370 #include <CoreServices/CoreServices.h>
371
372 static SGPath platformDefaultDataPath()
373 {
374   FSRef ref;
375   OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
376   if (err) {
377     return SGPath();
378   }
379   
380   unsigned char path[1024];
381   if (FSRefMakePath(&ref, path, 1024) != noErr) {
382     return SGPath();
383   }
384   
385   SGPath appData;
386   appData.set((const char*) path);
387   appData.append("FlightGear");
388   return appData;
389 }
390 #else
391 static SGPath platformDefaultDataPath()
392 {
393   SGPath config( getenv("HOME") );
394   config.append( ".fgfs" );
395   return config;
396 }
397 #endif
398
399 void fgInitHome()
400 {
401     SGPath dataPath = platformDefaultDataPath();
402     const char *fg_home = getenv("FG_HOME");
403     if (fg_home)
404         dataPath = fg_home;
405     
406     globals->set_fg_home(dataPath.c_str());
407 }
408
409 // Read in configuration (file and command line)
410 bool fgInitConfig ( int argc, char **argv )
411 {
412     SGPath dataPath = globals->get_fg_home();
413     simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
414     if (!exportDir.exists()) {
415       exportDir.create(0777);
416     }
417     
418     // Set /sim/fg-home and don't allow malign code to override it until
419     // Nasal security is set up.  Use FG_HOME if necessary.
420     SGPropertyNode *home = fgGetNode("/sim", true);
421     home->removeChild("fg-home", 0, false);
422     home = home->getChild("fg-home", 0, true);
423     home->setStringValue(dataPath.c_str());
424     home->setAttribute(SGPropertyNode::WRITE, false);
425   
426     flightgear::Options* options = flightgear::Options::sharedInstance();
427     options->init(argc, argv, dataPath);
428     bool loadDefaults = flightgear::Options::sharedInstance()->shouldLoadDefaultConfig();
429     if (loadDefaults) {
430       // Read global preferences from $FG_ROOT/preferences.xml
431       SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
432       fgLoadProps("preferences.xml", globals->get_props());
433       SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
434
435       // do not load user settings when reset to default is requested
436       if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
437       {
438           SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
439       }
440       else
441       {
442           globals->loadUserSettings(dataPath);
443       }
444     } else {
445       SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
446     }// of no-default-config selected
447   
448     // Scan user config files and command line for a specified aircraft.
449     options->initAircraft();
450
451     FindAndCacheAircraft f(globals->get_props());
452     if (!f.loadAircraft()) {
453       return false;
454     }
455
456     // parse options after loading aircraft to ensure any user
457     // overrides of defaults are honored.
458     options->processOptions();
459       
460     return true;
461 }
462
463
464
465 /**
466  * Initialize vor/ndb/ils/fix list management and query systems (as
467  * well as simple airport db list)
468  * This is called multiple times in the case of a cache rebuild,
469  * to allow length caching to take place in the background, without
470  * blocking the main/UI thread.
471  */
472 bool
473 fgInitNav ()
474 {
475   flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
476   static bool doingRebuild = false;
477   if (doingRebuild || cache->isRebuildRequired()) {
478     doingRebuild = true;
479     bool finished = cache->rebuild();
480     if (!finished) {
481       // sleep to give the rebuild thread more time
482       SGTimeStamp::sleepForMSec(50);
483       return false;
484     }
485   }
486   
487   FGTACANList *channellist = new FGTACANList;
488   globals->set_channellist( channellist );
489   
490   SGPath path(globals->get_fg_root());
491   path.append( "Navaids/TACAN_freq.dat" );
492   flightgear::loadTacan(path, channellist);
493   
494   return true;
495 }
496
497 // General house keeping initializations
498 bool fgInitGeneral() {
499     string root;
500
501     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
502     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
503
504     root = globals->get_fg_root();
505     if ( ! root.length() ) {
506         // No root path set? Then bail ...
507         SG_LOG( SG_GENERAL, SG_ALERT,
508                 "Cannot continue without a path to the base package "
509                 << "being defined." );
510         exit(-1);
511     }
512     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
513
514     // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
515     globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
516     fgSetString("/sim/startup/browser-app", globals->get_browser());
517
518     simgear::Dir cwd(simgear::Dir::current());
519     SGPropertyNode *curr = fgGetNode("/sim", true);
520     curr->removeChild("fg-current", 0, false);
521     curr = curr->getChild("fg-current", 0, true);
522     curr->setStringValue(cwd.path().str());
523     curr->setAttribute(SGPropertyNode::WRITE, false);
524
525     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
526     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
527     return true;
528 }
529
530 // Write various configuraton values out to the logs
531 void fgOutputSettings()
532 {    
533     SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
534     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
535     
536     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
537     SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
538     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
539     
540     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
541     SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
542 }
543
544 // This is the top level init routine which calls all the other
545 // initialization routines.  If you are adding a subsystem to flight
546 // gear, its initialization call should located in this routine.
547 // Returns non-zero if a problem encountered.
548 void fgCreateSubsystems() {
549
550     SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
551     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
552
553     ////////////////////////////////////////////////////////////////////
554     // Initialize the sound subsystem.
555     ////////////////////////////////////////////////////////////////////
556     // Sound manager uses an own subsystem group "SOUND" which is the last
557     // to be updated in every loop.
558     // Sound manager is updated last so it can use the CPU while the GPU
559     // is processing the scenery (doubled the frame-rate for me) -EMH-
560     globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
561
562     ////////////////////////////////////////////////////////////////////
563     // Initialize the event manager subsystem.
564     ////////////////////////////////////////////////////////////////////
565
566     globals->get_event_mgr()->init();
567     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
568
569     ////////////////////////////////////////////////////////////////////
570     // Initialize the property interpolator subsystem. Put into the INIT
571     // group because the "nasal" subsystem may need it at GENERAL take-down.
572     ////////////////////////////////////////////////////////////////////
573     globals->add_subsystem( "prop-interpolator",
574                             new FGInterpolator,
575                             SGSubsystemMgr::INIT );
576
577
578     ////////////////////////////////////////////////////////////////////
579     // Add the FlightGear property utilities.
580     ////////////////////////////////////////////////////////////////////
581     globals->add_subsystem("properties", new FGProperties);
582
583
584     ////////////////////////////////////////////////////////////////////
585     // Add the performance monitoring system.
586     ////////////////////////////////////////////////////////////////////
587     globals->add_subsystem("performance-mon",
588             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
589                                      fgGetNode("/sim/performance-monitor", true)));
590
591     ////////////////////////////////////////////////////////////////////
592     // Initialize the material property subsystem.
593     ////////////////////////////////////////////////////////////////////
594
595     SGPath mpath( globals->get_fg_root() );
596     mpath.append( fgGetString("/sim/rendering/materials-file") );
597     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
598             globals->get_props()) ) {
599         SG_LOG( SG_GENERAL, SG_ALERT,
600                 "Error loading materials file " << mpath.str() );
601         exit(-1);
602     }
603
604     globals->add_subsystem( "http", new FGHTTPClient );
605     
606     ////////////////////////////////////////////////////////////////////
607     // Initialize the scenery management subsystem.
608     ////////////////////////////////////////////////////////////////////
609
610     globals->get_scenery()->get_scene_graph()
611         ->addChild(simgear::Particles::getCommonRoot());
612     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
613
614     ////////////////////////////////////////////////////////////////////
615     // Initialize the flight model subsystem.
616     ////////////////////////////////////////////////////////////////////
617
618     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
619
620     ////////////////////////////////////////////////////////////////////
621     // Initialize the weather subsystem.
622     ////////////////////////////////////////////////////////////////////
623
624     // Initialize the weather modeling subsystem
625     globals->add_subsystem("environment", new FGEnvironmentMgr);
626     globals->add_subsystem("ephemeris", new Ephemeris);
627     
628     ////////////////////////////////////////////////////////////////////
629     // Initialize the aircraft systems and instrumentation (before the
630     // autopilot.)
631     ////////////////////////////////////////////////////////////////////
632
633     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
634     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
635     globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
636     globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
637   
638     ////////////////////////////////////////////////////////////////////
639     // Initialize the XML Autopilot subsystem.
640     ////////////////////////////////////////////////////////////////////
641
642     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
643     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
644     globals->add_subsystem( "route-manager", new FGRouteMgr );
645
646     ////////////////////////////////////////////////////////////////////
647     // Initialize the Input-Output subsystem
648     ////////////////////////////////////////////////////////////////////
649     globals->add_subsystem( "io", new FGIO );
650   
651     ////////////////////////////////////////////////////////////////////
652     // Create and register the logger.
653     ////////////////////////////////////////////////////////////////////
654     
655     globals->add_subsystem("logger", new FGLogger);
656
657     ////////////////////////////////////////////////////////////////////
658     // Create and register the XML GUI.
659     ////////////////////////////////////////////////////////////////////
660
661     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
662
663     //////////////////////////////////////////////////////////////////////
664     // Initialize the 2D cloud subsystem.
665     ////////////////////////////////////////////////////////////////////
666     fgGetBool("/sim/rendering/bump-mapping", false);
667
668     ////////////////////////////////////////////////////////////////////
669     // Initialize the canvas 2d drawing subsystem.
670     ////////////////////////////////////////////////////////////////////
671     globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
672     globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
673
674     ////////////////////////////////////////////////////////////////////
675     // Initialise the ATIS Manager
676     // Note that this is old stuff, but is necessary for the
677     // current ATIS implementation. Therefore, leave it in here
678     // until the ATIS system is ported over to make use of the ATIS 
679     // sub system infrastructure.
680     ////////////////////////////////////////////////////////////////////
681
682     globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
683
684     ////////////////////////////////////////////////////////////////////
685    // Initialize the ATC subsystem
686     ////////////////////////////////////////////////////////////////////
687     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
688
689     ////////////////////////////////////////////////////////////////////
690     // Initialize multiplayer subsystem
691     ////////////////////////////////////////////////////////////////////
692
693     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
694
695     ////////////////////////////////////////////////////////////////////
696     // Initialise the AI Model Manager
697     ////////////////////////////////////////////////////////////////////
698     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
699     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
700     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
701
702
703     // It's probably a good idea to initialize the top level traffic manager
704     // After the AI and ATC systems have been initialized properly.
705     // AI Traffic manager
706     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
707
708     ////////////////////////////////////////////////////////////////////
709     // Add a new 2D panel.
710     ////////////////////////////////////////////////////////////////////
711
712     fgSetArchivable("/sim/panel/visibility");
713     fgSetArchivable("/sim/panel/x-offset");
714     fgSetArchivable("/sim/panel/y-offset");
715     fgSetArchivable("/sim/panel/jitter");
716   
717     ////////////////////////////////////////////////////////////////////
718     // Initialize the controls subsystem.
719     ////////////////////////////////////////////////////////////////////
720     
721     globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
722
723     ////////////////////////////////////////////////////////////////////
724     // Initialize the input subsystem.
725     ////////////////////////////////////////////////////////////////////
726
727     globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
728
729
730     ////////////////////////////////////////////////////////////////////
731     // Initialize the replay subsystem
732     ////////////////////////////////////////////////////////////////////
733     globals->add_subsystem("replay", new FGReplay);
734     globals->add_subsystem("history", new FGFlightHistory);
735     
736 #ifdef ENABLE_AUDIO_SUPPORT
737     ////////////////////////////////////////////////////////////////////
738     // Initialize the sound-effects subsystem.
739     ////////////////////////////////////////////////////////////////////
740     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
741 #endif
742
743     ////////////////////////////////////////////////////////////////////
744     // Initialize the lighting subsystem.
745     ////////////////////////////////////////////////////////////////////
746
747     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
748     
749     // ordering here is important : Nasal (via events), then models, then views
750     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
751
752     globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
753     globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
754
755     globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
756
757     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
758       SGSubsystemMgr::DISPLAY);
759 }
760
761 void fgPostInitSubsystems()
762 {
763     SGTimeStamp st;
764     st.stamp();
765   
766     ////////////////////////////////////////////////////////////////////////
767     // Initialize the Nasal interpreter.
768     // Do this last, so that the loaded scripts see initialized state
769     ////////////////////////////////////////////////////////////////////////
770     FGNasalSys* nasal = new FGNasalSys();
771     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
772     nasal->init();
773     SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
774   
775     // initialize methods that depend on other subsystems.
776     st.stamp();
777     globals->get_subsystem_mgr()->postinit();
778     SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
779   
780     ////////////////////////////////////////////////////////////////////////
781     // End of subsystem initialization.
782     ////////////////////////////////////////////////////////////////////
783
784     fgSetBool("/sim/crashed", false);
785     fgSetBool("/sim/initialized", true);
786
787     SG_LOG( SG_GENERAL, SG_INFO, endl);
788
789                                 // Save the initial state for future
790                                 // reference.
791     globals->saveInitialState();
792 }
793
794 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
795 void fgReInitSubsystems()
796 {
797     SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
798
799     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
800
801 // setup state to begin re-init
802     bool freeze = master_freeze->getBoolValue();
803     if ( !freeze ) {
804         master_freeze->setBoolValue(true);
805     }
806     
807     fgSetBool("/sim/signals/reinit", true);
808     fgSetBool("/sim/crashed", false);
809
810 // do actual re-init steps
811     globals->get_subsystem("flight")->unbind();
812     
813   // reset control state, before restoring initial state; -set or config files
814   // may specify values for flaps, trim tabs, magnetos, etc
815     globals->get_controls()->reset_all();
816         
817     globals->restoreInitialState();
818
819     // update our position based on current presets
820     // this will mark position as needed finalized which we'll do in the
821     // main-loop
822     flightgear::initPosition();
823     
824     // Force reupdating the positions of the ai 3d models. They are used for
825     // initializing ground level for the FDM.
826     globals->get_subsystem("ai-model")->reinit();
827
828     // Initialize the FDM
829     globals->get_subsystem("flight")->reinit();
830
831     // reset replay buffers
832     globals->get_subsystem("replay")->reinit();
833     
834     // reload offsets from config defaults
835     globals->get_viewmgr()->reinit();
836
837     // ugly: finalizePosition waits for METAR to arrive for the new airport.
838     // we don't re-init the environment manager here, since historically we did
839     // not, and doing so seems to have other issues. All that's needed is to
840     // schedule METAR fetch immediately, so it's available for finalizePosition.
841     // So we manually extract the METAR-fetching component inside the environment
842     // manager, and re-init that.
843     SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
844     if (envMgr) {
845       envMgr->get_subsystem("realwx")->reinit();
846     }
847   
848     globals->get_subsystem("time")->reinit();
849
850     // need to bind FDMshell again, since we manually unbound it above...
851     globals->get_subsystem("flight")->bind();
852
853     // need to reset aircraft (systems/instruments) so they can adapt to current environment
854     globals->get_subsystem("systems")->reinit();
855     globals->get_subsystem("instrumentation")->reinit();
856
857     globals->get_subsystem("ATIS")->reinit();
858
859 // setup state to end re-init
860     fgSetBool("/sim/signals/reinit", false);
861     if ( !freeze ) {
862         master_freeze->setBoolValue(false);
863     }
864     fgSetBool("/sim/sceneryloaded",false);
865 }
866
867
868 ///////////////////////////////////////////////////////////////////////////////
869 // helper object to implement the --show-aircraft command.
870 // resides here so we can share the fgFindAircraftInDir template above,
871 // and hence ensure this command lists exectly the same aircraft as the normal
872 // loading path.
873 class ShowAircraft 
874 {
875 public:
876   ShowAircraft()
877   {
878     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
879   }
880   
881   
882   void show(const SGPath& path)
883   {
884     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
885   
886     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
887     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
888     cout << "Available aircraft:" << endl;
889     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
890         cout << _aircraft[i] << endl;
891     }
892   }
893   
894 private:
895   bool processAircraft(const SGPath& path)
896   {
897     SGPropertyNode root;
898     try {
899        readProperties(path.str(), &root);
900     } catch (sg_exception& ) {
901        return false;
902     }
903   
904     int maturity = 0;
905     string descStr("   ");
906     descStr += path.file();
907   // trim common suffix from file names
908     int nPos = descStr.rfind("-set.xml");
909     if (nPos == (int)(descStr.size() - 8)) {
910       descStr.resize(nPos);
911     }
912     
913     SGPropertyNode *node = root.getNode("sim");
914     if (node) {
915       SGPropertyNode* desc = node->getNode("description");
916       // if a status tag is found, read it in
917       if (node->hasValue("status")) {
918         maturity = getNumMaturity(node->getStringValue("status"));
919       }
920       
921       if (desc) {
922         if (descStr.size() <= 27+3) {
923           descStr.append(29+3-descStr.size(), ' ');
924         } else {
925           descStr += '\n';
926           descStr.append( 32, ' ');
927         }
928         descStr += desc->getStringValue();
929       }
930     } // of have 'sim' node
931     
932     if (maturity < _minStatus) {
933       return false;
934     }
935
936     _aircraft.push_back(descStr);
937     return false;
938   }
939
940
941   int getNumMaturity(const char * str) 
942   {
943     // changes should also be reflected in $FG_ROOT/data/options.xml & 
944     // $FG_ROOT/data/Translations/string-default.xml
945     const char* levels[] = {"alpha","beta","early-production","production"}; 
946
947     if (!strcmp(str, "all")) {
948       return 0;
949     }
950
951     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
952       if (strcmp(str,levels[i])==0)
953         return i;
954
955     return 0;
956   }
957
958   // recommended in Meyers, Effective STL when internationalization and embedded
959   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
960   struct ciLessLibC : public std::binary_function<string, string, bool>
961   {
962     bool operator()(const std::string &lhs, const std::string &rhs) const
963     {
964       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
965     }
966   };
967
968   int _minStatus;
969   string_list _aircraft;
970 };
971
972 void fgShowAircraft(const SGPath &path)
973 {
974     ShowAircraft s;
975     s.show(path);
976         
977 #ifdef _MSC_VER
978     cout << "Hit a key to continue..." << endl;
979     std::cin.get();
980 #endif
981 }
982
983