]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Tweak ODGauge usage, fix multiple instances of NavDisplay or wxRadar.
[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");
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     globals->loadUserSettings(dataPath);
552
553     // Scan user config files and command line for a specified aircraft.
554     flightgear::Options::sharedInstance()->initAircraft();
555
556     FindAndCacheAircraft f(globals->get_props());
557     if (!f.loadAircraft()) {
558       return false;
559     }
560
561     // parse options after loading aircraft to ensure any user
562     // overrides of defaults are honored.
563     flightgear::Options::sharedInstance()->processOptions();
564       
565     return true;
566 }
567
568 // Set current tower position lon/lat given an airport id
569 static bool fgSetTowerPosFromAirportID( const string& id) {
570     const FGAirport *a = fgFindAirportID( id);
571     if (a) {
572         SGGeod tower = a->getTowerLocation();
573         fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
574         fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
575         fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
576         return true;
577     } else {
578         return false;
579     }
580
581 }
582
583 struct FGTowerLocationListener : SGPropertyChangeListener {
584     void valueChanged(SGPropertyNode* node) {
585         string id(node->getStringValue());
586         if (fgGetBool("/sim/tower/auto-position",true))
587         {
588             // enforce using closest airport when auto-positioning is enabled 
589             const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
590             if (closest_airport && (id != closest_airport))
591             {
592                 id = closest_airport;
593                 node->setStringValue(id);
594             }
595         }
596         fgSetTowerPosFromAirportID(id);
597     }
598 };
599
600 struct FGClosestTowerLocationListener : SGPropertyChangeListener
601 {
602     void valueChanged(SGPropertyNode* )
603     {
604         // closest airport has changed
605         if (fgGetBool("/sim/tower/auto-position",true))
606         {
607             // update tower position
608             const char* id = fgGetString("/sim/airport/closest-airport-id", "");
609             if (id && *id!=0)
610                 fgSetString("/sim/tower/airport-id", id);
611         }
612     }
613 };
614
615 void fgInitTowerLocationListener() {
616     fgGetNode("/sim/tower/airport-id",  true)
617         ->addChangeListener( new FGTowerLocationListener(), true );
618     FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
619     fgGetNode("/sim/airport/closest-airport-id", true)
620         ->addChangeListener(ntcl , true );
621     fgGetNode("/sim/tower/auto-position", true)
622            ->addChangeListener(ntcl, true );
623 }
624
625 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
626 {
627   SGGeod startPos(aStartPos);
628   if (aTargetHeading == HUGE_VAL) {
629     aTargetHeading = aHeading;
630   }
631   
632   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
633     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
634     offsetDistance *= SG_NM_TO_METER;
635     double offsetAzimuth = aHeading;
636     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
637       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
638       aHeading = aTargetHeading;
639     }
640
641     SGGeod offset;
642     double az2; // dummy
643     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
644     startPos = offset;
645   }
646
647   // presets
648   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
649   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
650   fgSetDouble("/sim/presets/heading-deg", aHeading );
651
652   // other code depends on the actual values being set ...
653   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
654   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
655   fgSetDouble("/orientation/heading-deg", aHeading );
656 }
657
658 // Set current_options lon/lat given an airport id and heading (degrees)
659 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
660     if ( id.empty() )
661         return false;
662
663     // set initial position from runway and heading
664     SG_LOG( SG_GENERAL, SG_INFO,
665             "Attempting to set starting position from airport code "
666             << id << " heading " << tgt_hdg );
667
668     const FGAirport* apt = fgFindAirportID(id);
669     if (!apt) return false;
670     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
671     fgSetString("/sim/atc/runway", r->ident().c_str());
672
673     SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
674           fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
675     return true;
676 }
677
678 // Set current_options lon/lat given an airport id and parkig position name
679 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
680     if ( id.empty() )
681         return false;
682
683     // can't see an easy way around this const_cast at the moment
684     FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
685     if (!apt) {
686         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
687         return false;
688     }
689     FGAirportDynamics* dcs = apt->getDynamics();
690     if (!dcs) {
691         SG_LOG( SG_GENERAL, SG_ALERT,
692                 "Airport " << id << "does not appear to have parking information available");
693         return false;
694     }
695     
696     int park_index = dcs->getNrOfParkings() - 1;
697     bool succes;
698     double radius = fgGetDouble("/sim/dimensions/radius-m");
699     if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
700         double lat, lon, heading;
701         string fltType;
702         string acOperator;
703         SGPath acData;
704         try {
705             acData = fgGetString("/sim/fg-home");
706             acData.append("aircraft-data");
707             string acfile = fgGetString("/sim/aircraft") + string(".xml");
708             acData.append(acfile);
709             SGPropertyNode root;
710             readProperties(acData.str(), &root);
711             SGPropertyNode * node = root.getNode("sim");
712             fltType    = node->getStringValue("aircraft-class", "NONE"     );
713             acOperator = node->getStringValue("aircraft-operator", "NONE"     );
714         } catch (const sg_exception &) {
715             SG_LOG(SG_GENERAL, SG_INFO,
716                 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
717
718        // cout << path.str() << endl;
719         }
720         if (fltType.empty() || fltType == "NONE") {
721             SG_LOG(SG_GENERAL, SG_INFO,
722                 "Aircraft type information not found in: " << acData.str() << ". Using default value");
723                 fltType = fgGetString("/sim/aircraft-class"   );
724         }
725         if (acOperator.empty() || fltType == "NONE") {
726             SG_LOG(SG_GENERAL, SG_INFO,
727                 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
728                 acOperator = fgGetString("/sim/aircraft-operator"   );
729         }
730
731         cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
732         string acType; // Currently not used by findAvailable parking, so safe to leave empty. 
733         succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
734         if (succes) {
735             fgGetString("/sim/presets/parkpos");
736             fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
737         } else {
738             SG_LOG( SG_GENERAL, SG_ALERT,
739                     "Failed to find a suitable parking at airport " << id );
740             return false;
741         }
742     } else {
743         //cerr << "We shouldn't get here when AVAILABLE" << endl;
744         while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
745         if (park_index < 0) {
746             SG_LOG( SG_GENERAL, SG_ALERT,
747                     "Failed to find parking position " << parkpos <<
748                     " at airport " << id );
749             return false;
750         }
751     }
752     FGParking* parking = dcs->getParking(park_index);
753     parking->setAvailable(false);
754     fgApplyStartOffset(
755       SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
756       parking->getHeading());
757     return true;
758 }
759
760
761 // Set current_options lon/lat given an airport id and runway number
762 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
763     if ( id.empty() )
764         return false;
765
766     // set initial position from airport and runway number
767     SG_LOG( SG_GENERAL, SG_INFO,
768             "Attempting to set starting position for "
769             << id << ":" << rwy );
770
771     const FGAirport* apt = fgFindAirportID(id);
772     if (!apt) {
773       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
774       return false;
775     }
776     
777     if (!apt->hasRunwayWithIdent(rwy)) {
778       SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
779                 "Failed to find runway " << rwy <<
780                 " at airport " << id << ". Using default runway." );
781       return false;
782     }
783     
784     FGRunway* r(apt->getRunwayByIdent(rwy));
785     fgSetString("/sim/atc/runway", r->ident().c_str());
786     SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
787           fgApplyStartOffset(startPos, r->headingDeg());
788     return true;
789 }
790
791
792 static void fgSetDistOrAltFromGlideSlope() {
793     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
794     string apt_id = fgGetString("/sim/presets/airport-id");
795     double gs = fgGetDouble("/sim/presets/glideslope-deg")
796         * SG_DEGREES_TO_RADIANS ;
797     double od = fgGetDouble("/sim/presets/offset-distance-nm");
798     double alt = fgGetDouble("/sim/presets/altitude-ft");
799
800     double apt_elev = 0.0;
801     if ( ! apt_id.empty() ) {
802         apt_elev = fgGetAirportElev( apt_id );
803         if ( apt_elev < -9990.0 ) {
804             apt_elev = 0.0;
805         }
806     } else {
807         apt_elev = 0.0;
808     }
809
810     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
811         // set altitude from glideslope and offset-distance
812         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
813         alt = fabs(od*tan(gs)) + apt_elev;
814         fgSetDouble("/sim/presets/altitude-ft", alt);
815         fgSetBool("/sim/presets/onground", false);
816         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
817                 << alt  << " ft" );
818     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
819         // set offset-distance from glideslope and altitude
820         od  = (alt - apt_elev) / tan(gs);
821         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
822         fgSetDouble("/sim/presets/offset-distance-nm", od);
823         fgSetBool("/sim/presets/onground", false);
824         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
825                 << od  << " nm" );
826     } else if( fabs(gs) > 0.01 ) {
827         SG_LOG( SG_GENERAL, SG_ALERT,
828                 "Glideslope given but not altitude or offset-distance." );
829         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
830         fgSetDouble("/sim/presets/glideslope-deg", 0);
831         fgSetBool("/sim/presets/onground", true);
832     }
833 }
834
835
836 // Set current_options lon/lat given an airport id and heading (degrees)
837 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
838
839     const nav_list_type navlist
840         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
841
842     if (navlist.size() == 0 ) {
843         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
844             << id << ":" << freq );
845         return false;
846     }
847
848     if( navlist.size() > 1 ) {
849         ostringstream buf;
850         buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
851         for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
852             // NDB stored in kHz, VOR stored in MHz * 100 :-P
853             double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
854             string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
855             buf << (*it)->ident() << " "
856                 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
857                 << (*it)->get_lat() << "/" << (*it)->get_lon()
858                 << endl;
859         }
860
861         SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
862         return false;
863     }
864
865     FGNavRecord *nav = navlist[0];
866     fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
867     return true;
868 }
869
870 // Set current_options lon/lat given an aircraft carrier id
871 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
872
873     // set initial position from runway and heading
874     SGGeod geodPos;
875     double heading;
876     SGVec3d uvw;
877     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
878         double lon = geodPos.getLongitudeDeg();
879         double lat = geodPos.getLatitudeDeg();
880         double alt = geodPos.getElevationFt();
881
882         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
883                 << carrier << " at lat = " << lat << ", lon = " << lon
884                 << ", alt = " << alt << ", heading = " << heading);
885
886         fgSetDouble("/sim/presets/longitude-deg",  lon);
887         fgSetDouble("/sim/presets/latitude-deg",  lat);
888         fgSetDouble("/sim/presets/altitude-ft", alt);
889         fgSetDouble("/sim/presets/heading-deg", heading);
890         fgSetDouble("/position/longitude-deg",  lon);
891         fgSetDouble("/position/latitude-deg",  lat);
892         fgSetDouble("/position/altitude-ft", alt);
893         fgSetDouble("/orientation/heading-deg", heading);
894
895         fgSetString("/sim/presets/speed-set", "UVW");
896         fgSetDouble("/velocities/uBody-fps", uvw(0));
897         fgSetDouble("/velocities/vBody-fps", uvw(1));
898         fgSetDouble("/velocities/wBody-fps", uvw(2));
899         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
900         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
901         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
902
903         fgSetBool("/sim/presets/onground", true);
904
905         return true;
906     } else {
907         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
908                 << carrier );
909         return false;
910     }
911 }
912  
913 // Set current_options lon/lat given an airport id and heading (degrees)
914 static bool fgSetPosFromFix( const string& id )
915 {
916   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
917   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
918   if (!fix) {
919     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
920     return false;
921   }
922   
923   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
924   return true;
925 }
926
927 /**
928  * Initialize vor/ndb/ils/fix list management and query systems (as
929  * well as simple airport db list)
930  */
931 bool
932 fgInitNav ()
933 {
934     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
935
936     SGPath aptdb( globals->get_fg_root() );
937     aptdb.append( "Airports/apt.dat" );
938
939     SGPath p_metar( globals->get_fg_root() );
940     p_metar.append( "Airports/metar.dat" );
941
942     fgAirportDBLoad( aptdb.str(), p_metar.str() );
943     FGAirport::installPropertyListener();
944     FGPositioned::installCommands();
945     
946     FGNavList *navlist = new FGNavList;
947     FGNavList *loclist = new FGNavList;
948     FGNavList *gslist = new FGNavList;
949     FGNavList *dmelist = new FGNavList;
950     FGNavList *tacanlist = new FGNavList;
951     FGNavList *carrierlist = new FGNavList;
952     FGTACANList *channellist = new FGTACANList;
953
954     globals->set_navlist( navlist );
955     globals->set_loclist( loclist );
956     globals->set_gslist( gslist );
957     globals->set_dmelist( dmelist );
958     globals->set_tacanlist( tacanlist );
959     globals->set_carrierlist( carrierlist );
960     globals->set_channellist( channellist );
961
962     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
963         SG_LOG( SG_GENERAL, SG_ALERT,
964                 "Problems loading one or more navigational database" );
965     }
966     
967     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
968     SGPath p_fix( globals->get_fg_root() );
969     p_fix.append( "Navaids/fix.dat" );
970     FGFixList fixlist;
971     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
972
973     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
974     flightgear::Airway::load();
975     
976     return true;
977 }
978
979
980 // Set the initial position based on presets (or defaults)
981 bool fgInitPosition() {
982     // cout << "fgInitPosition()" << endl;
983     double gs = fgGetDouble("/sim/presets/glideslope-deg")
984         * SG_DEGREES_TO_RADIANS ;
985     double od = fgGetDouble("/sim/presets/offset-distance-nm");
986     double alt = fgGetDouble("/sim/presets/altitude-ft");
987
988     bool set_pos = false;
989
990     // If glideslope is specified, then calculate offset-distance or
991     // altitude relative to glide slope if either of those was not
992     // specified.
993     if ( fabs( gs ) > 0.01 ) {
994         fgSetDistOrAltFromGlideSlope();
995     }
996
997
998     // If we have an explicit, in-range lon/lat, don't change it, just use it.
999     // If not, check for an airport-id and use that.
1000     // If not, default to the middle of the KSFO field.
1001     // The default values for lon/lat are deliberately out of range
1002     // so that the airport-id can take effect; valid lon/lat will
1003     // override airport-id, however.
1004     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1005     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1006     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1007          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1008     {
1009         set_pos = true;
1010     }
1011
1012     string apt = fgGetString("/sim/presets/airport-id");
1013     string rwy_no = fgGetString("/sim/presets/runway");
1014     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1015     string vor = fgGetString("/sim/presets/vor-id");
1016     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1017     string ndb = fgGetString("/sim/presets/ndb-id");
1018     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1019     string carrier = fgGetString("/sim/presets/carrier");
1020     string parkpos = fgGetString("/sim/presets/parkpos");
1021     string fix = fgGetString("/sim/presets/fix");
1022     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1023     double hdg = hdg_preset->getDoubleValue();
1024
1025     // save some start parameters, so that we can later say what the
1026     // user really requested. TODO generalize that and move it to options.cxx
1027     static bool start_options_saved = false;
1028     if (!start_options_saved) {
1029         start_options_saved = true;
1030         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1031
1032         opt->setDoubleValue("latitude-deg", lat_deg);
1033         opt->setDoubleValue("longitude-deg", lon_deg);
1034         opt->setDoubleValue("heading-deg", hdg);
1035         opt->setStringValue("airport", apt.c_str());
1036         opt->setStringValue("runway", rwy_no.c_str());
1037     }
1038
1039     if (hdg > 9990.0)
1040         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1041
1042     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1043         // An airport + parking position is requested
1044         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1045             // set tower position
1046             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1047             fgSetString("/sim/tower/airport-id",  apt.c_str());
1048             set_pos = true;
1049         }
1050     }
1051
1052     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1053         // An airport + runway is requested
1054         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1055             // set tower position (a little off the heading for single
1056             // runway airports)
1057             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1058             fgSetString("/sim/tower/airport-id",  apt.c_str());
1059             set_pos = true;
1060         }
1061     }
1062
1063     if ( !set_pos && !apt.empty() ) {
1064         // An airport is requested (find runway closest to hdg)
1065         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1066             // set tower position (a little off the heading for single
1067             // runway airports)
1068             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1069             fgSetString("/sim/tower/airport-id",  apt.c_str());
1070             set_pos = true;
1071         }
1072     }
1073
1074     if (hdg_preset->getDoubleValue() > 9990.0)
1075         hdg_preset->setDoubleValue(hdg);
1076
1077     if ( !set_pos && !vor.empty() ) {
1078         // a VOR is requested
1079         if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
1080             set_pos = true;
1081         }
1082     }
1083
1084     if ( !set_pos && !ndb.empty() ) {
1085         // an NDB is requested
1086         if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
1087             set_pos = true;
1088         }
1089     }
1090
1091     if ( !set_pos && !carrier.empty() ) {
1092         // an aircraft carrier is requested
1093         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1094             set_pos = true;
1095         }
1096     }
1097
1098     if ( !set_pos && !fix.empty() ) {
1099         // a Fix is requested
1100         if ( fgSetPosFromFix( fix ) ) {
1101             set_pos = true;
1102         }
1103     }
1104
1105     if ( !set_pos ) {
1106         // No lon/lat specified, no airport specified, default to
1107         // middle of KSFO field.
1108         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1109         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1110     }
1111
1112     fgSetDouble( "/position/longitude-deg",
1113                  fgGetDouble("/sim/presets/longitude-deg") );
1114     fgSetDouble( "/position/latitude-deg",
1115                  fgGetDouble("/sim/presets/latitude-deg") );
1116     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1117
1118     // determine if this should be an on-ground or in-air start
1119     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1120         fgSetBool("/sim/presets/onground", false);
1121     } else {
1122         fgSetBool("/sim/presets/onground", true);
1123     }
1124
1125     return true;
1126 }
1127
1128
1129 // General house keeping initializations
1130 bool fgInitGeneral() {
1131     string root;
1132
1133     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1134     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1135
1136     root = globals->get_fg_root();
1137     if ( ! root.length() ) {
1138         // No root path set? Then bail ...
1139         SG_LOG( SG_GENERAL, SG_ALERT,
1140                 "Cannot continue without a path to the base package "
1141                 << "being defined." );
1142         exit(-1);
1143     }
1144     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1145
1146     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1147
1148     char buf[512], *cwd = getcwd(buf, 511);
1149     buf[511] = '\0';
1150     SGPropertyNode *curr = fgGetNode("/sim", true);
1151     curr->removeChild("fg-current", 0, false);
1152     curr = curr->getChild("fg-current", 0, true);
1153     curr->setStringValue(cwd ? cwd : "");
1154     curr->setAttribute(SGPropertyNode::WRITE, false);
1155
1156     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1157     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1158     return true;
1159 }
1160
1161 // This is the top level init routine which calls all the other
1162 // initialization routines.  If you are adding a subsystem to flight
1163 // gear, its initialization call should located in this routine.
1164 // Returns non-zero if a problem encountered.
1165 bool fgInitSubsystems() {
1166
1167     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1168     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1169
1170     ////////////////////////////////////////////////////////////////////
1171     // Initialize the sound subsystem.
1172     ////////////////////////////////////////////////////////////////////
1173     // Sound manager uses an own subsystem group "SOUND" which is the last
1174     // to be updated in every loop.
1175     // Sound manager is updated last so it can use the CPU while the GPU
1176     // is processing the scenery (doubled the frame-rate for me) -EMH-
1177     globals->add_subsystem("sound", new SGSoundMgr, SGSubsystemMgr::SOUND);
1178
1179     ////////////////////////////////////////////////////////////////////
1180     // Initialize the event manager subsystem.
1181     ////////////////////////////////////////////////////////////////////
1182
1183     globals->get_event_mgr()->init();
1184     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1185
1186     ////////////////////////////////////////////////////////////////////
1187     // Initialize the property interpolator subsystem. Put into the INIT
1188     // group because the "nasal" subsystem may need it at GENERAL take-down.
1189     ////////////////////////////////////////////////////////////////////
1190     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1191
1192
1193     ////////////////////////////////////////////////////////////////////
1194     // Add the FlightGear property utilities.
1195     ////////////////////////////////////////////////////////////////////
1196     globals->add_subsystem("properties", new FGProperties);
1197
1198
1199     ////////////////////////////////////////////////////////////////////
1200     // Add the performance monitoring system.
1201     ////////////////////////////////////////////////////////////////////
1202     globals->add_subsystem("performance-mon",
1203             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
1204                                      fgGetNode("/sim/performance-monitor", true)));
1205
1206     ////////////////////////////////////////////////////////////////////
1207     // Initialize the material property subsystem.
1208     ////////////////////////////////////////////////////////////////////
1209
1210     SGPath mpath( globals->get_fg_root() );
1211     mpath.append( fgGetString("/sim/rendering/materials-file") );
1212     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1213             globals->get_props()) ) {
1214         SG_LOG( SG_GENERAL, SG_ALERT,
1215                 "Error loading materials file " << mpath.str() );
1216         exit(-1);
1217     }
1218
1219
1220     ////////////////////////////////////////////////////////////////////
1221     // Initialize the scenery management subsystem.
1222     ////////////////////////////////////////////////////////////////////
1223
1224     globals->get_scenery()->get_scene_graph()
1225         ->addChild(simgear::Particles::getCommonRoot());
1226     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1227
1228     ////////////////////////////////////////////////////////////////////
1229     // Initialize the flight model subsystem.
1230     ////////////////////////////////////////////////////////////////////
1231
1232     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1233
1234     ////////////////////////////////////////////////////////////////////
1235     // Initialize the weather subsystem.
1236     ////////////////////////////////////////////////////////////////////
1237
1238     // Initialize the weather modeling subsystem
1239     globals->add_subsystem("environment", new FGEnvironmentMgr);
1240     globals->add_subsystem("ephemeris", new Ephemeris);
1241     
1242     ////////////////////////////////////////////////////////////////////
1243     // Initialize the aircraft systems and instrumentation (before the
1244     // autopilot.)
1245     ////////////////////////////////////////////////////////////////////
1246
1247     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1248     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1249
1250     ////////////////////////////////////////////////////////////////////
1251     // Initialize the XML Autopilot subsystem.
1252     ////////////////////////////////////////////////////////////////////
1253
1254     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
1255     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
1256     globals->add_subsystem( "route-manager", new FGRouteMgr );
1257
1258     ////////////////////////////////////////////////////////////////////
1259     // Initialize the Input-Output subsystem
1260     ////////////////////////////////////////////////////////////////////
1261     globals->add_subsystem( "io", new FGIO );
1262
1263     ////////////////////////////////////////////////////////////////////
1264     // Create and register the logger.
1265     ////////////////////////////////////////////////////////////////////
1266     
1267     globals->add_subsystem("logger", new FGLogger);
1268
1269     ////////////////////////////////////////////////////////////////////
1270     // Create and register the XML GUI.
1271     ////////////////////////////////////////////////////////////////////
1272
1273     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1274
1275     //////////////////////////////////////////////////////////////////////
1276     // Initialize the 2D cloud subsystem.
1277     ////////////////////////////////////////////////////////////////////
1278     fgGetBool("/sim/rendering/bump-mapping", false);
1279
1280
1281
1282     ////////////////////////////////////////////////////////////////////
1283     // Initialise the ATC Manager
1284     // Note that this is old stuff, but might be necessesary for the 
1285     // current ATIS implementation. Therefore, leave it in here
1286     // until the ATIS system is ported over to make use of the ATIS 
1287     // sub system infrastructure.
1288     ////////////////////////////////////////////////////////////////////
1289
1290     globals->add_subsystem("ATC-old", new FGATCMgr, SGSubsystemMgr::INIT);
1291
1292     ////////////////////////////////////////////////////////////////////
1293    // Initialize the ATC subsystem
1294     ////////////////////////////////////////////////////////////////////
1295     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1296     ////////////////////////////////////////////////////////////////////
1297     // Initialise the ATIS Subsystem
1298     ////////////////////////////////////////////////////////////////////
1299     //globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1300
1301
1302     ////////////////////////////////////////////////////////////////////
1303     // Initialize multiplayer subsystem
1304     ////////////////////////////////////////////////////////////////////
1305
1306     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1307
1308     ////////////////////////////////////////////////////////////////////
1309     // Initialise the AI Model Manager
1310     ////////////////////////////////////////////////////////////////////
1311     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1312     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1313     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1314
1315
1316     // It's probably a good idea to initialize the top level traffic manager
1317     // After the AI and ATC systems have been initialized properly.
1318     // AI Traffic manager
1319     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1320
1321     ////////////////////////////////////////////////////////////////////
1322     // Add a new 2D panel.
1323     ////////////////////////////////////////////////////////////////////
1324
1325     string panel_path(fgGetString("/sim/panel/path"));
1326     if (!panel_path.empty()) {
1327       FGPanel* p = fgReadPanel(panel_path);
1328       if (p) {
1329         globals->set_current_panel(p);
1330         p->init();
1331         p->bind();
1332         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1333       } else {
1334         SG_LOG( SG_INPUT, SG_ALERT,
1335                 "Error reading new panel from " << panel_path );
1336       }
1337     }
1338
1339     ////////////////////////////////////////////////////////////////////
1340     // Initialize the controls subsystem.
1341     ////////////////////////////////////////////////////////////////////
1342
1343     globals->get_controls()->init();
1344     globals->get_controls()->bind();
1345
1346
1347     ////////////////////////////////////////////////////////////////////
1348     // Initialize the input subsystem.
1349     ////////////////////////////////////////////////////////////////////
1350
1351     globals->add_subsystem("input", new FGInput);
1352
1353
1354     ////////////////////////////////////////////////////////////////////
1355     // Initialize the replay subsystem
1356     ////////////////////////////////////////////////////////////////////
1357     globals->add_subsystem("replay", new FGReplay);
1358
1359 #ifdef ENABLE_AUDIO_SUPPORT
1360     ////////////////////////////////////////////////////////////////////
1361     // Initialize the sound-effects subsystem.
1362     ////////////////////////////////////////////////////////////////////
1363     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1364 #endif
1365
1366     ////////////////////////////////////////////////////////////////////
1367     // Initialize the lighting subsystem.
1368     ////////////////////////////////////////////////////////////////////
1369
1370     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1371     
1372     // ordering here is important : Nasal (via events), then models, then views
1373     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1374     
1375     FGAircraftModel* acm = new FGAircraftModel;
1376     globals->set_aircraft_model(acm);
1377     globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1378
1379     FGModelMgr* mm = new FGModelMgr;
1380     globals->set_model_mgr(mm);
1381     globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1382
1383     FGViewMgr *viewmgr = new FGViewMgr;
1384     globals->set_viewmgr( viewmgr );
1385     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1386
1387     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
1388       SGSubsystemMgr::DISPLAY);
1389       
1390     ////////////////////////////////////////////////////////////////////
1391     // Bind and initialize subsystems.
1392     ////////////////////////////////////////////////////////////////////
1393
1394     globals->get_subsystem_mgr()->bind();
1395     globals->get_subsystem_mgr()->init();
1396
1397     ////////////////////////////////////////////////////////////////////////
1398     // Initialize the Nasal interpreter.
1399     // Do this last, so that the loaded scripts see initialized state
1400     ////////////////////////////////////////////////////////////////////////
1401     FGNasalSys* nasal = new FGNasalSys();
1402     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1403     nasal->init();
1404
1405     // initialize methods that depend on other subsystems.
1406     globals->get_subsystem_mgr()->postinit();
1407
1408     ////////////////////////////////////////////////////////////////////////
1409     // End of subsystem initialization.
1410     ////////////////////////////////////////////////////////////////////
1411
1412     fgSetBool("/sim/crashed", false);
1413     fgSetBool("/sim/initialized", true);
1414
1415     SG_LOG( SG_GENERAL, SG_INFO, endl);
1416
1417                                 // Save the initial state for future
1418                                 // reference.
1419     globals->saveInitialState();
1420     
1421     return true;
1422 }
1423
1424 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1425 void fgReInitSubsystems()
1426 {
1427     static const SGPropertyNode *master_freeze
1428         = fgGetNode("/sim/freeze/master");
1429
1430     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1431
1432 // setup state to begin re-init
1433     bool freeze = master_freeze->getBoolValue();
1434     if ( !freeze ) {
1435         fgSetBool("/sim/freeze/master", true);
1436     }
1437     
1438     fgSetBool("/sim/signals/reinit", true);
1439     fgSetBool("/sim/crashed", false);
1440
1441 // do actual re-init steps
1442     globals->get_subsystem("flight")->unbind();
1443     
1444   // reset control state, before restoring initial state; -set or config files
1445   // may specify values for flaps, trim tabs, magnetos, etc
1446     globals->get_controls()->reset_all();
1447         
1448     globals->restoreInitialState();
1449
1450     // update our position based on current presets
1451     fgInitPosition();
1452     
1453     // Force reupdating the positions of the ai 3d models. They are used for
1454     // initializing ground level for the FDM.
1455     globals->get_subsystem("ai-model")->reinit();
1456
1457     // Initialize the FDM
1458     globals->get_subsystem("flight")->reinit();
1459
1460     // reset replay buffers
1461     globals->get_subsystem("replay")->reinit();
1462     
1463     // reload offsets from config defaults
1464     globals->get_viewmgr()->reinit();
1465
1466     globals->get_subsystem("time")->reinit();
1467
1468     // need to bind FDMshell again, since we manually unbound it above...
1469     globals->get_subsystem("flight")->bind();
1470
1471 // setup state to end re-init
1472     fgSetBool("/sim/signals/reinit", false);
1473     if ( !freeze ) {
1474         fgSetBool("/sim/freeze/master", false);
1475     }
1476     fgSetBool("/sim/sceneryloaded",false);
1477 }
1478
1479
1480 ///////////////////////////////////////////////////////////////////////////////
1481 // helper object to implement the --show-aircraft command.
1482 // resides here so we can share the fgFindAircraftInDir template above,
1483 // and hence ensure this command lists exectly the same aircraft as the normal
1484 // loading path.
1485 class ShowAircraft 
1486 {
1487 public:
1488   ShowAircraft()
1489   {
1490     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1491   }
1492   
1493   
1494   void show(const SGPath& path)
1495   {
1496     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1497   
1498     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1499     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1500     cout << "Available aircraft:" << endl;
1501     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1502         cout << _aircraft[i] << endl;
1503     }
1504   }
1505   
1506 private:
1507   bool processAircraft(const SGPath& path)
1508   {
1509     SGPropertyNode root;
1510     try {
1511        readProperties(path.str(), &root);
1512     } catch (sg_exception& ) {
1513        return false;
1514     }
1515   
1516     int maturity = 0;
1517     string descStr("   ");
1518     descStr += path.file();
1519   // trim common suffix from file names
1520     int nPos = descStr.rfind("-set.xml");
1521     if (nPos == (int)(descStr.size() - 8)) {
1522       descStr.resize(nPos);
1523     }
1524     
1525     SGPropertyNode *node = root.getNode("sim");
1526     if (node) {
1527       SGPropertyNode* desc = node->getNode("description");
1528       // if a status tag is found, read it in
1529       if (node->hasValue("status")) {
1530         maturity = getNumMaturity(node->getStringValue("status"));
1531       }
1532       
1533       if (desc) {
1534         if (descStr.size() <= 27+3) {
1535           descStr.append(29+3-descStr.size(), ' ');
1536         } else {
1537           descStr += '\n';
1538           descStr.append( 32, ' ');
1539         }
1540         descStr += desc->getStringValue();
1541       }
1542     } // of have 'sim' node
1543     
1544     if (maturity < _minStatus) {
1545       return false;
1546     }
1547
1548     _aircraft.push_back(descStr);
1549     return false;
1550   }
1551
1552
1553   int getNumMaturity(const char * str) 
1554   {
1555     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1556     // $FG_ROOT/data/Translations/string-default.xml
1557     const char* levels[] = {"alpha","beta","early-production","production"}; 
1558
1559     if (!strcmp(str, "all")) {
1560       return 0;
1561     }
1562
1563     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1564       if (strcmp(str,levels[i])==0)
1565         return i;
1566
1567     return 0;
1568   }
1569
1570   // recommended in Meyers, Effective STL when internationalization and embedded
1571   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1572   struct ciLessLibC : public std::binary_function<string, string, bool>
1573   {
1574     bool operator()(const std::string &lhs, const std::string &rhs) const
1575     {
1576       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1577     }
1578   };
1579
1580   int _minStatus;
1581   string_list _aircraft;
1582 };
1583
1584 void fgShowAircraft(const SGPath &path)
1585 {
1586     ShowAircraft s;
1587     s.show(path);
1588         
1589 #ifdef _MSC_VER
1590     cout << "Hit a key to continue..." << endl;
1591     cin.get();
1592 #endif
1593 }
1594
1595