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