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.
28 // For BC 5.01 this must be included before OpenGL includes.
29 #ifdef SG_MATH_EXCEPTION_CLASH
35 #include <string.h> // strcmp()
37 #if defined( unix ) || defined( __CYGWIN__ )
38 # include <unistd.h> // for gethostname()
40 #if defined( _MSC_VER) || defined(__MINGW32__)
41 # include <direct.h> // for getcwd()
42 # define getcwd _getcwd
45 // work around a stdc++ lib bug in some versions of linux, but doesn't
46 // seem to hurt to have this here for all versions of Linux.
48 # define _G_NO_EXTERN_TEMPLATES
51 #include <simgear/compiler.h>
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/math/point3d.hxx>
60 #include <simgear/math/polar3d.hxx>
61 #include <simgear/math/sg_geodesy.hxx>
62 #include <simgear/misc/sg_path.hxx>
63 #include <simgear/misc/interpolator.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/timing/sg_time.hxx>
66 #include <simgear/timing/lowleveltime.h>
68 #include <Aircraft/aircraft.hxx>
69 #include <Aircraft/replay.hxx>
70 #include <Airports/apt_loader.hxx>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <AIModel/AIManager.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/AIMgr.hxx>
76 #include <Autopilot/route_mgr.hxx>
77 #include <Autopilot/xmlauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
85 #include <FDM/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/MagicCarpet.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Sound/voice.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/sunsolver.hxx>
113 #include <Time/tmp.hxx>
114 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
117 #include <Environment/environment_mgr.hxx>
119 #include "fg_init.hxx"
121 #include "fg_commands.hxx"
122 #include "fg_props.hxx"
123 #include "options.hxx"
124 #include "globals.hxx"
125 #include "logger.hxx"
126 #include "viewmgr.hxx"
129 #if defined(FX) && defined(XMESA)
130 #include <GL/xmesa.h>
133 SG_USING_STD(string);
137 extern const char *default_root;
141 // Scan the command line options for the specified option and return
143 static string fgScanForOption( const string& option, int argc, char **argv ) {
146 if (hostname == NULL)
149 gethostname(_hostname, 256);
150 hostname = strdup(_hostname);
151 free_hostname = true;
154 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
156 int len = option.length();
159 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
161 string arg = argv[i];
162 if ( arg.find( option ) == 0 ) {
163 return arg.substr( len );
173 // Scan the user config files for the specified option and return
175 static string fgScanForOption( const string& option, const string& path ) {
176 sg_gzifstream in( path );
177 if ( !in.is_open() ) {
181 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
183 int len = option.length();
187 while ( ! in.eof() ) {
190 while ( in.get(c) && c != '\0' ) {
195 #if defined( macintosh )
196 getline( in, line, '\r' );
198 getline( in, line, '\n' );
201 // catch extraneous (DOS) line ending character
202 if ( line[line.length() - 1] < 32 ) {
203 line = line.substr( 0, line.length()-1 );
206 if ( line.find( option ) == 0 ) {
207 return line.substr( len );
216 // Scan the user config files for the specified option and return
218 static string fgScanForOption( const string& option ) {
221 #if defined( unix ) || defined( __CYGWIN__ )
222 // Next check home directory for .fgfsrc.hostname file
224 if ( homedir != NULL ) {
225 SGPath config( homedir );
226 config.append( ".fgfsrc" );
227 config.concat( "." );
228 config.concat( hostname );
229 arg = fgScanForOption( option, config.str() );
234 // Next check home directory for .fgfsrc file
236 if ( homedir != NULL ) {
237 SGPath config( homedir );
238 config.append( ".fgfsrc" );
239 arg = fgScanForOption( option, config.str() );
244 // Check for $fg_root/system.fgfsrc
245 SGPath config( globals->get_fg_root() );
246 config.append( "system.fgfsrc" );
247 arg = fgScanForOption( option, config.str() );
254 // Read in configuration (files and command line options) but only set
256 bool fgInitFGRoot ( int argc, char **argv ) {
259 // First parse command line options looking for --fg-root=, this
260 // will override anything specified in a config file
261 root = fgScanForOption( "--fg-root=", argc, argv);
263 // Check in one of the user configuration files.
265 root = fgScanForOption( "--fg-root=" );
267 // Next check if fg-root is set as an env variable
268 if ( root.empty() ) {
269 char *envp = ::getenv( "FG_ROOT" );
270 if ( envp != NULL ) {
275 // Otherwise, default to a random compiled-in location if we can't
276 // find fg-root any other way.
277 if ( root.empty() ) {
278 #if defined( __CYGWIN__ )
279 root = "/FlightGear";
280 #elif defined( WIN32 )
281 root = "\\FlightGear";
282 #elif defined(OSX_BUNDLE)
283 /* the following code looks for the base package directly inside
284 the application bundle. This can be changed fairly easily by
285 fiddling with the code below. And yes, I know it's ugly and verbose.
287 CFBundleRef appBundle = CFBundleGetMainBundle();
288 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
289 CFRelease(appBundle);
291 // look for a 'data' subdir directly inside the bundle : is there
292 // a better place? maybe in Resources? I don't know ...
293 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
295 // now convert down to a path, and the a c-string
296 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
297 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
300 CFRelease(appBundle);
308 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
309 globals->set_fg_root(root);
315 // Read in configuration (files and command line options) but only set
317 bool fgInitFGAircraft ( int argc, char **argv ) {
320 // First parse command line options looking for --aircraft=, this
321 // will override anything specified in a config file
322 aircraft = fgScanForOption( "--aircraft=", argc, argv );
324 // Check in one of the user configuration files.
325 if ( aircraft.empty() )
326 aircraft = fgScanForOption( "--aircraft=" );
328 // if an aircraft was specified, set the property name
329 if ( !aircraft.empty() ) {
330 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
331 fgSetString("/sim/aircraft", aircraft.c_str() );
333 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
340 // Return the current base package version
341 string fgBasePackageVersion() {
342 SGPath base_path( globals->get_fg_root() );
343 base_path.append("version");
345 sg_gzifstream in( base_path.str() );
346 if ( !in.is_open() ) {
347 SGPath old_path( globals->get_fg_root() );
348 old_path.append( "Thanks" );
349 sg_gzifstream old( old_path.str() );
350 if ( !old.is_open() ) {
353 return "[old version]";
364 // Initialize the localization
365 SGPropertyNode *fgInitLocale(const char *language) {
366 SGPropertyNode *c_node = NULL, *d_node = NULL;
367 SGPropertyNode *intl = fgGetNode("/sim/intl");
369 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
371 // localization not defined
376 // Select the proper language from the list
378 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
379 for (unsigned int i = 0; i < locale.size(); i++) {
381 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
382 for (unsigned int j = 0; j < lang.size(); j++) {
384 if (!strcmp(lang[j]->getStringValue(), language)) {
393 d_node = intl->getChild("locale");
397 // Check for localized font
398 SGPropertyNode *font_n = c_node->getNode("font", true);
399 if ( !strcmp(font_n->getStringValue(), "") )
400 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
404 // Load the default strings
406 SGPath d_path( globals->get_fg_root() );
408 const char *d_path_str = d_node->getStringValue("strings");
410 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
414 d_path.append(d_path_str);
415 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
417 SGPropertyNode *strings = c_node->getNode("strings");
419 readProperties(d_path.str(), strings);
420 } catch (const sg_exception &e) {
421 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
426 // Load the language specific strings
428 if (c_node != d_node) {
429 SGPath c_path( globals->get_fg_root() );
431 const char *c_path_str = c_node->getStringValue("strings");
433 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
437 c_path.append(c_path_str);
438 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
441 readProperties(c_path.str(), strings);
442 } catch (const sg_exception &e) {
443 SG_LOG(SG_GENERAL, SG_ALERT,
444 "Unable to read the localized strings from " << c_path.str());
454 // Initialize the localization routines
455 bool fgDetectLanguage() {
456 char *language = ::getenv("LANG");
458 if (language == NULL) {
459 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
463 SGPropertyNode *locale = fgInitLocale(language);
465 SG_LOG(SG_GENERAL, SG_ALERT,
466 "No internationalization settings specified in preferences.xml" );
471 globals->set_locale( locale );
476 // Attempt to locate and parse the various non-XML config files in order
477 // from least precidence to greatest precidence
479 do_options (int argc, char ** argv)
481 // Check for $fg_root/system.fgfsrc
482 SGPath config( globals->get_fg_root() );
483 config.append( "system.fgfsrc" );
484 fgParseOptions(config.str());
486 #if defined( unix ) || defined( __CYGWIN__ )
487 config.concat( "." );
488 config.concat( hostname );
489 fgParseOptions(config.str());
492 // Check for ~/.fgfsrc
493 if ( homedir != NULL ) {
494 config.set( homedir );
495 config.append( ".fgfsrc" );
496 fgParseOptions(config.str());
499 #if defined( unix ) || defined( __CYGWIN__ )
500 // Check for ~/.fgfsrc.hostname
501 config.concat( "." );
502 config.concat( hostname );
503 fgParseOptions(config.str());
506 // Parse remaining command line options
507 // These will override anything specified in a config file
508 fgParseArgs(argc, argv);
512 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
513 SGPropertyNode *cache, int depth = 0 )
515 const int MAXDEPTH = 1;
518 ulDir *dirp = ulOpenDir(path.str().c_str());
520 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
525 while ((dire = ulReadDir(dirp)) != NULL) {
527 if (depth > MAXDEPTH)
530 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
531 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
535 next.append(dire->d_name);
537 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
538 if ( ! result.empty() )
542 int len = strlen(dire->d_name);
543 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
549 if (!cache->getChild("aircraft", i++, false))
552 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
554 n = entry->getNode("file", true);
555 n->setStringValue(dire->d_name);
556 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
558 n = entry->getNode("path", true);
559 n->setStringValue(path.str().c_str());
560 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
562 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
574 // Read in configuration (file and command line)
575 bool fgInitConfig ( int argc, char **argv ) {
577 // First, set some sane default values
580 // Read global preferences from $FG_ROOT/preferences.xml
581 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
582 fgLoadProps("preferences.xml", globals->get_props());
583 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
585 // Detect the required language as early as possible
586 if ( !fgDetectLanguage() ) {
590 SGPropertyNode autosave;
592 char *envp = ::getenv( "APPDATA" );
594 SGPath config( envp );
595 config.append( "flightgear.org" );
597 if ( homedir != NULL ) {
598 SGPath config( homedir );
599 config.append( ".fgfs" );
601 fgSetString("/sim/fg-home", config.c_str());
602 config.append( "autosave.xml" );
603 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
605 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
607 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
609 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
611 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
614 // Scan user config files and command line for a specified aircraft.
615 fgInitFGAircraft(argc, argv);
617 string aircraft = fgGetString( "/sim/aircraft", "" );
618 if ( aircraft.size() > 0 ) {
619 SGPath aircraft_search( globals->get_fg_root() );
620 aircraft_search.append( "Aircraft" );
622 string aircraft_set = aircraft + "-set.xml";
625 // check if the *-set.xml file is already in the cache
626 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
627 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
628 for (unsigned int i = 0; i < cache.size(); i++) {
629 const char *name = cache[i]->getStringValue("file", "");
630 if (aircraft_set == name) {
631 const char *path = cache[i]->getStringValue("path", "");
641 if (result.empty()) {
642 // prepare cache for rescan
643 SGPropertyNode *n = cache_root->getNode("fg-root", true);
644 n->setStringValue(globals->get_fg_root().c_str());
645 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
646 cache_root->removeChildren("aircraft");
648 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
651 if ( !result.empty() ) {
652 fgSetString( "/sim/aircraft-dir", result.c_str() );
653 SGPath full_name( result );
654 full_name.append( aircraft_set );
656 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
657 << " from " << full_name.str());
659 readProperties( full_name.str(), globals->get_props() );
660 } catch ( const sg_exception &e ) {
661 string message = "Error reading default aircraft: ";
662 message += e.getFormattedMessage();
663 SG_LOG(SG_INPUT, SG_ALERT, message);
667 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
673 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
676 copyProperties(&autosave, globals->get_props());
678 // parse options after loading aircraft to ensure any user
679 // overrides of defaults are honored.
680 do_options(argc, argv);
691 // This function is never used, but maybe useful in the future ???
694 // Preset lon/lat given an airport id
695 static bool fgSetPosFromAirportID( const string& id ) {
699 SG_LOG( SG_GENERAL, SG_INFO,
700 "Attempting to set starting position from airport code " << id );
702 if ( fgFindAirportID( id, &a ) ) {
704 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
705 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
707 // other code depends on the actual postition being set so set
709 fgSetDouble("/position/longitude-deg", a->longitude );
710 fgSetDouble("/position/latitude-deg", a->latitude );
712 SG_LOG( SG_GENERAL, SG_INFO,
713 "Position for " << id << " is (" << a->longitude
714 << ", " << a->latitude << ")" );
724 // Set current tower position lon/lat given an airport id
725 static bool fgSetTowerPosFromAirportID( const string& id) {
726 const FGAirport *a = fgFindAirportID( id);
728 SGGeod tower = a->getTowerLocation();
729 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
730 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
731 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
739 struct FGTowerLocationListener : SGPropertyChangeListener {
740 void valueChanged(SGPropertyNode* node) {
741 const string id(node->getStringValue());
742 fgSetTowerPosFromAirportID(id);
746 void fgInitTowerLocationListener() {
747 fgGetNode("/sim/tower/airport-id", true)
748 ->addChangeListener( new FGTowerLocationListener(), true );
751 // Set current_options lon/lat given an airport id and heading (degrees)
752 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
758 // set initial position from runway and heading
759 SG_LOG( SG_GENERAL, SG_INFO,
760 "Attempting to set starting position from airport code "
761 << id << " heading " << tgt_hdg );
763 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
764 SG_LOG( SG_GENERAL, SG_ALERT,
765 "Failed to find a good runway for " << id << '\n' );
768 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
770 double lat2, lon2, az2;
771 double heading = r._heading;
772 double azimuth = heading + 180.0;
773 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
775 SG_LOG( SG_GENERAL, SG_INFO,
776 "runway = " << r._lon << ", " << r._lat
777 << " length = " << r._length * SG_FEET_TO_METER
778 << " heading = " << azimuth );
780 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
781 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
782 &lat2, &lon2, &az2 );
784 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
786 double odist = fgGetDouble("/sim/presets/offset-distance");
787 odist *= SG_NM_TO_METER;
788 double oaz = azimuth;
789 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
790 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
793 while ( oaz >= 360.0 ) { oaz -= 360.0; }
794 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
800 fgSetDouble("/sim/presets/longitude-deg", lon2 );
801 fgSetDouble("/sim/presets/latitude-deg", lat2 );
802 fgSetDouble("/sim/presets/heading-deg", heading );
804 // other code depends on the actual values being set ...
805 fgSetDouble("/position/longitude-deg", lon2 );
806 fgSetDouble("/position/latitude-deg", lat2 );
807 fgSetDouble("/orientation/heading-deg", heading );
809 SG_LOG( SG_GENERAL, SG_INFO,
810 "Position for " << id << " is ("
812 << lat2 << ") new heading is "
819 // Set current_options lon/lat given an airport id and runway number
820 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
826 // set initial position from airport and runway number
827 SG_LOG( SG_GENERAL, SG_INFO,
828 "Attempting to set starting position for "
829 << id << ":" << rwy );
831 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
832 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
833 "Failed to find runway " << rwy <<
834 " at airport " << id << ". Using default runway." );
837 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
839 double lat2, lon2, az2;
840 double heading = r._heading;
841 double azimuth = heading + 180.0;
842 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
844 SG_LOG( SG_GENERAL, SG_INFO,
845 "runway = " << r._lon << ", " << r._lat
846 << " length = " << r._length * SG_FEET_TO_METER
847 << " heading = " << azimuth );
849 geo_direct_wgs_84 ( 0, r._lat, r._lon,
851 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
852 &lat2, &lon2, &az2 );
854 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
857 double odist = fgGetDouble("/sim/presets/offset-distance");
858 odist *= SG_NM_TO_METER;
859 double oaz = azimuth;
860 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
862 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
863 heading = fgGetDouble("/sim/presets/heading-deg");
865 while ( oaz >= 360.0 ) { oaz -= 360.0; }
866 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
872 fgSetDouble("/sim/presets/longitude-deg", lon2 );
873 fgSetDouble("/sim/presets/latitude-deg", lat2 );
874 fgSetDouble("/sim/presets/heading-deg", heading );
876 // other code depends on the actual values being set ...
877 fgSetDouble("/position/longitude-deg", lon2 );
878 fgSetDouble("/position/latitude-deg", lat2 );
879 fgSetDouble("/orientation/heading-deg", heading );
881 SG_LOG( SG_GENERAL, SG_INFO,
882 "Position for " << id << " is ("
884 << lat2 << ") new heading is "
891 static void fgSetDistOrAltFromGlideSlope() {
892 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
893 string apt_id = fgGetString("/sim/presets/airport-id");
894 double gs = fgGetDouble("/sim/presets/glideslope-deg")
895 * SG_DEGREES_TO_RADIANS ;
896 double od = fgGetDouble("/sim/presets/offset-distance");
897 double alt = fgGetDouble("/sim/presets/altitude-ft");
899 double apt_elev = 0.0;
900 if ( ! apt_id.empty() ) {
901 apt_elev = fgGetAirportElev( apt_id );
902 if ( apt_elev < -9990.0 ) {
909 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
910 // set altitude from glideslope and offset-distance
911 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
912 alt = fabs(od*tan(gs)) + apt_elev;
913 fgSetDouble("/sim/presets/altitude-ft", alt);
914 fgSetBool("/sim/presets/onground", false);
915 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
917 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
918 // set offset-distance from glideslope and altitude
919 od = (alt - apt_elev) / tan(gs);
920 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
921 fgSetDouble("/sim/presets/offset-distance", od);
922 fgSetBool("/sim/presets/onground", false);
923 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
925 } else if( fabs(gs) > 0.01 ) {
926 SG_LOG( SG_GENERAL, SG_ALERT,
927 "Glideslope given but not altitude or offset-distance." );
928 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
929 fgSetDouble("/sim/presets/glideslope-deg", 0);
930 fgSetBool("/sim/presets/onground", true);
935 // Set current_options lon/lat given an airport id and heading (degrees)
936 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
938 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
940 // set initial position from runway and heading
942 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
943 << id << ":" << freq );
945 double lon = nav->get_lon();
946 double lat = nav->get_lat();
948 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
950 double odist = fgGetDouble("/sim/presets/offset-distance")
952 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
954 while ( oaz >= 360.0 ) { oaz -= 360.0; }
955 double olat, olon, az2;
956 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
963 fgSetDouble("/sim/presets/longitude-deg", lon );
964 fgSetDouble("/sim/presets/latitude-deg", lat );
966 // other code depends on the actual values being set ...
967 fgSetDouble("/position/longitude-deg", lon );
968 fgSetDouble("/position/latitude-deg", lat );
969 fgSetDouble("/orientation/heading-deg",
970 fgGetDouble("/sim/presets/heading-deg") );
972 SG_LOG( SG_GENERAL, SG_INFO,
973 "Position for " << id << ":" << freq << " is ("
974 << lon << ", "<< lat << ")" );
978 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
979 << id << ":" << freq );
984 // Set current_options lon/lat given an aircraft carrier id
985 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
987 // set initial position from runway and heading
991 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
992 double lon = geodPos.getLongitudeDeg();
993 double lat = geodPos.getLatitudeDeg();
994 double alt = geodPos.getElevationFt();
996 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
997 << carrier << " at lat = " << lat << ", lon = " << lon
998 << ", alt = " << alt << ", heading = " << heading);
1000 fgSetDouble("/sim/presets/longitude-deg", lon);
1001 fgSetDouble("/sim/presets/latitude-deg", lat);
1002 fgSetDouble("/sim/presets/altitude-ft", alt);
1003 fgSetDouble("/sim/presets/heading-deg", heading);
1004 fgSetDouble("/position/longitude-deg", lon);
1005 fgSetDouble("/position/latitude-deg", lat);
1006 fgSetDouble("/position/altitude-ft", alt);
1007 fgSetDouble("/orientation/heading-deg", heading);
1009 fgSetString("/sim/presets/speed-set", "UVW");
1010 fgSetDouble("/velocities/uBody-fps", uvw(0));
1011 fgSetDouble("/velocities/vBody-fps", uvw(1));
1012 fgSetDouble("/velocities/wBody-fps", uvw(2));
1013 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1014 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1015 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1017 fgSetBool("/sim/presets/onground", true);
1021 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1027 // Set current_options lon/lat given an airport id and heading (degrees)
1028 static bool fgSetPosFromFix( const string& id ) {
1031 // set initial position from runway and heading
1032 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1033 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1036 double lon = fix.get_lon();
1037 double lat = fix.get_lat();
1039 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1041 double odist = fgGetDouble("/sim/presets/offset-distance")
1043 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1045 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1046 double olat, olon, az2;
1047 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1054 fgSetDouble("/sim/presets/longitude-deg", lon );
1055 fgSetDouble("/sim/presets/latitude-deg", lat );
1057 // other code depends on the actual values being set ...
1058 fgSetDouble("/position/longitude-deg", lon );
1059 fgSetDouble("/position/latitude-deg", lat );
1060 fgSetDouble("/orientation/heading-deg",
1061 fgGetDouble("/sim/presets/heading-deg") );
1063 SG_LOG( SG_GENERAL, SG_INFO,
1064 "Position for " << id << " is ("
1065 << lon << ", "<< lat << ")" );
1069 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1077 * Initialize vor/ndb/ils/fix list management and query systems (as
1078 * well as simple airport db list)
1083 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1085 SGPath aptdb( globals->get_fg_root() );
1086 aptdb.append( "Airports/apt.dat" );
1088 SGPath p_metar( globals->get_fg_root() );
1089 p_metar.append( "Airports/metar.dat" );
1091 FGAirportList *airports = new FGAirportList();
1092 globals->set_airports( airports );
1093 FGRunwayList *runways = new FGRunwayList();
1094 globals->set_runways( runways );
1096 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1098 FGNavList *navlist = new FGNavList;
1099 FGNavList *loclist = new FGNavList;
1100 FGNavList *gslist = new FGNavList;
1101 FGNavList *dmelist = new FGNavList;
1102 FGNavList *mkrlist = new FGNavList;
1103 FGNavList *tacanlist = new FGNavList;
1104 FGNavList *carrierlist = new FGNavList;
1105 FGTACANList *channellist = new FGTACANList;
1107 globals->set_navlist( navlist );
1108 globals->set_loclist( loclist );
1109 globals->set_gslist( gslist );
1110 globals->set_dmelist( dmelist );
1111 globals->set_mkrlist( mkrlist );
1112 globals->set_tacanlist( tacanlist );
1113 globals->set_carrierlist( carrierlist );
1114 globals->set_channellist( channellist );
1116 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1117 SG_LOG( SG_GENERAL, SG_ALERT,
1118 "Problems loading one or more navigational database" );
1121 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1122 // align all the localizers with their corresponding runways
1123 // since data sources are good for cockpit navigation
1124 // purposes, but not always to the error tolerances needed to
1125 // exactly place these items.
1127 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1129 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1132 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1133 SGPath p_fix( globals->get_fg_root() );
1134 p_fix.append( "Navaids/fix.dat" );
1135 FGFixList *fixlist = new FGFixList;
1136 fixlist->init( p_fix );
1137 globals->set_fixlist( fixlist );
1139 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1140 SGPath p_awy( globals->get_fg_root() );
1141 p_awy.append( "Navaids/awy.dat" );
1142 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1143 //cerr << "Loading Airways" << endl;
1144 awyNet->load (p_awy );
1146 //cerr << "initializing airways" << endl;
1147 globals->set_airwaynet( awyNet );
1153 // Set the initial position based on presets (or defaults)
1154 bool fgInitPosition() {
1155 // cout << "fgInitPosition()" << endl;
1156 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1157 * SG_DEGREES_TO_RADIANS ;
1158 double od = fgGetDouble("/sim/presets/offset-distance");
1159 double alt = fgGetDouble("/sim/presets/altitude-ft");
1161 bool set_pos = false;
1163 // If glideslope is specified, then calculate offset-distance or
1164 // altitude relative to glide slope if either of those was not
1166 if ( fabs( gs ) > 0.01 ) {
1167 fgSetDistOrAltFromGlideSlope();
1171 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1172 // If not, check for an airport-id and use that.
1173 // If not, default to the middle of the KSFO field.
1174 // The default values for lon/lat are deliberately out of range
1175 // so that the airport-id can take effect; valid lon/lat will
1176 // override airport-id, however.
1177 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1178 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1179 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1180 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1185 string apt = fgGetString("/sim/presets/airport-id");
1186 string rwy_no = fgGetString("/sim/presets/runway");
1187 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1188 string vor = fgGetString("/sim/presets/vor-id");
1189 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1190 string ndb = fgGetString("/sim/presets/ndb-id");
1191 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1192 string carrier = fgGetString("/sim/presets/carrier");
1193 string parkpos = fgGetString("/sim/presets/parkpos");
1194 string fix = fgGetString("/sim/presets/fix");
1195 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1196 double hdg = hdg_preset->getDoubleValue();
1198 // save some start parameters, so that we can later say what the
1199 // user really requested. TODO generalize that and move it to options.cxx
1200 static bool start_options_saved = false;
1201 if (!start_options_saved) {
1202 start_options_saved = true;
1203 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1205 opt->setDoubleValue("latitude-deg", lat_deg);
1206 opt->setDoubleValue("longitude-deg", lon_deg);
1207 opt->setDoubleValue("heading-deg", hdg);
1208 opt->setStringValue("airport", apt.c_str());
1209 opt->setStringValue("runway", rwy_no.c_str());
1213 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1215 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1216 // An airport + runway is requested
1217 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1218 // set tower position (a little off the heading for single
1220 fgSetString("/sim/tower/airport-id", apt.c_str());
1225 if ( !set_pos && !apt.empty() ) {
1226 // An airport is requested (find runway closest to hdg)
1227 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1228 // set tower position (a little off the heading for single
1230 fgSetString("/sim/tower/airport-id", apt.c_str());
1235 if (hdg_preset->getDoubleValue() > 9990.0)
1236 hdg_preset->setDoubleValue(hdg);
1238 if ( !set_pos && !vor.empty() ) {
1239 // a VOR is requested
1240 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1245 if ( !set_pos && !ndb.empty() ) {
1246 // an NDB is requested
1247 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1252 if ( !set_pos && !carrier.empty() ) {
1253 // an aircraft carrier is requested
1254 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1259 if ( !set_pos && !fix.empty() ) {
1260 // a Fix is requested
1261 if ( fgSetPosFromFix( fix ) ) {
1267 // No lon/lat specified, no airport specified, default to
1268 // middle of KSFO field.
1269 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1270 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1273 fgSetDouble( "/position/longitude-deg",
1274 fgGetDouble("/sim/presets/longitude-deg") );
1275 fgSetDouble( "/position/latitude-deg",
1276 fgGetDouble("/sim/presets/latitude-deg") );
1277 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1279 // determine if this should be an on-ground or in-air start
1280 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1281 fgSetBool("/sim/presets/onground", false);
1283 fgSetBool("/sim/presets/onground", true);
1290 // General house keeping initializations
1291 bool fgInitGeneral() {
1294 #if defined(FX) && defined(XMESA)
1295 char *mesa_win_state;
1298 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1299 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1301 root = globals->get_fg_root();
1302 if ( ! root.length() ) {
1303 // No root path set? Then bail ...
1304 SG_LOG( SG_GENERAL, SG_ALERT,
1305 "Cannot continue without a path to the base package "
1306 << "being defined." );
1309 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1311 #if defined(FX) && defined(XMESA)
1312 // initialize full screen flag
1313 globals->set_fullscreen(false);
1314 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1315 // Test for the MESA_GLX_FX env variable
1316 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1317 // test if we are fullscreen mesa/glide
1318 if ( (mesa_win_state[0] == 'f') ||
1319 (mesa_win_state[0] == 'F') ) {
1320 globals->set_fullscreen(true);
1326 char buf[512], *cwd = getcwd(buf, 512);
1327 fgSetString("/sim/fg-current", cwd ? cwd : "");
1332 // Initialize the flight model subsystem. This just creates the
1333 // object. The actual fdm initialization is delayed until we get a
1334 // proper scenery elevation hit. This is checked for in main.cxx
1338 if ( cur_fdm_state ) {
1339 delete cur_fdm_state;
1343 double dt = 1.0 / fgGetInt("/sim/model-hz");
1344 string model = fgGetString("/sim/flight-model");
1346 if ( model == "larcsim" ) {
1347 cur_fdm_state = new FGLaRCsim( dt );
1348 } else if ( model == "jsb" ) {
1349 cur_fdm_state = new FGJSBsim( dt );
1351 } else if ( model == "ada" ) {
1352 cur_fdm_state = new FGADA( dt );
1353 } else if ( model == "acms" ) {
1354 cur_fdm_state = new FGACMS( dt );
1356 } else if ( model == "balloon" ) {
1357 cur_fdm_state = new FGBalloonSim( dt );
1358 } else if ( model == "magic" ) {
1359 cur_fdm_state = new FGMagicCarpet( dt );
1360 } else if ( model == "ufo" ) {
1361 cur_fdm_state = new FGUFO( dt );
1362 } else if ( model == "external" ) {
1363 // external is a synonym for "--fdm=null" and is
1364 // maintained here for backwards compatibility
1365 cur_fdm_state = new FGNullFDM( dt );
1366 } else if ( model.find("network") == 0 ) {
1367 string host = "localhost";
1371 string net_options = model.substr(8);
1372 string::size_type begin, end;
1375 end = net_options.find( ",", begin );
1376 if ( end != string::npos ) {
1377 host = net_options.substr(begin, end - begin);
1381 end = net_options.find( ",", begin );
1382 if ( end != string::npos ) {
1383 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1387 end = net_options.find( ",", begin );
1388 if ( end != string::npos ) {
1389 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1393 end = net_options.find( ",", begin );
1394 if ( end != string::npos ) {
1395 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1398 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1399 } else if ( model.find("pipe") == 0 ) {
1400 // /* old */ string pipe_path = model.substr(5);
1401 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1402 string pipe_path = "";
1403 string pipe_protocol = "";
1404 string pipe_options = model.substr(5);
1405 string::size_type begin, end;
1408 end = pipe_options.find( ",", begin );
1409 if ( end != string::npos ) {
1410 pipe_path = pipe_options.substr(begin, end - begin);
1413 // protocol (last option)
1414 pipe_protocol = pipe_options.substr(begin);
1415 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1416 } else if ( model == "null" ) {
1417 cur_fdm_state = new FGNullFDM( dt );
1418 } else if ( model == "yasim" ) {
1419 cur_fdm_state = new YASim( dt );
1421 throw sg_throwable(string("Unrecognized flight model '") + model
1422 + "', cannot init flight dynamics model.");
1426 // Initialize view parameters
1428 // force update of model so that viewer can get some data...
1429 globals->get_aircraft_model()->update(0);
1430 // run update for current view so that data is current...
1431 globals->get_viewmgr()->update(0);
1435 SGTime *fgInitTime() {
1437 static const SGPropertyNode *longitude
1438 = fgGetNode("/position/longitude-deg");
1439 static const SGPropertyNode *latitude
1440 = fgGetNode("/position/latitude-deg");
1441 static const SGPropertyNode *cur_time_override
1442 = fgGetNode("/sim/time/cur-time-override", true);
1444 SGPath zone( globals->get_fg_root() );
1445 zone.append( "Timezone" );
1446 SGTime *t = new SGTime( longitude->getDoubleValue()
1447 * SGD_DEGREES_TO_RADIANS,
1448 latitude->getDoubleValue()
1449 * SGD_DEGREES_TO_RADIANS,
1451 cur_time_override->getLongValue() );
1453 globals->set_warp_delta( 0 );
1455 t->update( 0.0, 0.0,
1456 cur_time_override->getLongValue(),
1457 globals->get_warp() );
1463 // set up a time offset (aka warp) if one is specified
1464 void fgInitTimeOffset() {
1465 static const SGPropertyNode *longitude
1466 = fgGetNode("/position/longitude-deg");
1467 static const SGPropertyNode *latitude
1468 = fgGetNode("/position/latitude-deg");
1469 static const SGPropertyNode *cur_time_override
1470 = fgGetNode("/sim/time/cur-time-override", true);
1472 // Handle potential user specified time offsets
1473 int orig_warp = globals->get_warp();
1474 SGTime *t = globals->get_time_params();
1475 time_t cur_time = t->get_cur_time();
1476 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1477 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1478 time_t aircraftLocalTime =
1479 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1481 // Okay, we now have several possible scenarios
1482 int offset = fgGetInt("/sim/startup/time-offset");
1483 string offset_type = fgGetString("/sim/startup/time-offset-type");
1486 if ( offset_type == "real" ) {
1488 } else if ( offset_type == "dawn" ) {
1489 warp = fgTimeSecondsUntilSunAngle( cur_time,
1490 longitude->getDoubleValue()
1491 * SGD_DEGREES_TO_RADIANS,
1492 latitude->getDoubleValue()
1493 * SGD_DEGREES_TO_RADIANS,
1495 } else if ( offset_type == "morning" ) {
1496 warp = fgTimeSecondsUntilSunAngle( cur_time,
1497 longitude->getDoubleValue()
1498 * SGD_DEGREES_TO_RADIANS,
1499 latitude->getDoubleValue()
1500 * SGD_DEGREES_TO_RADIANS,
1502 } else if ( offset_type == "noon" ) {
1503 warp = fgTimeSecondsUntilSunAngle( cur_time,
1504 longitude->getDoubleValue()
1505 * SGD_DEGREES_TO_RADIANS,
1506 latitude->getDoubleValue()
1507 * SGD_DEGREES_TO_RADIANS,
1509 } else if ( offset_type == "afternoon" ) {
1510 warp = fgTimeSecondsUntilSunAngle( cur_time,
1511 longitude->getDoubleValue()
1512 * SGD_DEGREES_TO_RADIANS,
1513 latitude->getDoubleValue()
1514 * SGD_DEGREES_TO_RADIANS,
1516 } else if ( offset_type == "dusk" ) {
1517 warp = fgTimeSecondsUntilSunAngle( cur_time,
1518 longitude->getDoubleValue()
1519 * SGD_DEGREES_TO_RADIANS,
1520 latitude->getDoubleValue()
1521 * SGD_DEGREES_TO_RADIANS,
1523 } else if ( offset_type == "evening" ) {
1524 warp = fgTimeSecondsUntilSunAngle( cur_time,
1525 longitude->getDoubleValue()
1526 * SGD_DEGREES_TO_RADIANS,
1527 latitude->getDoubleValue()
1528 * SGD_DEGREES_TO_RADIANS,
1530 } else if ( offset_type == "midnight" ) {
1531 warp = fgTimeSecondsUntilSunAngle( cur_time,
1532 longitude->getDoubleValue()
1533 * SGD_DEGREES_TO_RADIANS,
1534 latitude->getDoubleValue()
1535 * SGD_DEGREES_TO_RADIANS,
1537 } else if ( offset_type == "system-offset" ) {
1540 } else if ( offset_type == "gmt-offset" ) {
1541 warp = offset - (currGMT - systemLocalTime);
1543 } else if ( offset_type == "latitude-offset" ) {
1544 warp = offset - (aircraftLocalTime - systemLocalTime);
1546 } else if ( offset_type == "system" ) {
1547 warp = offset - (systemLocalTime - currGMT) - cur_time;
1548 } else if ( offset_type == "gmt" ) {
1549 warp = offset - cur_time;
1550 } else if ( offset_type == "latitude" ) {
1551 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1553 SG_LOG( SG_GENERAL, SG_ALERT,
1554 "FG_TIME::Unsupported offset type " << offset_type );
1557 globals->set_warp( orig_warp + warp );
1558 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1559 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1560 cur_time_override->getLongValue(),
1561 globals->get_warp() );
1563 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1564 << globals->get_warp() );
1568 // This is the top level init routine which calls all the other
1569 // initialization routines. If you are adding a subsystem to flight
1570 // gear, its initialization call should located in this routine.
1571 // Returns non-zero if a problem encountered.
1572 bool fgInitSubsystems() {
1573 // static const SGPropertyNode *longitude
1574 // = fgGetNode("/sim/presets/longitude-deg");
1575 // static const SGPropertyNode *latitude
1576 // = fgGetNode("/sim/presets/latitude-deg");
1577 // static const SGPropertyNode *altitude
1578 // = fgGetNode("/sim/presets/altitude-ft");
1579 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1580 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1582 ////////////////////////////////////////////////////////////////////
1583 // Initialize the event manager subsystem.
1584 ////////////////////////////////////////////////////////////////////
1586 globals->get_event_mgr()->init();
1587 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1589 ////////////////////////////////////////////////////////////////////
1590 // Initialize the property interpolator subsystem. Put into the INIT
1591 // group because the "nasal" subsystem may need it at GENERAL take-down.
1592 ////////////////////////////////////////////////////////////////////
1593 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1596 ////////////////////////////////////////////////////////////////////
1597 // Add the FlightGear property utilities.
1598 ////////////////////////////////////////////////////////////////////
1599 globals->add_subsystem("properties", new FGProperties);
1601 ////////////////////////////////////////////////////////////////////
1602 // Initialize the material property subsystem.
1603 ////////////////////////////////////////////////////////////////////
1605 SGPath mpath( globals->get_fg_root() );
1606 mpath.append( "materials.xml" );
1607 string season = fgGetString("/sim/startup/season", "summer");
1608 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1609 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1614 ////////////////////////////////////////////////////////////////////
1615 // Initialize the scenery management subsystem.
1616 ////////////////////////////////////////////////////////////////////
1618 if ( globals->get_tile_mgr()->init() ) {
1619 // Load the local scenery data
1620 double visibility_meters = fgGetDouble("/environment/visibility-m");
1622 globals->get_tile_mgr()->update( visibility_meters );
1624 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1628 // cause refresh of viewer scenery timestamps every 15 seconds...
1629 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1630 globals->get_tile_mgr(),
1631 &FGTileMgr::refresh_view_timestamps,
1635 ////////////////////////////////////////////////////////////////////
1636 // Initialize the flight model subsystem.
1637 ////////////////////////////////////////////////////////////////////
1641 // allocates structures so must happen before any of the flight
1642 // model or control parameters are set
1643 fgAircraftInit(); // In the future this might not be the case.
1645 ////////////////////////////////////////////////////////////////////
1646 // Initialize the aircraft systems and instrumentation (before the
1648 ////////////////////////////////////////////////////////////////////
1650 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1651 globals->add_subsystem("systems", new FGSystemMgr);
1653 ////////////////////////////////////////////////////////////////////
1654 // Initialize the XML Autopilot subsystem.
1655 ////////////////////////////////////////////////////////////////////
1657 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1658 globals->add_subsystem( "route-manager", new FGRouteMgr );
1661 ////////////////////////////////////////////////////////////////////
1662 // Initialize the view manager subsystem.
1663 ////////////////////////////////////////////////////////////////////
1667 ////////////////////////////////////////////////////////////////////
1668 // Create and register the logger.
1669 ////////////////////////////////////////////////////////////////////
1671 globals->add_subsystem("logger", new FGLogger);
1673 ////////////////////////////////////////////////////////////////////
1674 // Create and register the XML GUI.
1675 ////////////////////////////////////////////////////////////////////
1677 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1680 ////////////////////////////////////////////////////////////////////
1681 // Initialize the local time subsystem.
1682 ////////////////////////////////////////////////////////////////////
1684 // update the current timezone each 30 minutes
1685 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1686 &fgUpdateLocalTime, 30*60 );
1687 fgInitTimeOffset(); // the environment subsystem needs this
1690 ////////////////////////////////////////////////////////////////////
1691 // Initialize the weather subsystem.
1692 ////////////////////////////////////////////////////////////////////
1694 // Initialize the weather modeling subsystem
1695 globals->add_subsystem("environment", new FGEnvironmentMgr);
1698 ////////////////////////////////////////////////////////////////////
1699 // Initialize the lighting subsystem.
1700 ////////////////////////////////////////////////////////////////////
1702 globals->add_subsystem("lighting", new FGLight);
1704 //////////////////////////////////////////////////////////////////////
1705 // Initialize the 2D cloud subsystem.
1706 ////////////////////////////////////////////////////////////////////
1707 fgGetBool("/sim/rendering/bump-mapping", false);
1709 #ifdef ENABLE_AUDIO_SUPPORT
1710 ////////////////////////////////////////////////////////////////////
1711 // Initialize the sound subsystem.
1712 ////////////////////////////////////////////////////////////////////
1714 init_volume = fgGetFloat("/sim/sound/volume");
1715 fgSetFloat("/sim/sound/volume", 0.0f);
1716 globals->set_soundmgr(new SGSoundMgr);
1717 globals->get_soundmgr()->init();
1718 globals->get_soundmgr()->bind();
1721 ////////////////////////////////////////////////////////////////////
1722 // Initialize the sound-effects subsystem.
1723 ////////////////////////////////////////////////////////////////////
1725 globals->add_subsystem("fx", new FGFX);
1726 globals->add_subsystem("voice", new FGVoiceMgr);
1729 ////////////////////////////////////////////////////////////////////
1730 // Initialise the ATC Manager
1731 ////////////////////////////////////////////////////////////////////
1733 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1734 globals->set_ATC_mgr(new FGATCMgr);
1735 globals->get_ATC_mgr()->init();
1737 ////////////////////////////////////////////////////////////////////
1738 // Initialise the AI Manager
1739 ////////////////////////////////////////////////////////////////////
1741 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1742 globals->set_AI_mgr(new FGAIMgr);
1743 globals->get_AI_mgr()->init();
1745 ////////////////////////////////////////////////////////////////////
1746 // Initialise the AI Model Manager
1747 ////////////////////////////////////////////////////////////////////
1748 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1749 globals->add_subsystem("ai_model", new FGAIManager);
1750 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1753 // It's probably a good idea to initialize the top level traffic manager
1754 // After the AI and ATC systems have been initialized properly.
1755 // AI Traffic manager
1756 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1759 ////////////////////////////////////////////////////////////////////
1760 // Initialize the cockpit subsystem
1761 ////////////////////////////////////////////////////////////////////
1762 if( fgCockpitInit( ¤t_aircraft )) {
1763 // Cockpit initialized ok.
1765 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1770 ////////////////////////////////////////////////////////////////////
1771 // Initialize I/O subsystem.
1772 ////////////////////////////////////////////////////////////////////
1774 globals->get_io()->init();
1775 globals->get_io()->bind();
1778 ////////////////////////////////////////////////////////////////////
1779 // Add a new 2D panel.
1780 ////////////////////////////////////////////////////////////////////
1782 string panel_path = fgGetString("/sim/panel/path",
1783 "Panels/Default/default.xml");
1785 globals->set_current_panel( fgReadPanel(panel_path) );
1786 if (globals->get_current_panel() == 0) {
1787 SG_LOG( SG_INPUT, SG_ALERT,
1788 "Error reading new panel from " << panel_path );
1790 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1791 globals->get_current_panel()->init();
1792 globals->get_current_panel()->bind();
1796 ////////////////////////////////////////////////////////////////////
1797 // Initialize the controls subsystem.
1798 ////////////////////////////////////////////////////////////////////
1800 globals->get_controls()->init();
1801 globals->get_controls()->bind();
1804 ////////////////////////////////////////////////////////////////////
1805 // Initialize the input subsystem.
1806 ////////////////////////////////////////////////////////////////////
1808 globals->add_subsystem("input", new FGInput);
1811 ////////////////////////////////////////////////////////////////////
1812 // Initialize the replay subsystem
1813 ////////////////////////////////////////////////////////////////////
1814 globals->add_subsystem("replay", new FGReplay);
1816 ////////////////////////////////////////////////////////////////////
1817 // Bind and initialize subsystems.
1818 ////////////////////////////////////////////////////////////////////
1820 globals->get_subsystem_mgr()->bind();
1821 globals->get_subsystem_mgr()->init();
1823 ////////////////////////////////////////////////////////////////////
1824 // Initialize multiplayer subsystem
1825 ////////////////////////////////////////////////////////////////////
1827 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1828 globals->get_multiplayer_mgr()->init();
1830 ////////////////////////////////////////////////////////////////////////
1831 // Initialize the Nasal interpreter.
1832 // Do this last, so that the loaded scripts see initialized state
1833 ////////////////////////////////////////////////////////////////////////
1834 FGNasalSys* nasal = new FGNasalSys();
1835 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1838 // initialize methods that depend on other subsystems.
1839 globals->get_subsystem_mgr()->postinit();
1841 ////////////////////////////////////////////////////////////////////////
1842 // End of subsystem initialization.
1843 ////////////////////////////////////////////////////////////////////
1845 SG_LOG( SG_GENERAL, SG_INFO, endl);
1847 // Save the initial state for future
1849 globals->saveInitialState();
1855 void fgReInitSubsystems()
1857 // static const SGPropertyNode *longitude
1858 // = fgGetNode("/sim/presets/longitude-deg");
1859 // static const SGPropertyNode *latitude
1860 // = fgGetNode("/sim/presets/latitude-deg");
1861 static const SGPropertyNode *altitude
1862 = fgGetNode("/sim/presets/altitude-ft");
1863 static const SGPropertyNode *master_freeze
1864 = fgGetNode("/sim/freeze/master");
1866 SG_LOG( SG_GENERAL, SG_INFO,
1867 "fgReInitSubsystems(): /position/altitude = "
1868 << altitude->getDoubleValue() );
1870 bool freeze = master_freeze->getBoolValue();
1872 fgSetBool("/sim/freeze/master", true);
1874 fgSetBool("/sim/crashed", false);
1876 // Force reupdating the positions of the ai 3d models. They are used for
1877 // initializing ground level for the FDM.
1878 globals->get_subsystem("ai_model")->reinit();
1880 // Initialize the FDM
1883 // allocates structures so must happen before any of the flight
1884 // model or control parameters are set
1885 fgAircraftInit(); // In the future this might not be the case.
1887 // reload offsets from config defaults
1888 globals->get_viewmgr()->reinit();
1892 globals->get_controls()->reset_all();
1894 fgUpdateLocalTime();
1896 // re-init to proper time of day setting
1900 fgSetBool("/sim/freeze/master", false);
1902 fgSetBool("/sim/sceneryloaded",false);