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