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()
35 #if defined( _MSC_VER) || defined(__MINGW32__)
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
42 // work around a stdc++ lib bug in some versions of linux, but doesn't
43 // seem to hurt to have this here for all versions of Linux.
45 # define _G_NO_EXTERN_TEMPLATES
48 #include <simgear/compiler.h>
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/event_mgr.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/interpolator.hxx>
58 #include <simgear/scene/material/matlib.hxx>
59 #include <simgear/scene/model/particles.hxx>
60 #include <simgear/sound/soundmgr_openal.hxx>
61 #include <simgear/timing/sg_time.hxx>
62 #include <simgear/timing/lowleveltime.h>
64 #include <Aircraft/aircraft.hxx>
65 #include <Aircraft/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/dynamics.hxx>
72 #include <AIModel/AIManager.hxx>
73 #include <ATCDCL/ATCmgr.hxx>
74 #include <ATCDCL/AIMgr.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/xmlauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <FDM/SP/ADA.hxx>
82 #include <FDM/SP/ACMS.hxx>
83 #include <FDM/SP/MagicCarpet.hxx>
84 #include <FDM/SP/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/UFO.hxx>
91 #include <FDM/NullFDM.hxx>
92 #include <FDM/YASim/YASim.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Navaids/fix.hxx>
103 #include <Navaids/fixlist.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 <Time/sunsolver.hxx>
111 #include <Time/tmp.hxx>
112 #include <Traffic/TrafficMgr.hxx>
113 #include <MultiPlayer/multiplaymgr.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Environment/ridge_lift.hxx>
118 #include "fg_init.hxx"
120 #include "fg_commands.hxx"
121 #include "fg_props.hxx"
122 #include "options.hxx"
123 #include "globals.hxx"
124 #include "logger.hxx"
125 #include "renderer.hxx"
126 #include "viewmgr.hxx"
128 #include "ATCDCL/commlist.hxx"
131 # include <CoreFoundation/CoreFoundation.h>
136 extern const char *default_root;
139 // Scan the command line options for the specified option and return
141 static string fgScanForOption( const string& option, int argc, char **argv ) {
144 if (hostname == NULL)
147 gethostname(_hostname, 256);
148 hostname = strdup(_hostname);
149 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__ )
209 // Next check home directory for .fgfsrc.hostname file
211 if ( homedir != NULL ) {
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
243 bool fgInitFGRoot ( int argc, char **argv ) {
246 // First parse command line options looking for --fg-root=, this
247 // will override anything specified in a config file
248 root = fgScanForOption( "--fg-root=", argc, argv);
250 // Check in one of the user configuration files.
252 root = fgScanForOption( "--fg-root=" );
254 // Next check if fg-root is set as an env variable
255 if ( root.empty() ) {
256 char *envp = ::getenv( "FG_ROOT" );
257 if ( envp != NULL ) {
262 // Otherwise, default to a random compiled-in location if we can't
263 // find fg-root any other way.
264 if ( root.empty() ) {
265 #if defined( __CYGWIN__ )
266 root = "/FlightGear";
267 #elif defined( WIN32 )
268 root = "\\FlightGear";
269 #elif defined(__APPLE__)
271 The following code looks for the base package inside the application
272 bundle, in the standard Contents/Resources location.
274 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
276 // look for a 'data' subdir
277 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
279 // now convert down to a path, and the a c-string
280 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
281 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
283 CFRelease(resourcesUrl);
291 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
292 globals->set_fg_root(root);
298 // Read in configuration (files and command line options) but only set
300 bool fgInitFGAircraft ( int argc, char **argv ) {
303 // First parse command line options looking for --aircraft=, this
304 // will override anything specified in a config file
305 aircraft = fgScanForOption( "--aircraft=", argc, argv );
306 if ( aircraft.empty() ) {
307 // check synonym option
308 aircraft = fgScanForOption( "--vehicle=", argc, argv );
311 // Check in one of the user configuration files.
312 if ( aircraft.empty() ) {
313 aircraft = fgScanForOption( "--aircraft=" );
315 if ( aircraft.empty() ) {
316 aircraft = fgScanForOption( "--vehicle=" );
319 // if an aircraft was specified, set the property name
320 if ( !aircraft.empty() ) {
321 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
322 fgSetString("/sim/aircraft", aircraft.c_str() );
324 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
331 // Return the current base package version
332 string fgBasePackageVersion() {
333 SGPath base_path( globals->get_fg_root() );
334 base_path.append("version");
336 sg_gzifstream in( base_path.str() );
337 if ( !in.is_open() ) {
338 SGPath old_path( globals->get_fg_root() );
339 old_path.append( "Thanks" );
340 sg_gzifstream old( old_path.str() );
341 if ( !old.is_open() ) {
344 return "[old version]";
355 // Initialize the localization
356 SGPropertyNode *fgInitLocale(const char *language) {
357 SGPropertyNode *c_node = NULL, *d_node = NULL;
358 SGPropertyNode *intl = fgGetNode("/sim/intl");
360 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
362 // localization not defined
367 // Select the proper language from the list
369 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
370 for (unsigned int i = 0; i < locale.size(); i++) {
372 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
373 for (unsigned int j = 0; j < lang.size(); j++) {
375 if (!strcmp(lang[j]->getStringValue(), language)) {
384 d_node = intl->getChild("locale");
388 // Check for localized font
389 SGPropertyNode *font_n = c_node->getNode("font", true);
390 if ( !strcmp(font_n->getStringValue(), "") )
391 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
395 // Load the default strings
397 SGPath d_path( globals->get_fg_root() );
399 const char *d_path_str = d_node->getStringValue("strings");
401 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
405 d_path.append(d_path_str);
406 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
408 SGPropertyNode *strings = c_node->getNode("strings");
410 readProperties(d_path.str(), strings);
411 } catch (const sg_exception &) {
412 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
417 // Load the language specific strings
419 if (c_node != d_node) {
420 SGPath c_path( globals->get_fg_root() );
422 const char *c_path_str = c_node->getStringValue("strings");
424 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
428 c_path.append(c_path_str);
429 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
432 readProperties(c_path.str(), strings);
433 } catch (const sg_exception &) {
434 SG_LOG(SG_GENERAL, SG_ALERT,
435 "Unable to read the localized strings from " << c_path.str());
445 // Initialize the localization routines
446 bool fgDetectLanguage() {
447 const char *language = ::getenv("LANG");
449 if (language == NULL) {
450 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
454 SGPropertyNode *locale = fgInitLocale(language);
456 SG_LOG(SG_GENERAL, SG_ALERT,
457 "No internationalization settings specified in preferences.xml" );
462 globals->set_locale( locale );
467 // Attempt to locate and parse the various non-XML config files in order
468 // from least precidence to greatest precidence
470 do_options (int argc, char ** argv)
472 // Check for $fg_root/system.fgfsrc
473 SGPath config( globals->get_fg_root() );
474 config.append( "system.fgfsrc" );
475 fgParseOptions(config.str());
477 #if defined( unix ) || defined( __CYGWIN__ )
478 config.concat( "." );
479 config.concat( hostname );
480 fgParseOptions(config.str());
483 // Check for ~/.fgfsrc
484 if ( homedir != NULL ) {
485 config.set( homedir );
486 config.append( ".fgfsrc" );
487 fgParseOptions(config.str());
490 #if defined( unix ) || defined( __CYGWIN__ )
491 // Check for ~/.fgfsrc.hostname
492 config.concat( "." );
493 config.concat( hostname );
494 fgParseOptions(config.str());
497 // Parse remaining command line options
498 // These will override anything specified in a config file
499 fgParseArgs(argc, argv);
503 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
504 SGPropertyNode *cache, int depth = 0 )
506 const int MAXDEPTH = 1;
509 ulDir *dirp = ulOpenDir(path.str().c_str());
511 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
516 while ((dire = ulReadDir(dirp)) != NULL) {
518 if (depth > MAXDEPTH)
521 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
522 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
526 next.append(dire->d_name);
528 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
529 if ( ! result.empty() )
533 int len = strlen(dire->d_name);
534 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
540 if (!cache->getChild("aircraft", i++, false))
543 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
545 n = entry->getNode("file", true);
546 n->setStringValue(dire->d_name);
547 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
549 n = entry->getNode("path", true);
550 n->setStringValue(path.str().c_str());
551 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
553 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
565 // Read in configuration (file and command line)
566 bool fgInitConfig ( int argc, char **argv ) {
568 // First, set some sane default values
571 // Read global preferences from $FG_ROOT/preferences.xml
572 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
573 fgLoadProps("preferences.xml", globals->get_props());
574 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
576 // Detect the required language as early as possible
577 if ( !fgDetectLanguage() ) {
581 SGPropertyNode autosave;
582 #if defined( _MSC_VER ) || defined( __MINGW32__ )
583 char *envp = ::getenv( "APPDATA" );
585 SGPath config( envp );
586 config.append( "flightgear.org" );
588 if ( homedir != NULL ) {
589 SGPath config( homedir );
590 config.append( ".fgfs" );
592 const char *fg_home = getenv("FG_HOME");
596 SGPath home_export(config.str());
597 home_export.append("Export/dummy");
598 home_export.create_dir(0777);
600 // Set /sim/fg-home and don't allow malign code to override it until
601 // Nasal security is set up. Use FG_HOME if necessary.
602 SGPropertyNode *home = fgGetNode("/sim", true);
603 home->removeChild("fg-home", 0, false);
604 home = home->getChild("fg-home", 0, true);
605 home->setStringValue(config.c_str());
606 home->setAttribute(SGPropertyNode::WRITE, false);
608 config.append( "autosave.xml" );
609 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
611 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
613 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
615 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
617 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
620 // Scan user config files and command line for a specified aircraft.
621 fgInitFGAircraft(argc, argv);
623 string aircraft = fgGetString( "/sim/aircraft", "" );
624 if ( aircraft.size() > 0 ) {
625 SGPath aircraft_search( globals->get_fg_root() );
626 aircraft_search.append( "Aircraft" );
628 string aircraft_set = aircraft + "-set.xml";
631 // check if the *-set.xml file is already in the cache
632 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
633 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
634 for (unsigned int i = 0; i < cache.size(); i++) {
635 const char *name = cache[i]->getStringValue("file", "");
636 if (aircraft_set == name) {
637 const char *path = cache[i]->getStringValue("path", "");
647 if (result.empty()) {
648 // prepare cache for rescan
649 SGPropertyNode *n = cache_root->getNode("fg-root", true);
650 n->setStringValue(globals->get_fg_root().c_str());
651 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
652 cache_root->removeChildren("aircraft");
654 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
657 if ( !result.empty() ) {
658 fgSetString( "/sim/aircraft-dir", result.c_str() );
659 SGPath full_name( result );
660 full_name.append( aircraft_set );
662 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
663 << " from " << full_name.str());
665 readProperties( full_name.str(), globals->get_props() );
666 } catch ( const sg_exception &e ) {
667 string message = "Error reading default aircraft: ";
668 message += e.getFormattedMessage();
669 SG_LOG(SG_INPUT, SG_ALERT, message);
673 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
679 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
682 copyProperties(&autosave, globals->get_props());
684 // parse options after loading aircraft to ensure any user
685 // overrides of defaults are honored.
686 do_options(argc, argv);
691 // Set current tower position lon/lat given an airport id
692 static bool fgSetTowerPosFromAirportID( const string& id) {
693 const FGAirport *a = fgFindAirportID( id);
695 SGGeod tower = a->getTowerLocation();
696 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
697 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
698 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
706 struct FGTowerLocationListener : SGPropertyChangeListener {
707 void valueChanged(SGPropertyNode* node) {
708 const string id(node->getStringValue());
709 fgSetTowerPosFromAirportID(id);
713 void fgInitTowerLocationListener() {
714 fgGetNode("/sim/tower/airport-id", true)
715 ->addChangeListener( new FGTowerLocationListener(), true );
718 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
720 SGGeod startPos(aStartPos);
721 if (aTargetHeading == HUGE_VAL) {
722 aTargetHeading = aHeading;
725 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
726 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
727 offsetDistance *= SG_NM_TO_METER;
728 double offsetAzimuth = aHeading;
729 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
730 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
731 aHeading = aTargetHeading;
736 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
741 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
742 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
743 fgSetDouble("/sim/presets/heading-deg", aHeading );
745 // other code depends on the actual values being set ...
746 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
747 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
748 fgSetDouble("/orientation/heading-deg", aHeading );
751 // Set current_options lon/lat given an airport id and heading (degrees)
752 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
756 // set initial position from runway and heading
757 SG_LOG( SG_GENERAL, SG_INFO,
758 "Attempting to set starting position from airport code "
759 << id << " heading " << tgt_hdg );
761 const FGAirport* apt = fgFindAirportID(id);
762 if (!apt) return false;
763 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
764 fgSetString("/sim/atc/runway", r->ident().c_str());
766 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
767 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
771 // Set current_options lon/lat given an airport id and parkig position name
772 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
776 // can't see an easy way around this const_cast at the moment
777 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
779 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
782 FGAirportDynamics* dcs = apt->getDynamics();
784 SG_LOG( SG_GENERAL, SG_ALERT,
785 "Failed to find parking position " << parkpos <<
786 " at airport " << id );
790 int park_index = dcs->getNrOfParkings() - 1;
791 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
792 if (park_index < 0) {
793 SG_LOG( SG_GENERAL, SG_ALERT,
794 "Failed to find parking position " << parkpos <<
795 " at airport " << id );
798 FGParking* parking = dcs->getParking(park_index);
800 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
801 parking->getHeading());
806 // Set current_options lon/lat given an airport id and runway number
807 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
811 // set initial position from airport and runway number
812 SG_LOG( SG_GENERAL, SG_INFO,
813 "Attempting to set starting position for "
814 << id << ":" << rwy );
816 const FGAirport* apt = fgFindAirportID(id);
818 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
822 if (!apt->hasRunwayWithIdent(rwy)) {
823 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
824 "Failed to find runway " << rwy <<
825 " at airport " << id << ". Using default runway." );
829 FGRunway* r(apt->getRunwayByIdent(rwy));
830 fgSetString("/sim/atc/runway", r->ident().c_str());
831 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
832 fgApplyStartOffset(startPos, r->headingDeg());
837 static void fgSetDistOrAltFromGlideSlope() {
838 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
839 string apt_id = fgGetString("/sim/presets/airport-id");
840 double gs = fgGetDouble("/sim/presets/glideslope-deg")
841 * SG_DEGREES_TO_RADIANS ;
842 double od = fgGetDouble("/sim/presets/offset-distance-nm");
843 double alt = fgGetDouble("/sim/presets/altitude-ft");
845 double apt_elev = 0.0;
846 if ( ! apt_id.empty() ) {
847 apt_elev = fgGetAirportElev( apt_id );
848 if ( apt_elev < -9990.0 ) {
855 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
856 // set altitude from glideslope and offset-distance
857 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
858 alt = fabs(od*tan(gs)) + apt_elev;
859 fgSetDouble("/sim/presets/altitude-ft", alt);
860 fgSetBool("/sim/presets/onground", false);
861 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
863 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
864 // set offset-distance from glideslope and altitude
865 od = (alt - apt_elev) / tan(gs);
866 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
867 fgSetDouble("/sim/presets/offset-distance-nm", od);
868 fgSetBool("/sim/presets/onground", false);
869 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
871 } else if( fabs(gs) > 0.01 ) {
872 SG_LOG( SG_GENERAL, SG_ALERT,
873 "Glideslope given but not altitude or offset-distance." );
874 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
875 fgSetDouble("/sim/presets/glideslope-deg", 0);
876 fgSetBool("/sim/presets/onground", true);
881 // Set current_options lon/lat given an airport id and heading (degrees)
882 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
884 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
887 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
888 << id << ":" << freq );
892 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
896 // Set current_options lon/lat given an aircraft carrier id
897 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
899 // set initial position from runway and heading
903 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
904 double lon = geodPos.getLongitudeDeg();
905 double lat = geodPos.getLatitudeDeg();
906 double alt = geodPos.getElevationFt();
908 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
909 << carrier << " at lat = " << lat << ", lon = " << lon
910 << ", alt = " << alt << ", heading = " << heading);
912 fgSetDouble("/sim/presets/longitude-deg", lon);
913 fgSetDouble("/sim/presets/latitude-deg", lat);
914 fgSetDouble("/sim/presets/altitude-ft", alt);
915 fgSetDouble("/sim/presets/heading-deg", heading);
916 fgSetDouble("/position/longitude-deg", lon);
917 fgSetDouble("/position/latitude-deg", lat);
918 fgSetDouble("/position/altitude-ft", alt);
919 fgSetDouble("/orientation/heading-deg", heading);
921 fgSetString("/sim/presets/speed-set", "UVW");
922 fgSetDouble("/velocities/uBody-fps", uvw(0));
923 fgSetDouble("/velocities/vBody-fps", uvw(1));
924 fgSetDouble("/velocities/wBody-fps", uvw(2));
925 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
926 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
927 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
929 fgSetBool("/sim/presets/onground", true);
933 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
939 // Set current_options lon/lat given an airport id and heading (degrees)
940 static bool fgSetPosFromFix( const string& id )
942 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
943 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
945 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
949 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
954 * Initialize vor/ndb/ils/fix list management and query systems (as
955 * well as simple airport db list)
960 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
962 SGPath aptdb( globals->get_fg_root() );
963 aptdb.append( "Airports/apt.dat" );
965 SGPath p_metar( globals->get_fg_root() );
966 p_metar.append( "Airports/metar.dat" );
968 // Initialise the frequency search map BEFORE reading
969 // the airport database:
970 current_commlist = new FGCommList;
971 current_commlist->init( globals->get_fg_root() );
972 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
974 FGNavList *navlist = new FGNavList;
975 FGNavList *loclist = new FGNavList;
976 FGNavList *gslist = new FGNavList;
977 FGNavList *dmelist = new FGNavList;
978 FGNavList *tacanlist = new FGNavList;
979 FGNavList *carrierlist = new FGNavList;
980 FGTACANList *channellist = new FGTACANList;
982 globals->set_navlist( navlist );
983 globals->set_loclist( loclist );
984 globals->set_gslist( gslist );
985 globals->set_dmelist( dmelist );
986 globals->set_tacanlist( tacanlist );
987 globals->set_carrierlist( carrierlist );
988 globals->set_channellist( channellist );
990 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
991 SG_LOG( SG_GENERAL, SG_ALERT,
992 "Problems loading one or more navigational database" );
995 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
996 SGPath p_fix( globals->get_fg_root() );
997 p_fix.append( "Navaids/fix.dat" );
999 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1001 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1002 SGPath p_awy( globals->get_fg_root() );
1003 p_awy.append( "Navaids/awy.dat" );
1004 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1005 //cerr << "Loading Airways" << endl;
1006 awyNet->load (p_awy );
1008 //cerr << "initializing airways" << endl;
1009 globals->set_airwaynet( awyNet );
1015 // Set the initial position based on presets (or defaults)
1016 bool fgInitPosition() {
1017 // cout << "fgInitPosition()" << endl;
1018 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1019 * SG_DEGREES_TO_RADIANS ;
1020 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1021 double alt = fgGetDouble("/sim/presets/altitude-ft");
1023 bool set_pos = false;
1025 // If glideslope is specified, then calculate offset-distance or
1026 // altitude relative to glide slope if either of those was not
1028 if ( fabs( gs ) > 0.01 ) {
1029 fgSetDistOrAltFromGlideSlope();
1033 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1034 // If not, check for an airport-id and use that.
1035 // If not, default to the middle of the KSFO field.
1036 // The default values for lon/lat are deliberately out of range
1037 // so that the airport-id can take effect; valid lon/lat will
1038 // override airport-id, however.
1039 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1040 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1041 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1042 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1047 string apt = fgGetString("/sim/presets/airport-id");
1048 string rwy_no = fgGetString("/sim/presets/runway");
1049 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1050 string vor = fgGetString("/sim/presets/vor-id");
1051 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1052 string ndb = fgGetString("/sim/presets/ndb-id");
1053 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1054 string carrier = fgGetString("/sim/presets/carrier");
1055 string parkpos = fgGetString("/sim/presets/parkpos");
1056 string fix = fgGetString("/sim/presets/fix");
1057 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1058 double hdg = hdg_preset->getDoubleValue();
1060 // save some start parameters, so that we can later say what the
1061 // user really requested. TODO generalize that and move it to options.cxx
1062 static bool start_options_saved = false;
1063 if (!start_options_saved) {
1064 start_options_saved = true;
1065 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1067 opt->setDoubleValue("latitude-deg", lat_deg);
1068 opt->setDoubleValue("longitude-deg", lon_deg);
1069 opt->setDoubleValue("heading-deg", hdg);
1070 opt->setStringValue("airport", apt.c_str());
1071 opt->setStringValue("runway", rwy_no.c_str());
1075 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1077 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1078 // An airport + parking position is requested
1079 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1080 // set tower position
1081 fgSetString("/sim/tower/airport-id", apt.c_str());
1086 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1087 // An airport + runway is requested
1088 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1089 // set tower position (a little off the heading for single
1091 fgSetString("/sim/tower/airport-id", apt.c_str());
1096 if ( !set_pos && !apt.empty() ) {
1097 // An airport is requested (find runway closest to hdg)
1098 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1099 // set tower position (a little off the heading for single
1101 fgSetString("/sim/tower/airport-id", apt.c_str());
1106 if (hdg_preset->getDoubleValue() > 9990.0)
1107 hdg_preset->setDoubleValue(hdg);
1109 if ( !set_pos && !vor.empty() ) {
1110 // a VOR is requested
1111 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1116 if ( !set_pos && !ndb.empty() ) {
1117 // an NDB is requested
1118 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1123 if ( !set_pos && !carrier.empty() ) {
1124 // an aircraft carrier is requested
1125 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1130 if ( !set_pos && !fix.empty() ) {
1131 // a Fix is requested
1132 if ( fgSetPosFromFix( fix ) ) {
1138 // No lon/lat specified, no airport specified, default to
1139 // middle of KSFO field.
1140 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1141 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1144 fgSetDouble( "/position/longitude-deg",
1145 fgGetDouble("/sim/presets/longitude-deg") );
1146 fgSetDouble( "/position/latitude-deg",
1147 fgGetDouble("/sim/presets/latitude-deg") );
1148 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1150 // determine if this should be an on-ground or in-air start
1151 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1152 fgSetBool("/sim/presets/onground", false);
1154 fgSetBool("/sim/presets/onground", true);
1161 // General house keeping initializations
1162 bool fgInitGeneral() {
1165 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1166 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1168 root = globals->get_fg_root();
1169 if ( ! root.length() ) {
1170 // No root path set? Then bail ...
1171 SG_LOG( SG_GENERAL, SG_ALERT,
1172 "Cannot continue without a path to the base package "
1173 << "being defined." );
1176 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1178 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1180 char buf[512], *cwd = getcwd(buf, 511);
1182 SGPropertyNode *curr = fgGetNode("/sim", true);
1183 curr->removeChild("fg-current", 0, false);
1184 curr = curr->getChild("fg-current", 0, true);
1185 curr->setStringValue(cwd ? cwd : "");
1186 curr->setAttribute(SGPropertyNode::WRITE, false);
1188 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1189 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1194 // Initialize the flight model subsystem. This just creates the
1195 // object. The actual fdm initialization is delayed until we get a
1196 // proper scenery elevation hit. This is checked for in main.cxx
1200 if ( cur_fdm_state ) {
1201 delete cur_fdm_state;
1205 double dt = 1.0 / fgGetInt("/sim/model-hz");
1206 string model = fgGetString("/sim/flight-model");
1208 if ( model == "larcsim" ) {
1209 cur_fdm_state = new FGLaRCsim( dt );
1210 } else if ( model == "jsb" ) {
1211 cur_fdm_state = new FGJSBsim( dt );
1213 } else if ( model == "ada" ) {
1214 cur_fdm_state = new FGADA( dt );
1215 } else if ( model == "acms" ) {
1216 cur_fdm_state = new FGACMS( dt );
1217 } else if ( model == "balloon" ) {
1218 cur_fdm_state = new FGBalloonSim( dt );
1219 } else if ( model == "magic" ) {
1220 cur_fdm_state = new FGMagicCarpet( dt );
1222 } else if ( model == "ufo" ) {
1223 cur_fdm_state = new FGUFO( dt );
1224 } else if ( model == "external" ) {
1225 // external is a synonym for "--fdm=null" and is
1226 // maintained here for backwards compatibility
1227 cur_fdm_state = new FGNullFDM( dt );
1228 } else if ( model.find("network") == 0 ) {
1229 string host = "localhost";
1233 string net_options = model.substr(8);
1234 string::size_type begin, end;
1237 end = net_options.find( ",", begin );
1238 if ( end != string::npos ) {
1239 host = net_options.substr(begin, end - begin);
1243 end = net_options.find( ",", begin );
1244 if ( end != string::npos ) {
1245 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1249 end = net_options.find( ",", begin );
1250 if ( end != string::npos ) {
1251 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1255 end = net_options.find( ",", begin );
1256 if ( end != string::npos ) {
1257 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1260 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1261 } else if ( model.find("pipe") == 0 ) {
1262 // /* old */ string pipe_path = model.substr(5);
1263 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1264 string pipe_path = "";
1265 string pipe_protocol = "";
1266 string pipe_options = model.substr(5);
1267 string::size_type begin, end;
1270 end = pipe_options.find( ",", begin );
1271 if ( end != string::npos ) {
1272 pipe_path = pipe_options.substr(begin, end - begin);
1275 // protocol (last option)
1276 pipe_protocol = pipe_options.substr(begin);
1277 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1278 } else if ( model == "null" ) {
1279 cur_fdm_state = new FGNullFDM( dt );
1280 } else if ( model == "yasim" ) {
1281 cur_fdm_state = new YASim( dt );
1283 throw sg_exception(string("Unrecognized flight model '") + model
1284 + "', cannot init flight dynamics model.");
1288 // Initialize view parameters
1290 // force update of model so that viewer can get some data...
1291 globals->get_aircraft_model()->update(0);
1292 // run update for current view so that data is current...
1293 globals->get_viewmgr()->update(0);
1297 SGTime *fgInitTime() {
1299 static const SGPropertyNode *longitude
1300 = fgGetNode("/position/longitude-deg");
1301 static const SGPropertyNode *latitude
1302 = fgGetNode("/position/latitude-deg");
1303 static const SGPropertyNode *cur_time_override
1304 = fgGetNode("/sim/time/cur-time-override", true);
1306 SGPath zone( globals->get_fg_root() );
1307 zone.append( "Timezone" );
1308 SGTime *t = new SGTime( longitude->getDoubleValue()
1309 * SGD_DEGREES_TO_RADIANS,
1310 latitude->getDoubleValue()
1311 * SGD_DEGREES_TO_RADIANS,
1313 cur_time_override->getLongValue() );
1315 globals->set_warp_delta( 0 );
1317 t->update( 0.0, 0.0,
1318 cur_time_override->getLongValue(),
1319 globals->get_warp() );
1325 // set up a time offset (aka warp) if one is specified
1326 void fgInitTimeOffset() {
1327 static const SGPropertyNode *longitude
1328 = fgGetNode("/position/longitude-deg");
1329 static const SGPropertyNode *latitude
1330 = fgGetNode("/position/latitude-deg");
1331 static const SGPropertyNode *cur_time_override
1332 = fgGetNode("/sim/time/cur-time-override", true);
1334 // Handle potential user specified time offsets
1335 int orig_warp = globals->get_warp();
1336 SGTime *t = globals->get_time_params();
1337 time_t cur_time = t->get_cur_time();
1338 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1339 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1340 time_t aircraftLocalTime =
1341 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1343 // Okay, we now have several possible scenarios
1344 int offset = fgGetInt("/sim/startup/time-offset");
1345 string offset_type = fgGetString("/sim/startup/time-offset-type");
1348 if ( offset_type == "real" ) {
1350 } else if ( offset_type == "dawn" ) {
1351 warp = fgTimeSecondsUntilSunAngle( cur_time,
1352 longitude->getDoubleValue()
1353 * SGD_DEGREES_TO_RADIANS,
1354 latitude->getDoubleValue()
1355 * SGD_DEGREES_TO_RADIANS,
1357 } else if ( offset_type == "morning" ) {
1358 warp = fgTimeSecondsUntilSunAngle( cur_time,
1359 longitude->getDoubleValue()
1360 * SGD_DEGREES_TO_RADIANS,
1361 latitude->getDoubleValue()
1362 * SGD_DEGREES_TO_RADIANS,
1364 } else if ( offset_type == "noon" ) {
1365 warp = fgTimeSecondsUntilSunAngle( cur_time,
1366 longitude->getDoubleValue()
1367 * SGD_DEGREES_TO_RADIANS,
1368 latitude->getDoubleValue()
1369 * SGD_DEGREES_TO_RADIANS,
1371 } else if ( offset_type == "afternoon" ) {
1372 warp = fgTimeSecondsUntilSunAngle( cur_time,
1373 longitude->getDoubleValue()
1374 * SGD_DEGREES_TO_RADIANS,
1375 latitude->getDoubleValue()
1376 * SGD_DEGREES_TO_RADIANS,
1378 } else if ( offset_type == "dusk" ) {
1379 warp = fgTimeSecondsUntilSunAngle( cur_time,
1380 longitude->getDoubleValue()
1381 * SGD_DEGREES_TO_RADIANS,
1382 latitude->getDoubleValue()
1383 * SGD_DEGREES_TO_RADIANS,
1385 } else if ( offset_type == "evening" ) {
1386 warp = fgTimeSecondsUntilSunAngle( cur_time,
1387 longitude->getDoubleValue()
1388 * SGD_DEGREES_TO_RADIANS,
1389 latitude->getDoubleValue()
1390 * SGD_DEGREES_TO_RADIANS,
1392 } else if ( offset_type == "midnight" ) {
1393 warp = fgTimeSecondsUntilSunAngle( cur_time,
1394 longitude->getDoubleValue()
1395 * SGD_DEGREES_TO_RADIANS,
1396 latitude->getDoubleValue()
1397 * SGD_DEGREES_TO_RADIANS,
1399 } else if ( offset_type == "system-offset" ) {
1402 } else if ( offset_type == "gmt-offset" ) {
1403 warp = offset - (currGMT - systemLocalTime);
1405 } else if ( offset_type == "latitude-offset" ) {
1406 warp = offset - (aircraftLocalTime - systemLocalTime);
1408 } else if ( offset_type == "system" ) {
1409 warp = offset - (systemLocalTime - currGMT) - cur_time;
1410 } else if ( offset_type == "gmt" ) {
1411 warp = offset - cur_time;
1412 } else if ( offset_type == "latitude" ) {
1413 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1415 SG_LOG( SG_GENERAL, SG_ALERT,
1416 "FG_TIME::Unsupported offset type " << offset_type );
1419 globals->set_warp( orig_warp + warp );
1420 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1421 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1422 cur_time_override->getLongValue(),
1423 globals->get_warp() );
1425 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1426 << globals->get_warp() );
1430 // This is the top level init routine which calls all the other
1431 // initialization routines. If you are adding a subsystem to flight
1432 // gear, its initialization call should located in this routine.
1433 // Returns non-zero if a problem encountered.
1434 bool fgInitSubsystems() {
1435 // static const SGPropertyNode *longitude
1436 // = fgGetNode("/sim/presets/longitude-deg");
1437 // static const SGPropertyNode *latitude
1438 // = fgGetNode("/sim/presets/latitude-deg");
1439 // static const SGPropertyNode *altitude
1440 // = fgGetNode("/sim/presets/altitude-ft");
1441 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1442 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1444 ////////////////////////////////////////////////////////////////////
1445 // Initialize the event manager subsystem.
1446 ////////////////////////////////////////////////////////////////////
1448 globals->get_event_mgr()->init();
1449 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1451 ////////////////////////////////////////////////////////////////////
1452 // Initialize the sound manager subsystem.
1453 ////////////////////////////////////////////////////////////////////
1455 globals->get_soundmgr()->bind();
1456 globals->get_soundmgr()->init(fgGetString("/sim/sound/device-name", NULL));
1458 vector <const char*>devices =
1459 globals->get_soundmgr()->get_available_devices();
1460 for (unsigned int i=0; i<devices.size(); i++) {
1461 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
1462 p->setStringValue(devices[i]);
1466 ////////////////////////////////////////////////////////////////////
1467 // Initialize the property interpolator subsystem. Put into the INIT
1468 // group because the "nasal" subsystem may need it at GENERAL take-down.
1469 ////////////////////////////////////////////////////////////////////
1470 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1473 ////////////////////////////////////////////////////////////////////
1474 // Add the FlightGear property utilities.
1475 ////////////////////////////////////////////////////////////////////
1476 globals->add_subsystem("properties", new FGProperties);
1478 ////////////////////////////////////////////////////////////////////
1479 // Initialize the material property subsystem.
1480 ////////////////////////////////////////////////////////////////////
1482 SGPath mpath( globals->get_fg_root() );
1483 mpath.append( "materials.xml" );
1484 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1485 globals->get_props()) ) {
1486 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1491 ////////////////////////////////////////////////////////////////////
1492 // Initialize the scenery management subsystem.
1493 ////////////////////////////////////////////////////////////////////
1495 if ( globals->get_tile_mgr()->init() ) {
1496 // Load the local scenery data
1497 double visibility_meters = fgGetDouble("/environment/visibility-m");
1499 globals->get_tile_mgr()->update( visibility_meters );
1501 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1505 globals->get_scenery()->get_scene_graph()
1506 ->addChild(simgear::Particles::getCommonRoot());
1507 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1509 ////////////////////////////////////////////////////////////////////
1510 // Initialize the flight model subsystem.
1511 ////////////////////////////////////////////////////////////////////
1515 // allocates structures so must happen before any of the flight
1516 // model or control parameters are set
1517 fgAircraftInit(); // In the future this might not be the case.
1520 ////////////////////////////////////////////////////////////////////
1521 // Initialize the weather subsystem.
1522 ////////////////////////////////////////////////////////////////////
1524 // Initialize the weather modeling subsystem
1525 globals->add_subsystem("environment", new FGEnvironmentMgr);
1527 ////////////////////////////////////////////////////////////////////
1528 // Initialize the ridge lift simulation.
1529 ////////////////////////////////////////////////////////////////////
1531 // Initialize the ridgelift subsystem
1532 globals->add_subsystem("ridgelift", new FGRidgeLift);
1534 ////////////////////////////////////////////////////////////////////
1535 // Initialize the aircraft systems and instrumentation (before the
1537 ////////////////////////////////////////////////////////////////////
1539 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1540 globals->add_subsystem("systems", new FGSystemMgr);
1542 ////////////////////////////////////////////////////////////////////
1543 // Initialize the XML Autopilot subsystem.
1544 ////////////////////////////////////////////////////////////////////
1546 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1547 globals->add_subsystem( "route-manager", new FGRouteMgr );
1549 ////////////////////////////////////////////////////////////////////
1550 // Initialize the view manager subsystem.
1551 ////////////////////////////////////////////////////////////////////
1555 ////////////////////////////////////////////////////////////////////
1556 // Initialize the Input-Output subsystem
1557 ////////////////////////////////////////////////////////////////////
1558 globals->add_subsystem( "io", new FGIO );
1560 ////////////////////////////////////////////////////////////////////
1561 // Create and register the logger.
1562 ////////////////////////////////////////////////////////////////////
1564 globals->add_subsystem("logger", new FGLogger);
1566 ////////////////////////////////////////////////////////////////////
1567 // Create and register the XML GUI.
1568 ////////////////////////////////////////////////////////////////////
1570 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1573 ////////////////////////////////////////////////////////////////////
1574 // Initialize the local time subsystem.
1575 ////////////////////////////////////////////////////////////////////
1577 // update the current timezone each 30 minutes
1578 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1579 &fgUpdateLocalTime, 30*60 );
1580 fgInitTimeOffset(); // the environment subsystem needs this
1583 ////////////////////////////////////////////////////////////////////
1584 // Initialize the lighting subsystem.
1585 ////////////////////////////////////////////////////////////////////
1587 globals->add_subsystem("lighting", new FGLight);
1589 //////////////////////////////////////////////////////////////////////
1590 // Initialize the 2D cloud subsystem.
1591 ////////////////////////////////////////////////////////////////////
1592 fgGetBool("/sim/rendering/bump-mapping", false);
1594 #ifdef ENABLE_AUDIO_SUPPORT
1595 ////////////////////////////////////////////////////////////////////
1596 // Initialize the sound-effects subsystem.
1597 ////////////////////////////////////////////////////////////////////
1598 globals->add_subsystem("voice", new FGVoiceMgr);
1601 ////////////////////////////////////////////////////////////////////
1602 // Initialise the ATC Manager
1603 ////////////////////////////////////////////////////////////////////
1605 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1606 globals->set_ATC_mgr(new FGATCMgr);
1607 globals->get_ATC_mgr()->init();
1609 ////////////////////////////////////////////////////////////////////
1610 // Initialise the AI Manager
1611 ////////////////////////////////////////////////////////////////////
1613 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1614 globals->set_AI_mgr(new FGAIMgr);
1615 globals->get_AI_mgr()->init();
1617 ////////////////////////////////////////////////////////////////////
1618 // Initialise the AI Model Manager
1619 ////////////////////////////////////////////////////////////////////
1620 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1621 globals->add_subsystem("ai_model", new FGAIManager);
1622 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1625 // It's probably a good idea to initialize the top level traffic manager
1626 // After the AI and ATC systems have been initialized properly.
1627 // AI Traffic manager
1628 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1631 ////////////////////////////////////////////////////////////////////
1632 // Initialize the cockpit subsystem
1633 ////////////////////////////////////////////////////////////////////
1634 if( fgCockpitInit( ¤t_aircraft )) {
1635 // Cockpit initialized ok.
1637 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1642 ////////////////////////////////////////////////////////////////////
1643 // Add a new 2D panel.
1644 ////////////////////////////////////////////////////////////////////
1646 string panel_path = fgGetString("/sim/panel/path",
1647 "Panels/Default/default.xml");
1649 globals->set_current_panel( fgReadPanel(panel_path) );
1650 if (globals->get_current_panel() == 0) {
1651 SG_LOG( SG_INPUT, SG_ALERT,
1652 "Error reading new panel from " << panel_path );
1654 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1655 globals->get_current_panel()->init();
1656 globals->get_current_panel()->bind();
1660 ////////////////////////////////////////////////////////////////////
1661 // Initialize the controls subsystem.
1662 ////////////////////////////////////////////////////////////////////
1664 globals->get_controls()->init();
1665 globals->get_controls()->bind();
1668 ////////////////////////////////////////////////////////////////////
1669 // Initialize the input subsystem.
1670 ////////////////////////////////////////////////////////////////////
1672 globals->add_subsystem("input", new FGInput);
1675 ////////////////////////////////////////////////////////////////////
1676 // Initialize the replay subsystem
1677 ////////////////////////////////////////////////////////////////////
1678 globals->add_subsystem("replay", new FGReplay);
1681 ////////////////////////////////////////////////////////////////////
1682 // Bind and initialize subsystems.
1683 ////////////////////////////////////////////////////////////////////
1685 globals->get_subsystem_mgr()->bind();
1686 globals->get_subsystem_mgr()->init();
1688 ////////////////////////////////////////////////////////////////////
1689 // Initialize multiplayer subsystem
1690 ////////////////////////////////////////////////////////////////////
1692 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1693 globals->get_multiplayer_mgr()->init();
1695 ////////////////////////////////////////////////////////////////////////
1696 // Initialize the Nasal interpreter.
1697 // Do this last, so that the loaded scripts see initialized state
1698 ////////////////////////////////////////////////////////////////////////
1699 FGNasalSys* nasal = new FGNasalSys();
1700 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1703 // initialize methods that depend on other subsystems.
1704 globals->get_subsystem_mgr()->postinit();
1706 ////////////////////////////////////////////////////////////////////////
1707 // End of subsystem initialization.
1708 ////////////////////////////////////////////////////////////////////
1710 SG_LOG( SG_GENERAL, SG_INFO, endl);
1712 // Save the initial state for future
1714 globals->saveInitialState();
1720 void fgReInitSubsystems()
1722 // static const SGPropertyNode *longitude
1723 // = fgGetNode("/sim/presets/longitude-deg");
1724 // static const SGPropertyNode *latitude
1725 // = fgGetNode("/sim/presets/latitude-deg");
1726 static const SGPropertyNode *altitude
1727 = fgGetNode("/sim/presets/altitude-ft");
1728 static const SGPropertyNode *master_freeze
1729 = fgGetNode("/sim/freeze/master");
1731 SG_LOG( SG_GENERAL, SG_INFO,
1732 "fgReInitSubsystems(): /position/altitude = "
1733 << altitude->getDoubleValue() );
1735 bool freeze = master_freeze->getBoolValue();
1737 fgSetBool("/sim/freeze/master", true);
1739 fgSetBool("/sim/crashed", false);
1741 // Force reupdating the positions of the ai 3d models. They are used for
1742 // initializing ground level for the FDM.
1743 globals->get_subsystem("ai_model")->reinit();
1745 // Initialize the FDM
1748 // allocates structures so must happen before any of the flight
1749 // model or control parameters are set
1750 fgAircraftInit(); // In the future this might not be the case.
1752 // reload offsets from config defaults
1753 globals->get_viewmgr()->reinit();
1757 globals->get_controls()->reset_all();
1759 fgUpdateLocalTime();
1761 // re-init to proper time of day setting
1765 fgSetBool("/sim/freeze/master", false);
1767 fgSetBool("/sim/sceneryloaded",false);
1771 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1773 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1775 bool freeze = master_freeze->getBoolValue();
1777 master_freeze->setBoolValue(true);
1779 fgSetBool("/sim/signals/reinit", true);
1780 cur_fdm_state->unbind();
1782 // in case user has changed window size as
1783 // restoreInitialState() overwrites these
1784 int xsize = fgGetInt("/sim/startup/xsize");
1785 int ysize = fgGetInt("/sim/startup/ysize");
1787 // viewports also needs to be saved/restored as
1788 // restoreInitialState() overwrites these
1789 SGPropertyNode *guiNode = new SGPropertyNode;
1790 SGPropertyNode *cameraNode = new SGPropertyNode;
1791 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1792 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1793 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1795 globals->restoreInitialState();
1797 // update our position based on current presets
1800 // We don't know how to resize the window, so keep the last values
1801 // for xsize and ysize, and don't use the one set initially
1802 fgSetInt("/sim/startup/xsize", xsize);
1803 fgSetInt("/sim/startup/ysize", ysize);
1805 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1806 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1811 SGTime *t = globals->get_time_params();
1814 globals->set_time_params(t);
1816 fgReInitSubsystems();
1818 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1819 globals->get_renderer()->resize(xsize, ysize);
1820 fgSetBool("/sim/signals/reinit", false);
1823 master_freeze->setBoolValue(false);