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