]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
8d01e88e66fd7588044e0be827eead47eaf0deb8
[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 #if defined( unix ) || defined( __CYGWIN__ )
33 #  include <unistd.h>           // for gethostname()
34 #endif
35 #ifdef _WIN32
36 #  include <direct.h>           // for getcwd()
37 #  define getcwd _getcwd
38 #  include <io.h>               // isatty()
39 #  define isatty _isatty
40 #  include "winsock2.h"         // for gethostname()
41 #endif
42
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
45 #ifdef linux
46 #  define _G_NO_EXTERN_TEMPLATES
47 #endif
48
49 #include <simgear/compiler.h>
50
51 #include <string>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
54
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/structure/SGPerfMon.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/sg_dir.hxx>
62 #include <simgear/misc/sgstream.hxx>
63 #include <simgear/misc/strutils.hxx>
64 #include <simgear/props/props_io.hxx>
65
66 #include <simgear/misc/interpolator.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/particles.hxx>
69 #include <simgear/sound/soundmgr_openal.hxx>
70
71 #include <Aircraft/controls.hxx>
72 #include <Aircraft/replay.hxx>
73 #include <Airports/apt_loader.hxx>
74 #include <Airports/runways.hxx>
75 #include <Airports/simple.hxx>
76 #include <Airports/dynamics.hxx>
77
78 #include <AIModel/AIManager.hxx>
79
80 #include <ATCDCL/ATCmgr.hxx>
81 #include <ATC/atc_mgr.hxx>
82
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
85
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
88
89 #include <GUI/new_gui.hxx>
90 #include <Input/input.hxx>
91 #include <Instrumentation/instrument_mgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Model/modelmgr.hxx>
94 #include <AIModel/submodel.hxx>
95 #include <AIModel/AIManager.hxx>
96 #include <Navaids/navdb.hxx>
97 #include <Navaids/navlist.hxx>
98 #include <Navaids/fix.hxx>
99 #include <Navaids/fixlist.hxx>
100 #include <Navaids/airways.hxx>
101 #include <Scenery/scenery.hxx>
102 #include <Scenery/tilemgr.hxx>
103 #include <Scripting/NasalSys.hxx>
104 #include <Sound/voice.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Traffic/TrafficMgr.hxx>
108 #include <MultiPlayer/multiplaymgr.hxx>
109 #include <FDM/fdm_shell.hxx>
110 #include <Environment/ephemeris.hxx>
111 #include <Environment/environment_mgr.hxx>
112
113 #include "fg_init.hxx"
114 #include "fg_io.hxx"
115 #include "fg_commands.hxx"
116 #include "fg_props.hxx"
117 #include "options.hxx"
118 #include "globals.hxx"
119 #include "logger.hxx"
120 #include "renderer.hxx"
121 #include "viewmgr.hxx"
122 #include "main.hxx"
123
124
125 using std::string;
126 using namespace boost::algorithm;
127
128
129 // Return the current base package version
130 string fgBasePackageVersion() {
131     SGPath base_path( globals->get_fg_root() );
132     base_path.append("version");
133
134     sg_gzifstream in( base_path.str() );
135     if ( !in.is_open() ) {
136         SGPath old_path( globals->get_fg_root() );
137         old_path.append( "Thanks" );
138         sg_gzifstream old( old_path.str() );
139         if ( !old.is_open() ) {
140             return "[none]";
141         } else {
142             return "[old version]";
143         }
144     }
145
146     string version;
147     in >> version;
148
149     return version;
150 }
151
152
153 // Initialize the localization
154 SGPropertyNode *fgInitLocale(const char *language) {
155    SGPropertyNode *c_node = NULL, *d_node = NULL;
156    SGPropertyNode *intl = fgGetNode("/sim/intl");
157
158    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
159
160    // localization not defined
161    if (!intl)
162       return NULL;
163
164    //
165    // Select the proper language from the list
166    //
167    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
168    for (unsigned int i = 0; i < locale.size(); i++) {
169
170       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
171       for (unsigned int j = 0; j < lang.size(); j++) {
172
173          if (!strcmp(lang[j]->getStringValue(), language)) {
174             c_node = locale[i];
175             break;
176          }
177       }
178    }
179
180
181    // Get the defaults
182    d_node = intl->getChild("locale");
183    if (!c_node)
184       c_node = d_node;
185
186    // Check for localized font
187    SGPropertyNode *font_n = c_node->getNode("font", true);
188    if ( !strcmp(font_n->getStringValue(), "") )
189       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
190
191
192    //
193    // Load the default strings
194    //
195    SGPath d_path( globals->get_fg_root() );
196
197    const char *d_path_str = d_node->getStringValue("strings");
198    if (!d_path_str) {
199       SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
200       return NULL;
201    }
202
203    d_path.append(d_path_str);
204    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
205
206    SGPropertyNode *strings = c_node->getNode("strings");
207    try {
208       readProperties(d_path.str(), strings);
209    } catch (const sg_exception &) {
210       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
211       return NULL;
212    }
213
214    //
215    // Load the language specific strings
216    //
217    if (c_node != d_node) {
218       SGPath c_path( globals->get_fg_root() );
219
220       const char *c_path_str = c_node->getStringValue("strings");
221       if (!c_path_str) {
222          SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
223          return NULL;
224       }
225
226       c_path.append(c_path_str);
227       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
228
229       try {
230          readProperties(c_path.str(), strings);
231       } catch (const sg_exception &) {
232          SG_LOG(SG_GENERAL, SG_ALERT,
233                  "Unable to read the localized strings from " << c_path.str());
234          return NULL;
235       }
236    }
237
238    return c_node;
239 }
240
241
242
243 // Initialize the localization routines
244 bool fgDetectLanguage() {
245     const char *language = ::getenv("LANG");
246
247     if (language == NULL) {
248         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
249         language = "C";
250     }
251
252     SGPropertyNode *locale = fgInitLocale(language);
253     if (!locale) {
254        SG_LOG(SG_GENERAL, SG_ALERT,
255               "No internationalization settings specified in preferences.xml" );
256
257        return false;
258     }
259
260     globals->set_locale( locale );
261
262     return true;
263 }
264
265 template <class T>
266 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
267 {
268   if (!dirPath.exists()) {
269     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
270     return false;
271   }
272     
273   bool recurse = true;
274   simgear::Dir dir(dirPath);
275   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
276   simgear::PathList::iterator p;
277   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
278     // check file name ends with -set.xml
279     
280     // if we found a -set.xml at this level, don't recurse any deeper
281     recurse = false;
282     
283     bool done = (obj->*pred)(*p);
284     if (done) {
285       return true;
286     }
287   } // of -set.xml iteration
288   
289   if (!recurse) {
290     return false;
291   }
292   
293   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
294   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
295     if (p->file() == "CVS") {
296       continue;
297     }
298     
299     if (fgFindAircraftInDir(*p, obj, pred)) {
300       return true;
301     }
302   } // of subdirs iteration
303   
304   return false;
305 }
306
307 template <class T>
308 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
309 {
310   const string_list& paths(globals->get_aircraft_paths());
311   string_list::const_iterator it = paths.begin();
312   for (; it != paths.end(); ++it) {
313     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
314     if (done) {
315       return;
316     }
317   } // of aircraft paths iteration
318   
319   // if we reach this point, search the default location (always last)
320   SGPath rootAircraft(globals->get_fg_root());
321   rootAircraft.append("Aircraft");
322   fgFindAircraftInDir(rootAircraft, obj, pred);
323 }
324
325 class FindAndCacheAircraft
326 {
327 public:
328   FindAndCacheAircraft(SGPropertyNode* autoSave)
329   {
330     _cache = autoSave->getNode("sim/startup/path-cache", true);
331   }
332   
333   bool loadAircraft()
334   {
335     std::string aircraft = fgGetString( "/sim/aircraft", "");
336     if (aircraft.empty()) {
337       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
338       return false;
339     }
340     
341     _searchAircraft = aircraft + "-set.xml";
342     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
343     if (!aircraftDir.empty()) {
344       // aircraft-dir was set, skip any searching at all, if it's valid
345       simgear::Dir acPath(aircraftDir);
346       SGPath setFile = acPath.file(_searchAircraft);
347       if (setFile.exists()) {
348         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
349         
350         try {
351           readProperties(setFile.str(), globals->get_props());
352         } catch ( const sg_exception &e ) {
353           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
354           return false;
355         }
356         
357         return true;
358       } else {
359         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
360                "' not found in specified dir:" << aircraftDir);
361         return false;
362       }
363     }
364     
365     if (!checkCache()) {
366       // prepare cache for re-scan
367       SGPropertyNode *n = _cache->getNode("fg-root", true);
368       n->setStringValue(globals->get_fg_root().c_str());
369       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
370       n = _cache->getNode("fg-aircraft", true);
371       n->setStringValue(getAircraftPaths().c_str());
372       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
373       _cache->removeChildren("aircraft");
374   
375       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
376     }
377     
378     if (_foundPath.str().empty()) {
379       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
380       return false;
381     }
382     
383     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
384     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
385     if (!_foundPath.exists()) {
386       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
387       return false;
388     }
389     
390     try {
391       readProperties(_foundPath.str(), globals->get_props());
392     } catch ( const sg_exception &e ) {
393       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
394       return false;
395     }
396     
397     return true;
398   }
399   
400 private:
401   SGPath getAircraftPaths() {
402     string_list pathList = globals->get_aircraft_paths();
403     SGPath aircraftPaths;
404     string_list::const_iterator it = pathList.begin();
405     if (it != pathList.end()) {
406         aircraftPaths.set(*it);
407         it++;
408     }
409     for (; it != pathList.end(); ++it) {
410         aircraftPaths.add(*it);
411     }
412     return aircraftPaths;
413   }
414   
415   bool checkCache()
416   {
417     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
418       return false; // cache mismatch
419     }
420
421     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
422       return false; // cache mismatch
423     }
424     
425     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
426     for (unsigned int i = 0; i < cache.size(); i++) {
427       const char *name = cache[i]->getStringValue("file", "");
428       if (!boost::equals(_searchAircraft, name, is_iequal())) {
429         continue;
430       }
431       
432       SGPath xml(cache[i]->getStringValue("path", ""));
433       xml.append(name);
434       if (xml.exists()) {
435         _foundPath = xml;
436         return true;
437       } 
438       
439       return false;
440     } // of aircraft in cache iteration
441     
442     return false;
443   }
444   
445   bool checkAircraft(const SGPath& p)
446   {
447     // create cache node
448     int i = 0;
449     while (1) {
450         if (!_cache->getChild("aircraft", i++, false))
451             break;
452     }
453     
454     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
455
456     std::string fileName(p.file());
457     n = entry->getNode("file", true);
458     n->setStringValue(fileName);
459     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
460
461     n = entry->getNode("path", true);
462     n->setStringValue(p.dir());
463     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
464
465     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
466         _foundPath = p;
467         return true;
468     }
469
470     return false;
471   }
472   
473   std::string _searchAircraft;
474   SGPath _foundPath;
475   SGPropertyNode* _cache;
476 };
477
478 #ifdef _WIN32
479 static SGPath platformDefaultDataPath()
480 {
481   char *envp = ::getenv( "APPDATA" );
482   SGPath config( envp );
483   config.append( "flightgear.org" );
484   return config;
485 }
486 #elif __APPLE__
487
488 #include <CoreServices/CoreServices.h>
489
490 static SGPath platformDefaultDataPath()
491 {
492   FSRef ref;
493   OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
494   if (err) {
495     return SGPath();
496   }
497   
498   unsigned char path[1024];
499   if (FSRefMakePath(&ref, path, 1024) != noErr) {
500     return SGPath();
501   }
502   
503   SGPath appData;
504   appData.set((const char*) path);
505   appData.append("flightgear.org");
506   return appData;
507 }
508 #else
509 static SGPath platformDefaultDataPath()
510 {
511   SGPath config( homedir );
512   config.append( ".fgfs" );
513   return config;
514 }
515 #endif
516
517 // Read in configuration (file and command line)
518 bool fgInitConfig ( int argc, char **argv )
519 {
520     SGPath dataPath = platformDefaultDataPath();
521     
522     const char *fg_home = getenv("FG_HOME");
523     if (fg_home)
524       dataPath = fg_home;
525     
526     simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
527     if (!exportDir.exists()) {
528       exportDir.create(0777);
529     }
530     
531     // Set /sim/fg-home and don't allow malign code to override it until
532     // Nasal security is set up.  Use FG_HOME if necessary.
533     SGPropertyNode *home = fgGetNode("/sim", true);
534     home->removeChild("fg-home", 0, false);
535     home = home->getChild("fg-home", 0, true);
536     home->setStringValue(dataPath.c_str());
537     home->setAttribute(SGPropertyNode::WRITE, false);
538   
539     flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
540   
541     // Read global preferences from $FG_ROOT/preferences.xml
542     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
543     fgLoadProps("preferences.xml", globals->get_props());
544     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
545
546     // Detect the required language as early as possible
547     if ( !fgDetectLanguage() ) {
548         return false;
549     }
550
551     SGPropertyNode autosave;
552
553
554     SGPath autosaveFile = simgear::Dir(dataPath).file("autosave.xml");
555     if (autosaveFile.exists()) {
556       SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
557       try {
558           readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
559       } catch (sg_exception& e) {
560           SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
561             << "(from " << e.getOrigin() << ")");
562       }
563     }
564   
565   // Scan user config files and command line for a specified aircraft.
566     flightgear::Options::sharedInstance()->initAircraft();
567       
568     FindAndCacheAircraft f(&autosave);
569     if (!f.loadAircraft()) {
570       return false;
571     }
572
573     copyProperties(&autosave, globals->get_props());
574
575     // parse options after loading aircraft to ensure any user
576     // overrides of defaults are honored.
577     flightgear::Options::sharedInstance()->processOptions();
578       
579     return true;
580 }
581
582 // Set current tower position lon/lat given an airport id
583 static bool fgSetTowerPosFromAirportID( const string& id) {
584     const FGAirport *a = fgFindAirportID( id);
585     if (a) {
586         SGGeod tower = a->getTowerLocation();
587         fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
588         fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
589         fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
590         return true;
591     } else {
592         return false;
593     }
594
595 }
596
597 struct FGTowerLocationListener : SGPropertyChangeListener {
598     void valueChanged(SGPropertyNode* node) {
599         string id(node->getStringValue());
600         if (fgGetBool("/sim/tower/auto-position",true))
601         {
602             // enforce using closest airport when auto-positioning is enabled 
603             const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
604             if (closest_airport && (id != closest_airport))
605             {
606                 id = closest_airport;
607                 node->setStringValue(id);
608             }
609         }
610         fgSetTowerPosFromAirportID(id);
611     }
612 };
613
614 struct FGClosestTowerLocationListener : SGPropertyChangeListener
615 {
616     void valueChanged(SGPropertyNode* )
617     {
618         // closest airport has changed
619         if (fgGetBool("/sim/tower/auto-position",true))
620         {
621             // update tower position
622             const char* id = fgGetString("/sim/airport/closest-airport-id", "");
623             if (id && *id!=0)
624                 fgSetString("/sim/tower/airport-id", id);
625         }
626     }
627 };
628
629 void fgInitTowerLocationListener() {
630     fgGetNode("/sim/tower/airport-id",  true)
631         ->addChangeListener( new FGTowerLocationListener(), true );
632     FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
633     fgGetNode("/sim/airport/closest-airport-id", true)
634         ->addChangeListener(ntcl , true );
635     fgGetNode("/sim/tower/auto-position", true)
636            ->addChangeListener(ntcl, true );
637 }
638
639 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
640 {
641   SGGeod startPos(aStartPos);
642   if (aTargetHeading == HUGE_VAL) {
643     aTargetHeading = aHeading;
644   }
645   
646   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
647     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
648     offsetDistance *= SG_NM_TO_METER;
649     double offsetAzimuth = aHeading;
650     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
651       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
652       aHeading = aTargetHeading;
653     }
654
655     SGGeod offset;
656     double az2; // dummy
657     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
658     startPos = offset;
659   }
660
661   // presets
662   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
663   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
664   fgSetDouble("/sim/presets/heading-deg", aHeading );
665
666   // other code depends on the actual values being set ...
667   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
668   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
669   fgSetDouble("/orientation/heading-deg", aHeading );
670 }
671
672 // Set current_options lon/lat given an airport id and heading (degrees)
673 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
674     if ( id.empty() )
675         return false;
676
677     // set initial position from runway and heading
678     SG_LOG( SG_GENERAL, SG_INFO,
679             "Attempting to set starting position from airport code "
680             << id << " heading " << tgt_hdg );
681
682     const FGAirport* apt = fgFindAirportID(id);
683     if (!apt) return false;
684     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
685     fgSetString("/sim/atc/runway", r->ident().c_str());
686
687     SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
688           fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
689     return true;
690 }
691
692 // Set current_options lon/lat given an airport id and parkig position name
693 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
694     if ( id.empty() )
695         return false;
696
697     // can't see an easy way around this const_cast at the moment
698     FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
699     if (!apt) {
700         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
701         return false;
702     }
703     FGAirportDynamics* dcs = apt->getDynamics();
704     if (!dcs) {
705         SG_LOG( SG_GENERAL, SG_ALERT,
706                 "Airport " << id << "does not appear to have parking information available");
707         return false;
708     }
709     
710     int park_index = dcs->getNrOfParkings() - 1;
711     bool succes;
712     double radius = fgGetDouble("/sim/dimensions/radius-m");
713     if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
714         double lat, lon, heading;
715         string fltType;
716         string acOperator;
717         SGPath acData;
718         try {
719             acData = fgGetString("/sim/fg-home");
720             acData.append("aircraft-data");
721             string acfile = fgGetString("/sim/aircraft") + string(".xml");
722             acData.append(acfile);
723             SGPropertyNode root;
724             readProperties(acData.str(), &root);
725             SGPropertyNode * node = root.getNode("sim");
726             fltType    = node->getStringValue("aircraft-class", "NONE"     );
727             acOperator = node->getStringValue("aircraft-operator", "NONE"     );
728         } catch (const sg_exception &) {
729             SG_LOG(SG_GENERAL, SG_INFO,
730                 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
731
732        // cout << path.str() << endl;
733         }
734         if (fltType.empty() || fltType == "NONE") {
735             SG_LOG(SG_GENERAL, SG_INFO,
736                 "Aircraft type information not found in: " << acData.str() << ". Using default value");
737                 fltType = fgGetString("/sim/aircraft-class"   );
738         }
739         if (acOperator.empty() || fltType == "NONE") {
740             SG_LOG(SG_GENERAL, SG_INFO,
741                 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
742                 acOperator = fgGetString("/sim/aircraft-operator"   );
743         }
744
745         cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
746         string acType; // Currently not used by findAvailable parking, so safe to leave empty. 
747         succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
748         if (succes) {
749             fgGetString("/sim/presets/parkpos");
750             fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
751         } else {
752             SG_LOG( SG_GENERAL, SG_ALERT,
753                     "Failed to find a suitable parking at airport " << id );
754             return false;
755         }
756     } else {
757         //cerr << "We shouldn't get here when AVAILABLE" << endl;
758         while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
759         if (park_index < 0) {
760             SG_LOG( SG_GENERAL, SG_ALERT,
761                     "Failed to find parking position " << parkpos <<
762                     " at airport " << id );
763             return false;
764         }
765     }
766     FGParking* parking = dcs->getParking(park_index);
767     parking->setAvailable(false);
768     fgApplyStartOffset(
769       SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
770       parking->getHeading());
771     return true;
772 }
773
774
775 // Set current_options lon/lat given an airport id and runway number
776 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
777     if ( id.empty() )
778         return false;
779
780     // set initial position from airport and runway number
781     SG_LOG( SG_GENERAL, SG_INFO,
782             "Attempting to set starting position for "
783             << id << ":" << rwy );
784
785     const FGAirport* apt = fgFindAirportID(id);
786     if (!apt) {
787       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
788       return false;
789     }
790     
791     if (!apt->hasRunwayWithIdent(rwy)) {
792       SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
793                 "Failed to find runway " << rwy <<
794                 " at airport " << id << ". Using default runway." );
795       return false;
796     }
797     
798     FGRunway* r(apt->getRunwayByIdent(rwy));
799     fgSetString("/sim/atc/runway", r->ident().c_str());
800     SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
801           fgApplyStartOffset(startPos, r->headingDeg());
802     return true;
803 }
804
805
806 static void fgSetDistOrAltFromGlideSlope() {
807     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
808     string apt_id = fgGetString("/sim/presets/airport-id");
809     double gs = fgGetDouble("/sim/presets/glideslope-deg")
810         * SG_DEGREES_TO_RADIANS ;
811     double od = fgGetDouble("/sim/presets/offset-distance-nm");
812     double alt = fgGetDouble("/sim/presets/altitude-ft");
813
814     double apt_elev = 0.0;
815     if ( ! apt_id.empty() ) {
816         apt_elev = fgGetAirportElev( apt_id );
817         if ( apt_elev < -9990.0 ) {
818             apt_elev = 0.0;
819         }
820     } else {
821         apt_elev = 0.0;
822     }
823
824     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
825         // set altitude from glideslope and offset-distance
826         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
827         alt = fabs(od*tan(gs)) + apt_elev;
828         fgSetDouble("/sim/presets/altitude-ft", alt);
829         fgSetBool("/sim/presets/onground", false);
830         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
831                 << alt  << " ft" );
832     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
833         // set offset-distance from glideslope and altitude
834         od  = (alt - apt_elev) / tan(gs);
835         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
836         fgSetDouble("/sim/presets/offset-distance-nm", od);
837         fgSetBool("/sim/presets/onground", false);
838         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
839                 << od  << " nm" );
840     } else if( fabs(gs) > 0.01 ) {
841         SG_LOG( SG_GENERAL, SG_ALERT,
842                 "Glideslope given but not altitude or offset-distance." );
843         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
844         fgSetDouble("/sim/presets/glideslope-deg", 0);
845         fgSetBool("/sim/presets/onground", true);
846     }
847 }
848
849
850 // Set current_options lon/lat given an airport id and heading (degrees)
851 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
852
853     const nav_list_type navlist
854         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
855
856     if (navlist.size() == 0 ) {
857         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
858             << id << ":" << freq );
859         return false;
860     }
861
862     if( navlist.size() > 1 ) {
863         ostringstream buf;
864         buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
865         for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
866             // NDB stored in kHz, VOR stored in MHz * 100 :-P
867             double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
868             string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
869             buf << (*it)->ident() << " "
870                 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
871                 << (*it)->get_lat() << "/" << (*it)->get_lon()
872                 << endl;
873         }
874
875         SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
876         return false;
877     }
878
879     FGNavRecord *nav = navlist[0];
880     fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
881     return true;
882 }
883
884 // Set current_options lon/lat given an aircraft carrier id
885 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
886
887     // set initial position from runway and heading
888     SGGeod geodPos;
889     double heading;
890     SGVec3d uvw;
891     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
892         double lon = geodPos.getLongitudeDeg();
893         double lat = geodPos.getLatitudeDeg();
894         double alt = geodPos.getElevationFt();
895
896         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
897                 << carrier << " at lat = " << lat << ", lon = " << lon
898                 << ", alt = " << alt << ", heading = " << heading);
899
900         fgSetDouble("/sim/presets/longitude-deg",  lon);
901         fgSetDouble("/sim/presets/latitude-deg",  lat);
902         fgSetDouble("/sim/presets/altitude-ft", alt);
903         fgSetDouble("/sim/presets/heading-deg", heading);
904         fgSetDouble("/position/longitude-deg",  lon);
905         fgSetDouble("/position/latitude-deg",  lat);
906         fgSetDouble("/position/altitude-ft", alt);
907         fgSetDouble("/orientation/heading-deg", heading);
908
909         fgSetString("/sim/presets/speed-set", "UVW");
910         fgSetDouble("/velocities/uBody-fps", uvw(0));
911         fgSetDouble("/velocities/vBody-fps", uvw(1));
912         fgSetDouble("/velocities/wBody-fps", uvw(2));
913         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
914         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
915         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
916
917         fgSetBool("/sim/presets/onground", true);
918
919         return true;
920     } else {
921         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
922                 << carrier );
923         return false;
924     }
925 }
926  
927 // Set current_options lon/lat given an airport id and heading (degrees)
928 static bool fgSetPosFromFix( const string& id )
929 {
930   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
931   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
932   if (!fix) {
933     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
934     return false;
935   }
936   
937   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
938   return true;
939 }
940
941 /**
942  * Initialize vor/ndb/ils/fix list management and query systems (as
943  * well as simple airport db list)
944  */
945 bool
946 fgInitNav ()
947 {
948     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
949
950     SGPath aptdb( globals->get_fg_root() );
951     aptdb.append( "Airports/apt.dat" );
952
953     SGPath p_metar( globals->get_fg_root() );
954     p_metar.append( "Airports/metar.dat" );
955
956     fgAirportDBLoad( aptdb.str(), p_metar.str() );
957     FGAirport::installPropertyListener();
958     FGPositioned::installCommands();
959     
960     FGNavList *navlist = new FGNavList;
961     FGNavList *loclist = new FGNavList;
962     FGNavList *gslist = new FGNavList;
963     FGNavList *dmelist = new FGNavList;
964     FGNavList *tacanlist = new FGNavList;
965     FGNavList *carrierlist = new FGNavList;
966     FGTACANList *channellist = new FGTACANList;
967
968     globals->set_navlist( navlist );
969     globals->set_loclist( loclist );
970     globals->set_gslist( gslist );
971     globals->set_dmelist( dmelist );
972     globals->set_tacanlist( tacanlist );
973     globals->set_carrierlist( carrierlist );
974     globals->set_channellist( channellist );
975
976     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
977         SG_LOG( SG_GENERAL, SG_ALERT,
978                 "Problems loading one or more navigational database" );
979     }
980     
981     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
982     SGPath p_fix( globals->get_fg_root() );
983     p_fix.append( "Navaids/fix.dat" );
984     FGFixList fixlist;
985     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
986
987     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
988     flightgear::Airway::load();
989     
990     return true;
991 }
992
993
994 // Set the initial position based on presets (or defaults)
995 bool fgInitPosition() {
996     // cout << "fgInitPosition()" << endl;
997     double gs = fgGetDouble("/sim/presets/glideslope-deg")
998         * SG_DEGREES_TO_RADIANS ;
999     double od = fgGetDouble("/sim/presets/offset-distance-nm");
1000     double alt = fgGetDouble("/sim/presets/altitude-ft");
1001
1002     bool set_pos = false;
1003
1004     // If glideslope is specified, then calculate offset-distance or
1005     // altitude relative to glide slope if either of those was not
1006     // specified.
1007     if ( fabs( gs ) > 0.01 ) {
1008         fgSetDistOrAltFromGlideSlope();
1009     }
1010
1011
1012     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1013     // If not, check for an airport-id and use that.
1014     // If not, default to the middle of the KSFO field.
1015     // The default values for lon/lat are deliberately out of range
1016     // so that the airport-id can take effect; valid lon/lat will
1017     // override airport-id, however.
1018     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1019     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1020     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1021          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1022     {
1023         set_pos = true;
1024     }
1025
1026     string apt = fgGetString("/sim/presets/airport-id");
1027     string rwy_no = fgGetString("/sim/presets/runway");
1028     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1029     string vor = fgGetString("/sim/presets/vor-id");
1030     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1031     string ndb = fgGetString("/sim/presets/ndb-id");
1032     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1033     string carrier = fgGetString("/sim/presets/carrier");
1034     string parkpos = fgGetString("/sim/presets/parkpos");
1035     string fix = fgGetString("/sim/presets/fix");
1036     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1037     double hdg = hdg_preset->getDoubleValue();
1038
1039     // save some start parameters, so that we can later say what the
1040     // user really requested. TODO generalize that and move it to options.cxx
1041     static bool start_options_saved = false;
1042     if (!start_options_saved) {
1043         start_options_saved = true;
1044         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1045
1046         opt->setDoubleValue("latitude-deg", lat_deg);
1047         opt->setDoubleValue("longitude-deg", lon_deg);
1048         opt->setDoubleValue("heading-deg", hdg);
1049         opt->setStringValue("airport", apt.c_str());
1050         opt->setStringValue("runway", rwy_no.c_str());
1051     }
1052
1053     if (hdg > 9990.0)
1054         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1055
1056     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1057         // An airport + parking position is requested
1058         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1059             // set tower position
1060             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1061             fgSetString("/sim/tower/airport-id",  apt.c_str());
1062             set_pos = true;
1063         }
1064     }
1065
1066     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1067         // An airport + runway is requested
1068         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1069             // set tower position (a little off the heading for single
1070             // runway airports)
1071             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1072             fgSetString("/sim/tower/airport-id",  apt.c_str());
1073             set_pos = true;
1074         }
1075     }
1076
1077     if ( !set_pos && !apt.empty() ) {
1078         // An airport is requested (find runway closest to hdg)
1079         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1080             // set tower position (a little off the heading for single
1081             // runway airports)
1082             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1083             fgSetString("/sim/tower/airport-id",  apt.c_str());
1084             set_pos = true;
1085         }
1086     }
1087
1088     if (hdg_preset->getDoubleValue() > 9990.0)
1089         hdg_preset->setDoubleValue(hdg);
1090
1091     if ( !set_pos && !vor.empty() ) {
1092         // a VOR is requested
1093         if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
1094             set_pos = true;
1095         }
1096     }
1097
1098     if ( !set_pos && !ndb.empty() ) {
1099         // an NDB is requested
1100         if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
1101             set_pos = true;
1102         }
1103     }
1104
1105     if ( !set_pos && !carrier.empty() ) {
1106         // an aircraft carrier is requested
1107         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1108             set_pos = true;
1109         }
1110     }
1111
1112     if ( !set_pos && !fix.empty() ) {
1113         // a Fix is requested
1114         if ( fgSetPosFromFix( fix ) ) {
1115             set_pos = true;
1116         }
1117     }
1118
1119     if ( !set_pos ) {
1120         // No lon/lat specified, no airport specified, default to
1121         // middle of KSFO field.
1122         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1123         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1124     }
1125
1126     fgSetDouble( "/position/longitude-deg",
1127                  fgGetDouble("/sim/presets/longitude-deg") );
1128     fgSetDouble( "/position/latitude-deg",
1129                  fgGetDouble("/sim/presets/latitude-deg") );
1130     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1131
1132     // determine if this should be an on-ground or in-air start
1133     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1134         fgSetBool("/sim/presets/onground", false);
1135     } else {
1136         fgSetBool("/sim/presets/onground", true);
1137     }
1138
1139     return true;
1140 }
1141
1142
1143 // General house keeping initializations
1144 bool fgInitGeneral() {
1145     string root;
1146
1147     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1148     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1149
1150     root = globals->get_fg_root();
1151     if ( ! root.length() ) {
1152         // No root path set? Then bail ...
1153         SG_LOG( SG_GENERAL, SG_ALERT,
1154                 "Cannot continue without a path to the base package "
1155                 << "being defined." );
1156         exit(-1);
1157     }
1158     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1159
1160     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1161
1162     char buf[512], *cwd = getcwd(buf, 511);
1163     buf[511] = '\0';
1164     SGPropertyNode *curr = fgGetNode("/sim", true);
1165     curr->removeChild("fg-current", 0, false);
1166     curr = curr->getChild("fg-current", 0, true);
1167     curr->setStringValue(cwd ? cwd : "");
1168     curr->setAttribute(SGPropertyNode::WRITE, false);
1169
1170     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1171     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1172     return true;
1173 }
1174
1175 // This is the top level init routine which calls all the other
1176 // initialization routines.  If you are adding a subsystem to flight
1177 // gear, its initialization call should located in this routine.
1178 // Returns non-zero if a problem encountered.
1179 bool fgInitSubsystems() {
1180
1181     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1182     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1183
1184     ////////////////////////////////////////////////////////////////////
1185     // Initialize the event manager subsystem.
1186     ////////////////////////////////////////////////////////////////////
1187
1188     globals->get_event_mgr()->init();
1189     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1190
1191     ////////////////////////////////////////////////////////////////////
1192     // Initialize the property interpolator subsystem. Put into the INIT
1193     // group because the "nasal" subsystem may need it at GENERAL take-down.
1194     ////////////////////////////////////////////////////////////////////
1195     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1196
1197
1198     ////////////////////////////////////////////////////////////////////
1199     // Add the FlightGear property utilities.
1200     ////////////////////////////////////////////////////////////////////
1201     globals->add_subsystem("properties", new FGProperties);
1202
1203
1204     ////////////////////////////////////////////////////////////////////
1205     // Add the performance monitoring system.
1206     ////////////////////////////////////////////////////////////////////
1207     globals->add_subsystem("performance-mon",
1208             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1209                                      fgGetNode("/sim/performance-monitor", true)));
1210
1211     ////////////////////////////////////////////////////////////////////
1212     // Initialize the material property subsystem.
1213     ////////////////////////////////////////////////////////////////////
1214
1215     SGPath mpath( globals->get_fg_root() );
1216     mpath.append( fgGetString("/sim/rendering/materials-file") );
1217     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1218             globals->get_props()) ) {
1219         SG_LOG( SG_GENERAL, SG_ALERT,
1220                 "Error loading materials file " << mpath.str() );
1221         exit(-1);
1222     }
1223
1224
1225     ////////////////////////////////////////////////////////////////////
1226     // Initialize the scenery management subsystem.
1227     ////////////////////////////////////////////////////////////////////
1228
1229     globals->get_scenery()->get_scene_graph()
1230         ->addChild(simgear::Particles::getCommonRoot());
1231     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1232
1233     ////////////////////////////////////////////////////////////////////
1234     // Initialize the flight model subsystem.
1235     ////////////////////////////////////////////////////////////////////
1236
1237     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1238
1239     ////////////////////////////////////////////////////////////////////
1240     // Initialize the weather subsystem.
1241     ////////////////////////////////////////////////////////////////////
1242
1243     // Initialize the weather modeling subsystem
1244     globals->add_subsystem("environment", new FGEnvironmentMgr);
1245     globals->add_subsystem("ephemeris", new Ephemeris);
1246     
1247     ////////////////////////////////////////////////////////////////////
1248     // Initialize the aircraft systems and instrumentation (before the
1249     // autopilot.)
1250     ////////////////////////////////////////////////////////////////////
1251
1252     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1253     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1254
1255     ////////////////////////////////////////////////////////////////////
1256     // Initialize the XML Autopilot subsystem.
1257     ////////////////////////////////////////////////////////////////////
1258
1259     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1260     globals->add_subsystem( "route-manager", new FGRouteMgr );
1261
1262     ////////////////////////////////////////////////////////////////////
1263     // Initialize the Input-Output subsystem
1264     ////////////////////////////////////////////////////////////////////
1265     globals->add_subsystem( "io", new FGIO );
1266
1267     ////////////////////////////////////////////////////////////////////
1268     // Create and register the logger.
1269     ////////////////////////////////////////////////////////////////////
1270     
1271     globals->add_subsystem("logger", new FGLogger);
1272
1273     ////////////////////////////////////////////////////////////////////
1274     // Create and register the XML GUI.
1275     ////////////////////////////////////////////////////////////////////
1276
1277     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1278
1279     //////////////////////////////////////////////////////////////////////
1280     // Initialize the 2D cloud subsystem.
1281     ////////////////////////////////////////////////////////////////////
1282     fgGetBool("/sim/rendering/bump-mapping", false);
1283
1284
1285
1286     ////////////////////////////////////////////////////////////////////
1287     // Initialise the ATC Manager
1288     // Note that this is old stuff, but might be necessesary for the 
1289     // current ATIS implementation. Therefore, leave it in here
1290     // until the ATIS system is ported over to make use of the ATIS 
1291     // sub system infrastructure.
1292     ////////////////////////////////////////////////////////////////////
1293
1294     globals->add_subsystem("ATC-old", new FGATCMgr, SGSubsystemMgr::INIT);
1295
1296     ////////////////////////////////////////////////////////////////////
1297    // Initialize the ATC subsystem
1298     ////////////////////////////////////////////////////////////////////
1299     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1300     ////////////////////////////////////////////////////////////////////
1301     // Initialise the ATIS Subsystem
1302     ////////////////////////////////////////////////////////////////////
1303     //globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1304
1305
1306     ////////////////////////////////////////////////////////////////////
1307     // Initialize multiplayer subsystem
1308     ////////////////////////////////////////////////////////////////////
1309
1310     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1311
1312     ////////////////////////////////////////////////////////////////////
1313     // Initialise the AI Model Manager
1314     ////////////////////////////////////////////////////////////////////
1315     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1316     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1317     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1318
1319
1320     // It's probably a good idea to initialize the top level traffic manager
1321     // After the AI and ATC systems have been initialized properly.
1322     // AI Traffic manager
1323     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1324
1325     ////////////////////////////////////////////////////////////////////
1326     // Add a new 2D panel.
1327     ////////////////////////////////////////////////////////////////////
1328
1329     string panel_path(fgGetString("/sim/panel/path"));
1330     if (!panel_path.empty()) {
1331       FGPanel* p = fgReadPanel(panel_path);
1332       if (p) {
1333         globals->set_current_panel(p);
1334         p->init();
1335         p->bind();
1336         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1337       } else {
1338         SG_LOG( SG_INPUT, SG_ALERT,
1339                 "Error reading new panel from " << panel_path );
1340       }
1341     }
1342
1343     ////////////////////////////////////////////////////////////////////
1344     // Initialize the controls subsystem.
1345     ////////////////////////////////////////////////////////////////////
1346
1347     globals->get_controls()->init();
1348     globals->get_controls()->bind();
1349
1350
1351     ////////////////////////////////////////////////////////////////////
1352     // Initialize the input subsystem.
1353     ////////////////////////////////////////////////////////////////////
1354
1355     globals->add_subsystem("input", new FGInput);
1356
1357
1358     ////////////////////////////////////////////////////////////////////
1359     // Initialize the replay subsystem
1360     ////////////////////////////////////////////////////////////////////
1361     globals->add_subsystem("replay", new FGReplay);
1362
1363 #ifdef ENABLE_AUDIO_SUPPORT
1364     ////////////////////////////////////////////////////////////////////
1365     // Initialize the sound-effects subsystem.
1366     ////////////////////////////////////////////////////////////////////
1367     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1368 #endif
1369
1370     ////////////////////////////////////////////////////////////////////
1371     // Initialize the lighting subsystem.
1372     ////////////////////////////////////////////////////////////////////
1373
1374     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1375     
1376     // ordering here is important : Nasal (via events), then models, then views
1377     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1378     
1379     FGAircraftModel* acm = new FGAircraftModel;
1380     globals->set_aircraft_model(acm);
1381     globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1382
1383     FGModelMgr* mm = new FGModelMgr;
1384     globals->set_model_mgr(mm);
1385     globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1386
1387     FGViewMgr *viewmgr = new FGViewMgr;
1388     globals->set_viewmgr( viewmgr );
1389     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1390
1391     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
1392       SGSubsystemMgr::DISPLAY);
1393       
1394     ////////////////////////////////////////////////////////////////////
1395     // Bind and initialize subsystems.
1396     ////////////////////////////////////////////////////////////////////
1397
1398     globals->get_subsystem_mgr()->bind();
1399     globals->get_subsystem_mgr()->init();
1400
1401     ////////////////////////////////////////////////////////////////////////
1402     // Initialize the Nasal interpreter.
1403     // Do this last, so that the loaded scripts see initialized state
1404     ////////////////////////////////////////////////////////////////////////
1405     FGNasalSys* nasal = new FGNasalSys();
1406     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1407     nasal->init();
1408
1409     // initialize methods that depend on other subsystems.
1410     globals->get_subsystem_mgr()->postinit();
1411
1412     ////////////////////////////////////////////////////////////////////////
1413     // End of subsystem initialization.
1414     ////////////////////////////////////////////////////////////////////
1415
1416     fgSetBool("/sim/initialized", true);
1417
1418     SG_LOG( SG_GENERAL, SG_INFO, endl);
1419
1420                                 // Save the initial state for future
1421                                 // reference.
1422     globals->saveInitialState();
1423     
1424     return true;
1425 }
1426
1427 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1428 void fgReInitSubsystems()
1429 {
1430     static const SGPropertyNode *master_freeze
1431         = fgGetNode("/sim/freeze/master");
1432
1433     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1434
1435 // setup state to begin re-init
1436     bool freeze = master_freeze->getBoolValue();
1437     if ( !freeze ) {
1438         fgSetBool("/sim/freeze/master", true);
1439     }
1440     
1441     fgSetBool("/sim/signals/reinit", true);
1442     fgSetBool("/sim/crashed", false);
1443
1444 // do actual re-init steps
1445     globals->get_subsystem("flight")->unbind();
1446     
1447   // reset control state, before restoring initial state; -set or config files
1448   // may specify values for flaps, trim tabs, magnetos, etc
1449     globals->get_controls()->reset_all();
1450         
1451     globals->restoreInitialState();
1452
1453     // update our position based on current presets
1454     fgInitPosition();
1455     
1456     // Force reupdating the positions of the ai 3d models. They are used for
1457     // initializing ground level for the FDM.
1458     globals->get_subsystem("ai-model")->reinit();
1459
1460     // Initialize the FDM
1461     globals->get_subsystem("flight")->reinit();
1462
1463     // reset replay buffers
1464     globals->get_subsystem("replay")->reinit();
1465     
1466     // reload offsets from config defaults
1467     globals->get_viewmgr()->reinit();
1468
1469     globals->get_subsystem("time")->reinit();
1470
1471     // need to bind FDMshell again, since we manually unbound it above...
1472     globals->get_subsystem("flight")->bind();
1473
1474 // setup state to end re-init
1475     fgSetBool("/sim/signals/reinit", false);
1476     if ( !freeze ) {
1477         fgSetBool("/sim/freeze/master", false);
1478     }
1479     fgSetBool("/sim/sceneryloaded",false);
1480 }
1481
1482
1483 ///////////////////////////////////////////////////////////////////////////////
1484 // helper object to implement the --show-aircraft command.
1485 // resides here so we can share the fgFindAircraftInDir template above,
1486 // and hence ensure this command lists exectly the same aircraft as the normal
1487 // loading path.
1488 class ShowAircraft 
1489 {
1490 public:
1491   ShowAircraft()
1492   {
1493     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1494   }
1495   
1496   
1497   void show(const SGPath& path)
1498   {
1499     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1500   
1501     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1502     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1503     cout << "Available aircraft:" << endl;
1504     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1505         cout << _aircraft[i] << endl;
1506     }
1507   }
1508   
1509 private:
1510   bool processAircraft(const SGPath& path)
1511   {
1512     SGPropertyNode root;
1513     try {
1514        readProperties(path.str(), &root);
1515     } catch (sg_exception& ) {
1516        return false;
1517     }
1518   
1519     int maturity = 0;
1520     string descStr("   ");
1521     descStr += path.file();
1522   // trim common suffix from file names
1523     int nPos = descStr.rfind("-set.xml");
1524     if (nPos == (int)(descStr.size() - 8)) {
1525       descStr.resize(nPos);
1526     }
1527     
1528     SGPropertyNode *node = root.getNode("sim");
1529     if (node) {
1530       SGPropertyNode* desc = node->getNode("description");
1531       // if a status tag is found, read it in
1532       if (node->hasValue("status")) {
1533         maturity = getNumMaturity(node->getStringValue("status"));
1534       }
1535       
1536       if (desc) {
1537         if (descStr.size() <= 27+3) {
1538           descStr.append(29+3-descStr.size(), ' ');
1539         } else {
1540           descStr += '\n';
1541           descStr.append( 32, ' ');
1542         }
1543         descStr += desc->getStringValue();
1544       }
1545     } // of have 'sim' node
1546     
1547     if (maturity < _minStatus) {
1548       return false;
1549     }
1550
1551     _aircraft.push_back(descStr);
1552     return false;
1553   }
1554
1555
1556   int getNumMaturity(const char * str) 
1557   {
1558     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1559     // $FG_ROOT/data/Translations/string-default.xml
1560     const char* levels[] = {"alpha","beta","early-production","production"}; 
1561
1562     if (!strcmp(str, "all")) {
1563       return 0;
1564     }
1565
1566     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1567       if (strcmp(str,levels[i])==0)
1568         return i;
1569
1570     return 0;
1571   }
1572
1573   // recommended in Meyers, Effective STL when internationalization and embedded
1574   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1575   struct ciLessLibC : public std::binary_function<string, string, bool>
1576   {
1577     bool operator()(const std::string &lhs, const std::string &rhs) const
1578     {
1579       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1580     }
1581   };
1582
1583   int _minStatus;
1584   string_list _aircraft;
1585 };
1586
1587 void fgShowAircraft(const SGPath &path)
1588 {
1589     ShowAircraft s;
1590     s.show(path);
1591         
1592 #ifdef _MSC_VER
1593     cout << "Hit a key to continue..." << endl;
1594     cin.get();
1595 #endif
1596 }
1597
1598