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