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