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