1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
35 #if defined( _MSC_VER) || defined(__MINGW32__)
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
40 // work around a stdc++ lib bug in some versions of linux, but doesn't
41 // seem to hurt to have this here for all versions of Linux.
43 # define _G_NO_EXTERN_TEMPLATES
46 #include <simgear/compiler.h>
50 #include <simgear/constants.h>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/structure/exception.hxx>
53 #include <simgear/structure/event_mgr.hxx>
54 #include <simgear/math/point3d.hxx>
55 #include <simgear/math/polar3d.hxx>
56 #include <simgear/math/sg_geodesy.hxx>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/misc/interpolator.hxx>
59 #include <simgear/scene/material/matlib.hxx>
60 #include <simgear/scene/model/particles.hxx>
61 #include <simgear/timing/sg_time.hxx>
62 #include <simgear/timing/lowleveltime.h>
64 #include <Aircraft/aircraft.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/apt_loader.hxx>
67 #include <Airports/runways.hxx>
68 #include <Airports/simple.hxx>
69 #include <AIModel/AIManager.hxx>
70 #include <ATCDCL/ATCmgr.hxx>
71 #include <ATCDCL/AIMgr.hxx>
72 #include <Autopilot/route_mgr.hxx>
73 #include <Autopilot/xmlauto.hxx>
74 #include <Cockpit/cockpit.hxx>
75 #include <Cockpit/panel.hxx>
76 #include <Cockpit/panel_io.hxx>
78 #include <FDM/SP/ADA.hxx>
79 #include <FDM/SP/ACMS.hxx>
80 #include <FDM/SP/MagicCarpet.hxx>
81 #include <FDM/SP/Balloon.h>
83 #include <FDM/ExternalNet/ExternalNet.hxx>
84 #include <FDM/ExternalPipe/ExternalPipe.hxx>
85 #include <FDM/JSBSim/JSBSim.hxx>
86 #include <FDM/LaRCsim/LaRCsim.hxx>
87 #include <FDM/UFO.hxx>
88 #include <FDM/NullFDM.hxx>
89 #include <FDM/YASim/YASim.hxx>
90 #include <GUI/new_gui.hxx>
91 #include <Include/general.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <AIModel/submodel.hxx>
96 #include <AIModel/AIManager.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/tilemgr.hxx>
101 #include <Scripting/NasalSys.hxx>
102 #include <Sound/fg_fx.hxx>
103 #include <Sound/beacon.hxx>
104 #include <Sound/morse.hxx>
105 #include <Sound/voice.hxx>
106 #include <Systems/system_mgr.hxx>
107 #include <Time/light.hxx>
108 #include <Time/sunsolver.hxx>
109 #include <Time/tmp.hxx>
110 #include <Traffic/TrafficMgr.hxx>
111 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <Environment/environment_mgr.hxx>
115 #include "fg_init.hxx"
117 #include "fg_commands.hxx"
118 #include "fg_props.hxx"
119 #include "options.hxx"
120 #include "globals.hxx"
121 #include "logger.hxx"
122 #include "renderer.hxx"
123 #include "viewmgr.hxx"
126 SG_USING_STD(string);
130 extern const char *default_root;
134 // Scan the command line options for the specified option and return
136 static string fgScanForOption( const string& option, int argc, char **argv ) {
139 if (hostname == NULL)
142 gethostname(_hostname, 256);
143 hostname = strdup(_hostname);
144 free_hostname = true;
147 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
149 int len = option.length();
152 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
154 string arg = argv[i];
155 if ( arg.find( option ) == 0 ) {
156 return arg.substr( len );
166 // Scan the user config files for the specified option and return
168 static string fgScanForOption( const string& option, const string& path ) {
169 sg_gzifstream in( path );
170 if ( !in.is_open() ) {
174 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
176 int len = option.length();
179 while ( ! in.eof() ) {
181 getline( in, line, '\n' );
183 // catch extraneous (DOS) line ending character
184 if ( line[line.length() - 1] < 32 ) {
185 line = line.substr( 0, line.length()-1 );
188 if ( line.find( option ) == 0 ) {
189 return line.substr( len );
198 // Scan the user config files for the specified option and return
200 static string fgScanForOption( const string& option ) {
203 #if defined( unix ) || defined( __CYGWIN__ )
204 // Next check home directory for .fgfsrc.hostname file
206 if ( homedir != NULL ) {
207 SGPath config( homedir );
208 config.append( ".fgfsrc" );
209 config.concat( "." );
210 config.concat( hostname );
211 arg = fgScanForOption( option, config.str() );
216 // Next check home directory for .fgfsrc file
218 if ( homedir != NULL ) {
219 SGPath config( homedir );
220 config.append( ".fgfsrc" );
221 arg = fgScanForOption( option, config.str() );
226 // Check for $fg_root/system.fgfsrc
227 SGPath config( globals->get_fg_root() );
228 config.append( "system.fgfsrc" );
229 arg = fgScanForOption( option, config.str() );
236 // Read in configuration (files and command line options) but only set
238 bool fgInitFGRoot ( int argc, char **argv ) {
241 // First parse command line options looking for --fg-root=, this
242 // will override anything specified in a config file
243 root = fgScanForOption( "--fg-root=", argc, argv);
245 // Check in one of the user configuration files.
247 root = fgScanForOption( "--fg-root=" );
249 // Next check if fg-root is set as an env variable
250 if ( root.empty() ) {
251 char *envp = ::getenv( "FG_ROOT" );
252 if ( envp != NULL ) {
257 // Otherwise, default to a random compiled-in location if we can't
258 // find fg-root any other way.
259 if ( root.empty() ) {
260 #if defined( __CYGWIN__ )
261 root = "/FlightGear";
262 #elif defined( WIN32 )
263 root = "\\FlightGear";
264 #elif defined(__APPLE__)
266 The following code looks for the base package inside the application
267 bundle, in the standard Contents/Resources location.
269 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
271 // look for a 'data' subdir
272 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
274 // now convert down to a path, and the a c-string
275 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
276 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
278 CFRelease(resourcesUrl);
286 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
287 globals->set_fg_root(root);
293 // Read in configuration (files and command line options) but only set
295 bool fgInitFGAircraft ( int argc, char **argv ) {
298 // First parse command line options looking for --aircraft=, this
299 // will override anything specified in a config file
300 aircraft = fgScanForOption( "--aircraft=", argc, argv );
301 if ( aircraft.empty() ) {
302 // check synonym option
303 aircraft = fgScanForOption( "--vehicle=", argc, argv );
306 // Check in one of the user configuration files.
307 if ( aircraft.empty() ) {
308 aircraft = fgScanForOption( "--aircraft=" );
310 if ( aircraft.empty() ) {
311 aircraft = fgScanForOption( "--vehicle=" );
314 // if an aircraft was specified, set the property name
315 if ( !aircraft.empty() ) {
316 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
317 fgSetString("/sim/aircraft", aircraft.c_str() );
319 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
326 // Return the current base package version
327 string fgBasePackageVersion() {
328 SGPath base_path( globals->get_fg_root() );
329 base_path.append("version");
331 sg_gzifstream in( base_path.str() );
332 if ( !in.is_open() ) {
333 SGPath old_path( globals->get_fg_root() );
334 old_path.append( "Thanks" );
335 sg_gzifstream old( old_path.str() );
336 if ( !old.is_open() ) {
339 return "[old version]";
350 // Initialize the localization
351 SGPropertyNode *fgInitLocale(const char *language) {
352 SGPropertyNode *c_node = NULL, *d_node = NULL;
353 SGPropertyNode *intl = fgGetNode("/sim/intl");
355 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
357 // localization not defined
362 // Select the proper language from the list
364 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
365 for (unsigned int i = 0; i < locale.size(); i++) {
367 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
368 for (unsigned int j = 0; j < lang.size(); j++) {
370 if (!strcmp(lang[j]->getStringValue(), language)) {
379 d_node = intl->getChild("locale");
383 // Check for localized font
384 SGPropertyNode *font_n = c_node->getNode("font", true);
385 if ( !strcmp(font_n->getStringValue(), "") )
386 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
390 // Load the default strings
392 SGPath d_path( globals->get_fg_root() );
394 const char *d_path_str = d_node->getStringValue("strings");
396 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
400 d_path.append(d_path_str);
401 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
403 SGPropertyNode *strings = c_node->getNode("strings");
405 readProperties(d_path.str(), strings);
406 } catch (const sg_exception &e) {
407 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
412 // Load the language specific strings
414 if (c_node != d_node) {
415 SGPath c_path( globals->get_fg_root() );
417 const char *c_path_str = c_node->getStringValue("strings");
419 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
423 c_path.append(c_path_str);
424 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
427 readProperties(c_path.str(), strings);
428 } catch (const sg_exception &e) {
429 SG_LOG(SG_GENERAL, SG_ALERT,
430 "Unable to read the localized strings from " << c_path.str());
440 // Initialize the localization routines
441 bool fgDetectLanguage() {
442 const char *language = ::getenv("LANG");
444 if (language == NULL) {
445 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
449 SGPropertyNode *locale = fgInitLocale(language);
451 SG_LOG(SG_GENERAL, SG_ALERT,
452 "No internationalization settings specified in preferences.xml" );
457 globals->set_locale( locale );
462 // Attempt to locate and parse the various non-XML config files in order
463 // from least precidence to greatest precidence
465 do_options (int argc, char ** argv)
467 // Check for $fg_root/system.fgfsrc
468 SGPath config( globals->get_fg_root() );
469 config.append( "system.fgfsrc" );
470 fgParseOptions(config.str());
472 #if defined( unix ) || defined( __CYGWIN__ )
473 config.concat( "." );
474 config.concat( hostname );
475 fgParseOptions(config.str());
478 // Check for ~/.fgfsrc
479 if ( homedir != NULL ) {
480 config.set( homedir );
481 config.append( ".fgfsrc" );
482 fgParseOptions(config.str());
485 #if defined( unix ) || defined( __CYGWIN__ )
486 // Check for ~/.fgfsrc.hostname
487 config.concat( "." );
488 config.concat( hostname );
489 fgParseOptions(config.str());
492 // Parse remaining command line options
493 // These will override anything specified in a config file
494 fgParseArgs(argc, argv);
498 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
499 SGPropertyNode *cache, int depth = 0 )
501 const int MAXDEPTH = 1;
504 ulDir *dirp = ulOpenDir(path.str().c_str());
506 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
511 while ((dire = ulReadDir(dirp)) != NULL) {
513 if (depth > MAXDEPTH)
516 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
517 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
521 next.append(dire->d_name);
523 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
524 if ( ! result.empty() )
528 int len = strlen(dire->d_name);
529 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
535 if (!cache->getChild("aircraft", i++, false))
538 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
540 n = entry->getNode("file", true);
541 n->setStringValue(dire->d_name);
542 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
544 n = entry->getNode("path", true);
545 n->setStringValue(path.str().c_str());
546 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
548 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
560 // Read in configuration (file and command line)
561 bool fgInitConfig ( int argc, char **argv ) {
563 // First, set some sane default values
566 // Read global preferences from $FG_ROOT/preferences.xml
567 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
568 fgLoadProps("preferences.xml", globals->get_props());
569 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
571 // Detect the required language as early as possible
572 if ( !fgDetectLanguage() ) {
576 SGPropertyNode autosave;
578 char *envp = ::getenv( "APPDATA" );
580 SGPath config( envp );
581 config.append( "flightgear.org" );
583 if ( homedir != NULL ) {
584 SGPath config( homedir );
585 config.append( ".fgfs" );
587 const char *fg_home = getenv("FG_HOME");
591 // Set /sim/fg-home and don't allow malign code to override it until
592 // Nasal security is set up. Use FG_HOME if necessary.
593 SGPropertyNode *home = fgGetNode("/sim", true);
594 home->removeChild("fg-home", 0, false);
595 home = home->getChild("fg-home", 0, true);
596 home->setStringValue(config.c_str());
597 home->setAttribute(SGPropertyNode::WRITE, false);
599 config.append( "autosave.xml" );
600 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
602 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
604 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
606 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
608 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
611 // Scan user config files and command line for a specified aircraft.
612 fgInitFGAircraft(argc, argv);
614 string aircraft = fgGetString( "/sim/aircraft", "" );
615 if ( aircraft.size() > 0 ) {
616 SGPath aircraft_search( globals->get_fg_root() );
617 aircraft_search.append( "Aircraft" );
619 string aircraft_set = aircraft + "-set.xml";
622 // check if the *-set.xml file is already in the cache
623 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
624 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
625 for (unsigned int i = 0; i < cache.size(); i++) {
626 const char *name = cache[i]->getStringValue("file", "");
627 if (aircraft_set == name) {
628 const char *path = cache[i]->getStringValue("path", "");
638 if (result.empty()) {
639 // prepare cache for rescan
640 SGPropertyNode *n = cache_root->getNode("fg-root", true);
641 n->setStringValue(globals->get_fg_root().c_str());
642 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
643 cache_root->removeChildren("aircraft");
645 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
648 if ( !result.empty() ) {
649 fgSetString( "/sim/aircraft-dir", result.c_str() );
650 SGPath full_name( result );
651 full_name.append( aircraft_set );
653 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
654 << " from " << full_name.str());
656 readProperties( full_name.str(), globals->get_props() );
657 } catch ( const sg_exception &e ) {
658 string message = "Error reading default aircraft: ";
659 message += e.getFormattedMessage();
660 SG_LOG(SG_INPUT, SG_ALERT, message);
664 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
670 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
673 copyProperties(&autosave, globals->get_props());
675 // parse options after loading aircraft to ensure any user
676 // overrides of defaults are honored.
677 do_options(argc, argv);
688 // This function is never used, but maybe useful in the future ???
691 // Preset lon/lat given an airport id
692 static bool fgSetPosFromAirportID( const string& id ) {
696 SG_LOG( SG_GENERAL, SG_INFO,
697 "Attempting to set starting position from airport code " << id );
699 if ( fgFindAirportID( id, &a ) ) {
701 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
702 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
704 // other code depends on the actual postition being set so set
706 fgSetDouble("/position/longitude-deg", a->longitude );
707 fgSetDouble("/position/latitude-deg", a->latitude );
709 SG_LOG( SG_GENERAL, SG_INFO,
710 "Position for " << id << " is (" << a->longitude
711 << ", " << a->latitude << ")" );
721 // Set current tower position lon/lat given an airport id
722 static bool fgSetTowerPosFromAirportID( const string& id) {
723 const FGAirport *a = fgFindAirportID( id);
725 SGGeod tower = a->getTowerLocation();
726 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
727 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
728 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
736 struct FGTowerLocationListener : SGPropertyChangeListener {
737 void valueChanged(SGPropertyNode* node) {
738 const string id(node->getStringValue());
739 fgSetTowerPosFromAirportID(id);
743 void fgInitTowerLocationListener() {
744 fgGetNode("/sim/tower/airport-id", true)
745 ->addChangeListener( new FGTowerLocationListener(), true );
748 // Set current_options lon/lat given an airport id and heading (degrees)
749 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
755 // set initial position from runway and heading
756 SG_LOG( SG_GENERAL, SG_INFO,
757 "Attempting to set starting position from airport code "
758 << id << " heading " << tgt_hdg );
760 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
761 SG_LOG( SG_GENERAL, SG_ALERT,
762 "Failed to find a good runway for " << id << '\n' );
765 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
767 double lat2, lon2, az2;
768 double heading = r._heading;
769 double azimuth = heading + 180.0;
770 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
772 SG_LOG( SG_GENERAL, SG_INFO,
773 "runway = " << r._lon << ", " << r._lat
774 << " length = " << r._length * SG_FEET_TO_METER
775 << " heading = " << azimuth );
777 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
778 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
779 &lat2, &lon2, &az2 );
781 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
783 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
784 odist *= SG_NM_TO_METER;
785 double oaz = azimuth;
786 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
787 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
790 while ( oaz >= 360.0 ) { oaz -= 360.0; }
791 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
797 fgSetDouble("/sim/presets/longitude-deg", lon2 );
798 fgSetDouble("/sim/presets/latitude-deg", lat2 );
799 fgSetDouble("/sim/presets/heading-deg", heading );
801 // other code depends on the actual values being set ...
802 fgSetDouble("/position/longitude-deg", lon2 );
803 fgSetDouble("/position/latitude-deg", lat2 );
804 fgSetDouble("/orientation/heading-deg", heading );
806 SG_LOG( SG_GENERAL, SG_INFO,
807 "Position for " << id << " is ("
809 << lat2 << ") new heading is "
815 // Set current_options lon/lat given an airport id and parkig position name
816 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
820 // can't see an easy way around this const_cast at the moment
821 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
823 SG_LOG( SG_GENERAL, SG_ALERT,
824 "Failed to find airport " << id );
827 FGAirportDynamics* dcs = apt->getDynamics();
829 SG_LOG( SG_GENERAL, SG_ALERT,
830 "Failed to find parking position " << parkpos <<
831 " at airport " << id );
835 int park_index = dcs->getNrOfParkings() - 1;
836 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
837 if (park_index < 0) {
838 SG_LOG( SG_GENERAL, SG_ALERT,
839 "Failed to find parking position " << parkpos <<
840 " at airport " << id );
843 FGParking* parking = dcs->getParking(park_index);
845 double lat = parking->getLatitude();
846 double lon = parking->getLongitude();
847 double hdg = parking->getHeading();
850 fgSetDouble("/sim/presets/longitude-deg", lon );
851 fgSetDouble("/sim/presets/latitude-deg", lat );
852 fgSetDouble("/sim/presets/heading-deg", hdg );
854 // other code depends on the actual values being set ...
855 fgSetDouble("/position/longitude-deg", lon );
856 fgSetDouble("/position/latitude-deg", lat );
857 fgSetDouble("/orientation/heading-deg", hdg );
859 SG_LOG( SG_GENERAL, SG_INFO,
860 "Position for " << id << " is ("
862 << lat << ") new heading is "
869 // Set current_options lon/lat given an airport id and runway number
870 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
876 // set initial position from airport and runway number
877 SG_LOG( SG_GENERAL, SG_INFO,
878 "Attempting to set starting position for "
879 << id << ":" << rwy );
881 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
882 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
883 "Failed to find runway " << rwy <<
884 " at airport " << id << ". Using default runway." );
887 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
889 double lat2, lon2, az2;
890 double heading = r._heading;
891 double azimuth = heading + 180.0;
892 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
894 SG_LOG( SG_GENERAL, SG_INFO,
895 "runway = " << r._lon << ", " << r._lat
896 << " length = " << r._length * SG_FEET_TO_METER
897 << " heading = " << azimuth );
899 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
900 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
901 &lat2, &lon2, &az2 );
903 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
906 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
907 odist *= SG_NM_TO_METER;
908 double oaz = azimuth;
909 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
911 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
912 heading = fgGetDouble("/sim/presets/heading-deg");
914 while ( oaz >= 360.0 ) { oaz -= 360.0; }
915 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
921 fgSetDouble("/sim/presets/longitude-deg", lon2 );
922 fgSetDouble("/sim/presets/latitude-deg", lat2 );
923 fgSetDouble("/sim/presets/heading-deg", heading );
925 // other code depends on the actual values being set ...
926 fgSetDouble("/position/longitude-deg", lon2 );
927 fgSetDouble("/position/latitude-deg", lat2 );
928 fgSetDouble("/orientation/heading-deg", heading );
930 SG_LOG( SG_GENERAL, SG_INFO,
931 "Position for " << id << " is ("
933 << lat2 << ") new heading is "
940 static void fgSetDistOrAltFromGlideSlope() {
941 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
942 string apt_id = fgGetString("/sim/presets/airport-id");
943 double gs = fgGetDouble("/sim/presets/glideslope-deg")
944 * SG_DEGREES_TO_RADIANS ;
945 double od = fgGetDouble("/sim/presets/offset-distance-nm");
946 double alt = fgGetDouble("/sim/presets/altitude-ft");
948 double apt_elev = 0.0;
949 if ( ! apt_id.empty() ) {
950 apt_elev = fgGetAirportElev( apt_id );
951 if ( apt_elev < -9990.0 ) {
958 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
959 // set altitude from glideslope and offset-distance
960 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
961 alt = fabs(od*tan(gs)) + apt_elev;
962 fgSetDouble("/sim/presets/altitude-ft", alt);
963 fgSetBool("/sim/presets/onground", false);
964 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
966 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
967 // set offset-distance from glideslope and altitude
968 od = (alt - apt_elev) / tan(gs);
969 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
970 fgSetDouble("/sim/presets/offset-distance-nm", od);
971 fgSetBool("/sim/presets/onground", false);
972 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
974 } else if( fabs(gs) > 0.01 ) {
975 SG_LOG( SG_GENERAL, SG_ALERT,
976 "Glideslope given but not altitude or offset-distance." );
977 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
978 fgSetDouble("/sim/presets/glideslope-deg", 0);
979 fgSetBool("/sim/presets/onground", true);
984 // Set current_options lon/lat given an airport id and heading (degrees)
985 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
987 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
989 // set initial position from runway and heading
991 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
992 << id << ":" << freq );
994 double lon = nav->get_lon();
995 double lat = nav->get_lat();
997 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
999 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1001 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1003 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1004 double olat, olon, az2;
1005 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1012 fgSetDouble("/sim/presets/longitude-deg", lon );
1013 fgSetDouble("/sim/presets/latitude-deg", lat );
1015 // other code depends on the actual values being set ...
1016 fgSetDouble("/position/longitude-deg", lon );
1017 fgSetDouble("/position/latitude-deg", lat );
1018 fgSetDouble("/orientation/heading-deg",
1019 fgGetDouble("/sim/presets/heading-deg") );
1021 SG_LOG( SG_GENERAL, SG_INFO,
1022 "Position for " << id << ":" << freq << " is ("
1023 << lon << ", "<< lat << ")" );
1027 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1028 << id << ":" << freq );
1033 // Set current_options lon/lat given an aircraft carrier id
1034 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1036 // set initial position from runway and heading
1040 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1041 double lon = geodPos.getLongitudeDeg();
1042 double lat = geodPos.getLatitudeDeg();
1043 double alt = geodPos.getElevationFt();
1045 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1046 << carrier << " at lat = " << lat << ", lon = " << lon
1047 << ", alt = " << alt << ", heading = " << heading);
1049 fgSetDouble("/sim/presets/longitude-deg", lon);
1050 fgSetDouble("/sim/presets/latitude-deg", lat);
1051 fgSetDouble("/sim/presets/altitude-ft", alt);
1052 fgSetDouble("/sim/presets/heading-deg", heading);
1053 fgSetDouble("/position/longitude-deg", lon);
1054 fgSetDouble("/position/latitude-deg", lat);
1055 fgSetDouble("/position/altitude-ft", alt);
1056 fgSetDouble("/orientation/heading-deg", heading);
1058 fgSetString("/sim/presets/speed-set", "UVW");
1059 fgSetDouble("/velocities/uBody-fps", uvw(0));
1060 fgSetDouble("/velocities/vBody-fps", uvw(1));
1061 fgSetDouble("/velocities/wBody-fps", uvw(2));
1062 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1063 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1064 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1066 fgSetBool("/sim/presets/onground", true);
1070 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1076 // Set current_options lon/lat given an airport id and heading (degrees)
1077 static bool fgSetPosFromFix( const string& id ) {
1080 // set initial position from runway and heading
1081 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1082 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1085 double lon = fix.get_lon();
1086 double lat = fix.get_lat();
1088 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1090 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1092 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1094 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1095 double olat, olon, az2;
1096 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1103 fgSetDouble("/sim/presets/longitude-deg", lon );
1104 fgSetDouble("/sim/presets/latitude-deg", lat );
1106 // other code depends on the actual values being set ...
1107 fgSetDouble("/position/longitude-deg", lon );
1108 fgSetDouble("/position/latitude-deg", lat );
1109 fgSetDouble("/orientation/heading-deg",
1110 fgGetDouble("/sim/presets/heading-deg") );
1112 SG_LOG( SG_GENERAL, SG_INFO,
1113 "Position for " << id << " is ("
1114 << lon << ", "<< lat << ")" );
1118 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1126 * Initialize vor/ndb/ils/fix list management and query systems (as
1127 * well as simple airport db list)
1132 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1134 SGPath aptdb( globals->get_fg_root() );
1135 aptdb.append( "Airports/apt.dat" );
1137 SGPath p_metar( globals->get_fg_root() );
1138 p_metar.append( "Airports/metar.dat" );
1140 FGAirportList *airports = new FGAirportList();
1141 globals->set_airports( airports );
1142 FGRunwayList *runways = new FGRunwayList();
1143 globals->set_runways( runways );
1145 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1147 FGNavList *navlist = new FGNavList;
1148 FGNavList *loclist = new FGNavList;
1149 FGNavList *gslist = new FGNavList;
1150 FGNavList *dmelist = new FGNavList;
1151 FGNavList *mkrlist = new FGNavList;
1152 FGNavList *tacanlist = new FGNavList;
1153 FGNavList *carrierlist = new FGNavList;
1154 FGTACANList *channellist = new FGTACANList;
1156 globals->set_navlist( navlist );
1157 globals->set_loclist( loclist );
1158 globals->set_gslist( gslist );
1159 globals->set_dmelist( dmelist );
1160 globals->set_mkrlist( mkrlist );
1161 globals->set_tacanlist( tacanlist );
1162 globals->set_carrierlist( carrierlist );
1163 globals->set_channellist( channellist );
1165 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1166 SG_LOG( SG_GENERAL, SG_ALERT,
1167 "Problems loading one or more navigational database" );
1170 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1171 // align all the localizers with their corresponding runways
1172 // since data sources are good for cockpit navigation
1173 // purposes, but not always to the error tolerances needed to
1174 // exactly place these items.
1176 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1178 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1181 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1182 SGPath p_fix( globals->get_fg_root() );
1183 p_fix.append( "Navaids/fix.dat" );
1184 FGFixList *fixlist = new FGFixList;
1185 fixlist->init( p_fix );
1186 globals->set_fixlist( fixlist );
1188 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1189 SGPath p_awy( globals->get_fg_root() );
1190 p_awy.append( "Navaids/awy.dat" );
1191 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1192 //cerr << "Loading Airways" << endl;
1193 awyNet->load (p_awy );
1195 //cerr << "initializing airways" << endl;
1196 globals->set_airwaynet( awyNet );
1202 // Set the initial position based on presets (or defaults)
1203 bool fgInitPosition() {
1204 // cout << "fgInitPosition()" << endl;
1205 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1206 * SG_DEGREES_TO_RADIANS ;
1207 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1208 double alt = fgGetDouble("/sim/presets/altitude-ft");
1210 bool set_pos = false;
1212 // If glideslope is specified, then calculate offset-distance or
1213 // altitude relative to glide slope if either of those was not
1215 if ( fabs( gs ) > 0.01 ) {
1216 fgSetDistOrAltFromGlideSlope();
1220 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1221 // If not, check for an airport-id and use that.
1222 // If not, default to the middle of the KSFO field.
1223 // The default values for lon/lat are deliberately out of range
1224 // so that the airport-id can take effect; valid lon/lat will
1225 // override airport-id, however.
1226 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1227 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1228 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1229 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1234 string apt = fgGetString("/sim/presets/airport-id");
1235 string rwy_no = fgGetString("/sim/presets/runway");
1236 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1237 string vor = fgGetString("/sim/presets/vor-id");
1238 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1239 string ndb = fgGetString("/sim/presets/ndb-id");
1240 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1241 string carrier = fgGetString("/sim/presets/carrier");
1242 string parkpos = fgGetString("/sim/presets/parkpos");
1243 string fix = fgGetString("/sim/presets/fix");
1244 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1245 double hdg = hdg_preset->getDoubleValue();
1247 // save some start parameters, so that we can later say what the
1248 // user really requested. TODO generalize that and move it to options.cxx
1249 static bool start_options_saved = false;
1250 if (!start_options_saved) {
1251 start_options_saved = true;
1252 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1254 opt->setDoubleValue("latitude-deg", lat_deg);
1255 opt->setDoubleValue("longitude-deg", lon_deg);
1256 opt->setDoubleValue("heading-deg", hdg);
1257 opt->setStringValue("airport", apt.c_str());
1258 opt->setStringValue("runway", rwy_no.c_str());
1262 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1264 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1265 // An airport + parking position is requested
1266 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1267 // set tower position
1268 fgSetString("/sim/tower/airport-id", apt.c_str());
1273 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1274 // An airport + runway is requested
1275 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1276 // set tower position (a little off the heading for single
1278 fgSetString("/sim/tower/airport-id", apt.c_str());
1283 if ( !set_pos && !apt.empty() ) {
1284 // An airport is requested (find runway closest to hdg)
1285 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1286 // set tower position (a little off the heading for single
1288 fgSetString("/sim/tower/airport-id", apt.c_str());
1293 if (hdg_preset->getDoubleValue() > 9990.0)
1294 hdg_preset->setDoubleValue(hdg);
1296 if ( !set_pos && !vor.empty() ) {
1297 // a VOR is requested
1298 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1303 if ( !set_pos && !ndb.empty() ) {
1304 // an NDB is requested
1305 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1310 if ( !set_pos && !carrier.empty() ) {
1311 // an aircraft carrier is requested
1312 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1317 if ( !set_pos && !fix.empty() ) {
1318 // a Fix is requested
1319 if ( fgSetPosFromFix( fix ) ) {
1325 // No lon/lat specified, no airport specified, default to
1326 // middle of KSFO field.
1327 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1328 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1331 fgSetDouble( "/position/longitude-deg",
1332 fgGetDouble("/sim/presets/longitude-deg") );
1333 fgSetDouble( "/position/latitude-deg",
1334 fgGetDouble("/sim/presets/latitude-deg") );
1335 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1337 // determine if this should be an on-ground or in-air start
1338 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1339 fgSetBool("/sim/presets/onground", false);
1341 fgSetBool("/sim/presets/onground", true);
1348 // General house keeping initializations
1349 bool fgInitGeneral() {
1352 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1353 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1355 root = globals->get_fg_root();
1356 if ( ! root.length() ) {
1357 // No root path set? Then bail ...
1358 SG_LOG( SG_GENERAL, SG_ALERT,
1359 "Cannot continue without a path to the base package "
1360 << "being defined." );
1363 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1365 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1367 char buf[512], *cwd = getcwd(buf, 511);
1369 SGPropertyNode *curr = fgGetNode("/sim", true);
1370 curr->removeChild("fg-current", 0, false);
1371 curr = curr->getChild("fg-current", 0, true);
1372 curr->setStringValue(cwd ? cwd : "");
1373 curr->setAttribute(SGPropertyNode::WRITE, false);
1378 // Initialize the flight model subsystem. This just creates the
1379 // object. The actual fdm initialization is delayed until we get a
1380 // proper scenery elevation hit. This is checked for in main.cxx
1384 if ( cur_fdm_state ) {
1385 delete cur_fdm_state;
1389 double dt = 1.0 / fgGetInt("/sim/model-hz");
1390 string model = fgGetString("/sim/flight-model");
1392 if ( model == "larcsim" ) {
1393 cur_fdm_state = new FGLaRCsim( dt );
1394 } else if ( model == "jsb" ) {
1395 cur_fdm_state = new FGJSBsim( dt );
1397 } else if ( model == "ada" ) {
1398 cur_fdm_state = new FGADA( dt );
1399 } else if ( model == "acms" ) {
1400 cur_fdm_state = new FGACMS( dt );
1401 } else if ( model == "balloon" ) {
1402 cur_fdm_state = new FGBalloonSim( dt );
1403 } else if ( model == "magic" ) {
1404 cur_fdm_state = new FGMagicCarpet( dt );
1406 } else if ( model == "ufo" ) {
1407 cur_fdm_state = new FGUFO( dt );
1408 } else if ( model == "external" ) {
1409 // external is a synonym for "--fdm=null" and is
1410 // maintained here for backwards compatibility
1411 cur_fdm_state = new FGNullFDM( dt );
1412 } else if ( model.find("network") == 0 ) {
1413 string host = "localhost";
1417 string net_options = model.substr(8);
1418 string::size_type begin, end;
1421 end = net_options.find( ",", begin );
1422 if ( end != string::npos ) {
1423 host = net_options.substr(begin, end - begin);
1427 end = net_options.find( ",", begin );
1428 if ( end != string::npos ) {
1429 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1433 end = net_options.find( ",", begin );
1434 if ( end != string::npos ) {
1435 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1439 end = net_options.find( ",", begin );
1440 if ( end != string::npos ) {
1441 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1444 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1445 } else if ( model.find("pipe") == 0 ) {
1446 // /* old */ string pipe_path = model.substr(5);
1447 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1448 string pipe_path = "";
1449 string pipe_protocol = "";
1450 string pipe_options = model.substr(5);
1451 string::size_type begin, end;
1454 end = pipe_options.find( ",", begin );
1455 if ( end != string::npos ) {
1456 pipe_path = pipe_options.substr(begin, end - begin);
1459 // protocol (last option)
1460 pipe_protocol = pipe_options.substr(begin);
1461 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1462 } else if ( model == "null" ) {
1463 cur_fdm_state = new FGNullFDM( dt );
1464 } else if ( model == "yasim" ) {
1465 cur_fdm_state = new YASim( dt );
1467 throw sg_throwable(string("Unrecognized flight model '") + model
1468 + "', cannot init flight dynamics model.");
1472 // Initialize view parameters
1474 // force update of model so that viewer can get some data...
1475 globals->get_aircraft_model()->update(0);
1476 // run update for current view so that data is current...
1477 globals->get_viewmgr()->update(0);
1481 SGTime *fgInitTime() {
1483 static const SGPropertyNode *longitude
1484 = fgGetNode("/position/longitude-deg");
1485 static const SGPropertyNode *latitude
1486 = fgGetNode("/position/latitude-deg");
1487 static const SGPropertyNode *cur_time_override
1488 = fgGetNode("/sim/time/cur-time-override", true);
1490 SGPath zone( globals->get_fg_root() );
1491 zone.append( "Timezone" );
1492 SGTime *t = new SGTime( longitude->getDoubleValue()
1493 * SGD_DEGREES_TO_RADIANS,
1494 latitude->getDoubleValue()
1495 * SGD_DEGREES_TO_RADIANS,
1497 cur_time_override->getLongValue() );
1499 globals->set_warp_delta( 0 );
1501 t->update( 0.0, 0.0,
1502 cur_time_override->getLongValue(),
1503 globals->get_warp() );
1509 // set up a time offset (aka warp) if one is specified
1510 void fgInitTimeOffset() {
1511 static const SGPropertyNode *longitude
1512 = fgGetNode("/position/longitude-deg");
1513 static const SGPropertyNode *latitude
1514 = fgGetNode("/position/latitude-deg");
1515 static const SGPropertyNode *cur_time_override
1516 = fgGetNode("/sim/time/cur-time-override", true);
1518 // Handle potential user specified time offsets
1519 int orig_warp = globals->get_warp();
1520 SGTime *t = globals->get_time_params();
1521 time_t cur_time = t->get_cur_time();
1522 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1523 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1524 time_t aircraftLocalTime =
1525 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1527 // Okay, we now have several possible scenarios
1528 int offset = fgGetInt("/sim/startup/time-offset");
1529 string offset_type = fgGetString("/sim/startup/time-offset-type");
1532 if ( offset_type == "real" ) {
1534 } else if ( offset_type == "dawn" ) {
1535 warp = fgTimeSecondsUntilSunAngle( cur_time,
1536 longitude->getDoubleValue()
1537 * SGD_DEGREES_TO_RADIANS,
1538 latitude->getDoubleValue()
1539 * SGD_DEGREES_TO_RADIANS,
1541 } else if ( offset_type == "morning" ) {
1542 warp = fgTimeSecondsUntilSunAngle( cur_time,
1543 longitude->getDoubleValue()
1544 * SGD_DEGREES_TO_RADIANS,
1545 latitude->getDoubleValue()
1546 * SGD_DEGREES_TO_RADIANS,
1548 } else if ( offset_type == "noon" ) {
1549 warp = fgTimeSecondsUntilSunAngle( cur_time,
1550 longitude->getDoubleValue()
1551 * SGD_DEGREES_TO_RADIANS,
1552 latitude->getDoubleValue()
1553 * SGD_DEGREES_TO_RADIANS,
1555 } else if ( offset_type == "afternoon" ) {
1556 warp = fgTimeSecondsUntilSunAngle( cur_time,
1557 longitude->getDoubleValue()
1558 * SGD_DEGREES_TO_RADIANS,
1559 latitude->getDoubleValue()
1560 * SGD_DEGREES_TO_RADIANS,
1562 } else if ( offset_type == "dusk" ) {
1563 warp = fgTimeSecondsUntilSunAngle( cur_time,
1564 longitude->getDoubleValue()
1565 * SGD_DEGREES_TO_RADIANS,
1566 latitude->getDoubleValue()
1567 * SGD_DEGREES_TO_RADIANS,
1569 } else if ( offset_type == "evening" ) {
1570 warp = fgTimeSecondsUntilSunAngle( cur_time,
1571 longitude->getDoubleValue()
1572 * SGD_DEGREES_TO_RADIANS,
1573 latitude->getDoubleValue()
1574 * SGD_DEGREES_TO_RADIANS,
1576 } else if ( offset_type == "midnight" ) {
1577 warp = fgTimeSecondsUntilSunAngle( cur_time,
1578 longitude->getDoubleValue()
1579 * SGD_DEGREES_TO_RADIANS,
1580 latitude->getDoubleValue()
1581 * SGD_DEGREES_TO_RADIANS,
1583 } else if ( offset_type == "system-offset" ) {
1586 } else if ( offset_type == "gmt-offset" ) {
1587 warp = offset - (currGMT - systemLocalTime);
1589 } else if ( offset_type == "latitude-offset" ) {
1590 warp = offset - (aircraftLocalTime - systemLocalTime);
1592 } else if ( offset_type == "system" ) {
1593 warp = offset - (systemLocalTime - currGMT) - cur_time;
1594 } else if ( offset_type == "gmt" ) {
1595 warp = offset - cur_time;
1596 } else if ( offset_type == "latitude" ) {
1597 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1599 SG_LOG( SG_GENERAL, SG_ALERT,
1600 "FG_TIME::Unsupported offset type " << offset_type );
1603 globals->set_warp( orig_warp + warp );
1604 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1605 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1606 cur_time_override->getLongValue(),
1607 globals->get_warp() );
1609 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1610 << globals->get_warp() );
1614 // This is the top level init routine which calls all the other
1615 // initialization routines. If you are adding a subsystem to flight
1616 // gear, its initialization call should located in this routine.
1617 // Returns non-zero if a problem encountered.
1618 bool fgInitSubsystems() {
1619 // static const SGPropertyNode *longitude
1620 // = fgGetNode("/sim/presets/longitude-deg");
1621 // static const SGPropertyNode *latitude
1622 // = fgGetNode("/sim/presets/latitude-deg");
1623 // static const SGPropertyNode *altitude
1624 // = fgGetNode("/sim/presets/altitude-ft");
1625 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1626 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1628 ////////////////////////////////////////////////////////////////////
1629 // Initialize the event manager subsystem.
1630 ////////////////////////////////////////////////////////////////////
1632 globals->get_event_mgr()->init();
1633 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1635 ////////////////////////////////////////////////////////////////////
1636 // Initialize the property interpolator subsystem. Put into the INIT
1637 // group because the "nasal" subsystem may need it at GENERAL take-down.
1638 ////////////////////////////////////////////////////////////////////
1639 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1642 ////////////////////////////////////////////////////////////////////
1643 // Add the FlightGear property utilities.
1644 ////////////////////////////////////////////////////////////////////
1645 globals->add_subsystem("properties", new FGProperties);
1647 ////////////////////////////////////////////////////////////////////
1648 // Initialize the material property subsystem.
1649 ////////////////////////////////////////////////////////////////////
1651 SGPath mpath( globals->get_fg_root() );
1652 mpath.append( "materials.xml" );
1653 string season = fgGetString("/sim/startup/season", "summer");
1654 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1655 globals->get_props()) ) {
1656 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1661 ////////////////////////////////////////////////////////////////////
1662 // Initialize the scenery management subsystem.
1663 ////////////////////////////////////////////////////////////////////
1665 if ( globals->get_tile_mgr()->init() ) {
1666 // Load the local scenery data
1667 double visibility_meters = fgGetDouble("/environment/visibility-m");
1669 globals->get_tile_mgr()->update( visibility_meters );
1671 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1675 globals->get_scenery()->get_scene_graph()
1676 ->addChild(simgear::Particles::getCommonRoot());
1678 ////////////////////////////////////////////////////////////////////
1679 // Initialize the flight model subsystem.
1680 ////////////////////////////////////////////////////////////////////
1684 // allocates structures so must happen before any of the flight
1685 // model or control parameters are set
1686 fgAircraftInit(); // In the future this might not be the case.
1689 ////////////////////////////////////////////////////////////////////
1690 // Initialize the weather subsystem.
1691 ////////////////////////////////////////////////////////////////////
1693 // Initialize the weather modeling subsystem
1694 globals->add_subsystem("environment", new FGEnvironmentMgr);
1697 ////////////////////////////////////////////////////////////////////
1698 // Initialize the aircraft systems and instrumentation (before the
1700 ////////////////////////////////////////////////////////////////////
1702 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1703 globals->add_subsystem("systems", new FGSystemMgr);
1705 ////////////////////////////////////////////////////////////////////
1706 // Initialize the XML Autopilot subsystem.
1707 ////////////////////////////////////////////////////////////////////
1709 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1710 globals->add_subsystem( "route-manager", new FGRouteMgr );
1713 ////////////////////////////////////////////////////////////////////
1714 // Initialize the view manager subsystem.
1715 ////////////////////////////////////////////////////////////////////
1719 ////////////////////////////////////////////////////////////////////
1720 // Create and register the logger.
1721 ////////////////////////////////////////////////////////////////////
1723 globals->add_subsystem("logger", new FGLogger);
1725 ////////////////////////////////////////////////////////////////////
1726 // Create and register the XML GUI.
1727 ////////////////////////////////////////////////////////////////////
1729 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1732 ////////////////////////////////////////////////////////////////////
1733 // Initialize the local time subsystem.
1734 ////////////////////////////////////////////////////////////////////
1736 // update the current timezone each 30 minutes
1737 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1738 &fgUpdateLocalTime, 30*60 );
1739 fgInitTimeOffset(); // the environment subsystem needs this
1742 ////////////////////////////////////////////////////////////////////
1743 // Initialize the lighting subsystem.
1744 ////////////////////////////////////////////////////////////////////
1746 globals->add_subsystem("lighting", new FGLight);
1748 //////////////////////////////////////////////////////////////////////
1749 // Initialize the 2D cloud subsystem.
1750 ////////////////////////////////////////////////////////////////////
1751 fgGetBool("/sim/rendering/bump-mapping", false);
1753 #ifdef ENABLE_AUDIO_SUPPORT
1754 ////////////////////////////////////////////////////////////////////
1755 // Initialize the sound subsystem.
1756 ////////////////////////////////////////////////////////////////////
1758 init_volume = fgGetFloat("/sim/sound/volume");
1759 fgSetFloat("/sim/sound/volume", 0.0f);
1760 globals->set_soundmgr(new SGSoundMgr);
1761 globals->get_soundmgr()->init();
1762 globals->get_soundmgr()->bind();
1765 ////////////////////////////////////////////////////////////////////
1766 // Initialize the sound-effects subsystem.
1767 ////////////////////////////////////////////////////////////////////
1769 globals->add_subsystem("fx", new FGFX);
1770 globals->add_subsystem("voice", new FGVoiceMgr);
1773 ////////////////////////////////////////////////////////////////////
1774 // Initialise the ATC Manager
1775 ////////////////////////////////////////////////////////////////////
1777 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1778 globals->set_ATC_mgr(new FGATCMgr);
1779 globals->get_ATC_mgr()->init();
1781 ////////////////////////////////////////////////////////////////////
1782 // Initialise the AI Manager
1783 ////////////////////////////////////////////////////////////////////
1785 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1786 globals->set_AI_mgr(new FGAIMgr);
1787 globals->get_AI_mgr()->init();
1789 ////////////////////////////////////////////////////////////////////
1790 // Initialise the AI Model Manager
1791 ////////////////////////////////////////////////////////////////////
1792 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1793 globals->add_subsystem("ai_model", new FGAIManager);
1794 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1797 // It's probably a good idea to initialize the top level traffic manager
1798 // After the AI and ATC systems have been initialized properly.
1799 // AI Traffic manager
1800 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1803 ////////////////////////////////////////////////////////////////////
1804 // Initialize the cockpit subsystem
1805 ////////////////////////////////////////////////////////////////////
1806 if( fgCockpitInit( ¤t_aircraft )) {
1807 // Cockpit initialized ok.
1809 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1814 ////////////////////////////////////////////////////////////////////
1815 // Initialize I/O subsystem.
1816 ////////////////////////////////////////////////////////////////////
1818 globals->get_io()->init();
1819 globals->get_io()->bind();
1822 ////////////////////////////////////////////////////////////////////
1823 // Add a new 2D panel.
1824 ////////////////////////////////////////////////////////////////////
1826 string panel_path = fgGetString("/sim/panel/path",
1827 "Panels/Default/default.xml");
1829 globals->set_current_panel( fgReadPanel(panel_path) );
1830 if (globals->get_current_panel() == 0) {
1831 SG_LOG( SG_INPUT, SG_ALERT,
1832 "Error reading new panel from " << panel_path );
1834 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1835 globals->get_current_panel()->init();
1836 globals->get_current_panel()->bind();
1840 ////////////////////////////////////////////////////////////////////
1841 // Initialize the controls subsystem.
1842 ////////////////////////////////////////////////////////////////////
1844 globals->get_controls()->init();
1845 globals->get_controls()->bind();
1848 ////////////////////////////////////////////////////////////////////
1849 // Initialize the input subsystem.
1850 ////////////////////////////////////////////////////////////////////
1852 globals->add_subsystem("input", new FGInput);
1855 ////////////////////////////////////////////////////////////////////
1856 // Initialize the replay subsystem
1857 ////////////////////////////////////////////////////////////////////
1858 globals->add_subsystem("replay", new FGReplay);
1860 ////////////////////////////////////////////////////////////////////
1861 // Bind and initialize subsystems.
1862 ////////////////////////////////////////////////////////////////////
1864 globals->get_subsystem_mgr()->bind();
1865 globals->get_subsystem_mgr()->init();
1867 ////////////////////////////////////////////////////////////////////
1868 // Initialize multiplayer subsystem
1869 ////////////////////////////////////////////////////////////////////
1871 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1872 globals->get_multiplayer_mgr()->init();
1874 ////////////////////////////////////////////////////////////////////////
1875 // Initialize the Nasal interpreter.
1876 // Do this last, so that the loaded scripts see initialized state
1877 ////////////////////////////////////////////////////////////////////////
1878 FGNasalSys* nasal = new FGNasalSys();
1879 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1882 // initialize methods that depend on other subsystems.
1883 globals->get_subsystem_mgr()->postinit();
1885 ////////////////////////////////////////////////////////////////////////
1886 // End of subsystem initialization.
1887 ////////////////////////////////////////////////////////////////////
1889 SG_LOG( SG_GENERAL, SG_INFO, endl);
1891 // Save the initial state for future
1893 globals->saveInitialState();
1899 void fgReInitSubsystems()
1901 // static const SGPropertyNode *longitude
1902 // = fgGetNode("/sim/presets/longitude-deg");
1903 // static const SGPropertyNode *latitude
1904 // = fgGetNode("/sim/presets/latitude-deg");
1905 static const SGPropertyNode *altitude
1906 = fgGetNode("/sim/presets/altitude-ft");
1907 static const SGPropertyNode *master_freeze
1908 = fgGetNode("/sim/freeze/master");
1910 SG_LOG( SG_GENERAL, SG_INFO,
1911 "fgReInitSubsystems(): /position/altitude = "
1912 << altitude->getDoubleValue() );
1914 bool freeze = master_freeze->getBoolValue();
1916 fgSetBool("/sim/freeze/master", true);
1918 fgSetBool("/sim/crashed", false);
1920 // Force reupdating the positions of the ai 3d models. They are used for
1921 // initializing ground level for the FDM.
1922 globals->get_subsystem("ai_model")->reinit();
1924 // Initialize the FDM
1927 // allocates structures so must happen before any of the flight
1928 // model or control parameters are set
1929 fgAircraftInit(); // In the future this might not be the case.
1931 // reload offsets from config defaults
1932 globals->get_viewmgr()->reinit();
1936 globals->get_controls()->reset_all();
1938 fgUpdateLocalTime();
1940 // re-init to proper time of day setting
1944 fgSetBool("/sim/freeze/master", false);
1946 fgSetBool("/sim/sceneryloaded",false);
1950 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1952 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1954 bool freeze = master_freeze->getBoolValue();
1956 master_freeze->setBoolValue(true);
1958 fgSetBool("/sim/signals/reinit", true);
1959 cur_fdm_state->unbind();
1961 // in case user has changed window size as
1962 // restoreInitialState() overwrites these
1963 int xsize = fgGetInt("/sim/startup/xsize");
1964 int ysize = fgGetInt("/sim/startup/ysize");
1966 globals->restoreInitialState();
1968 // update our position based on current presets
1971 // We don't know how to resize the window, so keep the last values
1972 // for xsize and ysize, and don't use the one set initially
1973 fgSetInt("/sim/startup/xsize", xsize);
1974 fgSetInt("/sim/startup/ysize", ysize);
1976 SGTime *t = globals->get_time_params();
1979 globals->set_time_params(t);
1981 fgReInitSubsystems();
1983 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1984 globals->get_renderer()->resize(xsize, ysize);
1985 fgSetBool("/sim/signals/reinit", false);
1988 master_freeze->setBoolValue(false);