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