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>
62 #include <simgear/misc/strutils.hxx>
63 #include <simgear/props/props_io.hxx>
65 #include <simgear/misc/interpolator.hxx>
66 #include <simgear/scene/material/matlib.hxx>
67 #include <simgear/scene/model/particles.hxx>
68 #include <simgear/sound/soundmgr_openal.hxx>
70 #include <Aircraft/controls.hxx>
71 #include <Aircraft/replay.hxx>
72 #include <Airports/apt_loader.hxx>
73 #include <Airports/runways.hxx>
74 #include <Airports/simple.hxx>
75 #include <Airports/dynamics.hxx>
77 #include <AIModel/AIManager.hxx>
79 #include <ATCDCL/ATCmgr.hxx>
80 #include <ATC/atc_mgr.hxx>
82 #include <Autopilot/route_mgr.hxx>
83 #include <Autopilot/autopilotgroup.hxx>
85 #include <Cockpit/panel.hxx>
86 #include <Cockpit/panel_io.hxx>
88 #include <GUI/new_gui.hxx>
89 #include <Input/input.hxx>
90 #include <Instrumentation/instrument_mgr.hxx>
91 #include <Model/acmodel.hxx>
92 #include <Model/modelmgr.hxx>
93 #include <AIModel/submodel.hxx>
94 #include <AIModel/AIManager.hxx>
95 #include <Navaids/navdb.hxx>
96 #include <Navaids/navlist.hxx>
97 #include <Navaids/fix.hxx>
98 #include <Navaids/fixlist.hxx>
99 #include <Navaids/airways.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/tilemgr.hxx>
102 #include <Scripting/NasalSys.hxx>
103 #include <Sound/voice.hxx>
104 #include <Systems/system_mgr.hxx>
105 #include <Time/light.hxx>
106 #include <Traffic/TrafficMgr.hxx>
107 #include <MultiPlayer/multiplaymgr.hxx>
108 #include <FDM/fdm_shell.hxx>
110 #include <Environment/environment_mgr.hxx>
112 #include "fg_init.hxx"
114 #include "fg_commands.hxx"
115 #include "fg_props.hxx"
116 #include "options.hxx"
117 #include "globals.hxx"
118 #include "logger.hxx"
119 #include "renderer.hxx"
120 #include "viewmgr.hxx"
125 # include <CoreFoundation/CoreFoundation.h>
129 using namespace boost::algorithm;
131 extern const char *default_root;
134 // Scan the command line options for the specified option and return
136 static string fgScanForOption( const string& option, int argc, char **argv ) {
139 if (hostname == NULL)
142 if( gethostname(_hostname, 256) >= 0 ) {
143 hostname = strdup(_hostname);
144 free_hostname = true;
148 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
150 int len = option.length();
153 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
155 string arg = argv[i];
156 if ( arg.find( option ) == 0 ) {
157 return arg.substr( len );
167 // Scan the user config files for the specified option and return
169 static string fgScanForOption( const string& option, const string& path ) {
170 sg_gzifstream in( path );
171 if ( !in.is_open() ) {
175 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
177 int len = option.length();
180 while ( ! in.eof() ) {
182 getline( in, line, '\n' );
184 // catch extraneous (DOS) line ending character
185 if ( line[line.length() - 1] < 32 ) {
186 line = line.substr( 0, line.length()-1 );
189 if ( line.find( option ) == 0 ) {
190 return line.substr( len );
199 // Scan the user config files for the specified option and return
201 static string fgScanForOption( const string& option ) {
204 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
205 // Next check home directory for .fgfsrc.hostname file
207 if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
208 SGPath config( homedir );
209 config.append( ".fgfsrc" );
210 config.concat( "." );
211 config.concat( hostname );
212 arg = fgScanForOption( option, config.str() );
217 // Next check home directory for .fgfsrc file
219 if ( homedir != NULL ) {
220 SGPath config( homedir );
221 config.append( ".fgfsrc" );
222 arg = fgScanForOption( option, config.str() );
227 // Check for $fg_root/system.fgfsrc
228 SGPath config( globals->get_fg_root() );
229 config.append( "system.fgfsrc" );
230 arg = fgScanForOption( option, config.str() );
237 // Read in configuration (files and command line options) but only set
238 // fg_root and aircraft_paths, which are needed *before* do_options() is called
241 bool fgInitFGRoot ( int argc, char **argv ) {
244 // First parse command line options looking for --fg-root=, this
245 // will override anything specified in a config file
246 root = fgScanForOption( "--fg-root=", argc, argv);
248 // Check in one of the user configuration files.
250 root = fgScanForOption( "--fg-root=" );
252 // Next check if fg-root is set as an env variable
253 if ( root.empty() ) {
254 char *envp = ::getenv( "FG_ROOT" );
255 if ( envp != NULL ) {
260 // Otherwise, default to a random compiled-in location if we can't
261 // find fg-root any other way.
262 if ( root.empty() ) {
263 #if defined( __CYGWIN__ )
265 #elif defined( _WIN32 )
267 #elif defined(__APPLE__)
269 The following code looks for the base package inside the application
270 bundle, in the standard Contents/Resources location.
272 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
274 // look for a 'data' subdir
275 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
277 // now convert down to a path, and the a c-string
278 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
279 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
281 CFRelease(resourcesUrl);
289 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
290 globals->set_fg_root(root);
296 // Read in configuration (files and command line options) but only set
298 bool fgInitFGAircraft ( int argc, char **argv ) {
300 string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
301 if (aircraftDir.empty()) {
302 aircraftDir = fgScanForOption("--fg-aircraft=");
305 const char* envp = ::getenv("FG_AIRCRAFT");
306 if (aircraftDir.empty() && envp) {
307 globals->append_aircraft_paths(envp);
310 if (!aircraftDir.empty()) {
311 globals->append_aircraft_paths(aircraftDir);
316 // First parse command line options looking for --aircraft=, this
317 // will override anything specified in a config file
318 aircraft = fgScanForOption( "--aircraft=", argc, argv );
319 if ( aircraft.empty() ) {
320 // check synonym option
321 aircraft = fgScanForOption( "--vehicle=", argc, argv );
324 // Check in one of the user configuration files.
325 if ( aircraft.empty() ) {
326 aircraft = fgScanForOption( "--aircraft=" );
328 if ( aircraft.empty() ) {
329 aircraft = fgScanForOption( "--vehicle=" );
332 // if an aircraft was specified, set the property name
333 if ( !aircraft.empty() ) {
334 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
335 fgSetString("/sim/aircraft", aircraft.c_str() );
337 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
344 // Return the current base package version
345 string fgBasePackageVersion() {
346 SGPath base_path( globals->get_fg_root() );
347 base_path.append("version");
349 sg_gzifstream in( base_path.str() );
350 if ( !in.is_open() ) {
351 SGPath old_path( globals->get_fg_root() );
352 old_path.append( "Thanks" );
353 sg_gzifstream old( old_path.str() );
354 if ( !old.is_open() ) {
357 return "[old version]";
368 // Initialize the localization
369 SGPropertyNode *fgInitLocale(const char *language) {
370 SGPropertyNode *c_node = NULL, *d_node = NULL;
371 SGPropertyNode *intl = fgGetNode("/sim/intl");
373 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
375 // localization not defined
380 // Select the proper language from the list
382 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
383 for (unsigned int i = 0; i < locale.size(); i++) {
385 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
386 for (unsigned int j = 0; j < lang.size(); j++) {
388 if (!strcmp(lang[j]->getStringValue(), language)) {
397 d_node = intl->getChild("locale");
401 // Check for localized font
402 SGPropertyNode *font_n = c_node->getNode("font", true);
403 if ( !strcmp(font_n->getStringValue(), "") )
404 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
408 // Load the default strings
410 SGPath d_path( globals->get_fg_root() );
412 const char *d_path_str = d_node->getStringValue("strings");
414 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
418 d_path.append(d_path_str);
419 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
421 SGPropertyNode *strings = c_node->getNode("strings");
423 readProperties(d_path.str(), strings);
424 } catch (const sg_exception &) {
425 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
430 // Load the language specific strings
432 if (c_node != d_node) {
433 SGPath c_path( globals->get_fg_root() );
435 const char *c_path_str = c_node->getStringValue("strings");
437 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
441 c_path.append(c_path_str);
442 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
445 readProperties(c_path.str(), strings);
446 } catch (const sg_exception &) {
447 SG_LOG(SG_GENERAL, SG_ALERT,
448 "Unable to read the localized strings from " << c_path.str());
458 // Initialize the localization routines
459 bool fgDetectLanguage() {
460 const char *language = ::getenv("LANG");
462 if (language == NULL) {
463 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
467 SGPropertyNode *locale = fgInitLocale(language);
469 SG_LOG(SG_GENERAL, SG_ALERT,
470 "No internationalization settings specified in preferences.xml" );
475 globals->set_locale( locale );
480 // Attempt to locate and parse the various non-XML config files in order
481 // from least precidence to greatest precidence
483 do_options (int argc, char ** argv)
485 // Check for $fg_root/system.fgfsrc
486 SGPath config( globals->get_fg_root() );
487 config.append( "system.fgfsrc" );
488 fgParseOptions(config.str());
490 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
491 if( hostname != NULL && strlen(hostname) > 0 ) {
492 config.concat( "." );
493 config.concat( hostname );
494 fgParseOptions(config.str());
498 // Check for ~/.fgfsrc
499 if ( homedir != NULL ) {
500 config.set( homedir );
501 config.append( ".fgfsrc" );
502 fgParseOptions(config.str());
505 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
506 if( hostname != NULL && strlen(hostname) > 0 ) {
507 // Check for ~/.fgfsrc.hostname
508 config.concat( "." );
509 config.concat( hostname );
510 fgParseOptions(config.str());
514 // Parse remaining command line options
515 // These will override anything specified in a config file
516 fgParseArgs(argc, argv);
520 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
522 if (!dirPath.exists()) {
523 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
528 simgear::Dir dir(dirPath);
529 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
530 simgear::PathList::iterator p;
531 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
532 // check file name ends with -set.xml
534 // if we found a -set.xml at this level, don't recurse any deeper
537 bool done = (obj->*pred)(*p);
541 } // of -set.xml iteration
547 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
548 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
549 if (p->file() == "CVS") {
553 if (fgFindAircraftInDir(*p, obj, pred)) {
556 } // of subdirs iteration
562 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
564 const string_list& paths(globals->get_aircraft_paths());
565 string_list::const_iterator it = paths.begin();
566 for (; it != paths.end(); ++it) {
567 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
571 } // of aircraft paths iteration
573 // if we reach this point, search the default location (always last)
574 SGPath rootAircraft(globals->get_fg_root());
575 rootAircraft.append("Aircraft");
576 fgFindAircraftInDir(rootAircraft, obj, pred);
579 class FindAndCacheAircraft
582 FindAndCacheAircraft(SGPropertyNode* autoSave)
584 _cache = autoSave->getNode("sim/startup/path-cache", true);
589 std::string aircraft = fgGetString( "/sim/aircraft", "");
590 if (aircraft.empty()) {
591 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
595 _searchAircraft = aircraft + "-set.xml";
597 // prepare cache for re-scan
598 SGPropertyNode *n = _cache->getNode("fg-root", true);
599 n->setStringValue(globals->get_fg_root().c_str());
600 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
601 n = _cache->getNode("fg-aircraft", true);
602 n->setStringValue(getAircraftPaths().c_str());
603 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
604 _cache->removeChildren("aircraft");
606 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
609 if (_foundPath.str().empty()) {
610 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
614 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
615 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
616 if (!_foundPath.exists()) {
617 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
622 readProperties(_foundPath.str(), globals->get_props());
623 } catch ( const sg_exception &e ) {
624 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
632 SGPath getAircraftPaths() {
633 string_list pathList = globals->get_aircraft_paths();
634 SGPath aircraftPaths;
635 string_list::const_iterator it = pathList.begin();
636 if (it != pathList.end()) {
637 aircraftPaths.set(*it);
640 for (; it != pathList.end(); ++it) {
641 aircraftPaths.add(*it);
643 return aircraftPaths;
648 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
649 return false; // cache mismatch
652 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
653 return false; // cache mismatch
656 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
657 for (unsigned int i = 0; i < cache.size(); i++) {
658 const char *name = cache[i]->getStringValue("file", "");
659 if (!boost::equals(_searchAircraft, name, is_iequal())) {
663 SGPath xml(cache[i]->getStringValue("path", ""));
671 } // of aircraft in cache iteration
676 bool checkAircraft(const SGPath& p)
681 if (!_cache->getChild("aircraft", i++, false))
685 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
687 std::string fileName(p.file());
688 n = entry->getNode("file", true);
689 n->setStringValue(fileName);
690 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
692 n = entry->getNode("path", true);
693 n->setStringValue(p.dir());
694 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
696 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
704 std::string _searchAircraft;
706 SGPropertyNode* _cache;
709 // Read in configuration (file and command line)
710 bool fgInitConfig ( int argc, char **argv ) {
712 // First, set some sane default values
715 // Read global preferences from $FG_ROOT/preferences.xml
716 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
717 fgLoadProps("preferences.xml", globals->get_props());
718 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
720 // Detect the required language as early as possible
721 if ( !fgDetectLanguage() ) {
725 SGPropertyNode autosave;
727 char *envp = ::getenv( "APPDATA" );
729 SGPath config( envp );
730 config.append( "flightgear.org" );
732 if ( homedir != NULL ) {
733 SGPath config( homedir );
734 config.append( ".fgfs" );
736 const char *fg_home = getenv("FG_HOME");
740 SGPath home_export(config.str());
741 home_export.append("Export/dummy");
742 home_export.create_dir(0777);
744 // Set /sim/fg-home and don't allow malign code to override it until
745 // Nasal security is set up. Use FG_HOME if necessary.
746 SGPropertyNode *home = fgGetNode("/sim", true);
747 home->removeChild("fg-home", 0, false);
748 home = home->getChild("fg-home", 0, true);
749 home->setStringValue(config.c_str());
750 home->setAttribute(SGPropertyNode::WRITE, false);
752 config.append( "autosave.xml" );
753 if (config.exists()) {
754 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
756 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
757 } catch (sg_exception& e) {
758 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
759 << "(from " << e.getOrigin() << ")");
764 // Scan user config files and command line for a specified aircraft.
765 fgInitFGAircraft(argc, argv);
766 FindAndCacheAircraft f(&autosave);
767 if (!f.loadAircraft()) {
771 copyProperties(&autosave, globals->get_props());
773 // parse options after loading aircraft to ensure any user
774 // overrides of defaults are honored.
775 do_options(argc, argv);
780 // Set current tower position lon/lat given an airport id
781 static bool fgSetTowerPosFromAirportID( const string& id) {
782 const FGAirport *a = fgFindAirportID( id);
784 SGGeod tower = a->getTowerLocation();
785 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
786 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
787 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
795 struct FGTowerLocationListener : SGPropertyChangeListener {
796 void valueChanged(SGPropertyNode* node) {
797 string id(node->getStringValue());
798 if (fgGetBool("/sim/tower/auto-position",true))
800 // enforce using closest airport when auto-positioning is enabled
801 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
802 if (closest_airport && (id != closest_airport))
804 id = closest_airport;
805 node->setStringValue(id);
808 fgSetTowerPosFromAirportID(id);
812 struct FGClosestTowerLocationListener : SGPropertyChangeListener
814 void valueChanged(SGPropertyNode* )
816 // closest airport has changed
817 if (fgGetBool("/sim/tower/auto-position",true))
819 // update tower position
820 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
822 fgSetString("/sim/tower/airport-id", id);
827 void fgInitTowerLocationListener() {
828 fgGetNode("/sim/tower/airport-id", true)
829 ->addChangeListener( new FGTowerLocationListener(), true );
830 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
831 fgGetNode("/sim/airport/closest-airport-id", true)
832 ->addChangeListener(ntcl , true );
833 fgGetNode("/sim/tower/auto-position", true)
834 ->addChangeListener(ntcl, true );
837 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
839 SGGeod startPos(aStartPos);
840 if (aTargetHeading == HUGE_VAL) {
841 aTargetHeading = aHeading;
844 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
845 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
846 offsetDistance *= SG_NM_TO_METER;
847 double offsetAzimuth = aHeading;
848 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
849 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
850 aHeading = aTargetHeading;
855 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
860 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
861 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
862 fgSetDouble("/sim/presets/heading-deg", aHeading );
864 // other code depends on the actual values being set ...
865 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
866 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
867 fgSetDouble("/orientation/heading-deg", aHeading );
870 // Set current_options lon/lat given an airport id and heading (degrees)
871 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
875 // set initial position from runway and heading
876 SG_LOG( SG_GENERAL, SG_INFO,
877 "Attempting to set starting position from airport code "
878 << id << " heading " << tgt_hdg );
880 const FGAirport* apt = fgFindAirportID(id);
881 if (!apt) return false;
882 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
883 fgSetString("/sim/atc/runway", r->ident().c_str());
885 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
886 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
890 // Set current_options lon/lat given an airport id and parkig position name
891 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
895 // can't see an easy way around this const_cast at the moment
896 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
898 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
901 FGAirportDynamics* dcs = apt->getDynamics();
903 SG_LOG( SG_GENERAL, SG_ALERT,
904 "Airport " << id << "does not appear to have parking information available");
908 int park_index = dcs->getNrOfParkings() - 1;
910 double radius = fgGetDouble("/sim/atc/acradius");
911 //cerr << "Using radius " << radius << endl;
912 //cerr << "Checking parkpos comparison " << (bool) (parkpos == string("AVAILABLE")) << endl;
913 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
914 double lat, lon, heading;
915 string fltType = fgGetString("/sim/atc/flight-type");
916 string airline = fgGetString("/sim/atc/airline" );
917 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
918 succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, airline);
920 fgGetString("/sim/presets/parkpos");
921 fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
923 SG_LOG( SG_GENERAL, SG_ALERT,
924 "Failed to find a suitable parking at airport " << id );
928 //cerr << "We shouldn't get here when AVAILABLE" << endl;
929 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
930 if (park_index < 0) {
931 SG_LOG( SG_GENERAL, SG_ALERT,
932 "Failed to find parking position " << parkpos <<
933 " at airport " << id );
937 FGParking* parking = dcs->getParking(park_index);
938 parking->setAvailable(false);
940 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
941 parking->getHeading());
946 // Set current_options lon/lat given an airport id and runway number
947 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
951 // set initial position from airport and runway number
952 SG_LOG( SG_GENERAL, SG_INFO,
953 "Attempting to set starting position for "
954 << id << ":" << rwy );
956 const FGAirport* apt = fgFindAirportID(id);
958 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
962 if (!apt->hasRunwayWithIdent(rwy)) {
963 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
964 "Failed to find runway " << rwy <<
965 " at airport " << id << ". Using default runway." );
969 FGRunway* r(apt->getRunwayByIdent(rwy));
970 fgSetString("/sim/atc/runway", r->ident().c_str());
971 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
972 fgApplyStartOffset(startPos, r->headingDeg());
977 static void fgSetDistOrAltFromGlideSlope() {
978 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
979 string apt_id = fgGetString("/sim/presets/airport-id");
980 double gs = fgGetDouble("/sim/presets/glideslope-deg")
981 * SG_DEGREES_TO_RADIANS ;
982 double od = fgGetDouble("/sim/presets/offset-distance-nm");
983 double alt = fgGetDouble("/sim/presets/altitude-ft");
985 double apt_elev = 0.0;
986 if ( ! apt_id.empty() ) {
987 apt_elev = fgGetAirportElev( apt_id );
988 if ( apt_elev < -9990.0 ) {
995 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
996 // set altitude from glideslope and offset-distance
997 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
998 alt = fabs(od*tan(gs)) + apt_elev;
999 fgSetDouble("/sim/presets/altitude-ft", alt);
1000 fgSetBool("/sim/presets/onground", false);
1001 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
1003 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
1004 // set offset-distance from glideslope and altitude
1005 od = (alt - apt_elev) / tan(gs);
1006 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
1007 fgSetDouble("/sim/presets/offset-distance-nm", od);
1008 fgSetBool("/sim/presets/onground", false);
1009 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
1011 } else if( fabs(gs) > 0.01 ) {
1012 SG_LOG( SG_GENERAL, SG_ALERT,
1013 "Glideslope given but not altitude or offset-distance." );
1014 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
1015 fgSetDouble("/sim/presets/glideslope-deg", 0);
1016 fgSetBool("/sim/presets/onground", true);
1021 // Set current_options lon/lat given an airport id and heading (degrees)
1022 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type ) {
1024 const nav_list_type navlist
1025 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq, type );
1027 if (navlist.size() == 0 ) {
1028 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1029 << id << ":" << freq );
1033 if( navlist.size() > 1 ) {
1035 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
1036 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
1037 // NDB stored in kHz, VOR stored in MHz * 100 :-P
1038 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
1039 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
1040 buf << (*it)->ident() << " "
1041 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
1042 << (*it)->get_lat() << "/" << (*it)->get_lon()
1046 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
1050 FGNavRecord *nav = navlist[0];
1051 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
1055 // Set current_options lon/lat given an aircraft carrier id
1056 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1058 // set initial position from runway and heading
1062 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1063 double lon = geodPos.getLongitudeDeg();
1064 double lat = geodPos.getLatitudeDeg();
1065 double alt = geodPos.getElevationFt();
1067 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1068 << carrier << " at lat = " << lat << ", lon = " << lon
1069 << ", alt = " << alt << ", heading = " << heading);
1071 fgSetDouble("/sim/presets/longitude-deg", lon);
1072 fgSetDouble("/sim/presets/latitude-deg", lat);
1073 fgSetDouble("/sim/presets/altitude-ft", alt);
1074 fgSetDouble("/sim/presets/heading-deg", heading);
1075 fgSetDouble("/position/longitude-deg", lon);
1076 fgSetDouble("/position/latitude-deg", lat);
1077 fgSetDouble("/position/altitude-ft", alt);
1078 fgSetDouble("/orientation/heading-deg", heading);
1080 fgSetString("/sim/presets/speed-set", "UVW");
1081 fgSetDouble("/velocities/uBody-fps", uvw(0));
1082 fgSetDouble("/velocities/vBody-fps", uvw(1));
1083 fgSetDouble("/velocities/wBody-fps", uvw(2));
1084 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1085 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1086 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1088 fgSetBool("/sim/presets/onground", true);
1092 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1098 // Set current_options lon/lat given an airport id and heading (degrees)
1099 static bool fgSetPosFromFix( const string& id )
1101 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1102 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1104 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1108 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1113 * Initialize vor/ndb/ils/fix list management and query systems (as
1114 * well as simple airport db list)
1119 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1121 SGPath aptdb( globals->get_fg_root() );
1122 aptdb.append( "Airports/apt.dat" );
1124 SGPath p_metar( globals->get_fg_root() );
1125 p_metar.append( "Airports/metar.dat" );
1127 fgAirportDBLoad( aptdb.str(), p_metar.str() );
1128 FGAirport::installPropertyListener();
1129 FGPositioned::installCommands();
1131 FGNavList *navlist = new FGNavList;
1132 FGNavList *loclist = new FGNavList;
1133 FGNavList *gslist = new FGNavList;
1134 FGNavList *dmelist = new FGNavList;
1135 FGNavList *tacanlist = new FGNavList;
1136 FGNavList *carrierlist = new FGNavList;
1137 FGTACANList *channellist = new FGTACANList;
1139 globals->set_navlist( navlist );
1140 globals->set_loclist( loclist );
1141 globals->set_gslist( gslist );
1142 globals->set_dmelist( dmelist );
1143 globals->set_tacanlist( tacanlist );
1144 globals->set_carrierlist( carrierlist );
1145 globals->set_channellist( channellist );
1147 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1148 SG_LOG( SG_GENERAL, SG_ALERT,
1149 "Problems loading one or more navigational database" );
1152 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1153 SGPath p_fix( globals->get_fg_root() );
1154 p_fix.append( "Navaids/fix.dat" );
1156 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1158 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1159 flightgear::Airway::load();
1165 // Set the initial position based on presets (or defaults)
1166 bool fgInitPosition() {
1167 // cout << "fgInitPosition()" << endl;
1168 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1169 * SG_DEGREES_TO_RADIANS ;
1170 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1171 double alt = fgGetDouble("/sim/presets/altitude-ft");
1173 bool set_pos = false;
1175 // If glideslope is specified, then calculate offset-distance or
1176 // altitude relative to glide slope if either of those was not
1178 if ( fabs( gs ) > 0.01 ) {
1179 fgSetDistOrAltFromGlideSlope();
1183 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1184 // If not, check for an airport-id and use that.
1185 // If not, default to the middle of the KSFO field.
1186 // The default values for lon/lat are deliberately out of range
1187 // so that the airport-id can take effect; valid lon/lat will
1188 // override airport-id, however.
1189 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1190 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1191 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1192 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1197 string apt = fgGetString("/sim/presets/airport-id");
1198 string rwy_no = fgGetString("/sim/presets/runway");
1199 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1200 string vor = fgGetString("/sim/presets/vor-id");
1201 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1202 string ndb = fgGetString("/sim/presets/ndb-id");
1203 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1204 string carrier = fgGetString("/sim/presets/carrier");
1205 string parkpos = fgGetString("/sim/presets/parkpos");
1206 string fix = fgGetString("/sim/presets/fix");
1207 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1208 double hdg = hdg_preset->getDoubleValue();
1210 // save some start parameters, so that we can later say what the
1211 // user really requested. TODO generalize that and move it to options.cxx
1212 static bool start_options_saved = false;
1213 if (!start_options_saved) {
1214 start_options_saved = true;
1215 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1217 opt->setDoubleValue("latitude-deg", lat_deg);
1218 opt->setDoubleValue("longitude-deg", lon_deg);
1219 opt->setDoubleValue("heading-deg", hdg);
1220 opt->setStringValue("airport", apt.c_str());
1221 opt->setStringValue("runway", rwy_no.c_str());
1225 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1227 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1228 // An airport + parking position is requested
1229 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1230 // set tower position
1231 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1232 fgSetString("/sim/tower/airport-id", apt.c_str());
1237 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1238 // An airport + runway is requested
1239 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1240 // set tower position (a little off the heading for single
1242 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1243 fgSetString("/sim/tower/airport-id", apt.c_str());
1248 if ( !set_pos && !apt.empty() ) {
1249 // An airport is requested (find runway closest to hdg)
1250 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1251 // set tower position (a little off the heading for single
1253 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
1254 fgSetString("/sim/tower/airport-id", apt.c_str());
1259 if (hdg_preset->getDoubleValue() > 9990.0)
1260 hdg_preset->setDoubleValue(hdg);
1262 if ( !set_pos && !vor.empty() ) {
1263 // a VOR is requested
1264 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
1269 if ( !set_pos && !ndb.empty() ) {
1270 // an NDB is requested
1271 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
1276 if ( !set_pos && !carrier.empty() ) {
1277 // an aircraft carrier is requested
1278 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1283 if ( !set_pos && !fix.empty() ) {
1284 // a Fix is requested
1285 if ( fgSetPosFromFix( fix ) ) {
1291 // No lon/lat specified, no airport specified, default to
1292 // middle of KSFO field.
1293 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1294 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1297 fgSetDouble( "/position/longitude-deg",
1298 fgGetDouble("/sim/presets/longitude-deg") );
1299 fgSetDouble( "/position/latitude-deg",
1300 fgGetDouble("/sim/presets/latitude-deg") );
1301 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1303 // determine if this should be an on-ground or in-air start
1304 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1305 fgSetBool("/sim/presets/onground", false);
1307 fgSetBool("/sim/presets/onground", true);
1314 // General house keeping initializations
1315 bool fgInitGeneral() {
1318 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1319 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1321 root = globals->get_fg_root();
1322 if ( ! root.length() ) {
1323 // No root path set? Then bail ...
1324 SG_LOG( SG_GENERAL, SG_ALERT,
1325 "Cannot continue without a path to the base package "
1326 << "being defined." );
1329 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1331 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1333 char buf[512], *cwd = getcwd(buf, 511);
1335 SGPropertyNode *curr = fgGetNode("/sim", true);
1336 curr->removeChild("fg-current", 0, false);
1337 curr = curr->getChild("fg-current", 0, true);
1338 curr->setStringValue(cwd ? cwd : "");
1339 curr->setAttribute(SGPropertyNode::WRITE, false);
1341 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1342 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1346 // This is the top level init routine which calls all the other
1347 // initialization routines. If you are adding a subsystem to flight
1348 // gear, its initialization call should located in this routine.
1349 // Returns non-zero if a problem encountered.
1350 bool fgInitSubsystems() {
1351 // static const SGPropertyNode *longitude
1352 // = fgGetNode("/sim/presets/longitude-deg");
1353 // static const SGPropertyNode *latitude
1354 // = fgGetNode("/sim/presets/latitude-deg");
1355 // static const SGPropertyNode *altitude
1356 // = fgGetNode("/sim/presets/altitude-ft");
1358 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1359 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1361 ////////////////////////////////////////////////////////////////////
1362 // Initialize the event manager subsystem.
1363 ////////////////////////////////////////////////////////////////////
1365 globals->get_event_mgr()->init();
1366 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1368 ////////////////////////////////////////////////////////////////////
1369 // Initialize the property interpolator subsystem. Put into the INIT
1370 // group because the "nasal" subsystem may need it at GENERAL take-down.
1371 ////////////////////////////////////////////////////////////////////
1372 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1375 ////////////////////////////////////////////////////////////////////
1376 // Add the FlightGear property utilities.
1377 ////////////////////////////////////////////////////////////////////
1378 globals->add_subsystem("properties", new FGProperties);
1380 ////////////////////////////////////////////////////////////////////
1381 // Initialize the material property subsystem.
1382 ////////////////////////////////////////////////////////////////////
1384 SGPath mpath( globals->get_fg_root() );
1385 mpath.append( fgGetString("/sim/rendering/materials-file") );
1386 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1387 globals->get_props()) ) {
1388 SG_LOG( SG_GENERAL, SG_ALERT,
1389 "Error loading materials file " << mpath.str() );
1394 ////////////////////////////////////////////////////////////////////
1395 // Initialize the scenery management subsystem.
1396 ////////////////////////////////////////////////////////////////////
1398 globals->get_scenery()->get_scene_graph()
1399 ->addChild(simgear::Particles::getCommonRoot());
1400 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1402 ////////////////////////////////////////////////////////////////////
1403 // Initialize the flight model subsystem.
1404 ////////////////////////////////////////////////////////////////////
1406 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1408 ////////////////////////////////////////////////////////////////////
1409 // Initialize the weather subsystem.
1410 ////////////////////////////////////////////////////////////////////
1412 // Initialize the weather modeling subsystem
1413 globals->add_subsystem("environment", new FGEnvironmentMgr);
1415 ////////////////////////////////////////////////////////////////////
1416 // Initialize the aircraft systems and instrumentation (before the
1418 ////////////////////////////////////////////////////////////////////
1420 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1421 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1423 ////////////////////////////////////////////////////////////////////
1424 // Initialize the XML Autopilot subsystem.
1425 ////////////////////////////////////////////////////////////////////
1427 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1428 globals->add_subsystem( "route-manager", new FGRouteMgr );
1430 ////////////////////////////////////////////////////////////////////
1431 // Initialize the Input-Output subsystem
1432 ////////////////////////////////////////////////////////////////////
1433 globals->add_subsystem( "io", new FGIO );
1435 ////////////////////////////////////////////////////////////////////
1436 // Create and register the logger.
1437 ////////////////////////////////////////////////////////////////////
1439 globals->add_subsystem("logger", new FGLogger);
1441 ////////////////////////////////////////////////////////////////////
1442 // Create and register the XML GUI.
1443 ////////////////////////////////////////////////////////////////////
1445 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1447 //////////////////////////////////////////////////////////////////////
1448 // Initialize the 2D cloud subsystem.
1449 ////////////////////////////////////////////////////////////////////
1450 fgGetBool("/sim/rendering/bump-mapping", false);
1454 ////////////////////////////////////////////////////////////////////
1455 // Initialise the ATC Manager
1456 // Note that this is old stuff, but might be necessesary for the
1457 // current ATIS implementation. Therefore, leave it in here
1458 // until the ATIS system is ported over to make use of the ATIS
1459 // sub system infrastructure.
1460 ////////////////////////////////////////////////////////////////////
1462 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1463 globals->set_ATC_mgr(new FGATCMgr);
1464 globals->get_ATC_mgr()->init();
1466 ////////////////////////////////////////////////////////////////////
1467 // Initialize the ATC subsystem
1468 ////////////////////////////////////////////////////////////////////
1469 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1470 ////////////////////////////////////////////////////////////////////
1471 // Initialise the ATIS Subsystem
1472 ////////////////////////////////////////////////////////////////////
1473 //globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1476 ////////////////////////////////////////////////////////////////////
1477 // Initialize multiplayer subsystem
1478 ////////////////////////////////////////////////////////////////////
1480 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1482 ////////////////////////////////////////////////////////////////////
1483 // Initialise the AI Model Manager
1484 ////////////////////////////////////////////////////////////////////
1485 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1486 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1487 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1490 // It's probably a good idea to initialize the top level traffic manager
1491 // After the AI and ATC systems have been initialized properly.
1492 // AI Traffic manager
1493 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1495 ////////////////////////////////////////////////////////////////////
1496 // Add a new 2D panel.
1497 ////////////////////////////////////////////////////////////////////
1499 string panel_path(fgGetString("/sim/panel/path"));
1500 if (!panel_path.empty()) {
1501 FGPanel* p = fgReadPanel(panel_path);
1503 globals->set_current_panel(p);
1506 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1508 SG_LOG( SG_INPUT, SG_ALERT,
1509 "Error reading new panel from " << panel_path );
1513 ////////////////////////////////////////////////////////////////////
1514 // Initialize the controls subsystem.
1515 ////////////////////////////////////////////////////////////////////
1517 globals->get_controls()->init();
1518 globals->get_controls()->bind();
1521 ////////////////////////////////////////////////////////////////////
1522 // Initialize the input subsystem.
1523 ////////////////////////////////////////////////////////////////////
1525 globals->add_subsystem("input", new FGInput);
1528 ////////////////////////////////////////////////////////////////////
1529 // Initialize the replay subsystem
1530 ////////////////////////////////////////////////////////////////////
1531 globals->add_subsystem("replay", new FGReplay);
1533 #ifdef ENABLE_AUDIO_SUPPORT
1534 ////////////////////////////////////////////////////////////////////
1535 // Initialize the sound-effects subsystem.
1536 ////////////////////////////////////////////////////////////////////
1537 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1540 ////////////////////////////////////////////////////////////////////
1541 // Initialize the lighting subsystem.
1542 ////////////////////////////////////////////////////////////////////
1544 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1546 // ordering here is important : Nasal (via events), then models, then views
1547 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1549 FGAircraftModel* acm = new FGAircraftModel;
1550 globals->set_aircraft_model(acm);
1551 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1553 FGModelMgr* mm = new FGModelMgr;
1554 globals->set_model_mgr(mm);
1555 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1557 FGViewMgr *viewmgr = new FGViewMgr;
1558 globals->set_viewmgr( viewmgr );
1559 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1561 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1562 SGSubsystemMgr::DISPLAY);
1564 ////////////////////////////////////////////////////////////////////
1565 // Bind and initialize subsystems.
1566 ////////////////////////////////////////////////////////////////////
1568 globals->get_subsystem_mgr()->bind();
1569 globals->get_subsystem_mgr()->init();
1571 ////////////////////////////////////////////////////////////////////////
1572 // Initialize the Nasal interpreter.
1573 // Do this last, so that the loaded scripts see initialized state
1574 ////////////////////////////////////////////////////////////////////////
1575 FGNasalSys* nasal = new FGNasalSys();
1576 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1579 // initialize methods that depend on other subsystems.
1580 globals->get_subsystem_mgr()->postinit();
1582 ////////////////////////////////////////////////////////////////////////
1583 // End of subsystem initialization.
1584 ////////////////////////////////////////////////////////////////////
1586 fgSetBool("/sim/initialized", true);
1588 SG_LOG( SG_GENERAL, SG_INFO, endl);
1590 // Save the initial state for future
1592 globals->saveInitialState();
1597 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1598 void fgReInitSubsystems()
1600 static const SGPropertyNode *master_freeze
1601 = fgGetNode("/sim/freeze/master");
1603 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1605 // setup state to begin re-init
1606 bool freeze = master_freeze->getBoolValue();
1608 fgSetBool("/sim/freeze/master", true);
1611 fgSetBool("/sim/signals/reinit", true);
1612 fgSetBool("/sim/crashed", false);
1614 // do actual re-init steps
1615 globals->get_subsystem("flight")->unbind();
1617 // reset control state, before restoring initial state; -set or config files
1618 // may specify values for flaps, trim tabs, magnetos, etc
1619 globals->get_controls()->reset_all();
1621 globals->restoreInitialState();
1623 // update our position based on current presets
1626 // Force reupdating the positions of the ai 3d models. They are used for
1627 // initializing ground level for the FDM.
1628 globals->get_subsystem("ai_model")->reinit();
1630 // Initialize the FDM
1631 globals->get_subsystem("flight")->reinit();
1633 // reset replay buffers
1634 globals->get_subsystem("replay")->reinit();
1636 // reload offsets from config defaults
1637 globals->get_viewmgr()->reinit();
1639 globals->get_subsystem("time")->reinit();
1641 // need to bind FDMshell again, since we manually unbound it above...
1642 globals->get_subsystem("flight")->bind();
1644 // setup state to end re-init
1645 fgSetBool("/sim/signals/reinit", false);
1647 fgSetBool("/sim/freeze/master", false);
1649 fgSetBool("/sim/sceneryloaded",false);
1653 ///////////////////////////////////////////////////////////////////////////////
1654 // helper object to implement the --show-aircraft command.
1655 // resides here so we can share the fgFindAircraftInDir template above,
1656 // and hence ensure this command lists exectly the same aircraft as the normal
1663 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1667 void show(const SGPath& path)
1669 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1671 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1672 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1673 cout << "Available aircraft:" << endl;
1674 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1675 cout << _aircraft[i] << endl;
1680 bool processAircraft(const SGPath& path)
1682 SGPropertyNode root;
1684 readProperties(path.str(), &root);
1685 } catch (sg_exception& ) {
1690 string descStr(" ");
1691 descStr += path.file();
1692 // trim common suffix from file names
1693 int nPos = descStr.rfind("-set.xml");
1694 if (nPos == (int)(descStr.size() - 8)) {
1695 descStr.resize(nPos);
1698 SGPropertyNode *node = root.getNode("sim");
1700 SGPropertyNode* desc = node->getNode("description");
1701 // if a status tag is found, read it in
1702 if (node->hasValue("status")) {
1703 maturity = getNumMaturity(node->getStringValue("status"));
1707 if (descStr.size() <= 27+3) {
1708 descStr.append(29+3-descStr.size(), ' ');
1711 descStr.append( 32, ' ');
1713 descStr += desc->getStringValue();
1715 } // of have 'sim' node
1717 if (maturity < _minStatus) {
1721 _aircraft.push_back(descStr);
1726 int getNumMaturity(const char * str)
1728 // changes should also be reflected in $FG_ROOT/data/options.xml &
1729 // $FG_ROOT/data/Translations/string-default.xml
1730 const char* levels[] = {"alpha","beta","early-production","production"};
1732 if (!strcmp(str, "all")) {
1736 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1737 if (strcmp(str,levels[i])==0)
1743 // recommended in Meyers, Effective STL when internationalization and embedded
1744 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1745 struct ciLessLibC : public std::binary_function<string, string, bool>
1747 bool operator()(const std::string &lhs, const std::string &rhs) const
1749 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1754 string_list _aircraft;
1757 void fgShowAircraft(const SGPath &path)
1763 cout << "Hit a key to continue..." << endl;