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