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