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