1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
40 # include "winsock2.h" // for gethostname()
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
46 # define _G_NO_EXTERN_TEMPLATES
49 #include <simgear/compiler.h>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/sgstream.hxx>
63 #include <simgear/misc/interpolator.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/scene/model/particles.hxx>
66 #include <simgear/sound/soundmgr_openal.hxx>
68 #include <Aircraft/controls.hxx>
69 #include <Aircraft/replay.hxx>
70 #include <Airports/apt_loader.hxx>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/dynamics.hxx>
75 #include <AIModel/AIManager.hxx>
77 #include <ATCDCL/ATCmgr.hxx>
78 #include <ATCDCL/commlist.hxx>
79 #include <ATC/atis_mgr.hxx>
81 #include <Autopilot/route_mgr.hxx>
82 #include <Autopilot/autopilotgroup.hxx>
84 #include <Cockpit/panel.hxx>
85 #include <Cockpit/panel_io.hxx>
87 #include <GUI/new_gui.hxx>
88 #include <Input/input.hxx>
89 #include <Instrumentation/instrument_mgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <AIModel/submodel.hxx>
93 #include <AIModel/AIManager.hxx>
94 #include <Navaids/navdb.hxx>
95 #include <Navaids/navlist.hxx>
96 #include <Navaids/fix.hxx>
97 #include <Navaids/fixlist.hxx>
98 #include <Navaids/airways.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/tilemgr.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/voice.hxx>
103 #include <Systems/system_mgr.hxx>
104 #include <Time/light.hxx>
105 #include <Traffic/TrafficMgr.hxx>
106 #include <MultiPlayer/multiplaymgr.hxx>
107 #include <FDM/fdm_shell.hxx>
109 #include <Environment/environment_mgr.hxx>
111 #include "fg_init.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 "renderer.hxx"
119 #include "viewmgr.hxx"
124 # include <CoreFoundation/CoreFoundation.h>
128 using namespace boost::algorithm;
130 extern const char *default_root;
133 // Scan the command line options for the specified option and return
135 static string fgScanForOption( const string& option, int argc, char **argv ) {
138 if (hostname == NULL)
141 if( gethostname(_hostname, 256) >= 0 ) {
142 hostname = strdup(_hostname);
143 free_hostname = true;
147 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
149 int len = option.length();
152 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
154 string arg = argv[i];
155 if ( arg.find( option ) == 0 ) {
156 return arg.substr( len );
166 // Scan the user config files for the specified option and return
168 static string fgScanForOption( const string& option, const string& path ) {
169 sg_gzifstream in( path );
170 if ( !in.is_open() ) {
174 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
176 int len = option.length();
179 while ( ! in.eof() ) {
181 getline( in, line, '\n' );
183 // catch extraneous (DOS) line ending character
184 if ( line[line.length() - 1] < 32 ) {
185 line = line.substr( 0, line.length()-1 );
188 if ( line.find( option ) == 0 ) {
189 return line.substr( len );
198 // Scan the user config files for the specified option and return
200 static string fgScanForOption( const string& option ) {
203 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
204 // Next check home directory for .fgfsrc.hostname file
206 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
207 SGPath config( homedir );
208 config.append( ".fgfsrc" );
209 config.concat( "." );
210 config.concat( hostname );
211 arg = fgScanForOption( option, config.str() );
216 // Next check home directory for .fgfsrc file
218 if ( homedir != NULL ) {
219 SGPath config( homedir );
220 config.append( ".fgfsrc" );
221 arg = fgScanForOption( option, config.str() );
226 // Check for $fg_root/system.fgfsrc
227 SGPath config( globals->get_fg_root() );
228 config.append( "system.fgfsrc" );
229 arg = fgScanForOption( option, config.str() );
236 // Read in configuration (files and command line options) but only set
237 // fg_root and aircraft_paths, which are needed *before* do_options() is called
240 bool fgInitFGRoot ( int argc, char **argv ) {
243 // First parse command line options looking for --fg-root=, this
244 // will override anything specified in a config file
245 root = fgScanForOption( "--fg-root=", argc, argv);
247 // Check in one of the user configuration files.
249 root = fgScanForOption( "--fg-root=" );
251 // Next check if fg-root is set as an env variable
252 if ( root.empty() ) {
253 char *envp = ::getenv( "FG_ROOT" );
254 if ( envp != NULL ) {
259 // Otherwise, default to a random compiled-in location if we can't
260 // find fg-root any other way.
261 if ( root.empty() ) {
262 #if defined( __CYGWIN__ )
264 #elif defined( _WIN32 )
266 #elif defined(__APPLE__)
268 The following code looks for the base package inside the application
269 bundle, in the standard Contents/Resources location.
271 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
273 // look for a 'data' subdir
274 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
276 // now convert down to a path, and the a c-string
277 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
278 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
280 CFRelease(resourcesUrl);
288 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
289 globals->set_fg_root(root);
295 // Read in configuration (files and command line options) but only set
297 bool fgInitFGAircraft ( int argc, char **argv ) {
299 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
300 if (aircraftDir.empty()) {
301 aircraftDir = fgScanForOption("--fg-aircraft=");
304 const char* envp = ::getenv("FG_AIRCRAFT");
305 if (aircraftDir.empty() && envp) {
306 globals->append_aircraft_paths(envp);
309 if (!aircraftDir.empty()) {
310 globals->append_aircraft_paths(aircraftDir);
315 // First parse command line options looking for --aircraft=, this
316 // will override anything specified in a config file
317 aircraft = fgScanForOption( "--aircraft=", argc, argv );
318 if ( aircraft.empty() ) {
319 // check synonym option
320 aircraft = fgScanForOption( "--vehicle=", argc, argv );
323 // Check in one of the user configuration files.
324 if ( aircraft.empty() ) {
325 aircraft = fgScanForOption( "--aircraft=" );
327 if ( aircraft.empty() ) {
328 aircraft = fgScanForOption( "--vehicle=" );
331 // if an aircraft was specified, set the property name
332 if ( !aircraft.empty() ) {
333 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
334 fgSetString("/sim/aircraft", aircraft.c_str() );
336 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
343 // Return the current base package version
344 string fgBasePackageVersion() {
345 SGPath base_path( globals->get_fg_root() );
346 base_path.append("version");
348 sg_gzifstream in( base_path.str() );
349 if ( !in.is_open() ) {
350 SGPath old_path( globals->get_fg_root() );
351 old_path.append( "Thanks" );
352 sg_gzifstream old( old_path.str() );
353 if ( !old.is_open() ) {
356 return "[old version]";
367 // Initialize the localization
368 SGPropertyNode *fgInitLocale(const char *language) {
369 SGPropertyNode *c_node = NULL, *d_node = NULL;
370 SGPropertyNode *intl = fgGetNode("/sim/intl");
372 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
374 // localization not defined
379 // Select the proper language from the list
381 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
382 for (unsigned int i = 0; i < locale.size(); i++) {
384 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
385 for (unsigned int j = 0; j < lang.size(); j++) {
387 if (!strcmp(lang[j]->getStringValue(), language)) {
396 d_node = intl->getChild("locale");
400 // Check for localized font
401 SGPropertyNode *font_n = c_node->getNode("font", true);
402 if ( !strcmp(font_n->getStringValue(), "") )
403 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
407 // Load the default strings
409 SGPath d_path( globals->get_fg_root() );
411 const char *d_path_str = d_node->getStringValue("strings");
413 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
417 d_path.append(d_path_str);
418 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
420 SGPropertyNode *strings = c_node->getNode("strings");
422 readProperties(d_path.str(), strings);
423 } catch (const sg_exception &) {
424 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
429 // Load the language specific strings
431 if (c_node != d_node) {
432 SGPath c_path( globals->get_fg_root() );
434 const char *c_path_str = c_node->getStringValue("strings");
436 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
440 c_path.append(c_path_str);
441 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
444 readProperties(c_path.str(), strings);
445 } catch (const sg_exception &) {
446 SG_LOG(SG_GENERAL, SG_ALERT,
447 "Unable to read the localized strings from " << c_path.str());
457 // Initialize the localization routines
458 bool fgDetectLanguage() {
459 const char *language = ::getenv("LANG");
461 if (language == NULL) {
462 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
466 SGPropertyNode *locale = fgInitLocale(language);
468 SG_LOG(SG_GENERAL, SG_ALERT,
469 "No internationalization settings specified in preferences.xml" );
474 globals->set_locale( locale );
479 // Attempt to locate and parse the various non-XML config files in order
480 // from least precidence to greatest precidence
482 do_options (int argc, char ** argv)
484 // Check for $fg_root/system.fgfsrc
485 SGPath config( globals->get_fg_root() );
486 config.append( "system.fgfsrc" );
487 fgParseOptions(config.str());
489 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
490 if( hostname != NULL && strlen(hostname) > 0 ) {
491 config.concat( "." );
492 config.concat( hostname );
493 fgParseOptions(config.str());
497 // Check for ~/.fgfsrc
498 if ( homedir != NULL ) {
499 config.set( homedir );
500 config.append( ".fgfsrc" );
501 fgParseOptions(config.str());
504 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
505 if( hostname != NULL && strlen(hostname) > 0 ) {
506 // Check for ~/.fgfsrc.hostname
507 config.concat( "." );
508 config.concat( hostname );
509 fgParseOptions(config.str());
513 // Parse remaining command line options
514 // These will override anything specified in a config file
515 fgParseArgs(argc, argv);
519 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
521 if (!dirPath.exists()) {
522 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
527 simgear::Dir dir(dirPath);
528 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
529 simgear::PathList::iterator p;
530 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
531 // check file name ends with -set.xml
533 // if we found a -set.xml at this level, don't recurse any deeper
536 bool done = (obj->*pred)(*p);
540 } // of -set.xml iteration
546 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
547 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
548 if (p->file() == "CVS") {
552 if (fgFindAircraftInDir(*p, obj, pred)) {
555 } // of subdirs iteration
561 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
563 const string_list& paths(globals->get_aircraft_paths());
564 string_list::const_iterator it = paths.begin();
565 for (; it != paths.end(); ++it) {
566 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
570 } // of aircraft paths iteration
572 // if we reach this point, search the default location (always last)
573 SGPath rootAircraft(globals->get_fg_root());
574 rootAircraft.append("Aircraft");
575 fgFindAircraftInDir(rootAircraft, obj, pred);
578 class FindAndCacheAircraft
581 FindAndCacheAircraft(SGPropertyNode* autoSave)
583 _cache = autoSave->getNode("sim/startup/path-cache", true);
588 std::string aircraft = fgGetString( "/sim/aircraft", "");
589 if (aircraft.empty()) {
590 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
594 _searchAircraft = aircraft + "-set.xml";
596 // prepare cache for re-scan
597 SGPropertyNode *n = _cache->getNode("fg-root", true);
598 n->setStringValue(globals->get_fg_root().c_str());
599 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
600 n = _cache->getNode("fg-aircraft", true);
601 n->setStringValue(getAircraftPaths().c_str());
602 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
603 _cache->removeChildren("aircraft");
605 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
608 if (_foundPath.str().empty()) {
609 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
613 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
614 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
615 if (!_foundPath.exists()) {
616 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
621 readProperties(_foundPath.str(), globals->get_props());
622 } catch ( const sg_exception &e ) {
623 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
631 SGPath getAircraftPaths() {
632 string_list pathList = globals->get_aircraft_paths();
633 SGPath aircraftPaths;
634 string_list::const_iterator it = pathList.begin();
635 if (it != pathList.end()) {
636 aircraftPaths.set(*it);
639 for (; it != pathList.end(); ++it) {
640 aircraftPaths.add(*it);
642 return aircraftPaths;
647 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
648 return false; // cache mismatch
651 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
652 return false; // cache mismatch
655 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
656 for (unsigned int i = 0; i < cache.size(); i++) {
657 const char *name = cache[i]->getStringValue("file", "");
658 if (!boost::equals(_searchAircraft, name, is_iequal())) {
662 SGPath xml(cache[i]->getStringValue("path", ""));
670 } // of aircraft in cache iteration
675 bool checkAircraft(const SGPath& p)
680 if (!_cache->getChild("aircraft", i++, false))
684 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
686 std::string fileName(p.file());
687 n = entry->getNode("file", true);
688 n->setStringValue(fileName);
689 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
691 n = entry->getNode("path", true);
692 n->setStringValue(p.dir());
693 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
695 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
703 std::string _searchAircraft;
705 SGPropertyNode* _cache;
708 // Read in configuration (file and command line)
709 bool fgInitConfig ( int argc, char **argv ) {
711 // First, set some sane default values
714 // Read global preferences from $FG_ROOT/preferences.xml
715 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
716 fgLoadProps("preferences.xml", globals->get_props());
717 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
719 // Detect the required language as early as possible
720 if ( !fgDetectLanguage() ) {
724 SGPropertyNode autosave;
726 char *envp = ::getenv( "APPDATA" );
728 SGPath config( envp );
729 config.append( "flightgear.org" );
731 if ( homedir != NULL ) {
732 SGPath config( homedir );
733 config.append( ".fgfs" );
735 const char *fg_home = getenv("FG_HOME");
739 SGPath home_export(config.str());
740 home_export.append("Export/dummy");
741 home_export.create_dir(0777);
743 // Set /sim/fg-home and don't allow malign code to override it until
744 // Nasal security is set up. Use FG_HOME if necessary.
745 SGPropertyNode *home = fgGetNode("/sim", true);
746 home->removeChild("fg-home", 0, false);
747 home = home->getChild("fg-home", 0, true);
748 home->setStringValue(config.c_str());
749 home->setAttribute(SGPropertyNode::WRITE, false);
751 config.append( "autosave.xml" );
752 if (config.exists()) {
753 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
755 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
756 } catch (sg_exception& e) {
757 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
758 << "(from " << e.getOrigin() << ")");
763 // Scan user config files and command line for a specified aircraft.
764 fgInitFGAircraft(argc, argv);
765 FindAndCacheAircraft f(&autosave);
766 if (!f.loadAircraft()) {
770 copyProperties(&autosave, globals->get_props());
772 // parse options after loading aircraft to ensure any user
773 // overrides of defaults are honored.
774 do_options(argc, argv);
779 // Set current tower position lon/lat given an airport id
780 static bool fgSetTowerPosFromAirportID( const string& id) {
781 const FGAirport *a = fgFindAirportID( id);
783 SGGeod tower = a->getTowerLocation();
784 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
785 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
786 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
794 struct FGTowerLocationListener : SGPropertyChangeListener {
795 void valueChanged(SGPropertyNode* node) {
796 const string id(node->getStringValue());
797 fgSetTowerPosFromAirportID(id);
801 void fgInitTowerLocationListener() {
802 fgGetNode("/sim/tower/airport-id", true)
803 ->addChangeListener( new FGTowerLocationListener(), true );
806 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
808 SGGeod startPos(aStartPos);
809 if (aTargetHeading == HUGE_VAL) {
810 aTargetHeading = aHeading;
813 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
814 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
815 offsetDistance *= SG_NM_TO_METER;
816 double offsetAzimuth = aHeading;
817 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
818 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
819 aHeading = aTargetHeading;
824 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
829 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
830 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
831 fgSetDouble("/sim/presets/heading-deg", aHeading );
833 // other code depends on the actual values being set ...
834 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
835 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
836 fgSetDouble("/orientation/heading-deg", aHeading );
839 // Set current_options lon/lat given an airport id and heading (degrees)
840 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
844 // set initial position from runway and heading
845 SG_LOG( SG_GENERAL, SG_INFO,
846 "Attempting to set starting position from airport code "
847 << id << " heading " << tgt_hdg );
849 const FGAirport* apt = fgFindAirportID(id);
850 if (!apt) return false;
851 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
852 fgSetString("/sim/atc/runway", r->ident().c_str());
854 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
855 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
859 // Set current_options lon/lat given an airport id and parkig position name
860 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
864 // can't see an easy way around this const_cast at the moment
865 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
867 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
870 FGAirportDynamics* dcs = apt->getDynamics();
872 SG_LOG( SG_GENERAL, SG_ALERT,
873 "Failed to find parking position " << parkpos <<
874 " at airport " << id );
878 int park_index = dcs->getNrOfParkings() - 1;
879 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
880 if (park_index < 0) {
881 SG_LOG( SG_GENERAL, SG_ALERT,
882 "Failed to find parking position " << parkpos <<
883 " at airport " << id );
886 FGParking* parking = dcs->getParking(park_index);
887 parking->setAvailable(false);
889 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
890 parking->getHeading());
895 // Set current_options lon/lat given an airport id and runway number
896 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
900 // set initial position from airport and runway number
901 SG_LOG( SG_GENERAL, SG_INFO,
902 "Attempting to set starting position for "
903 << id << ":" << rwy );
905 const FGAirport* apt = fgFindAirportID(id);
907 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
911 if (!apt->hasRunwayWithIdent(rwy)) {
912 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
913 "Failed to find runway " << rwy <<
914 " at airport " << id << ". Using default runway." );
918 FGRunway* r(apt->getRunwayByIdent(rwy));
919 fgSetString("/sim/atc/runway", r->ident().c_str());
920 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
921 fgApplyStartOffset(startPos, r->headingDeg());
926 static void fgSetDistOrAltFromGlideSlope() {
927 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
928 string apt_id = fgGetString("/sim/presets/airport-id");
929 double gs = fgGetDouble("/sim/presets/glideslope-deg")
930 * SG_DEGREES_TO_RADIANS ;
931 double od = fgGetDouble("/sim/presets/offset-distance-nm");
932 double alt = fgGetDouble("/sim/presets/altitude-ft");
934 double apt_elev = 0.0;
935 if ( ! apt_id.empty() ) {
936 apt_elev = fgGetAirportElev( apt_id );
937 if ( apt_elev < -9990.0 ) {
944 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
945 // set altitude from glideslope and offset-distance
946 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
947 alt = fabs(od*tan(gs)) + apt_elev;
948 fgSetDouble("/sim/presets/altitude-ft", alt);
949 fgSetBool("/sim/presets/onground", false);
950 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
952 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
953 // set offset-distance from glideslope and altitude
954 od = (alt - apt_elev) / tan(gs);
955 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
956 fgSetDouble("/sim/presets/offset-distance-nm", od);
957 fgSetBool("/sim/presets/onground", false);
958 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
960 } else if( fabs(gs) > 0.01 ) {
961 SG_LOG( SG_GENERAL, SG_ALERT,
962 "Glideslope given but not altitude or offset-distance." );
963 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
964 fgSetDouble("/sim/presets/glideslope-deg", 0);
965 fgSetBool("/sim/presets/onground", true);
970 // Set current_options lon/lat given an airport id and heading (degrees)
971 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
973 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
976 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
977 << id << ":" << freq );
981 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
985 // Set current_options lon/lat given an aircraft carrier id
986 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
988 // set initial position from runway and heading
992 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
993 double lon = geodPos.getLongitudeDeg();
994 double lat = geodPos.getLatitudeDeg();
995 double alt = geodPos.getElevationFt();
997 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
998 << carrier << " at lat = " << lat << ", lon = " << lon
999 << ", alt = " << alt << ", heading = " << heading);
1001 fgSetDouble("/sim/presets/longitude-deg", lon);
1002 fgSetDouble("/sim/presets/latitude-deg", lat);
1003 fgSetDouble("/sim/presets/altitude-ft", alt);
1004 fgSetDouble("/sim/presets/heading-deg", heading);
1005 fgSetDouble("/position/longitude-deg", lon);
1006 fgSetDouble("/position/latitude-deg", lat);
1007 fgSetDouble("/position/altitude-ft", alt);
1008 fgSetDouble("/orientation/heading-deg", heading);
1010 fgSetString("/sim/presets/speed-set", "UVW");
1011 fgSetDouble("/velocities/uBody-fps", uvw(0));
1012 fgSetDouble("/velocities/vBody-fps", uvw(1));
1013 fgSetDouble("/velocities/wBody-fps", uvw(2));
1014 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1015 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1016 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1018 fgSetBool("/sim/presets/onground", true);
1022 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1028 // Set current_options lon/lat given an airport id and heading (degrees)
1029 static bool fgSetPosFromFix( const string& id )
1031 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1032 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1034 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1038 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1043 * Initialize vor/ndb/ils/fix list management and query systems (as
1044 * well as simple airport db list)
1049 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1051 SGPath aptdb( globals->get_fg_root() );
1052 aptdb.append( "Airports/apt.dat" );
1054 SGPath p_metar( globals->get_fg_root() );
1055 p_metar.append( "Airports/metar.dat" );
1057 // Initialise the frequency search map BEFORE reading
1058 // the airport database:
1062 current_commlist = new FGCommList;
1063 current_commlist->init( globals->get_fg_root() );
1064 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1066 FGNavList *navlist = new FGNavList;
1067 FGNavList *loclist = new FGNavList;
1068 FGNavList *gslist = new FGNavList;
1069 FGNavList *dmelist = new FGNavList;
1070 FGNavList *tacanlist = new FGNavList;
1071 FGNavList *carrierlist = new FGNavList;
1072 FGTACANList *channellist = new FGTACANList;
1074 globals->set_navlist( navlist );
1075 globals->set_loclist( loclist );
1076 globals->set_gslist( gslist );
1077 globals->set_dmelist( dmelist );
1078 globals->set_tacanlist( tacanlist );
1079 globals->set_carrierlist( carrierlist );
1080 globals->set_channellist( channellist );
1082 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1083 SG_LOG( SG_GENERAL, SG_ALERT,
1084 "Problems loading one or more navigational database" );
1087 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1088 SGPath p_fix( globals->get_fg_root() );
1089 p_fix.append( "Navaids/fix.dat" );
1091 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1093 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1094 flightgear::Airway::load();
1100 // Set the initial position based on presets (or defaults)
1101 bool fgInitPosition() {
1102 // cout << "fgInitPosition()" << endl;
1103 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1104 * SG_DEGREES_TO_RADIANS ;
1105 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1106 double alt = fgGetDouble("/sim/presets/altitude-ft");
1108 bool set_pos = false;
1110 // If glideslope is specified, then calculate offset-distance or
1111 // altitude relative to glide slope if either of those was not
1113 if ( fabs( gs ) > 0.01 ) {
1114 fgSetDistOrAltFromGlideSlope();
1118 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1119 // If not, check for an airport-id and use that.
1120 // If not, default to the middle of the KSFO field.
1121 // The default values for lon/lat are deliberately out of range
1122 // so that the airport-id can take effect; valid lon/lat will
1123 // override airport-id, however.
1124 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1125 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1126 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1127 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1132 string apt = fgGetString("/sim/presets/airport-id");
1133 string rwy_no = fgGetString("/sim/presets/runway");
1134 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1135 string vor = fgGetString("/sim/presets/vor-id");
1136 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1137 string ndb = fgGetString("/sim/presets/ndb-id");
1138 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1139 string carrier = fgGetString("/sim/presets/carrier");
1140 string parkpos = fgGetString("/sim/presets/parkpos");
1141 string fix = fgGetString("/sim/presets/fix");
1142 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1143 double hdg = hdg_preset->getDoubleValue();
1145 // save some start parameters, so that we can later say what the
1146 // user really requested. TODO generalize that and move it to options.cxx
1147 static bool start_options_saved = false;
1148 if (!start_options_saved) {
1149 start_options_saved = true;
1150 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1152 opt->setDoubleValue("latitude-deg", lat_deg);
1153 opt->setDoubleValue("longitude-deg", lon_deg);
1154 opt->setDoubleValue("heading-deg", hdg);
1155 opt->setStringValue("airport", apt.c_str());
1156 opt->setStringValue("runway", rwy_no.c_str());
1160 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1162 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1163 // An airport + parking position is requested
1164 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1165 // set tower position
1166 fgSetString("/sim/tower/airport-id", apt.c_str());
1171 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1172 // An airport + runway is requested
1173 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1174 // set tower position (a little off the heading for single
1176 fgSetString("/sim/tower/airport-id", apt.c_str());
1181 if ( !set_pos && !apt.empty() ) {
1182 // An airport is requested (find runway closest to hdg)
1183 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1184 // set tower position (a little off the heading for single
1186 fgSetString("/sim/tower/airport-id", apt.c_str());
1191 if (hdg_preset->getDoubleValue() > 9990.0)
1192 hdg_preset->setDoubleValue(hdg);
1194 if ( !set_pos && !vor.empty() ) {
1195 // a VOR is requested
1196 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1201 if ( !set_pos && !ndb.empty() ) {
1202 // an NDB is requested
1203 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1208 if ( !set_pos && !carrier.empty() ) {
1209 // an aircraft carrier is requested
1210 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1215 if ( !set_pos && !fix.empty() ) {
1216 // a Fix is requested
1217 if ( fgSetPosFromFix( fix ) ) {
1223 // No lon/lat specified, no airport specified, default to
1224 // middle of KSFO field.
1225 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1226 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1229 fgSetDouble( "/position/longitude-deg",
1230 fgGetDouble("/sim/presets/longitude-deg") );
1231 fgSetDouble( "/position/latitude-deg",
1232 fgGetDouble("/sim/presets/latitude-deg") );
1233 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1235 // determine if this should be an on-ground or in-air start
1236 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1237 fgSetBool("/sim/presets/onground", false);
1239 fgSetBool("/sim/presets/onground", true);
1246 // General house keeping initializations
1247 bool fgInitGeneral() {
1250 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1251 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1253 root = globals->get_fg_root();
1254 if ( ! root.length() ) {
1255 // No root path set? Then bail ...
1256 SG_LOG( SG_GENERAL, SG_ALERT,
1257 "Cannot continue without a path to the base package "
1258 << "being defined." );
1261 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1263 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1265 char buf[512], *cwd = getcwd(buf, 511);
1267 SGPropertyNode *curr = fgGetNode("/sim", true);
1268 curr->removeChild("fg-current", 0, false);
1269 curr = curr->getChild("fg-current", 0, true);
1270 curr->setStringValue(cwd ? cwd : "");
1271 curr->setAttribute(SGPropertyNode::WRITE, false);
1273 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1274 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1278 // This is the top level init routine which calls all the other
1279 // initialization routines. If you are adding a subsystem to flight
1280 // gear, its initialization call should located in this routine.
1281 // Returns non-zero if a problem encountered.
1282 bool fgInitSubsystems() {
1283 // static const SGPropertyNode *longitude
1284 // = fgGetNode("/sim/presets/longitude-deg");
1285 // static const SGPropertyNode *latitude
1286 // = fgGetNode("/sim/presets/latitude-deg");
1287 // static const SGPropertyNode *altitude
1288 // = fgGetNode("/sim/presets/altitude-ft");
1290 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1291 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1293 ////////////////////////////////////////////////////////////////////
1294 // Initialize the event manager subsystem.
1295 ////////////////////////////////////////////////////////////////////
1297 globals->get_event_mgr()->init();
1298 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1300 ////////////////////////////////////////////////////////////////////
1301 // Initialize the property interpolator subsystem. Put into the INIT
1302 // group because the "nasal" subsystem may need it at GENERAL take-down.
1303 ////////////////////////////////////////////////////////////////////
1304 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1307 ////////////////////////////////////////////////////////////////////
1308 // Add the FlightGear property utilities.
1309 ////////////////////////////////////////////////////////////////////
1310 globals->add_subsystem("properties", new FGProperties);
1312 ////////////////////////////////////////////////////////////////////
1313 // Initialize the material property subsystem.
1314 ////////////////////////////////////////////////////////////////////
1316 SGPath mpath( globals->get_fg_root() );
1317 mpath.append( "materials.xml" );
1318 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1319 globals->get_props()) ) {
1320 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1325 ////////////////////////////////////////////////////////////////////
1326 // Initialize the scenery management subsystem.
1327 ////////////////////////////////////////////////////////////////////
1329 globals->get_scenery()->get_scene_graph()
1330 ->addChild(simgear::Particles::getCommonRoot());
1331 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1333 ////////////////////////////////////////////////////////////////////
1334 // Initialize the flight model subsystem.
1335 ////////////////////////////////////////////////////////////////////
1337 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1339 ////////////////////////////////////////////////////////////////////
1340 // Initialize the weather subsystem.
1341 ////////////////////////////////////////////////////////////////////
1343 // Initialize the weather modeling subsystem
1344 globals->add_subsystem("environment", new FGEnvironmentMgr);
1346 ////////////////////////////////////////////////////////////////////
1347 // Initialize the aircraft systems and instrumentation (before the
1349 ////////////////////////////////////////////////////////////////////
1351 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1352 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1354 ////////////////////////////////////////////////////////////////////
1355 // Initialize the XML Autopilot subsystem.
1356 ////////////////////////////////////////////////////////////////////
1358 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1359 globals->add_subsystem( "route-manager", new FGRouteMgr );
1361 ////////////////////////////////////////////////////////////////////
1362 // Initialize the Input-Output subsystem
1363 ////////////////////////////////////////////////////////////////////
1364 globals->add_subsystem( "io", new FGIO );
1366 ////////////////////////////////////////////////////////////////////
1367 // Create and register the logger.
1368 ////////////////////////////////////////////////////////////////////
1370 globals->add_subsystem("logger", new FGLogger);
1372 ////////////////////////////////////////////////////////////////////
1373 // Create and register the XML GUI.
1374 ////////////////////////////////////////////////////////////////////
1376 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1378 //////////////////////////////////////////////////////////////////////
1379 // Initialize the 2D cloud subsystem.
1380 ////////////////////////////////////////////////////////////////////
1381 fgGetBool("/sim/rendering/bump-mapping", false);
1385 ////////////////////////////////////////////////////////////////////
1386 // Initialise the ATC Manager
1387 ////////////////////////////////////////////////////////////////////
1389 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1390 globals->set_ATC_mgr(new FGATCMgr);
1391 globals->get_ATC_mgr()->init();
1393 ////////////////////////////////////////////////////////////////////
1394 // Initialise the ATIS Manager
1395 ////////////////////////////////////////////////////////////////////
1396 globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1399 ////////////////////////////////////////////////////////////////////
1400 // Initialize multiplayer subsystem
1401 ////////////////////////////////////////////////////////////////////
1403 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1405 ////////////////////////////////////////////////////////////////////
1406 // Initialise the AI Model Manager
1407 ////////////////////////////////////////////////////////////////////
1408 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1409 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1410 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1413 // It's probably a good idea to initialize the top level traffic manager
1414 // After the AI and ATC systems have been initialized properly.
1415 // AI Traffic manager
1416 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1418 ////////////////////////////////////////////////////////////////////
1419 // Add a new 2D panel.
1420 ////////////////////////////////////////////////////////////////////
1422 string panel_path(fgGetString("/sim/panel/path"));
1423 if (!panel_path.empty()) {
1424 FGPanel* p = fgReadPanel(panel_path);
1426 globals->set_current_panel(p);
1429 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1431 SG_LOG( SG_INPUT, SG_ALERT,
1432 "Error reading new panel from " << panel_path );
1436 ////////////////////////////////////////////////////////////////////
1437 // Initialize the controls subsystem.
1438 ////////////////////////////////////////////////////////////////////
1440 globals->get_controls()->init();
1441 globals->get_controls()->bind();
1444 ////////////////////////////////////////////////////////////////////
1445 // Initialize the input subsystem.
1446 ////////////////////////////////////////////////////////////////////
1448 globals->add_subsystem("input", new FGInput);
1451 ////////////////////////////////////////////////////////////////////
1452 // Initialize the replay subsystem
1453 ////////////////////////////////////////////////////////////////////
1454 globals->add_subsystem("replay", new FGReplay);
1456 #ifdef ENABLE_AUDIO_SUPPORT
1457 ////////////////////////////////////////////////////////////////////
1458 // Initialize the sound-effects subsystem.
1459 ////////////////////////////////////////////////////////////////////
1460 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1463 ////////////////////////////////////////////////////////////////////
1464 // Initialize the lighting subsystem.
1465 ////////////////////////////////////////////////////////////////////
1467 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1469 // ordering here is important : Nasal (via events), then models, then views
1470 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1472 FGAircraftModel* acm = new FGAircraftModel;
1473 globals->set_aircraft_model(acm);
1474 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1476 FGModelMgr* mm = new FGModelMgr;
1477 globals->set_model_mgr(mm);
1478 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1480 FGViewMgr *viewmgr = new FGViewMgr;
1481 globals->set_viewmgr( viewmgr );
1482 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1484 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1485 SGSubsystemMgr::DISPLAY);
1487 ////////////////////////////////////////////////////////////////////
1488 // Bind and initialize subsystems.
1489 ////////////////////////////////////////////////////////////////////
1491 globals->get_subsystem_mgr()->bind();
1492 globals->get_subsystem_mgr()->init();
1494 ////////////////////////////////////////////////////////////////////////
1495 // Initialize the Nasal interpreter.
1496 // Do this last, so that the loaded scripts see initialized state
1497 ////////////////////////////////////////////////////////////////////////
1498 FGNasalSys* nasal = new FGNasalSys();
1499 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1502 // initialize methods that depend on other subsystems.
1503 globals->get_subsystem_mgr()->postinit();
1505 ////////////////////////////////////////////////////////////////////////
1506 // End of subsystem initialization.
1507 ////////////////////////////////////////////////////////////////////
1509 fgSetBool("/sim/initialized", true);
1511 SG_LOG( SG_GENERAL, SG_INFO, endl);
1513 // Save the initial state for future
1515 globals->saveInitialState();
1520 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1521 void fgReInitSubsystems()
1523 static const SGPropertyNode *master_freeze
1524 = fgGetNode("/sim/freeze/master");
1526 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1528 // setup state to begin re-init
1529 bool freeze = master_freeze->getBoolValue();
1531 fgSetBool("/sim/freeze/master", true);
1534 fgSetBool("/sim/signals/reinit", true);
1535 fgSetBool("/sim/crashed", false);
1537 // do actual re-init steps
1538 globals->get_subsystem("flight")->unbind();
1540 // reset control state, before restoring initial state; -set or config files
1541 // may specify values for flaps, trim tabs, magnetos, etc
1542 globals->get_controls()->reset_all();
1544 globals->restoreInitialState();
1546 // update our position based on current presets
1549 // Force reupdating the positions of the ai 3d models. They are used for
1550 // initializing ground level for the FDM.
1551 globals->get_subsystem("ai_model")->reinit();
1553 // Initialize the FDM
1554 globals->get_subsystem("flight")->reinit();
1556 // reset replay buffers
1557 globals->get_subsystem("replay")->reinit();
1559 // reload offsets from config defaults
1560 globals->get_viewmgr()->reinit();
1562 globals->get_subsystem("time")->reinit();
1564 // setup state to end re-init
1565 fgSetBool("/sim/signals/reinit", false);
1567 fgSetBool("/sim/freeze/master", false);
1569 fgSetBool("/sim/sceneryloaded",false);
1573 ///////////////////////////////////////////////////////////////////////////////
1574 // helper object to implement the --show-aircraft command.
1575 // resides here so we can share the fgFindAircraftInDir template above,
1576 // and hence ensure this command lists exectly the same aircraft as the normal
1583 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1587 void show(const SGPath& path)
1589 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1591 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1592 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1593 cout << "Available aircraft:" << endl;
1594 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1595 cout << _aircraft[i] << endl;
1600 bool processAircraft(const SGPath& path)
1602 SGPropertyNode root;
1604 readProperties(path.str(), &root);
1605 } catch (sg_exception& ) {
1610 string descStr(" ");
1611 descStr += path.file();
1612 // trim common suffix from file names
1613 int nPos = descStr.rfind("-set.xml");
1614 if (nPos == (int)(descStr.size() - 8)) {
1615 descStr.resize(nPos);
1618 SGPropertyNode *node = root.getNode("sim");
1620 SGPropertyNode* desc = node->getNode("description");
1621 // if a status tag is found, read it in
1622 if (node->hasValue("status")) {
1623 maturity = getNumMaturity(node->getStringValue("status"));
1627 if (descStr.size() <= 27+3) {
1628 descStr.append(29+3-descStr.size(), ' ');
1631 descStr.append( 32, ' ');
1633 descStr += desc->getStringValue();
1635 } // of have 'sim' node
1637 if (maturity < _minStatus) {
1641 _aircraft.push_back(descStr);
1646 int getNumMaturity(const char * str)
1648 // changes should also be reflected in $FG_ROOT/data/options.xml &
1649 // $FG_ROOT/data/Translations/string-default.xml
1650 const char* levels[] = {"alpha","beta","early-production","production"};
1652 if (!strcmp(str, "all")) {
1656 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1657 if (strcmp(str,levels[i])==0)
1663 // recommended in Meyers, Effective STL when internationalization and embedded
1664 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1665 struct ciLessLibC : public std::binary_function<string, string, bool>
1667 bool operator()(const std::string &lhs, const std::string &rhs) const
1669 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1674 string_list _aircraft;
1677 void fgShowAircraft(const SGPath &path)
1683 cout << "Hit a key to continue..." << endl;