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/scene/model/particles.hxx>
66 #include <simgear/timing/sg_time.hxx>
67 #include <simgear/timing/lowleveltime.h>
69 #include <Aircraft/aircraft.hxx>
70 #include <Aircraft/replay.hxx>
71 #include <Airports/apt_loader.hxx>
72 #include <Airports/runways.hxx>
73 #include <Airports/simple.hxx>
74 #include <AIModel/AIManager.hxx>
75 #include <ATCDCL/ATCmgr.hxx>
76 #include <ATCDCL/AIMgr.hxx>
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/xmlauto.hxx>
79 #include <Cockpit/cockpit.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
83 #include <FDM/SP/ADA.hxx>
84 #include <FDM/SP/ACMS.hxx>
86 #include <FDM/Balloon.h>
87 #include <FDM/ExternalNet/ExternalNet.hxx>
88 #include <FDM/ExternalPipe/ExternalPipe.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim/LaRCsim.hxx>
91 #include <FDM/MagicCarpet.hxx>
92 #include <FDM/UFO.hxx>
93 #include <FDM/NullFDM.hxx>
94 #include <FDM/YASim/YASim.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Include/general.hxx>
97 #include <Input/input.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <AIModel/submodel.hxx>
101 #include <AIModel/AIManager.hxx>
102 #include <Navaids/navdb.hxx>
103 #include <Navaids/navlist.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/fg_fx.hxx>
108 #include <Sound/beacon.hxx>
109 #include <Sound/morse.hxx>
110 #include <Sound/voice.hxx>
111 #include <Systems/system_mgr.hxx>
112 #include <Time/light.hxx>
113 #include <Time/sunsolver.hxx>
114 #include <Time/tmp.hxx>
115 #include <Traffic/TrafficMgr.hxx>
116 #include <MultiPlayer/multiplaymgr.hxx>
118 #include <Environment/environment_mgr.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "renderer.hxx"
128 #include "viewmgr.hxx"
131 #if defined(FX) && defined(XMESA)
132 #include <GL/xmesa.h>
135 SG_USING_STD(string);
139 extern const char *default_root;
143 // Scan the command line options for the specified option and return
145 static string fgScanForOption( const string& option, int argc, char **argv ) {
148 if (hostname == NULL)
151 gethostname(_hostname, 256);
152 hostname = strdup(_hostname);
153 free_hostname = true;
156 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
158 int len = option.length();
161 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
163 string arg = argv[i];
164 if ( arg.find( option ) == 0 ) {
165 return arg.substr( len );
175 // Scan the user config files for the specified option and return
177 static string fgScanForOption( const string& option, const string& path ) {
178 sg_gzifstream in( path );
179 if ( !in.is_open() ) {
183 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
185 int len = option.length();
189 while ( ! in.eof() ) {
192 while ( in.get(c) && c != '\0' ) {
197 #if defined( macintosh )
198 getline( in, line, '\r' );
200 getline( in, line, '\n' );
203 // catch extraneous (DOS) line ending character
204 if ( line[line.length() - 1] < 32 ) {
205 line = line.substr( 0, line.length()-1 );
208 if ( line.find( option ) == 0 ) {
209 return line.substr( len );
218 // Scan the user config files for the specified option and return
220 static string fgScanForOption( const string& option ) {
223 #if defined( unix ) || defined( __CYGWIN__ )
224 // Next check home directory for .fgfsrc.hostname file
226 if ( homedir != NULL ) {
227 SGPath config( homedir );
228 config.append( ".fgfsrc" );
229 config.concat( "." );
230 config.concat( hostname );
231 arg = fgScanForOption( option, config.str() );
236 // Next check home directory for .fgfsrc file
238 if ( homedir != NULL ) {
239 SGPath config( homedir );
240 config.append( ".fgfsrc" );
241 arg = fgScanForOption( option, config.str() );
246 // Check for $fg_root/system.fgfsrc
247 SGPath config( globals->get_fg_root() );
248 config.append( "system.fgfsrc" );
249 arg = fgScanForOption( option, config.str() );
256 // Read in configuration (files and command line options) but only set
258 bool fgInitFGRoot ( int argc, char **argv ) {
261 // First parse command line options looking for --fg-root=, this
262 // will override anything specified in a config file
263 root = fgScanForOption( "--fg-root=", argc, argv);
265 // Check in one of the user configuration files.
267 root = fgScanForOption( "--fg-root=" );
269 // Next check if fg-root is set as an env variable
270 if ( root.empty() ) {
271 char *envp = ::getenv( "FG_ROOT" );
272 if ( envp != NULL ) {
277 // Otherwise, default to a random compiled-in location if we can't
278 // find fg-root any other way.
279 if ( root.empty() ) {
280 #if defined( __CYGWIN__ )
281 root = "/FlightGear";
282 #elif defined( WIN32 )
283 root = "\\FlightGear";
284 #elif defined(OSX_BUNDLE)
285 /* the following code looks for the base package directly inside
286 the application bundle. This can be changed fairly easily by
287 fiddling with the code below. And yes, I know it's ugly and verbose.
289 CFBundleRef appBundle = CFBundleGetMainBundle();
290 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
291 CFRelease(appBundle);
293 // look for a 'data' subdir directly inside the bundle : is there
294 // a better place? maybe in Resources? I don't know ...
295 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
297 // now convert down to a path, and the a c-string
298 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
299 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
302 CFRelease(appBundle);
310 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
311 globals->set_fg_root(root);
317 // Read in configuration (files and command line options) but only set
319 bool fgInitFGAircraft ( int argc, char **argv ) {
322 // First parse command line options looking for --aircraft=, this
323 // will override anything specified in a config file
324 aircraft = fgScanForOption( "--aircraft=", argc, argv );
325 if ( aircraft.empty() ) {
326 // check synonym option
327 aircraft = fgScanForOption( "--vehicle=", argc, argv );
330 // Check in one of the user configuration files.
331 if ( aircraft.empty() ) {
332 aircraft = fgScanForOption( "--aircraft=" );
334 if ( aircraft.empty() ) {
335 aircraft = fgScanForOption( "--vehicle=" );
338 // if an aircraft was specified, set the property name
339 if ( !aircraft.empty() ) {
340 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
341 fgSetString("/sim/aircraft", aircraft.c_str() );
343 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
350 // Return the current base package version
351 string fgBasePackageVersion() {
352 SGPath base_path( globals->get_fg_root() );
353 base_path.append("version");
355 sg_gzifstream in( base_path.str() );
356 if ( !in.is_open() ) {
357 SGPath old_path( globals->get_fg_root() );
358 old_path.append( "Thanks" );
359 sg_gzifstream old( old_path.str() );
360 if ( !old.is_open() ) {
363 return "[old version]";
374 // Initialize the localization
375 SGPropertyNode *fgInitLocale(const char *language) {
376 SGPropertyNode *c_node = NULL, *d_node = NULL;
377 SGPropertyNode *intl = fgGetNode("/sim/intl");
379 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
381 // localization not defined
386 // Select the proper language from the list
388 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
389 for (unsigned int i = 0; i < locale.size(); i++) {
391 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
392 for (unsigned int j = 0; j < lang.size(); j++) {
394 if (!strcmp(lang[j]->getStringValue(), language)) {
403 d_node = intl->getChild("locale");
407 // Check for localized font
408 SGPropertyNode *font_n = c_node->getNode("font", true);
409 if ( !strcmp(font_n->getStringValue(), "") )
410 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
414 // Load the default strings
416 SGPath d_path( globals->get_fg_root() );
418 const char *d_path_str = d_node->getStringValue("strings");
420 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
424 d_path.append(d_path_str);
425 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
427 SGPropertyNode *strings = c_node->getNode("strings");
429 readProperties(d_path.str(), strings);
430 } catch (const sg_exception &e) {
431 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
436 // Load the language specific strings
438 if (c_node != d_node) {
439 SGPath c_path( globals->get_fg_root() );
441 const char *c_path_str = c_node->getStringValue("strings");
443 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
447 c_path.append(c_path_str);
448 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
451 readProperties(c_path.str(), strings);
452 } catch (const sg_exception &e) {
453 SG_LOG(SG_GENERAL, SG_ALERT,
454 "Unable to read the localized strings from " << c_path.str());
464 // Initialize the localization routines
465 bool fgDetectLanguage() {
466 const char *language = ::getenv("LANG");
468 if (language == NULL) {
469 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
473 SGPropertyNode *locale = fgInitLocale(language);
475 SG_LOG(SG_GENERAL, SG_ALERT,
476 "No internationalization settings specified in preferences.xml" );
481 globals->set_locale( locale );
486 // Attempt to locate and parse the various non-XML config files in order
487 // from least precidence to greatest precidence
489 do_options (int argc, char ** argv)
491 // Check for $fg_root/system.fgfsrc
492 SGPath config( globals->get_fg_root() );
493 config.append( "system.fgfsrc" );
494 fgParseOptions(config.str());
496 #if defined( unix ) || defined( __CYGWIN__ )
497 config.concat( "." );
498 config.concat( hostname );
499 fgParseOptions(config.str());
502 // Check for ~/.fgfsrc
503 if ( homedir != NULL ) {
504 config.set( homedir );
505 config.append( ".fgfsrc" );
506 fgParseOptions(config.str());
509 #if defined( unix ) || defined( __CYGWIN__ )
510 // Check for ~/.fgfsrc.hostname
511 config.concat( "." );
512 config.concat( hostname );
513 fgParseOptions(config.str());
516 // Parse remaining command line options
517 // These will override anything specified in a config file
518 fgParseArgs(argc, argv);
522 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
523 SGPropertyNode *cache, int depth = 0 )
525 const int MAXDEPTH = 1;
528 ulDir *dirp = ulOpenDir(path.str().c_str());
530 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
535 while ((dire = ulReadDir(dirp)) != NULL) {
537 if (depth > MAXDEPTH)
540 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
541 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
545 next.append(dire->d_name);
547 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
548 if ( ! result.empty() )
552 int len = strlen(dire->d_name);
553 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
559 if (!cache->getChild("aircraft", i++, false))
562 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
564 n = entry->getNode("file", true);
565 n->setStringValue(dire->d_name);
566 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
568 n = entry->getNode("path", true);
569 n->setStringValue(path.str().c_str());
570 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
572 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
584 // Read in configuration (file and command line)
585 bool fgInitConfig ( int argc, char **argv ) {
587 // First, set some sane default values
590 // Read global preferences from $FG_ROOT/preferences.xml
591 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
592 fgLoadProps("preferences.xml", globals->get_props());
593 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
595 // Detect the required language as early as possible
596 if ( !fgDetectLanguage() ) {
600 SGPropertyNode autosave;
602 char *envp = ::getenv( "APPDATA" );
604 SGPath config( envp );
605 config.append( "flightgear.org" );
607 if ( homedir != NULL ) {
608 SGPath config( homedir );
609 config.append( ".fgfs" );
611 const char *fg_home = getenv("FG_HOME");
615 // Set /sim/fg-home and don't allow malign code to override it until
616 // Nasal security is set up. Use FG_HOME if necessary.
617 SGPropertyNode *home = fgGetNode("/sim", true);
618 home->removeChild("fg-home", 0, false);
619 home = home->getChild("fg-home", 0, true);
620 home->setStringValue(config.c_str());
621 home->setAttribute(SGPropertyNode::WRITE, false);
623 config.append( "autosave.xml" );
624 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
626 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
628 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
630 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
632 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
635 // Scan user config files and command line for a specified aircraft.
636 fgInitFGAircraft(argc, argv);
638 string aircraft = fgGetString( "/sim/aircraft", "" );
639 if ( aircraft.size() > 0 ) {
640 SGPath aircraft_search( globals->get_fg_root() );
641 aircraft_search.append( "Aircraft" );
643 string aircraft_set = aircraft + "-set.xml";
646 // check if the *-set.xml file is already in the cache
647 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
648 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
649 for (unsigned int i = 0; i < cache.size(); i++) {
650 const char *name = cache[i]->getStringValue("file", "");
651 if (aircraft_set == name) {
652 const char *path = cache[i]->getStringValue("path", "");
662 if (result.empty()) {
663 // prepare cache for rescan
664 SGPropertyNode *n = cache_root->getNode("fg-root", true);
665 n->setStringValue(globals->get_fg_root().c_str());
666 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
667 cache_root->removeChildren("aircraft");
669 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
672 if ( !result.empty() ) {
673 fgSetString( "/sim/aircraft-dir", result.c_str() );
674 SGPath full_name( result );
675 full_name.append( aircraft_set );
677 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
678 << " from " << full_name.str());
680 readProperties( full_name.str(), globals->get_props() );
681 } catch ( const sg_exception &e ) {
682 string message = "Error reading default aircraft: ";
683 message += e.getFormattedMessage();
684 SG_LOG(SG_INPUT, SG_ALERT, message);
688 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
694 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
697 copyProperties(&autosave, globals->get_props());
699 // parse options after loading aircraft to ensure any user
700 // overrides of defaults are honored.
701 do_options(argc, argv);
712 // This function is never used, but maybe useful in the future ???
715 // Preset lon/lat given an airport id
716 static bool fgSetPosFromAirportID( const string& id ) {
720 SG_LOG( SG_GENERAL, SG_INFO,
721 "Attempting to set starting position from airport code " << id );
723 if ( fgFindAirportID( id, &a ) ) {
725 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
726 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
728 // other code depends on the actual postition being set so set
730 fgSetDouble("/position/longitude-deg", a->longitude );
731 fgSetDouble("/position/latitude-deg", a->latitude );
733 SG_LOG( SG_GENERAL, SG_INFO,
734 "Position for " << id << " is (" << a->longitude
735 << ", " << a->latitude << ")" );
745 // Set current tower position lon/lat given an airport id
746 static bool fgSetTowerPosFromAirportID( const string& id) {
747 const FGAirport *a = fgFindAirportID( id);
749 SGGeod tower = a->getTowerLocation();
750 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
751 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
752 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
760 struct FGTowerLocationListener : SGPropertyChangeListener {
761 void valueChanged(SGPropertyNode* node) {
762 const string id(node->getStringValue());
763 fgSetTowerPosFromAirportID(id);
767 void fgInitTowerLocationListener() {
768 fgGetNode("/sim/tower/airport-id", true)
769 ->addChangeListener( new FGTowerLocationListener(), true );
772 // Set current_options lon/lat given an airport id and heading (degrees)
773 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
779 // set initial position from runway and heading
780 SG_LOG( SG_GENERAL, SG_INFO,
781 "Attempting to set starting position from airport code "
782 << id << " heading " << tgt_hdg );
784 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
785 SG_LOG( SG_GENERAL, SG_ALERT,
786 "Failed to find a good runway for " << id << '\n' );
789 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
791 double lat2, lon2, az2;
792 double heading = r._heading;
793 double azimuth = heading + 180.0;
794 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
796 SG_LOG( SG_GENERAL, SG_INFO,
797 "runway = " << r._lon << ", " << r._lat
798 << " length = " << r._length * SG_FEET_TO_METER
799 << " heading = " << azimuth );
801 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
802 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
803 &lat2, &lon2, &az2 );
805 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
807 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
808 odist *= SG_NM_TO_METER;
809 double oaz = azimuth;
810 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
811 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
814 while ( oaz >= 360.0 ) { oaz -= 360.0; }
815 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
821 fgSetDouble("/sim/presets/longitude-deg", lon2 );
822 fgSetDouble("/sim/presets/latitude-deg", lat2 );
823 fgSetDouble("/sim/presets/heading-deg", heading );
825 // other code depends on the actual values being set ...
826 fgSetDouble("/position/longitude-deg", lon2 );
827 fgSetDouble("/position/latitude-deg", lat2 );
828 fgSetDouble("/orientation/heading-deg", heading );
830 SG_LOG( SG_GENERAL, SG_INFO,
831 "Position for " << id << " is ("
833 << lat2 << ") new heading is "
839 // Set current_options lon/lat given an airport id and parkig position name
840 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
844 // can't see an easy way around this const_cast at the moment
845 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
847 SG_LOG( SG_GENERAL, SG_ALERT,
848 "Failed to find airport " << id );
851 FGAirportDynamics* dcs = apt->getDynamics();
853 SG_LOG( SG_GENERAL, SG_ALERT,
854 "Failed to find parking position " << parkpos <<
855 " at airport " << id );
859 int park_index = dcs->getNrOfParkings() - 1;
860 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
861 if (park_index < 0) {
862 SG_LOG( SG_GENERAL, SG_ALERT,
863 "Failed to find parking position " << parkpos <<
864 " at airport " << id );
867 FGParking* parking = dcs->getParking(park_index);
869 double lat = parking->getLatitude();
870 double lon = parking->getLongitude();
871 double hdg = parking->getHeading();
874 fgSetDouble("/sim/presets/longitude-deg", lon );
875 fgSetDouble("/sim/presets/latitude-deg", lat );
876 fgSetDouble("/sim/presets/heading-deg", hdg );
878 // other code depends on the actual values being set ...
879 fgSetDouble("/position/longitude-deg", lon );
880 fgSetDouble("/position/latitude-deg", lat );
881 fgSetDouble("/orientation/heading-deg", hdg );
883 SG_LOG( SG_GENERAL, SG_INFO,
884 "Position for " << id << " is ("
886 << lat << ") new heading is "
893 // Set current_options lon/lat given an airport id and runway number
894 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
900 // set initial position from airport and runway number
901 SG_LOG( SG_GENERAL, SG_INFO,
902 "Attempting to set starting position for "
903 << id << ":" << rwy );
905 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
906 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
907 "Failed to find runway " << rwy <<
908 " at airport " << id << ". Using default runway." );
911 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
913 double lat2, lon2, az2;
914 double heading = r._heading;
915 double azimuth = heading + 180.0;
916 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
918 SG_LOG( SG_GENERAL, SG_INFO,
919 "runway = " << r._lon << ", " << r._lat
920 << " length = " << r._length * SG_FEET_TO_METER
921 << " heading = " << azimuth );
923 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
924 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
925 &lat2, &lon2, &az2 );
927 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
930 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
931 odist *= SG_NM_TO_METER;
932 double oaz = azimuth;
933 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
935 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
936 heading = fgGetDouble("/sim/presets/heading-deg");
938 while ( oaz >= 360.0 ) { oaz -= 360.0; }
939 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
945 fgSetDouble("/sim/presets/longitude-deg", lon2 );
946 fgSetDouble("/sim/presets/latitude-deg", lat2 );
947 fgSetDouble("/sim/presets/heading-deg", heading );
949 // other code depends on the actual values being set ...
950 fgSetDouble("/position/longitude-deg", lon2 );
951 fgSetDouble("/position/latitude-deg", lat2 );
952 fgSetDouble("/orientation/heading-deg", heading );
954 SG_LOG( SG_GENERAL, SG_INFO,
955 "Position for " << id << " is ("
957 << lat2 << ") new heading is "
964 static void fgSetDistOrAltFromGlideSlope() {
965 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
966 string apt_id = fgGetString("/sim/presets/airport-id");
967 double gs = fgGetDouble("/sim/presets/glideslope-deg")
968 * SG_DEGREES_TO_RADIANS ;
969 double od = fgGetDouble("/sim/presets/offset-distance-nm");
970 double alt = fgGetDouble("/sim/presets/altitude-ft");
972 double apt_elev = 0.0;
973 if ( ! apt_id.empty() ) {
974 apt_elev = fgGetAirportElev( apt_id );
975 if ( apt_elev < -9990.0 ) {
982 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
983 // set altitude from glideslope and offset-distance
984 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
985 alt = fabs(od*tan(gs)) + apt_elev;
986 fgSetDouble("/sim/presets/altitude-ft", alt);
987 fgSetBool("/sim/presets/onground", false);
988 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
990 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
991 // set offset-distance from glideslope and altitude
992 od = (alt - apt_elev) / tan(gs);
993 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
994 fgSetDouble("/sim/presets/offset-distance-nm", od);
995 fgSetBool("/sim/presets/onground", false);
996 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
998 } else if( fabs(gs) > 0.01 ) {
999 SG_LOG( SG_GENERAL, SG_ALERT,
1000 "Glideslope given but not altitude or offset-distance." );
1001 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
1002 fgSetDouble("/sim/presets/glideslope-deg", 0);
1003 fgSetBool("/sim/presets/onground", true);
1008 // Set current_options lon/lat given an airport id and heading (degrees)
1009 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
1011 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
1013 // set initial position from runway and heading
1014 if ( nav != NULL ) {
1015 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1016 << id << ":" << freq );
1018 double lon = nav->get_lon();
1019 double lat = nav->get_lat();
1021 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1023 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1025 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1027 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1028 double olat, olon, az2;
1029 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1036 fgSetDouble("/sim/presets/longitude-deg", lon );
1037 fgSetDouble("/sim/presets/latitude-deg", lat );
1039 // other code depends on the actual values being set ...
1040 fgSetDouble("/position/longitude-deg", lon );
1041 fgSetDouble("/position/latitude-deg", lat );
1042 fgSetDouble("/orientation/heading-deg",
1043 fgGetDouble("/sim/presets/heading-deg") );
1045 SG_LOG( SG_GENERAL, SG_INFO,
1046 "Position for " << id << ":" << freq << " is ("
1047 << lon << ", "<< lat << ")" );
1051 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1052 << id << ":" << freq );
1057 // Set current_options lon/lat given an aircraft carrier id
1058 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1060 // set initial position from runway and heading
1064 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1065 double lon = geodPos.getLongitudeDeg();
1066 double lat = geodPos.getLatitudeDeg();
1067 double alt = geodPos.getElevationFt();
1069 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1070 << carrier << " at lat = " << lat << ", lon = " << lon
1071 << ", alt = " << alt << ", heading = " << heading);
1073 fgSetDouble("/sim/presets/longitude-deg", lon);
1074 fgSetDouble("/sim/presets/latitude-deg", lat);
1075 fgSetDouble("/sim/presets/altitude-ft", alt);
1076 fgSetDouble("/sim/presets/heading-deg", heading);
1077 fgSetDouble("/position/longitude-deg", lon);
1078 fgSetDouble("/position/latitude-deg", lat);
1079 fgSetDouble("/position/altitude-ft", alt);
1080 fgSetDouble("/orientation/heading-deg", heading);
1082 fgSetString("/sim/presets/speed-set", "UVW");
1083 fgSetDouble("/velocities/uBody-fps", uvw(0));
1084 fgSetDouble("/velocities/vBody-fps", uvw(1));
1085 fgSetDouble("/velocities/wBody-fps", uvw(2));
1086 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1087 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1088 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1090 fgSetBool("/sim/presets/onground", true);
1094 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1100 // Set current_options lon/lat given an airport id and heading (degrees)
1101 static bool fgSetPosFromFix( const string& id ) {
1104 // set initial position from runway and heading
1105 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1106 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1109 double lon = fix.get_lon();
1110 double lat = fix.get_lat();
1112 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1114 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1116 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1118 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1119 double olat, olon, az2;
1120 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1127 fgSetDouble("/sim/presets/longitude-deg", lon );
1128 fgSetDouble("/sim/presets/latitude-deg", lat );
1130 // other code depends on the actual values being set ...
1131 fgSetDouble("/position/longitude-deg", lon );
1132 fgSetDouble("/position/latitude-deg", lat );
1133 fgSetDouble("/orientation/heading-deg",
1134 fgGetDouble("/sim/presets/heading-deg") );
1136 SG_LOG( SG_GENERAL, SG_INFO,
1137 "Position for " << id << " is ("
1138 << lon << ", "<< lat << ")" );
1142 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1150 * Initialize vor/ndb/ils/fix list management and query systems (as
1151 * well as simple airport db list)
1156 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1158 SGPath aptdb( globals->get_fg_root() );
1159 aptdb.append( "Airports/apt.dat" );
1161 SGPath p_metar( globals->get_fg_root() );
1162 p_metar.append( "Airports/metar.dat" );
1164 FGAirportList *airports = new FGAirportList();
1165 globals->set_airports( airports );
1166 FGRunwayList *runways = new FGRunwayList();
1167 globals->set_runways( runways );
1169 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1171 FGNavList *navlist = new FGNavList;
1172 FGNavList *loclist = new FGNavList;
1173 FGNavList *gslist = new FGNavList;
1174 FGNavList *dmelist = new FGNavList;
1175 FGNavList *mkrlist = new FGNavList;
1176 FGNavList *tacanlist = new FGNavList;
1177 FGNavList *carrierlist = new FGNavList;
1178 FGTACANList *channellist = new FGTACANList;
1180 globals->set_navlist( navlist );
1181 globals->set_loclist( loclist );
1182 globals->set_gslist( gslist );
1183 globals->set_dmelist( dmelist );
1184 globals->set_mkrlist( mkrlist );
1185 globals->set_tacanlist( tacanlist );
1186 globals->set_carrierlist( carrierlist );
1187 globals->set_channellist( channellist );
1189 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1190 SG_LOG( SG_GENERAL, SG_ALERT,
1191 "Problems loading one or more navigational database" );
1194 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1195 // align all the localizers with their corresponding runways
1196 // since data sources are good for cockpit navigation
1197 // purposes, but not always to the error tolerances needed to
1198 // exactly place these items.
1200 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1202 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1205 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1206 SGPath p_fix( globals->get_fg_root() );
1207 p_fix.append( "Navaids/fix.dat" );
1208 FGFixList *fixlist = new FGFixList;
1209 fixlist->init( p_fix );
1210 globals->set_fixlist( fixlist );
1212 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1213 SGPath p_awy( globals->get_fg_root() );
1214 p_awy.append( "Navaids/awy.dat" );
1215 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1216 //cerr << "Loading Airways" << endl;
1217 awyNet->load (p_awy );
1219 //cerr << "initializing airways" << endl;
1220 globals->set_airwaynet( awyNet );
1226 // Set the initial position based on presets (or defaults)
1227 bool fgInitPosition() {
1228 // cout << "fgInitPosition()" << endl;
1229 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1230 * SG_DEGREES_TO_RADIANS ;
1231 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1232 double alt = fgGetDouble("/sim/presets/altitude-ft");
1234 bool set_pos = false;
1236 // If glideslope is specified, then calculate offset-distance or
1237 // altitude relative to glide slope if either of those was not
1239 if ( fabs( gs ) > 0.01 ) {
1240 fgSetDistOrAltFromGlideSlope();
1244 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1245 // If not, check for an airport-id and use that.
1246 // If not, default to the middle of the KSFO field.
1247 // The default values for lon/lat are deliberately out of range
1248 // so that the airport-id can take effect; valid lon/lat will
1249 // override airport-id, however.
1250 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1251 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1252 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1253 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1258 string apt = fgGetString("/sim/presets/airport-id");
1259 string rwy_no = fgGetString("/sim/presets/runway");
1260 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1261 string vor = fgGetString("/sim/presets/vor-id");
1262 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1263 string ndb = fgGetString("/sim/presets/ndb-id");
1264 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1265 string carrier = fgGetString("/sim/presets/carrier");
1266 string parkpos = fgGetString("/sim/presets/parkpos");
1267 string fix = fgGetString("/sim/presets/fix");
1268 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1269 double hdg = hdg_preset->getDoubleValue();
1271 // save some start parameters, so that we can later say what the
1272 // user really requested. TODO generalize that and move it to options.cxx
1273 static bool start_options_saved = false;
1274 if (!start_options_saved) {
1275 start_options_saved = true;
1276 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1278 opt->setDoubleValue("latitude-deg", lat_deg);
1279 opt->setDoubleValue("longitude-deg", lon_deg);
1280 opt->setDoubleValue("heading-deg", hdg);
1281 opt->setStringValue("airport", apt.c_str());
1282 opt->setStringValue("runway", rwy_no.c_str());
1286 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1288 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1289 // An airport + parking position is requested
1290 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1291 // set tower position
1292 fgSetString("/sim/tower/airport-id", apt.c_str());
1297 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1298 // An airport + runway is requested
1299 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1300 // set tower position (a little off the heading for single
1302 fgSetString("/sim/tower/airport-id", apt.c_str());
1307 if ( !set_pos && !apt.empty() ) {
1308 // An airport is requested (find runway closest to hdg)
1309 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1310 // set tower position (a little off the heading for single
1312 fgSetString("/sim/tower/airport-id", apt.c_str());
1317 if (hdg_preset->getDoubleValue() > 9990.0)
1318 hdg_preset->setDoubleValue(hdg);
1320 if ( !set_pos && !vor.empty() ) {
1321 // a VOR is requested
1322 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1327 if ( !set_pos && !ndb.empty() ) {
1328 // an NDB is requested
1329 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1334 if ( !set_pos && !carrier.empty() ) {
1335 // an aircraft carrier is requested
1336 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1341 if ( !set_pos && !fix.empty() ) {
1342 // a Fix is requested
1343 if ( fgSetPosFromFix( fix ) ) {
1349 // No lon/lat specified, no airport specified, default to
1350 // middle of KSFO field.
1351 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1352 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1355 fgSetDouble( "/position/longitude-deg",
1356 fgGetDouble("/sim/presets/longitude-deg") );
1357 fgSetDouble( "/position/latitude-deg",
1358 fgGetDouble("/sim/presets/latitude-deg") );
1359 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1361 // determine if this should be an on-ground or in-air start
1362 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1363 fgSetBool("/sim/presets/onground", false);
1365 fgSetBool("/sim/presets/onground", true);
1372 // General house keeping initializations
1373 bool fgInitGeneral() {
1376 #if defined(FX) && defined(XMESA)
1377 char *mesa_win_state;
1380 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1381 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1383 root = globals->get_fg_root();
1384 if ( ! root.length() ) {
1385 // No root path set? Then bail ...
1386 SG_LOG( SG_GENERAL, SG_ALERT,
1387 "Cannot continue without a path to the base package "
1388 << "being defined." );
1391 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1393 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1395 #if defined(FX) && defined(XMESA)
1396 // initialize full screen flag
1397 globals->set_fullscreen(false);
1398 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1399 // Test for the MESA_GLX_FX env variable
1400 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1401 // test if we are fullscreen mesa/glide
1402 if ( (mesa_win_state[0] == 'f') ||
1403 (mesa_win_state[0] == 'F') ) {
1404 globals->set_fullscreen(true);
1410 char buf[512], *cwd = getcwd(buf, 511);
1412 SGPropertyNode *curr = fgGetNode("/sim", true);
1413 curr->removeChild("fg-current", 0, false);
1414 curr = curr->getChild("fg-current", 0, true);
1415 curr->setStringValue(cwd ? cwd : "");
1416 curr->setAttribute(SGPropertyNode::WRITE, false);
1421 // Initialize the flight model subsystem. This just creates the
1422 // object. The actual fdm initialization is delayed until we get a
1423 // proper scenery elevation hit. This is checked for in main.cxx
1427 if ( cur_fdm_state ) {
1428 delete cur_fdm_state;
1432 double dt = 1.0 / fgGetInt("/sim/model-hz");
1433 string model = fgGetString("/sim/flight-model");
1435 if ( model == "larcsim" ) {
1436 cur_fdm_state = new FGLaRCsim( dt );
1437 } else if ( model == "jsb" ) {
1438 cur_fdm_state = new FGJSBsim( dt );
1440 } else if ( model == "ada" ) {
1441 cur_fdm_state = new FGADA( dt );
1442 } else if ( model == "acms" ) {
1443 cur_fdm_state = new FGACMS( dt );
1445 } else if ( model == "balloon" ) {
1446 cur_fdm_state = new FGBalloonSim( dt );
1447 } else if ( model == "magic" ) {
1448 cur_fdm_state = new FGMagicCarpet( dt );
1449 } else if ( model == "ufo" ) {
1450 cur_fdm_state = new FGUFO( dt );
1451 } else if ( model == "external" ) {
1452 // external is a synonym for "--fdm=null" and is
1453 // maintained here for backwards compatibility
1454 cur_fdm_state = new FGNullFDM( dt );
1455 } else if ( model.find("network") == 0 ) {
1456 string host = "localhost";
1460 string net_options = model.substr(8);
1461 string::size_type begin, end;
1464 end = net_options.find( ",", begin );
1465 if ( end != string::npos ) {
1466 host = net_options.substr(begin, end - begin);
1470 end = net_options.find( ",", begin );
1471 if ( end != string::npos ) {
1472 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1476 end = net_options.find( ",", begin );
1477 if ( end != string::npos ) {
1478 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1482 end = net_options.find( ",", begin );
1483 if ( end != string::npos ) {
1484 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1487 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1488 } else if ( model.find("pipe") == 0 ) {
1489 // /* old */ string pipe_path = model.substr(5);
1490 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1491 string pipe_path = "";
1492 string pipe_protocol = "";
1493 string pipe_options = model.substr(5);
1494 string::size_type begin, end;
1497 end = pipe_options.find( ",", begin );
1498 if ( end != string::npos ) {
1499 pipe_path = pipe_options.substr(begin, end - begin);
1502 // protocol (last option)
1503 pipe_protocol = pipe_options.substr(begin);
1504 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1505 } else if ( model == "null" ) {
1506 cur_fdm_state = new FGNullFDM( dt );
1507 } else if ( model == "yasim" ) {
1508 cur_fdm_state = new YASim( dt );
1510 throw sg_throwable(string("Unrecognized flight model '") + model
1511 + "', cannot init flight dynamics model.");
1515 // Initialize view parameters
1517 // force update of model so that viewer can get some data...
1518 globals->get_aircraft_model()->update(0);
1519 // run update for current view so that data is current...
1520 globals->get_viewmgr()->update(0);
1524 SGTime *fgInitTime() {
1526 static const SGPropertyNode *longitude
1527 = fgGetNode("/position/longitude-deg");
1528 static const SGPropertyNode *latitude
1529 = fgGetNode("/position/latitude-deg");
1530 static const SGPropertyNode *cur_time_override
1531 = fgGetNode("/sim/time/cur-time-override", true);
1533 SGPath zone( globals->get_fg_root() );
1534 zone.append( "Timezone" );
1535 SGTime *t = new SGTime( longitude->getDoubleValue()
1536 * SGD_DEGREES_TO_RADIANS,
1537 latitude->getDoubleValue()
1538 * SGD_DEGREES_TO_RADIANS,
1540 cur_time_override->getLongValue() );
1542 globals->set_warp_delta( 0 );
1544 t->update( 0.0, 0.0,
1545 cur_time_override->getLongValue(),
1546 globals->get_warp() );
1552 // set up a time offset (aka warp) if one is specified
1553 void fgInitTimeOffset() {
1554 static const SGPropertyNode *longitude
1555 = fgGetNode("/position/longitude-deg");
1556 static const SGPropertyNode *latitude
1557 = fgGetNode("/position/latitude-deg");
1558 static const SGPropertyNode *cur_time_override
1559 = fgGetNode("/sim/time/cur-time-override", true);
1561 // Handle potential user specified time offsets
1562 int orig_warp = globals->get_warp();
1563 SGTime *t = globals->get_time_params();
1564 time_t cur_time = t->get_cur_time();
1565 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1566 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1567 time_t aircraftLocalTime =
1568 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1570 // Okay, we now have several possible scenarios
1571 int offset = fgGetInt("/sim/startup/time-offset");
1572 string offset_type = fgGetString("/sim/startup/time-offset-type");
1575 if ( offset_type == "real" ) {
1577 } else if ( offset_type == "dawn" ) {
1578 warp = fgTimeSecondsUntilSunAngle( cur_time,
1579 longitude->getDoubleValue()
1580 * SGD_DEGREES_TO_RADIANS,
1581 latitude->getDoubleValue()
1582 * SGD_DEGREES_TO_RADIANS,
1584 } else if ( offset_type == "morning" ) {
1585 warp = fgTimeSecondsUntilSunAngle( cur_time,
1586 longitude->getDoubleValue()
1587 * SGD_DEGREES_TO_RADIANS,
1588 latitude->getDoubleValue()
1589 * SGD_DEGREES_TO_RADIANS,
1591 } else if ( offset_type == "noon" ) {
1592 warp = fgTimeSecondsUntilSunAngle( cur_time,
1593 longitude->getDoubleValue()
1594 * SGD_DEGREES_TO_RADIANS,
1595 latitude->getDoubleValue()
1596 * SGD_DEGREES_TO_RADIANS,
1598 } else if ( offset_type == "afternoon" ) {
1599 warp = fgTimeSecondsUntilSunAngle( cur_time,
1600 longitude->getDoubleValue()
1601 * SGD_DEGREES_TO_RADIANS,
1602 latitude->getDoubleValue()
1603 * SGD_DEGREES_TO_RADIANS,
1605 } else if ( offset_type == "dusk" ) {
1606 warp = fgTimeSecondsUntilSunAngle( cur_time,
1607 longitude->getDoubleValue()
1608 * SGD_DEGREES_TO_RADIANS,
1609 latitude->getDoubleValue()
1610 * SGD_DEGREES_TO_RADIANS,
1612 } else if ( offset_type == "evening" ) {
1613 warp = fgTimeSecondsUntilSunAngle( cur_time,
1614 longitude->getDoubleValue()
1615 * SGD_DEGREES_TO_RADIANS,
1616 latitude->getDoubleValue()
1617 * SGD_DEGREES_TO_RADIANS,
1619 } else if ( offset_type == "midnight" ) {
1620 warp = fgTimeSecondsUntilSunAngle( cur_time,
1621 longitude->getDoubleValue()
1622 * SGD_DEGREES_TO_RADIANS,
1623 latitude->getDoubleValue()
1624 * SGD_DEGREES_TO_RADIANS,
1626 } else if ( offset_type == "system-offset" ) {
1629 } else if ( offset_type == "gmt-offset" ) {
1630 warp = offset - (currGMT - systemLocalTime);
1632 } else if ( offset_type == "latitude-offset" ) {
1633 warp = offset - (aircraftLocalTime - systemLocalTime);
1635 } else if ( offset_type == "system" ) {
1636 warp = offset - (systemLocalTime - currGMT) - cur_time;
1637 } else if ( offset_type == "gmt" ) {
1638 warp = offset - cur_time;
1639 } else if ( offset_type == "latitude" ) {
1640 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1642 SG_LOG( SG_GENERAL, SG_ALERT,
1643 "FG_TIME::Unsupported offset type " << offset_type );
1646 globals->set_warp( orig_warp + warp );
1647 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1648 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1649 cur_time_override->getLongValue(),
1650 globals->get_warp() );
1652 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1653 << globals->get_warp() );
1657 // This is the top level init routine which calls all the other
1658 // initialization routines. If you are adding a subsystem to flight
1659 // gear, its initialization call should located in this routine.
1660 // Returns non-zero if a problem encountered.
1661 bool fgInitSubsystems() {
1662 // static const SGPropertyNode *longitude
1663 // = fgGetNode("/sim/presets/longitude-deg");
1664 // static const SGPropertyNode *latitude
1665 // = fgGetNode("/sim/presets/latitude-deg");
1666 // static const SGPropertyNode *altitude
1667 // = fgGetNode("/sim/presets/altitude-ft");
1668 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1669 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1671 ////////////////////////////////////////////////////////////////////
1672 // Initialize the event manager subsystem.
1673 ////////////////////////////////////////////////////////////////////
1675 globals->get_event_mgr()->init();
1676 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1678 ////////////////////////////////////////////////////////////////////
1679 // Initialize the property interpolator subsystem. Put into the INIT
1680 // group because the "nasal" subsystem may need it at GENERAL take-down.
1681 ////////////////////////////////////////////////////////////////////
1682 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1685 ////////////////////////////////////////////////////////////////////
1686 // Add the FlightGear property utilities.
1687 ////////////////////////////////////////////////////////////////////
1688 globals->add_subsystem("properties", new FGProperties);
1690 ////////////////////////////////////////////////////////////////////
1691 // Initialize the material property subsystem.
1692 ////////////////////////////////////////////////////////////////////
1694 SGPath mpath( globals->get_fg_root() );
1695 mpath.append( "materials.xml" );
1696 string season = fgGetString("/sim/startup/season", "summer");
1697 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1698 globals->get_props()) ) {
1699 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1704 ////////////////////////////////////////////////////////////////////
1705 // Initialize the scenery management subsystem.
1706 ////////////////////////////////////////////////////////////////////
1708 if ( globals->get_tile_mgr()->init() ) {
1709 // Load the local scenery data
1710 double visibility_meters = fgGetDouble("/environment/visibility-m");
1712 globals->get_tile_mgr()->update( visibility_meters );
1714 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1718 globals->get_scenery()->get_scene_graph()
1719 ->addChild(simgear::Particles::getCommonRoot());
1721 ////////////////////////////////////////////////////////////////////
1722 // Initialize the flight model subsystem.
1723 ////////////////////////////////////////////////////////////////////
1727 // allocates structures so must happen before any of the flight
1728 // model or control parameters are set
1729 fgAircraftInit(); // In the future this might not be the case.
1732 ////////////////////////////////////////////////////////////////////
1733 // Initialize the weather subsystem.
1734 ////////////////////////////////////////////////////////////////////
1736 // Initialize the weather modeling subsystem
1737 globals->add_subsystem("environment", new FGEnvironmentMgr);
1740 ////////////////////////////////////////////////////////////////////
1741 // Initialize the aircraft systems and instrumentation (before the
1743 ////////////////////////////////////////////////////////////////////
1745 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1746 globals->add_subsystem("systems", new FGSystemMgr);
1748 ////////////////////////////////////////////////////////////////////
1749 // Initialize the XML Autopilot subsystem.
1750 ////////////////////////////////////////////////////////////////////
1752 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1753 globals->add_subsystem( "route-manager", new FGRouteMgr );
1756 ////////////////////////////////////////////////////////////////////
1757 // Initialize the view manager subsystem.
1758 ////////////////////////////////////////////////////////////////////
1762 ////////////////////////////////////////////////////////////////////
1763 // Create and register the logger.
1764 ////////////////////////////////////////////////////////////////////
1766 globals->add_subsystem("logger", new FGLogger);
1768 ////////////////////////////////////////////////////////////////////
1769 // Create and register the XML GUI.
1770 ////////////////////////////////////////////////////////////////////
1772 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1775 ////////////////////////////////////////////////////////////////////
1776 // Initialize the local time subsystem.
1777 ////////////////////////////////////////////////////////////////////
1779 // update the current timezone each 30 minutes
1780 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1781 &fgUpdateLocalTime, 30*60 );
1782 fgInitTimeOffset(); // the environment subsystem needs this
1785 ////////////////////////////////////////////////////////////////////
1786 // Initialize the lighting subsystem.
1787 ////////////////////////////////////////////////////////////////////
1789 globals->add_subsystem("lighting", new FGLight);
1791 //////////////////////////////////////////////////////////////////////
1792 // Initialize the 2D cloud subsystem.
1793 ////////////////////////////////////////////////////////////////////
1794 fgGetBool("/sim/rendering/bump-mapping", false);
1796 #ifdef ENABLE_AUDIO_SUPPORT
1797 ////////////////////////////////////////////////////////////////////
1798 // Initialize the sound subsystem.
1799 ////////////////////////////////////////////////////////////////////
1801 init_volume = fgGetFloat("/sim/sound/volume");
1802 fgSetFloat("/sim/sound/volume", 0.0f);
1803 globals->set_soundmgr(new SGSoundMgr);
1804 globals->get_soundmgr()->init();
1805 globals->get_soundmgr()->bind();
1808 ////////////////////////////////////////////////////////////////////
1809 // Initialize the sound-effects subsystem.
1810 ////////////////////////////////////////////////////////////////////
1812 globals->add_subsystem("fx", new FGFX);
1813 globals->add_subsystem("voice", new FGVoiceMgr);
1816 ////////////////////////////////////////////////////////////////////
1817 // Initialise the ATC Manager
1818 ////////////////////////////////////////////////////////////////////
1820 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1821 globals->set_ATC_mgr(new FGATCMgr);
1822 globals->get_ATC_mgr()->init();
1824 ////////////////////////////////////////////////////////////////////
1825 // Initialise the AI Manager
1826 ////////////////////////////////////////////////////////////////////
1828 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1829 globals->set_AI_mgr(new FGAIMgr);
1830 globals->get_AI_mgr()->init();
1832 ////////////////////////////////////////////////////////////////////
1833 // Initialise the AI Model Manager
1834 ////////////////////////////////////////////////////////////////////
1835 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1836 globals->add_subsystem("ai_model", new FGAIManager);
1837 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1840 // It's probably a good idea to initialize the top level traffic manager
1841 // After the AI and ATC systems have been initialized properly.
1842 // AI Traffic manager
1843 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1846 ////////////////////////////////////////////////////////////////////
1847 // Initialize the cockpit subsystem
1848 ////////////////////////////////////////////////////////////////////
1849 if( fgCockpitInit( ¤t_aircraft )) {
1850 // Cockpit initialized ok.
1852 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1857 ////////////////////////////////////////////////////////////////////
1858 // Initialize I/O subsystem.
1859 ////////////////////////////////////////////////////////////////////
1861 globals->get_io()->init();
1862 globals->get_io()->bind();
1865 ////////////////////////////////////////////////////////////////////
1866 // Add a new 2D panel.
1867 ////////////////////////////////////////////////////////////////////
1869 string panel_path = fgGetString("/sim/panel/path",
1870 "Panels/Default/default.xml");
1872 globals->set_current_panel( fgReadPanel(panel_path) );
1873 if (globals->get_current_panel() == 0) {
1874 SG_LOG( SG_INPUT, SG_ALERT,
1875 "Error reading new panel from " << panel_path );
1877 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1878 globals->get_current_panel()->init();
1879 globals->get_current_panel()->bind();
1883 ////////////////////////////////////////////////////////////////////
1884 // Initialize the controls subsystem.
1885 ////////////////////////////////////////////////////////////////////
1887 globals->get_controls()->init();
1888 globals->get_controls()->bind();
1891 ////////////////////////////////////////////////////////////////////
1892 // Initialize the input subsystem.
1893 ////////////////////////////////////////////////////////////////////
1895 globals->add_subsystem("input", new FGInput);
1898 ////////////////////////////////////////////////////////////////////
1899 // Initialize the replay subsystem
1900 ////////////////////////////////////////////////////////////////////
1901 globals->add_subsystem("replay", new FGReplay);
1903 ////////////////////////////////////////////////////////////////////
1904 // Bind and initialize subsystems.
1905 ////////////////////////////////////////////////////////////////////
1907 globals->get_subsystem_mgr()->bind();
1908 globals->get_subsystem_mgr()->init();
1910 ////////////////////////////////////////////////////////////////////
1911 // Initialize multiplayer subsystem
1912 ////////////////////////////////////////////////////////////////////
1914 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1915 globals->get_multiplayer_mgr()->init();
1917 ////////////////////////////////////////////////////////////////////////
1918 // Initialize the Nasal interpreter.
1919 // Do this last, so that the loaded scripts see initialized state
1920 ////////////////////////////////////////////////////////////////////////
1921 FGNasalSys* nasal = new FGNasalSys();
1922 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1925 // initialize methods that depend on other subsystems.
1926 globals->get_subsystem_mgr()->postinit();
1928 ////////////////////////////////////////////////////////////////////////
1929 // End of subsystem initialization.
1930 ////////////////////////////////////////////////////////////////////
1932 SG_LOG( SG_GENERAL, SG_INFO, endl);
1934 // Save the initial state for future
1936 globals->saveInitialState();
1942 void fgReInitSubsystems()
1944 // static const SGPropertyNode *longitude
1945 // = fgGetNode("/sim/presets/longitude-deg");
1946 // static const SGPropertyNode *latitude
1947 // = fgGetNode("/sim/presets/latitude-deg");
1948 static const SGPropertyNode *altitude
1949 = fgGetNode("/sim/presets/altitude-ft");
1950 static const SGPropertyNode *master_freeze
1951 = fgGetNode("/sim/freeze/master");
1953 SG_LOG( SG_GENERAL, SG_INFO,
1954 "fgReInitSubsystems(): /position/altitude = "
1955 << altitude->getDoubleValue() );
1957 bool freeze = master_freeze->getBoolValue();
1959 fgSetBool("/sim/freeze/master", true);
1961 fgSetBool("/sim/crashed", false);
1963 // Force reupdating the positions of the ai 3d models. They are used for
1964 // initializing ground level for the FDM.
1965 globals->get_subsystem("ai_model")->reinit();
1967 // Initialize the FDM
1970 // allocates structures so must happen before any of the flight
1971 // model or control parameters are set
1972 fgAircraftInit(); // In the future this might not be the case.
1974 // reload offsets from config defaults
1975 globals->get_viewmgr()->reinit();
1979 globals->get_controls()->reset_all();
1981 fgUpdateLocalTime();
1983 // re-init to proper time of day setting
1987 fgSetBool("/sim/freeze/master", false);
1989 fgSetBool("/sim/sceneryloaded",false);
1993 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1995 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1997 bool freeze = master_freeze->getBoolValue();
1999 master_freeze->setBoolValue(true);
2001 fgSetBool("/sim/signals/reinit", true);
2002 cur_fdm_state->unbind();
2004 // in case user has changed window size as
2005 // restoreInitialState() overwrites these
2006 int xsize = fgGetInt("/sim/startup/xsize");
2007 int ysize = fgGetInt("/sim/startup/ysize");
2009 globals->restoreInitialState();
2011 // update our position based on current presets
2014 // We don't know how to resize the window, so keep the last values
2015 // for xsize and ysize, and don't use the one set initially
2016 fgSetInt("/sim/startup/xsize", xsize);
2017 fgSetInt("/sim/startup/ysize", ysize);
2019 SGTime *t = globals->get_time_params();
2022 globals->set_time_params(t);
2024 fgReInitSubsystems();
2026 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
2027 globals->get_renderer()->resize(xsize, ysize);
2028 fgSetBool("/sim/signals/reinit", false);
2031 master_freeze->setBoolValue(false);