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