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