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