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