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>
78 # include <ATCDCL/ATCmgr.hxx>
79 # include "ATCDCL/commlist.hxx"
81 # include "ATC/atis.hxx"
82 # include "ATC/atcutils.hxx"
85 #include <Autopilot/route_mgr.hxx>
86 #include <Autopilot/autopilotgroup.hxx>
88 #include <Cockpit/cockpit.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Cockpit/panel_io.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Input/input.hxx>
94 #include <Instrumentation/instrument_mgr.hxx>
95 #include <Model/acmodel.hxx>
96 #include <Model/modelmgr.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Navaids/fix.hxx>
102 #include <Navaids/fixlist.hxx>
103 #include <Navaids/airways.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/voice.hxx>
108 #include <Systems/system_mgr.hxx>
109 #include <Time/light.hxx>
110 #include <Traffic/TrafficMgr.hxx>
111 #include <MultiPlayer/multiplaymgr.hxx>
112 #include <FDM/fdm_shell.hxx>
114 #include <Environment/environment_mgr.hxx>
116 #include "fg_init.hxx"
118 #include "fg_commands.hxx"
119 #include "fg_props.hxx"
120 #include "options.hxx"
121 #include "globals.hxx"
122 #include "logger.hxx"
123 #include "renderer.hxx"
124 #include "viewmgr.hxx"
129 # include <CoreFoundation/CoreFoundation.h>
133 using namespace boost::algorithm;
135 extern const char *default_root;
138 // Scan the command line options for the specified option and return
140 static string fgScanForOption( const string& option, int argc, char **argv ) {
143 if (hostname == NULL)
146 if( gethostname(_hostname, 256) >= 0 ) {
147 hostname = strdup(_hostname);
148 free_hostname = true;
152 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
154 int len = option.length();
157 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
159 string arg = argv[i];
160 if ( arg.find( option ) == 0 ) {
161 return arg.substr( len );
171 // Scan the user config files for the specified option and return
173 static string fgScanForOption( const string& option, const string& path ) {
174 sg_gzifstream in( path );
175 if ( !in.is_open() ) {
179 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
181 int len = option.length();
184 while ( ! in.eof() ) {
186 getline( in, line, '\n' );
188 // catch extraneous (DOS) line ending character
189 if ( line[line.length() - 1] < 32 ) {
190 line = line.substr( 0, line.length()-1 );
193 if ( line.find( option ) == 0 ) {
194 return line.substr( len );
203 // Scan the user config files for the specified option and return
205 static string fgScanForOption( const string& option ) {
208 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
209 // Next check home directory for .fgfsrc.hostname file
211 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
212 SGPath config( homedir );
213 config.append( ".fgfsrc" );
214 config.concat( "." );
215 config.concat( hostname );
216 arg = fgScanForOption( option, config.str() );
221 // Next check home directory for .fgfsrc file
223 if ( homedir != NULL ) {
224 SGPath config( homedir );
225 config.append( ".fgfsrc" );
226 arg = fgScanForOption( option, config.str() );
231 // Check for $fg_root/system.fgfsrc
232 SGPath config( globals->get_fg_root() );
233 config.append( "system.fgfsrc" );
234 arg = fgScanForOption( option, config.str() );
241 // Read in configuration (files and command line options) but only set
242 // fg_root and aircraft_paths, which are needed *before* do_options() is called
245 bool fgInitFGRoot ( int argc, char **argv ) {
248 // First parse command line options looking for --fg-root=, this
249 // will override anything specified in a config file
250 root = fgScanForOption( "--fg-root=", argc, argv);
252 // Check in one of the user configuration files.
254 root = fgScanForOption( "--fg-root=" );
256 // Next check if fg-root is set as an env variable
257 if ( root.empty() ) {
258 char *envp = ::getenv( "FG_ROOT" );
259 if ( envp != NULL ) {
264 // Otherwise, default to a random compiled-in location if we can't
265 // find fg-root any other way.
266 if ( root.empty() ) {
267 #if defined( __CYGWIN__ )
269 #elif defined( _WIN32 )
271 #elif defined(__APPLE__)
273 The following code looks for the base package inside the application
274 bundle, in the standard Contents/Resources location.
276 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
278 // look for a 'data' subdir
279 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
281 // now convert down to a path, and the a c-string
282 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
283 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
285 CFRelease(resourcesUrl);
293 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
294 globals->set_fg_root(root);
300 // Read in configuration (files and command line options) but only set
302 bool fgInitFGAircraft ( int argc, char **argv ) {
304 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
305 if (aircraftDir.empty()) {
306 aircraftDir = fgScanForOption("--fg-aircraft=");
309 const char* envp = ::getenv("FG_AIRCRAFT");
310 if (aircraftDir.empty() && envp) {
311 globals->append_aircraft_paths(envp);
314 if (!aircraftDir.empty()) {
315 globals->append_aircraft_paths(aircraftDir);
320 // First parse command line options looking for --aircraft=, this
321 // will override anything specified in a config file
322 aircraft = fgScanForOption( "--aircraft=", argc, argv );
323 if ( aircraft.empty() ) {
324 // check synonym option
325 aircraft = fgScanForOption( "--vehicle=", argc, argv );
328 // Check in one of the user configuration files.
329 if ( aircraft.empty() ) {
330 aircraft = fgScanForOption( "--aircraft=" );
332 if ( aircraft.empty() ) {
333 aircraft = fgScanForOption( "--vehicle=" );
336 // if an aircraft was specified, set the property name
337 if ( !aircraft.empty() ) {
338 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
339 fgSetString("/sim/aircraft", aircraft.c_str() );
341 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
348 // Return the current base package version
349 string fgBasePackageVersion() {
350 SGPath base_path( globals->get_fg_root() );
351 base_path.append("version");
353 sg_gzifstream in( base_path.str() );
354 if ( !in.is_open() ) {
355 SGPath old_path( globals->get_fg_root() );
356 old_path.append( "Thanks" );
357 sg_gzifstream old( old_path.str() );
358 if ( !old.is_open() ) {
361 return "[old version]";
372 // Initialize the localization
373 SGPropertyNode *fgInitLocale(const char *language) {
374 SGPropertyNode *c_node = NULL, *d_node = NULL;
375 SGPropertyNode *intl = fgGetNode("/sim/intl");
377 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
379 // localization not defined
384 // Select the proper language from the list
386 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
387 for (unsigned int i = 0; i < locale.size(); i++) {
389 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
390 for (unsigned int j = 0; j < lang.size(); j++) {
392 if (!strcmp(lang[j]->getStringValue(), language)) {
401 d_node = intl->getChild("locale");
405 // Check for localized font
406 SGPropertyNode *font_n = c_node->getNode("font", true);
407 if ( !strcmp(font_n->getStringValue(), "") )
408 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
412 // Load the default strings
414 SGPath d_path( globals->get_fg_root() );
416 const char *d_path_str = d_node->getStringValue("strings");
418 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
422 d_path.append(d_path_str);
423 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
425 SGPropertyNode *strings = c_node->getNode("strings");
427 readProperties(d_path.str(), strings);
428 } catch (const sg_exception &) {
429 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
434 // Load the language specific strings
436 if (c_node != d_node) {
437 SGPath c_path( globals->get_fg_root() );
439 const char *c_path_str = c_node->getStringValue("strings");
441 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
445 c_path.append(c_path_str);
446 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
449 readProperties(c_path.str(), strings);
450 } catch (const sg_exception &) {
451 SG_LOG(SG_GENERAL, SG_ALERT,
452 "Unable to read the localized strings from " << c_path.str());
462 // Initialize the localization routines
463 bool fgDetectLanguage() {
464 const char *language = ::getenv("LANG");
466 if (language == NULL) {
467 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
471 SGPropertyNode *locale = fgInitLocale(language);
473 SG_LOG(SG_GENERAL, SG_ALERT,
474 "No internationalization settings specified in preferences.xml" );
479 globals->set_locale( locale );
484 // Attempt to locate and parse the various non-XML config files in order
485 // from least precidence to greatest precidence
487 do_options (int argc, char ** argv)
489 // Check for $fg_root/system.fgfsrc
490 SGPath config( globals->get_fg_root() );
491 config.append( "system.fgfsrc" );
492 fgParseOptions(config.str());
494 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
495 if( hostname != NULL && strlen(hostname) > 0 ) {
496 config.concat( "." );
497 config.concat( hostname );
498 fgParseOptions(config.str());
502 // Check for ~/.fgfsrc
503 if ( homedir != NULL ) {
504 config.set( homedir );
505 config.append( ".fgfsrc" );
506 fgParseOptions(config.str());
509 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
510 if( hostname != NULL && strlen(hostname) > 0 ) {
511 // Check for ~/.fgfsrc.hostname
512 config.concat( "." );
513 config.concat( hostname );
514 fgParseOptions(config.str());
518 // Parse remaining command line options
519 // These will override anything specified in a config file
520 fgParseArgs(argc, argv);
524 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
526 if (!dirPath.exists()) {
527 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
532 simgear::Dir dir(dirPath);
533 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
534 simgear::PathList::iterator p;
535 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
536 // check file name ends with -set.xml
538 // if we found a -set.xml at this level, don't recurse any deeper
541 bool done = (obj->*pred)(*p);
545 } // of -set.xml iteration
551 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
552 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
553 if (p->file() == "CVS") {
557 if (fgFindAircraftInDir(*p, obj, pred)) {
560 } // of subdirs iteration
566 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
568 const string_list& paths(globals->get_aircraft_paths());
569 string_list::const_iterator it = paths.begin();
570 for (; it != paths.end(); ++it) {
571 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
575 } // of aircraft paths iteration
577 // if we reach this point, search the default location (always last)
578 SGPath rootAircraft(globals->get_fg_root());
579 rootAircraft.append("Aircraft");
580 fgFindAircraftInDir(rootAircraft, obj, pred);
583 class FindAndCacheAircraft
586 FindAndCacheAircraft(SGPropertyNode* autoSave)
588 _cache = autoSave->getNode("sim/startup/path-cache", true);
593 std::string aircraft = fgGetString( "/sim/aircraft", "");
594 if (aircraft.empty()) {
595 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
599 _searchAircraft = aircraft + "-set.xml";
601 // prepare cache for re-scan
602 SGPropertyNode *n = _cache->getNode("fg-root", true);
603 n->setStringValue(globals->get_fg_root().c_str());
604 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
605 _cache->removeChildren("aircraft");
607 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
610 if (_foundPath.str().empty()) {
611 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
615 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
616 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
617 if (!_foundPath.exists()) {
618 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
623 readProperties(_foundPath.str(), globals->get_props());
624 } catch ( const sg_exception &e ) {
625 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
635 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
636 return false; // cache mismatch
639 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
640 for (unsigned int i = 0; i < cache.size(); i++) {
641 const char *name = cache[i]->getStringValue("file", "");
642 if (!boost::equals(_searchAircraft, name, is_iequal())) {
646 SGPath xml(cache[i]->getStringValue("path", ""));
654 } // of aircraft in cache iteration
659 bool checkAircraft(const SGPath& p)
664 if (!_cache->getChild("aircraft", i++, false))
668 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
670 std::string fileName(p.file());
671 n = entry->getNode("file", true);
672 n->setStringValue(fileName);
673 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
675 n = entry->getNode("path", true);
676 n->setStringValue(p.dir());
677 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
679 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
687 std::string _searchAircraft;
689 SGPropertyNode* _cache;
692 // Read in configuration (file and command line)
693 bool fgInitConfig ( int argc, char **argv ) {
695 // First, set some sane default values
698 // Read global preferences from $FG_ROOT/preferences.xml
699 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
700 fgLoadProps("preferences.xml", globals->get_props());
701 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
703 // Detect the required language as early as possible
704 if ( !fgDetectLanguage() ) {
708 SGPropertyNode autosave;
710 char *envp = ::getenv( "APPDATA" );
712 SGPath config( envp );
713 config.append( "flightgear.org" );
715 if ( homedir != NULL ) {
716 SGPath config( homedir );
717 config.append( ".fgfs" );
719 const char *fg_home = getenv("FG_HOME");
723 SGPath home_export(config.str());
724 home_export.append("Export/dummy");
725 home_export.create_dir(0777);
727 // Set /sim/fg-home and don't allow malign code to override it until
728 // Nasal security is set up. Use FG_HOME if necessary.
729 SGPropertyNode *home = fgGetNode("/sim", true);
730 home->removeChild("fg-home", 0, false);
731 home = home->getChild("fg-home", 0, true);
732 home->setStringValue(config.c_str());
733 home->setAttribute(SGPropertyNode::WRITE, false);
735 config.append( "autosave.xml" );
736 if (config.exists()) {
737 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
739 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
740 } catch (sg_exception& e) {
741 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
742 << "(from " << e.getOrigin() << ")");
747 // Scan user config files and command line for a specified aircraft.
748 fgInitFGAircraft(argc, argv);
749 FindAndCacheAircraft f(&autosave);
750 if (!f.loadAircraft()) {
754 copyProperties(&autosave, globals->get_props());
756 // parse options after loading aircraft to ensure any user
757 // overrides of defaults are honored.
758 do_options(argc, argv);
763 // Set current tower position lon/lat given an airport id
764 static bool fgSetTowerPosFromAirportID( const string& id) {
765 const FGAirport *a = fgFindAirportID( id);
767 SGGeod tower = a->getTowerLocation();
768 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
769 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
770 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
778 struct FGTowerLocationListener : SGPropertyChangeListener {
779 void valueChanged(SGPropertyNode* node) {
780 const string id(node->getStringValue());
781 fgSetTowerPosFromAirportID(id);
785 void fgInitTowerLocationListener() {
786 fgGetNode("/sim/tower/airport-id", true)
787 ->addChangeListener( new FGTowerLocationListener(), true );
790 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
792 SGGeod startPos(aStartPos);
793 if (aTargetHeading == HUGE_VAL) {
794 aTargetHeading = aHeading;
797 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
798 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
799 offsetDistance *= SG_NM_TO_METER;
800 double offsetAzimuth = aHeading;
801 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
802 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
803 aHeading = aTargetHeading;
808 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
813 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
814 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
815 fgSetDouble("/sim/presets/heading-deg", aHeading );
817 // other code depends on the actual values being set ...
818 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
819 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
820 fgSetDouble("/orientation/heading-deg", aHeading );
823 // Set current_options lon/lat given an airport id and heading (degrees)
824 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
828 // set initial position from runway and heading
829 SG_LOG( SG_GENERAL, SG_INFO,
830 "Attempting to set starting position from airport code "
831 << id << " heading " << tgt_hdg );
833 const FGAirport* apt = fgFindAirportID(id);
834 if (!apt) return false;
835 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
836 fgSetString("/sim/atc/runway", r->ident().c_str());
838 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
839 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
843 // Set current_options lon/lat given an airport id and parkig position name
844 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
848 // can't see an easy way around this const_cast at the moment
849 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
851 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
854 FGAirportDynamics* dcs = apt->getDynamics();
856 SG_LOG( SG_GENERAL, SG_ALERT,
857 "Failed to find parking position " << parkpos <<
858 " at airport " << id );
862 int park_index = dcs->getNrOfParkings() - 1;
863 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
864 if (park_index < 0) {
865 SG_LOG( SG_GENERAL, SG_ALERT,
866 "Failed to find parking position " << parkpos <<
867 " at airport " << id );
870 FGParking* parking = dcs->getParking(park_index);
871 parking->setAvailable(false);
873 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
874 parking->getHeading());
879 // Set current_options lon/lat given an airport id and runway number
880 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
884 // set initial position from airport and runway number
885 SG_LOG( SG_GENERAL, SG_INFO,
886 "Attempting to set starting position for "
887 << id << ":" << rwy );
889 const FGAirport* apt = fgFindAirportID(id);
891 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
895 if (!apt->hasRunwayWithIdent(rwy)) {
896 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
897 "Failed to find runway " << rwy <<
898 " at airport " << id << ". Using default runway." );
902 FGRunway* r(apt->getRunwayByIdent(rwy));
903 fgSetString("/sim/atc/runway", r->ident().c_str());
904 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
905 fgApplyStartOffset(startPos, r->headingDeg());
910 static void fgSetDistOrAltFromGlideSlope() {
911 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
912 string apt_id = fgGetString("/sim/presets/airport-id");
913 double gs = fgGetDouble("/sim/presets/glideslope-deg")
914 * SG_DEGREES_TO_RADIANS ;
915 double od = fgGetDouble("/sim/presets/offset-distance-nm");
916 double alt = fgGetDouble("/sim/presets/altitude-ft");
918 double apt_elev = 0.0;
919 if ( ! apt_id.empty() ) {
920 apt_elev = fgGetAirportElev( apt_id );
921 if ( apt_elev < -9990.0 ) {
928 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
929 // set altitude from glideslope and offset-distance
930 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
931 alt = fabs(od*tan(gs)) + apt_elev;
932 fgSetDouble("/sim/presets/altitude-ft", alt);
933 fgSetBool("/sim/presets/onground", false);
934 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
936 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
937 // set offset-distance from glideslope and altitude
938 od = (alt - apt_elev) / tan(gs);
939 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
940 fgSetDouble("/sim/presets/offset-distance-nm", od);
941 fgSetBool("/sim/presets/onground", false);
942 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
944 } else if( fabs(gs) > 0.01 ) {
945 SG_LOG( SG_GENERAL, SG_ALERT,
946 "Glideslope given but not altitude or offset-distance." );
947 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
948 fgSetDouble("/sim/presets/glideslope-deg", 0);
949 fgSetBool("/sim/presets/onground", true);
954 // Set current_options lon/lat given an airport id and heading (degrees)
955 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
957 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
960 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
961 << id << ":" << freq );
965 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
969 // Set current_options lon/lat given an aircraft carrier id
970 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
972 // set initial position from runway and heading
976 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
977 double lon = geodPos.getLongitudeDeg();
978 double lat = geodPos.getLatitudeDeg();
979 double alt = geodPos.getElevationFt();
981 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
982 << carrier << " at lat = " << lat << ", lon = " << lon
983 << ", alt = " << alt << ", heading = " << heading);
985 fgSetDouble("/sim/presets/longitude-deg", lon);
986 fgSetDouble("/sim/presets/latitude-deg", lat);
987 fgSetDouble("/sim/presets/altitude-ft", alt);
988 fgSetDouble("/sim/presets/heading-deg", heading);
989 fgSetDouble("/position/longitude-deg", lon);
990 fgSetDouble("/position/latitude-deg", lat);
991 fgSetDouble("/position/altitude-ft", alt);
992 fgSetDouble("/orientation/heading-deg", heading);
994 fgSetString("/sim/presets/speed-set", "UVW");
995 fgSetDouble("/velocities/uBody-fps", uvw(0));
996 fgSetDouble("/velocities/vBody-fps", uvw(1));
997 fgSetDouble("/velocities/wBody-fps", uvw(2));
998 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
999 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1000 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1002 fgSetBool("/sim/presets/onground", true);
1006 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1012 // Set current_options lon/lat given an airport id and heading (degrees)
1013 static bool fgSetPosFromFix( const string& id )
1015 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1016 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1018 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1022 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1027 * Initialize vor/ndb/ils/fix list management and query systems (as
1028 * well as simple airport db list)
1033 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1035 SGPath aptdb( globals->get_fg_root() );
1036 aptdb.append( "Airports/apt.dat" );
1038 SGPath p_metar( globals->get_fg_root() );
1039 p_metar.append( "Airports/metar.dat" );
1041 // Initialise the frequency search map BEFORE reading
1042 // the airport database:
1046 current_commlist = new FGCommList;
1047 current_commlist->init( globals->get_fg_root() );
1048 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1050 FGNavList *navlist = new FGNavList;
1051 FGNavList *loclist = new FGNavList;
1052 FGNavList *gslist = new FGNavList;
1053 FGNavList *dmelist = new FGNavList;
1054 FGNavList *tacanlist = new FGNavList;
1055 FGNavList *carrierlist = new FGNavList;
1056 FGTACANList *channellist = new FGTACANList;
1058 globals->set_navlist( navlist );
1059 globals->set_loclist( loclist );
1060 globals->set_gslist( gslist );
1061 globals->set_dmelist( dmelist );
1062 globals->set_tacanlist( tacanlist );
1063 globals->set_carrierlist( carrierlist );
1064 globals->set_channellist( channellist );
1066 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1067 SG_LOG( SG_GENERAL, SG_ALERT,
1068 "Problems loading one or more navigational database" );
1071 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1072 SGPath p_fix( globals->get_fg_root() );
1073 p_fix.append( "Navaids/fix.dat" );
1075 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1077 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1078 flightgear::Airway::load();
1084 // Set the initial position based on presets (or defaults)
1085 bool fgInitPosition() {
1086 // cout << "fgInitPosition()" << endl;
1087 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1088 * SG_DEGREES_TO_RADIANS ;
1089 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1090 double alt = fgGetDouble("/sim/presets/altitude-ft");
1092 bool set_pos = false;
1094 // If glideslope is specified, then calculate offset-distance or
1095 // altitude relative to glide slope if either of those was not
1097 if ( fabs( gs ) > 0.01 ) {
1098 fgSetDistOrAltFromGlideSlope();
1102 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1103 // If not, check for an airport-id and use that.
1104 // If not, default to the middle of the KSFO field.
1105 // The default values for lon/lat are deliberately out of range
1106 // so that the airport-id can take effect; valid lon/lat will
1107 // override airport-id, however.
1108 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1109 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1110 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1111 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1116 string apt = fgGetString("/sim/presets/airport-id");
1117 string rwy_no = fgGetString("/sim/presets/runway");
1118 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1119 string vor = fgGetString("/sim/presets/vor-id");
1120 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1121 string ndb = fgGetString("/sim/presets/ndb-id");
1122 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1123 string carrier = fgGetString("/sim/presets/carrier");
1124 string parkpos = fgGetString("/sim/presets/parkpos");
1125 string fix = fgGetString("/sim/presets/fix");
1126 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1127 double hdg = hdg_preset->getDoubleValue();
1129 // save some start parameters, so that we can later say what the
1130 // user really requested. TODO generalize that and move it to options.cxx
1131 static bool start_options_saved = false;
1132 if (!start_options_saved) {
1133 start_options_saved = true;
1134 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1136 opt->setDoubleValue("latitude-deg", lat_deg);
1137 opt->setDoubleValue("longitude-deg", lon_deg);
1138 opt->setDoubleValue("heading-deg", hdg);
1139 opt->setStringValue("airport", apt.c_str());
1140 opt->setStringValue("runway", rwy_no.c_str());
1144 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1146 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1147 // An airport + parking position is requested
1148 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1149 // set tower position
1150 fgSetString("/sim/tower/airport-id", apt.c_str());
1155 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1156 // An airport + runway is requested
1157 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1158 // set tower position (a little off the heading for single
1160 fgSetString("/sim/tower/airport-id", apt.c_str());
1165 if ( !set_pos && !apt.empty() ) {
1166 // An airport is requested (find runway closest to hdg)
1167 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1168 // set tower position (a little off the heading for single
1170 fgSetString("/sim/tower/airport-id", apt.c_str());
1175 if (hdg_preset->getDoubleValue() > 9990.0)
1176 hdg_preset->setDoubleValue(hdg);
1178 if ( !set_pos && !vor.empty() ) {
1179 // a VOR is requested
1180 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1185 if ( !set_pos && !ndb.empty() ) {
1186 // an NDB is requested
1187 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1192 if ( !set_pos && !carrier.empty() ) {
1193 // an aircraft carrier is requested
1194 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1199 if ( !set_pos && !fix.empty() ) {
1200 // a Fix is requested
1201 if ( fgSetPosFromFix( fix ) ) {
1207 // No lon/lat specified, no airport specified, default to
1208 // middle of KSFO field.
1209 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1210 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1213 fgSetDouble( "/position/longitude-deg",
1214 fgGetDouble("/sim/presets/longitude-deg") );
1215 fgSetDouble( "/position/latitude-deg",
1216 fgGetDouble("/sim/presets/latitude-deg") );
1217 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1219 // determine if this should be an on-ground or in-air start
1220 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1221 fgSetBool("/sim/presets/onground", false);
1223 fgSetBool("/sim/presets/onground", true);
1230 // General house keeping initializations
1231 bool fgInitGeneral() {
1234 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1235 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1237 root = globals->get_fg_root();
1238 if ( ! root.length() ) {
1239 // No root path set? Then bail ...
1240 SG_LOG( SG_GENERAL, SG_ALERT,
1241 "Cannot continue without a path to the base package "
1242 << "being defined." );
1245 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1247 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1249 char buf[512], *cwd = getcwd(buf, 511);
1251 SGPropertyNode *curr = fgGetNode("/sim", true);
1252 curr->removeChild("fg-current", 0, false);
1253 curr = curr->getChild("fg-current", 0, true);
1254 curr->setStringValue(cwd ? cwd : "");
1255 curr->setAttribute(SGPropertyNode::WRITE, false);
1257 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1258 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1262 // This is the top level init routine which calls all the other
1263 // initialization routines. If you are adding a subsystem to flight
1264 // gear, its initialization call should located in this routine.
1265 // Returns non-zero if a problem encountered.
1266 bool fgInitSubsystems() {
1267 // static const SGPropertyNode *longitude
1268 // = fgGetNode("/sim/presets/longitude-deg");
1269 // static const SGPropertyNode *latitude
1270 // = fgGetNode("/sim/presets/latitude-deg");
1271 // static const SGPropertyNode *altitude
1272 // = fgGetNode("/sim/presets/altitude-ft");
1274 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1275 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1277 ////////////////////////////////////////////////////////////////////
1278 // Initialize the event manager subsystem.
1279 ////////////////////////////////////////////////////////////////////
1281 globals->get_event_mgr()->init();
1282 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1284 ////////////////////////////////////////////////////////////////////
1285 // Initialize the property interpolator subsystem. Put into the INIT
1286 // group because the "nasal" subsystem may need it at GENERAL take-down.
1287 ////////////////////////////////////////////////////////////////////
1288 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1291 ////////////////////////////////////////////////////////////////////
1292 // Add the FlightGear property utilities.
1293 ////////////////////////////////////////////////////////////////////
1294 globals->add_subsystem("properties", new FGProperties);
1296 ////////////////////////////////////////////////////////////////////
1297 // Initialize the material property subsystem.
1298 ////////////////////////////////////////////////////////////////////
1300 SGPath mpath( globals->get_fg_root() );
1301 mpath.append( "materials.xml" );
1302 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1303 globals->get_props()) ) {
1304 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1309 ////////////////////////////////////////////////////////////////////
1310 // Initialize the scenery management subsystem.
1311 ////////////////////////////////////////////////////////////////////
1313 globals->get_scenery()->get_scene_graph()
1314 ->addChild(simgear::Particles::getCommonRoot());
1315 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1317 ////////////////////////////////////////////////////////////////////
1318 // Initialize the flight model subsystem.
1319 ////////////////////////////////////////////////////////////////////
1321 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1323 ////////////////////////////////////////////////////////////////////
1324 // Initialize the weather subsystem.
1325 ////////////////////////////////////////////////////////////////////
1327 // Initialize the weather modeling subsystem
1328 globals->add_subsystem("environment", new FGEnvironmentMgr);
1330 ////////////////////////////////////////////////////////////////////
1331 // Initialize the aircraft systems and instrumentation (before the
1333 ////////////////////////////////////////////////////////////////////
1335 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1336 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1338 ////////////////////////////////////////////////////////////////////
1339 // Initialize the XML Autopilot subsystem.
1340 ////////////////////////////////////////////////////////////////////
1342 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1343 globals->add_subsystem( "route-manager", new FGRouteMgr );
1345 ////////////////////////////////////////////////////////////////////
1346 // Initialize the Input-Output subsystem
1347 ////////////////////////////////////////////////////////////////////
1348 globals->add_subsystem( "io", new FGIO );
1350 ////////////////////////////////////////////////////////////////////
1351 // Create and register the logger.
1352 ////////////////////////////////////////////////////////////////////
1354 globals->add_subsystem("logger", new FGLogger);
1356 ////////////////////////////////////////////////////////////////////
1357 // Create and register the XML GUI.
1358 ////////////////////////////////////////////////////////////////////
1360 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1362 //////////////////////////////////////////////////////////////////////
1363 // Initialize the 2D cloud subsystem.
1364 ////////////////////////////////////////////////////////////////////
1365 fgGetBool("/sim/rendering/bump-mapping", false);
1369 ////////////////////////////////////////////////////////////////////
1370 // Initialise the ATC Manager
1371 ////////////////////////////////////////////////////////////////////
1374 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1375 globals->set_ATC_mgr(new FGATCMgr);
1376 globals->get_ATC_mgr()->init();
1378 ////////////////////////////////////////////////////////////////////
1379 // Initialise the ATIS Manager
1380 ////////////////////////////////////////////////////////////////////
1381 globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1385 ////////////////////////////////////////////////////////////////////
1386 // Initialize multiplayer subsystem
1387 ////////////////////////////////////////////////////////////////////
1389 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1391 ////////////////////////////////////////////////////////////////////
1392 // Initialise the AI Model Manager
1393 ////////////////////////////////////////////////////////////////////
1394 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1395 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1396 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1399 // It's probably a good idea to initialize the top level traffic manager
1400 // After the AI and ATC systems have been initialized properly.
1401 // AI Traffic manager
1402 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1405 if( fgCockpitInit()) {
1406 // Cockpit initialized ok.
1408 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1413 ////////////////////////////////////////////////////////////////////
1414 // Add a new 2D panel.
1415 ////////////////////////////////////////////////////////////////////
1417 string panel_path(fgGetString("/sim/panel/path"));
1418 if (!panel_path.empty()) {
1419 FGPanel* p = fgReadPanel(panel_path);
1421 globals->set_current_panel(p);
1424 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1426 SG_LOG( SG_INPUT, SG_ALERT,
1427 "Error reading new panel from " << panel_path );
1431 ////////////////////////////////////////////////////////////////////
1432 // Initialize the controls subsystem.
1433 ////////////////////////////////////////////////////////////////////
1435 globals->get_controls()->init();
1436 globals->get_controls()->bind();
1439 ////////////////////////////////////////////////////////////////////
1440 // Initialize the input subsystem.
1441 ////////////////////////////////////////////////////////////////////
1443 globals->add_subsystem("input", new FGInput);
1446 ////////////////////////////////////////////////////////////////////
1447 // Initialize the replay subsystem
1448 ////////////////////////////////////////////////////////////////////
1449 globals->add_subsystem("replay", new FGReplay);
1451 #ifdef ENABLE_AUDIO_SUPPORT
1452 ////////////////////////////////////////////////////////////////////
1453 // Initialize the sound-effects subsystem.
1454 ////////////////////////////////////////////////////////////////////
1455 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1458 ////////////////////////////////////////////////////////////////////
1459 // Initialize the lighting subsystem.
1460 ////////////////////////////////////////////////////////////////////
1462 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1464 // ordering here is important : Nasal (via events), then models, then views
1465 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1467 FGAircraftModel* acm = new FGAircraftModel;
1468 globals->set_aircraft_model(acm);
1469 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1471 FGModelMgr* mm = new FGModelMgr;
1472 globals->set_model_mgr(mm);
1473 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1475 FGViewMgr *viewmgr = new FGViewMgr;
1476 globals->set_viewmgr( viewmgr );
1477 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1479 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1480 SGSubsystemMgr::DISPLAY);
1482 ////////////////////////////////////////////////////////////////////
1483 // Bind and initialize subsystems.
1484 ////////////////////////////////////////////////////////////////////
1486 globals->get_subsystem_mgr()->bind();
1487 globals->get_subsystem_mgr()->init();
1489 ////////////////////////////////////////////////////////////////////////
1490 // Initialize the Nasal interpreter.
1491 // Do this last, so that the loaded scripts see initialized state
1492 ////////////////////////////////////////////////////////////////////////
1493 FGNasalSys* nasal = new FGNasalSys();
1494 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1497 // initialize methods that depend on other subsystems.
1498 globals->get_subsystem_mgr()->postinit();
1500 ////////////////////////////////////////////////////////////////////////
1501 // End of subsystem initialization.
1502 ////////////////////////////////////////////////////////////////////
1504 SG_LOG( SG_GENERAL, SG_INFO, endl);
1506 // Save the initial state for future
1508 globals->saveInitialState();
1514 void fgReInitSubsystems()
1516 // static const SGPropertyNode *longitude
1517 // = fgGetNode("/sim/presets/longitude-deg");
1518 // static const SGPropertyNode *latitude
1519 // = fgGetNode("/sim/presets/latitude-deg");
1520 static const SGPropertyNode *altitude
1521 = fgGetNode("/sim/presets/altitude-ft");
1522 static const SGPropertyNode *master_freeze
1523 = fgGetNode("/sim/freeze/master");
1525 SG_LOG( SG_GENERAL, SG_INFO,
1526 "fgReInitSubsystems(): /position/altitude = "
1527 << altitude->getDoubleValue() );
1529 bool freeze = master_freeze->getBoolValue();
1531 fgSetBool("/sim/freeze/master", true);
1533 fgSetBool("/sim/crashed", false);
1535 // Force reupdating the positions of the ai 3d models. They are used for
1536 // initializing ground level for the FDM.
1537 globals->get_subsystem("ai_model")->reinit();
1539 // Initialize the FDM
1540 globals->get_subsystem("flight")->reinit();
1542 // reload offsets from config defaults
1543 globals->get_viewmgr()->reinit();
1545 globals->get_controls()->reset_all();
1547 globals->get_subsystem("time")->reinit();
1548 globals->get_subsystem("tile-manager")->reinit();
1551 fgSetBool("/sim/freeze/master", false);
1553 fgSetBool("/sim/sceneryloaded",false);
1557 void doSimulatorReset(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1559 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1561 bool freeze = master_freeze->getBoolValue();
1563 master_freeze->setBoolValue(true);
1565 fgSetBool("/sim/signals/reinit", true);
1567 globals->get_subsystem("flight")->unbind();
1569 globals->restoreInitialState();
1571 // update our position based on current presets
1574 fgReInitSubsystems();
1576 fgSetBool("/sim/signals/reinit", false);
1579 master_freeze->setBoolValue(false);
1582 ///////////////////////////////////////////////////////////////////////////////
1583 // helper object to implement the --show-aircraft command.
1584 // resides here so we can share the fgFindAircraftInDir template above,
1585 // and hence ensure this command lists exectly the same aircraft as the normal
1592 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1596 void show(const SGPath& path)
1598 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1600 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1601 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1602 cout << "Available aircraft:" << endl;
1603 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1604 cout << _aircraft[i] << endl;
1609 bool processAircraft(const SGPath& path)
1611 SGPropertyNode root;
1613 readProperties(path.str(), &root);
1614 } catch (sg_exception& ) {
1619 string descStr(" ");
1620 descStr += path.file();
1621 // trim common suffix from file names
1622 int nPos = descStr.rfind("-set.xml");
1623 if (nPos == (int)(descStr.size() - 8)) {
1624 descStr.resize(nPos);
1627 SGPropertyNode *node = root.getNode("sim");
1629 SGPropertyNode* desc = node->getNode("description");
1630 // if a status tag is found, read it in
1631 if (node->hasValue("status")) {
1632 maturity = getNumMaturity(node->getStringValue("status"));
1636 if (descStr.size() <= 27+3) {
1637 descStr.append(29+3-descStr.size(), ' ');
1640 descStr.append( 32, ' ');
1642 descStr += desc->getStringValue();
1644 } // of have 'sim' node
1646 if (maturity < _minStatus) {
1650 _aircraft.push_back(descStr);
1655 int getNumMaturity(const char * str)
1657 // changes should also be reflected in $FG_ROOT/data/options.xml &
1658 // $FG_ROOT/data/Translations/string-default.xml
1659 const char* levels[] = {"alpha","beta","early-production","production"};
1661 if (!strcmp(str, "all")) {
1665 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1666 if (strcmp(str,levels[i])==0)
1672 // recommended in Meyers, Effective STL when internationalization and embedded
1673 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1674 struct ciLessLibC : public std::binary_function<string, string, bool>
1676 bool operator()(const std::string &lhs, const std::string &rhs) const
1678 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1683 string_list _aircraft;
1686 void fgShowAircraft(const SGPath &path)
1692 cout << "Hit a key to continue..." << endl;