]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
a796a612f3eb7ddff64f4f355ac3d8acc3ff2e7b
[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
64 #include <Aircraft/controls.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/runways.hxx>
67 #include <Airports/simple.hxx>
68 #include <Airports/dynamics.hxx>
69
70 #include <AIModel/AIManager.hxx>
71
72 #include <ATCDCL/ATISmgr.hxx>
73 #include <ATC/atc_mgr.hxx>
74
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/autopilotgroup.hxx>
77
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
80
81 #include <Canvas/canvas_mgr.hxx>
82 #include <Canvas/gui_mgr.hxx>
83 #include <GUI/new_gui.hxx>
84 #include <Input/input.hxx>
85 #include <Instrumentation/instrument_mgr.hxx>
86 #include <Model/acmodel.hxx>
87 #include <Model/modelmgr.hxx>
88 #include <AIModel/submodel.hxx>
89 #include <AIModel/AIManager.hxx>
90 #include <Navaids/navdb.hxx>
91 #include <Navaids/navlist.hxx>
92 #include <Scenery/scenery.hxx>
93 #include <Scenery/tilemgr.hxx>
94 #include <Scripting/NasalSys.hxx>
95 #include <Sound/voice.hxx>
96 #include <Sound/soundmanager.hxx>
97 #include <Systems/system_mgr.hxx>
98 #include <Time/light.hxx>
99 #include <Traffic/TrafficMgr.hxx>
100 #include <MultiPlayer/multiplaymgr.hxx>
101 #include <FDM/fdm_shell.hxx>
102 #include <Environment/ephemeris.hxx>
103 #include <Environment/environment_mgr.hxx>
104 #include <Viewer/renderer.hxx>
105 #include <Viewer/viewmgr.hxx>
106 #include <Navaids/NavDataCache.hxx>
107
108 #include "fg_init.hxx"
109 #include "fg_io.hxx"
110 #include "fg_commands.hxx"
111 #include "fg_props.hxx"
112 #include "options.hxx"
113 #include "globals.hxx"
114 #include "logger.hxx"
115 #include "main.hxx"
116 #include "positioninit.hxx"
117
118 using std::string;
119 using namespace boost::algorithm;
120
121
122 // Return the current base package version
123 string fgBasePackageVersion() {
124     SGPath base_path( globals->get_fg_root() );
125     base_path.append("version");
126
127     sg_gzifstream in( base_path.str() );
128     if ( !in.is_open() ) {
129         SGPath old_path( globals->get_fg_root() );
130         old_path.append( "Thanks" );
131         sg_gzifstream old( old_path.str() );
132         if ( !old.is_open() ) {
133             return "[none]";
134         } else {
135             return "[old version]";
136         }
137     }
138
139     string version;
140     in >> version;
141
142     return version;
143 }
144
145
146 template <class T>
147 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
148 {
149   if (!dirPath.exists()) {
150     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
151     return false;
152   }
153     
154   bool recurse = true;
155   simgear::Dir dir(dirPath);
156   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
157   simgear::PathList::iterator p;
158   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
159     // check file name ends with -set.xml
160     
161     // if we found a -set.xml at this level, don't recurse any deeper
162     recurse = false;
163     
164     bool done = (obj->*pred)(*p);
165     if (done) {
166       return true;
167     }
168   } // of -set.xml iteration
169   
170   if (!recurse) {
171     return false;
172   }
173   
174   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
175   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
176     if (p->file() == "CVS") {
177       continue;
178     }
179     
180     if (fgFindAircraftInDir(*p, obj, pred)) {
181       return true;
182     }
183   } // of subdirs iteration
184   
185   return false;
186 }
187
188 template <class T>
189 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
190 {
191   const string_list& paths(globals->get_aircraft_paths());
192   string_list::const_iterator it = paths.begin();
193   for (; it != paths.end(); ++it) {
194     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
195     if (done) {
196       return;
197     }
198   } // of aircraft paths iteration
199   
200   // if we reach this point, search the default location (always last)
201   SGPath rootAircraft(globals->get_fg_root());
202   rootAircraft.append("Aircraft");
203   fgFindAircraftInDir(rootAircraft, obj, pred);
204 }
205
206 class FindAndCacheAircraft
207 {
208 public:
209   FindAndCacheAircraft(SGPropertyNode* autoSave)
210   {
211     _cache = autoSave->getNode("sim/startup/path-cache", true);
212   }
213   
214   bool loadAircraft()
215   {
216     std::string aircraft = fgGetString( "/sim/aircraft", "");
217     if (aircraft.empty()) {
218       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
219       return false;
220     }
221     
222     _searchAircraft = aircraft + "-set.xml";
223     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
224     if (!aircraftDir.empty()) {
225       // aircraft-dir was set, skip any searching at all, if it's valid
226       simgear::Dir acPath(aircraftDir);
227       SGPath setFile = acPath.file(_searchAircraft);
228       if (setFile.exists()) {
229         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
230         
231         try {
232           readProperties(setFile.str(), globals->get_props());
233         } catch ( const sg_exception &e ) {
234           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
235           return false;
236         }
237         
238         return true;
239       } else {
240         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
241                "' not found in specified dir:" << aircraftDir);
242         return false;
243       }
244     }
245     
246     if (!checkCache()) {
247       // prepare cache for re-scan
248       SGPropertyNode *n = _cache->getNode("fg-root", true);
249       n->setStringValue(globals->get_fg_root().c_str());
250       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
251       n = _cache->getNode("fg-aircraft", true);
252       n->setStringValue(getAircraftPaths().c_str());
253       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
254       _cache->removeChildren("aircraft");
255   
256       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
257     }
258     
259     if (_foundPath.str().empty()) {
260       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
261       return false;
262     }
263     
264     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
265     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
266     if (!_foundPath.exists()) {
267       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
268       return false;
269     }
270     
271     try {
272       readProperties(_foundPath.str(), globals->get_props());
273     } catch ( const sg_exception &e ) {
274       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
275       return false;
276     }
277     
278     return true;
279   }
280   
281 private:
282   SGPath getAircraftPaths() {
283     string_list pathList = globals->get_aircraft_paths();
284     SGPath aircraftPaths;
285     string_list::const_iterator it = pathList.begin();
286     if (it != pathList.end()) {
287         aircraftPaths.set(*it);
288         it++;
289     }
290     for (; it != pathList.end(); ++it) {
291         aircraftPaths.add(*it);
292     }
293     return aircraftPaths;
294   }
295   
296   bool checkCache()
297   {
298     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
299       return false; // cache mismatch
300     }
301
302     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
303       return false; // cache mismatch
304     }
305     
306     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
307     for (unsigned int i = 0; i < cache.size(); i++) {
308       const char *name = cache[i]->getStringValue("file", "");
309       if (!boost::equals(_searchAircraft, name, is_iequal())) {
310         continue;
311       }
312       
313       SGPath xml(cache[i]->getStringValue("path", ""));
314       xml.append(name);
315       if (xml.exists()) {
316         _foundPath = xml;
317         return true;
318       } 
319       
320       return false;
321     } // of aircraft in cache iteration
322     
323     return false;
324   }
325   
326   bool checkAircraft(const SGPath& p)
327   {
328     // create cache node
329     int i = 0;
330     while (1) {
331         if (!_cache->getChild("aircraft", i++, false))
332             break;
333     }
334     
335     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
336
337     std::string fileName(p.file());
338     n = entry->getNode("file", true);
339     n->setStringValue(fileName);
340     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
341
342     n = entry->getNode("path", true);
343     n->setStringValue(p.dir());
344     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
345
346     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
347         _foundPath = p;
348         return true;
349     }
350
351     return false;
352   }
353   
354   std::string _searchAircraft;
355   SGPath _foundPath;
356   SGPropertyNode* _cache;
357 };
358
359 #ifdef _WIN32
360 static SGPath platformDefaultDataPath()
361 {
362   char *envp = ::getenv( "APPDATA" );
363   SGPath config( envp );
364   config.append( "flightgear.org" );
365   return config;
366 }
367 #elif __APPLE__
368
369 #include <CoreServices/CoreServices.h>
370
371 static SGPath platformDefaultDataPath()
372 {
373   FSRef ref;
374   OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
375   if (err) {
376     return SGPath();
377   }
378   
379   unsigned char path[1024];
380   if (FSRefMakePath(&ref, path, 1024) != noErr) {
381     return SGPath();
382   }
383   
384   SGPath appData;
385   appData.set((const char*) path);
386   appData.append("FlightGear");
387   return appData;
388 }
389 #else
390 static SGPath platformDefaultDataPath()
391 {
392   SGPath config( homedir );
393   config.append( ".fgfs" );
394   return config;
395 }
396 #endif
397
398 // Read in configuration (file and command line)
399 bool fgInitConfig ( int argc, char **argv )
400 {
401     SGPath dataPath = platformDefaultDataPath();
402     
403     const char *fg_home = getenv("FG_HOME");
404     if (fg_home)
405       dataPath = fg_home;
406       
407     globals->set_fg_home(dataPath.c_str());
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 = globals->get_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   FGNavList::TypeFilter filter(type);
726     const nav_list_type navlist
727       = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
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::findFirstWithIdent(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   flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
824   if (cache->isRebuildRequired()) {
825     SGTimeStamp st;
826     st.stamp();
827     cache->rebuild();
828     
829     SG_LOG(SG_GENERAL, SG_INFO, "rebuilding NavDataCache took:" << st.elapsedMSec());
830   }
831   
832   FGTACANList *channellist = new FGTACANList;
833   globals->set_channellist( channellist );
834   
835   SGPath path(globals->get_fg_root());
836   path.append( "Navaids/TACAN_freq.dat" );
837   flightgear::loadTacan(path, channellist);
838   
839   return true;
840 }
841
842 // General house keeping initializations
843 bool fgInitGeneral() {
844     string root;
845
846     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
847     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
848
849     root = globals->get_fg_root();
850     if ( ! root.length() ) {
851         // No root path set? Then bail ...
852         SG_LOG( SG_GENERAL, SG_ALERT,
853                 "Cannot continue without a path to the base package "
854                 << "being defined." );
855         exit(-1);
856     }
857     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
858
859     // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
860     globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
861     fgSetString("/sim/startup/browser-app", globals->get_browser());
862
863     simgear::Dir cwd(simgear::Dir::current());
864     SGPropertyNode *curr = fgGetNode("/sim", true);
865     curr->removeChild("fg-current", 0, false);
866     curr = curr->getChild("fg-current", 0, true);
867     curr->setStringValue(cwd.path().str());
868     curr->setAttribute(SGPropertyNode::WRITE, false);
869
870     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
871     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
872     return true;
873 }
874
875 // This is the top level init routine which calls all the other
876 // initialization routines.  If you are adding a subsystem to flight
877 // gear, its initialization call should located in this routine.
878 // Returns non-zero if a problem encountered.
879 void fgCreateSubsystems() {
880
881     SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
882     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
883
884     ////////////////////////////////////////////////////////////////////
885     // Initialize the sound subsystem.
886     ////////////////////////////////////////////////////////////////////
887     // Sound manager uses an own subsystem group "SOUND" which is the last
888     // to be updated in every loop.
889     // Sound manager is updated last so it can use the CPU while the GPU
890     // is processing the scenery (doubled the frame-rate for me) -EMH-
891     globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
892
893     ////////////////////////////////////////////////////////////////////
894     // Initialize the event manager subsystem.
895     ////////////////////////////////////////////////////////////////////
896
897     globals->get_event_mgr()->init();
898     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
899
900     ////////////////////////////////////////////////////////////////////
901     // Initialize the property interpolator subsystem. Put into the INIT
902     // group because the "nasal" subsystem may need it at GENERAL take-down.
903     ////////////////////////////////////////////////////////////////////
904     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
905
906
907     ////////////////////////////////////////////////////////////////////
908     // Add the FlightGear property utilities.
909     ////////////////////////////////////////////////////////////////////
910     globals->add_subsystem("properties", new FGProperties);
911
912
913     ////////////////////////////////////////////////////////////////////
914     // Add the performance monitoring system.
915     ////////////////////////////////////////////////////////////////////
916     globals->add_subsystem("performance-mon",
917             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
918                                      fgGetNode("/sim/performance-monitor", true)));
919
920     ////////////////////////////////////////////////////////////////////
921     // Initialize the material property subsystem.
922     ////////////////////////////////////////////////////////////////////
923
924     SGPath mpath( globals->get_fg_root() );
925     mpath.append( fgGetString("/sim/rendering/materials-file") );
926     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
927             globals->get_props()) ) {
928         SG_LOG( SG_GENERAL, SG_ALERT,
929                 "Error loading materials file " << mpath.str() );
930         exit(-1);
931     }
932
933
934     ////////////////////////////////////////////////////////////////////
935     // Initialize the scenery management subsystem.
936     ////////////////////////////////////////////////////////////////////
937
938     globals->get_scenery()->get_scene_graph()
939         ->addChild(simgear::Particles::getCommonRoot());
940     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
941
942     ////////////////////////////////////////////////////////////////////
943     // Initialize the flight model subsystem.
944     ////////////////////////////////////////////////////////////////////
945
946     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
947
948     ////////////////////////////////////////////////////////////////////
949     // Initialize the weather subsystem.
950     ////////////////////////////////////////////////////////////////////
951
952     // Initialize the weather modeling subsystem
953     globals->add_subsystem("environment", new FGEnvironmentMgr);
954     globals->add_subsystem("ephemeris", new Ephemeris);
955     
956     ////////////////////////////////////////////////////////////////////
957     // Initialize the aircraft systems and instrumentation (before the
958     // autopilot.)
959     ////////////////////////////////////////////////////////////////////
960
961     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
962     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
963
964     ////////////////////////////////////////////////////////////////////
965     // Initialize the XML Autopilot subsystem.
966     ////////////////////////////////////////////////////////////////////
967
968     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
969     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
970     globals->add_subsystem( "route-manager", new FGRouteMgr );
971
972     ////////////////////////////////////////////////////////////////////
973     // Initialize the Input-Output subsystem
974     ////////////////////////////////////////////////////////////////////
975     globals->add_subsystem( "io", new FGIO );
976
977     ////////////////////////////////////////////////////////////////////
978     // Create and register the logger.
979     ////////////////////////////////////////////////////////////////////
980     
981     globals->add_subsystem("logger", new FGLogger);
982
983     ////////////////////////////////////////////////////////////////////
984     // Create and register the XML GUI.
985     ////////////////////////////////////////////////////////////////////
986
987     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
988
989     //////////////////////////////////////////////////////////////////////
990     // Initialize the 2D cloud subsystem.
991     ////////////////////////////////////////////////////////////////////
992     fgGetBool("/sim/rendering/bump-mapping", false);
993
994     ////////////////////////////////////////////////////////////////////
995     // Initialize the canvas 2d drawing subsystem.
996     ////////////////////////////////////////////////////////////////////
997     globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
998     globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
999
1000     ////////////////////////////////////////////////////////////////////
1001     // Initialise the ATIS Manager
1002     // Note that this is old stuff, but is necessary for the
1003     // current ATIS implementation. Therefore, leave it in here
1004     // until the ATIS system is ported over to make use of the ATIS 
1005     // sub system infrastructure.
1006     ////////////////////////////////////////////////////////////////////
1007
1008     globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
1009
1010     ////////////////////////////////////////////////////////////////////
1011    // Initialize the ATC subsystem
1012     ////////////////////////////////////////////////////////////////////
1013     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1014
1015     ////////////////////////////////////////////////////////////////////
1016     // Initialize multiplayer subsystem
1017     ////////////////////////////////////////////////////////////////////
1018
1019     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1020
1021     ////////////////////////////////////////////////////////////////////
1022     // Initialise the AI Model Manager
1023     ////////////////////////////////////////////////////////////////////
1024     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1025     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1026     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1027
1028
1029     // It's probably a good idea to initialize the top level traffic manager
1030     // After the AI and ATC systems have been initialized properly.
1031     // AI Traffic manager
1032     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1033
1034     ////////////////////////////////////////////////////////////////////
1035     // Add a new 2D panel.
1036     ////////////////////////////////////////////////////////////////////
1037
1038     fgSetArchivable("/sim/panel/visibility");
1039     fgSetArchivable("/sim/panel/x-offset");
1040     fgSetArchivable("/sim/panel/y-offset");
1041     fgSetArchivable("/sim/panel/jitter");
1042   
1043     ////////////////////////////////////////////////////////////////////
1044     // Initialize the controls subsystem.
1045     ////////////////////////////////////////////////////////////////////
1046
1047     globals->get_controls()->init();
1048     globals->get_controls()->bind();
1049
1050
1051     ////////////////////////////////////////////////////////////////////
1052     // Initialize the input subsystem.
1053     ////////////////////////////////////////////////////////////////////
1054
1055     globals->add_subsystem("input", new FGInput);
1056
1057
1058     ////////////////////////////////////////////////////////////////////
1059     // Initialize the replay subsystem
1060     ////////////////////////////////////////////////////////////////////
1061     globals->add_subsystem("replay", new FGReplay);
1062
1063 #ifdef ENABLE_AUDIO_SUPPORT
1064     ////////////////////////////////////////////////////////////////////
1065     // Initialize the sound-effects subsystem.
1066     ////////////////////////////////////////////////////////////////////
1067     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1068 #endif
1069
1070     ////////////////////////////////////////////////////////////////////
1071     // Initialize the lighting subsystem.
1072     ////////////////////////////////////////////////////////////////////
1073
1074     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1075     
1076     // ordering here is important : Nasal (via events), then models, then views
1077     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1078     
1079     FGAircraftModel* acm = new FGAircraftModel;
1080     globals->set_aircraft_model(acm);
1081     globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1082
1083     FGModelMgr* mm = new FGModelMgr;
1084     globals->set_model_mgr(mm);
1085     globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1086
1087     FGViewMgr *viewmgr = new FGViewMgr;
1088     globals->set_viewmgr( viewmgr );
1089     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1090
1091     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
1092       SGSubsystemMgr::DISPLAY);
1093 }
1094
1095 void fgPostInitSubsystems()
1096 {
1097     SGTimeStamp st;
1098     st.stamp();
1099   
1100     ////////////////////////////////////////////////////////////////////////
1101     // Initialize the Nasal interpreter.
1102     // Do this last, so that the loaded scripts see initialized state
1103     ////////////////////////////////////////////////////////////////////////
1104     FGNasalSys* nasal = new FGNasalSys();
1105     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1106     nasal->init();
1107     SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
1108   
1109     // initialize methods that depend on other subsystems.
1110     st.stamp();
1111     globals->get_subsystem_mgr()->postinit();
1112     SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
1113   
1114     ////////////////////////////////////////////////////////////////////
1115     // TODO FIXME! UGLY KLUDGE!
1116     ////////////////////////////////////////////////////////////////////
1117     {
1118         /* Scenarios require Nasal, so FGAIManager loads the scenarios,
1119          * including its models such as a/c carriers, in its 'postinit',
1120          * which is the very last thing we do.
1121          * fgInitPosition is called very early in main.cxx/fgIdleFunction,
1122          * one of the first things we do, long before scenarios/carriers are
1123          * loaded. => When requested "initial preset position" relates to a
1124          * carrier, recalculate the 'initial' position here (how have things
1125          * ever worked before this hack - this init sequence has always been
1126          * this way...?)*/
1127         std::string carrier = fgGetString("/sim/presets/carrier","");
1128         if (carrier != "")
1129         {
1130             // clear preset location and re-trigger position setup
1131             fgSetDouble("/sim/presets/longitude-deg", 9999);
1132             fgSetDouble("/sim/presets/latitude-deg", 9999);
1133             flightgear::initPosition();
1134         }
1135     }
1136
1137     ////////////////////////////////////////////////////////////////////////
1138     // End of subsystem initialization.
1139     ////////////////////////////////////////////////////////////////////
1140
1141     fgSetBool("/sim/crashed", false);
1142     fgSetBool("/sim/initialized", true);
1143
1144     SG_LOG( SG_GENERAL, SG_INFO, endl);
1145
1146                                 // Save the initial state for future
1147                                 // reference.
1148     globals->saveInitialState();
1149 }
1150
1151 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1152 void fgReInitSubsystems()
1153 {
1154     static const SGPropertyNode *master_freeze
1155         = fgGetNode("/sim/freeze/master");
1156
1157     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1158
1159 // setup state to begin re-init
1160     bool freeze = master_freeze->getBoolValue();
1161     if ( !freeze ) {
1162         fgSetBool("/sim/freeze/master", true);
1163     }
1164     
1165     fgSetBool("/sim/signals/reinit", true);
1166     fgSetBool("/sim/crashed", false);
1167
1168 // do actual re-init steps
1169     globals->get_subsystem("flight")->unbind();
1170     
1171   // reset control state, before restoring initial state; -set or config files
1172   // may specify values for flaps, trim tabs, magnetos, etc
1173     globals->get_controls()->reset_all();
1174         
1175     globals->restoreInitialState();
1176
1177     // update our position based on current presets
1178     flightgear::initPosition();
1179     
1180     // Force reupdating the positions of the ai 3d models. They are used for
1181     // initializing ground level for the FDM.
1182     globals->get_subsystem("ai-model")->reinit();
1183
1184     // Initialize the FDM
1185     globals->get_subsystem("flight")->reinit();
1186
1187     // reset replay buffers
1188     globals->get_subsystem("replay")->reinit();
1189     
1190     // reload offsets from config defaults
1191     globals->get_viewmgr()->reinit();
1192
1193     globals->get_subsystem("time")->reinit();
1194
1195     // need to bind FDMshell again, since we manually unbound it above...
1196     globals->get_subsystem("flight")->bind();
1197
1198 // setup state to end re-init
1199     fgSetBool("/sim/signals/reinit", false);
1200     if ( !freeze ) {
1201         fgSetBool("/sim/freeze/master", false);
1202     }
1203     fgSetBool("/sim/sceneryloaded",false);
1204 }
1205
1206
1207 ///////////////////////////////////////////////////////////////////////////////
1208 // helper object to implement the --show-aircraft command.
1209 // resides here so we can share the fgFindAircraftInDir template above,
1210 // and hence ensure this command lists exectly the same aircraft as the normal
1211 // loading path.
1212 class ShowAircraft 
1213 {
1214 public:
1215   ShowAircraft()
1216   {
1217     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1218   }
1219   
1220   
1221   void show(const SGPath& path)
1222   {
1223     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1224   
1225     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1226     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1227     cout << "Available aircraft:" << endl;
1228     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1229         cout << _aircraft[i] << endl;
1230     }
1231   }
1232   
1233 private:
1234   bool processAircraft(const SGPath& path)
1235   {
1236     SGPropertyNode root;
1237     try {
1238        readProperties(path.str(), &root);
1239     } catch (sg_exception& ) {
1240        return false;
1241     }
1242   
1243     int maturity = 0;
1244     string descStr("   ");
1245     descStr += path.file();
1246   // trim common suffix from file names
1247     int nPos = descStr.rfind("-set.xml");
1248     if (nPos == (int)(descStr.size() - 8)) {
1249       descStr.resize(nPos);
1250     }
1251     
1252     SGPropertyNode *node = root.getNode("sim");
1253     if (node) {
1254       SGPropertyNode* desc = node->getNode("description");
1255       // if a status tag is found, read it in
1256       if (node->hasValue("status")) {
1257         maturity = getNumMaturity(node->getStringValue("status"));
1258       }
1259       
1260       if (desc) {
1261         if (descStr.size() <= 27+3) {
1262           descStr.append(29+3-descStr.size(), ' ');
1263         } else {
1264           descStr += '\n';
1265           descStr.append( 32, ' ');
1266         }
1267         descStr += desc->getStringValue();
1268       }
1269     } // of have 'sim' node
1270     
1271     if (maturity < _minStatus) {
1272       return false;
1273     }
1274
1275     _aircraft.push_back(descStr);
1276     return false;
1277   }
1278
1279
1280   int getNumMaturity(const char * str) 
1281   {
1282     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1283     // $FG_ROOT/data/Translations/string-default.xml
1284     const char* levels[] = {"alpha","beta","early-production","production"}; 
1285
1286     if (!strcmp(str, "all")) {
1287       return 0;
1288     }
1289
1290     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1291       if (strcmp(str,levels[i])==0)
1292         return i;
1293
1294     return 0;
1295   }
1296
1297   // recommended in Meyers, Effective STL when internationalization and embedded
1298   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1299   struct ciLessLibC : public std::binary_function<string, string, bool>
1300   {
1301     bool operator()(const std::string &lhs, const std::string &rhs) const
1302     {
1303       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1304     }
1305   };
1306
1307   int _minStatus;
1308   string_list _aircraft;
1309 };
1310
1311 void fgShowAircraft(const SGPath &path)
1312 {
1313     ShowAircraft s;
1314     s.show(path);
1315         
1316 #ifdef _MSC_VER
1317     cout << "Hit a key to continue..." << endl;
1318     cin.get();
1319 #endif
1320 }
1321
1322