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/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/dynamics.hxx>
72 #include <AIModel/AIManager.hxx>
73 #include <ATCDCL/ATCmgr.hxx>
74 #include <ATCDCL/AIMgr.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/xmlauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <FDM/SP/ADA.hxx>
82 #include <FDM/SP/ACMS.hxx>
83 #include <FDM/SP/MagicCarpet.hxx>
84 #include <FDM/SP/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/UFO.hxx>
91 #include <FDM/NullFDM.hxx>
92 #include <FDM/YASim/YASim.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Navaids/fix.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Sound/voice.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/sunsolver.hxx>
113 #include <Time/tmp.hxx>
114 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
117 #include <Environment/environment_mgr.hxx>
119 #include "fg_init.hxx"
121 #include "fg_commands.hxx"
122 #include "fg_props.hxx"
123 #include "options.hxx"
124 #include "globals.hxx"
125 #include "logger.hxx"
126 #include "renderer.hxx"
127 #include "viewmgr.hxx"
131 # include <CoreFoundation/CoreFoundation.h>
137 extern const char *default_root;
141 // Scan the command line options for the specified option and return
143 static string fgScanForOption( const string& option, int argc, char **argv ) {
146 if (hostname == NULL)
149 gethostname(_hostname, 256);
150 hostname = strdup(_hostname);
151 free_hostname = true;
154 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
156 int len = option.length();
159 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
161 string arg = argv[i];
162 if ( arg.find( option ) == 0 ) {
163 return arg.substr( len );
173 // Scan the user config files for the specified option and return
175 static string fgScanForOption( const string& option, const string& path ) {
176 sg_gzifstream in( path );
177 if ( !in.is_open() ) {
181 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
183 int len = option.length();
186 while ( ! in.eof() ) {
188 getline( in, line, '\n' );
190 // catch extraneous (DOS) line ending character
191 if ( line[line.length() - 1] < 32 ) {
192 line = line.substr( 0, line.length()-1 );
195 if ( line.find( option ) == 0 ) {
196 return line.substr( len );
205 // Scan the user config files for the specified option and return
207 static string fgScanForOption( const string& option ) {
210 #if defined( unix ) || defined( __CYGWIN__ )
211 // Next check home directory for .fgfsrc.hostname file
213 if ( homedir != NULL ) {
214 SGPath config( homedir );
215 config.append( ".fgfsrc" );
216 config.concat( "." );
217 config.concat( hostname );
218 arg = fgScanForOption( option, config.str() );
223 // Next check home directory for .fgfsrc file
225 if ( homedir != NULL ) {
226 SGPath config( homedir );
227 config.append( ".fgfsrc" );
228 arg = fgScanForOption( option, config.str() );
233 // Check for $fg_root/system.fgfsrc
234 SGPath config( globals->get_fg_root() );
235 config.append( "system.fgfsrc" );
236 arg = fgScanForOption( option, config.str() );
243 // Read in configuration (files and command line options) but only set
245 bool fgInitFGRoot ( int argc, char **argv ) {
248 // First parse command line options looking for --fg-root=, this
249 // will override anything specified in a config file
250 root = fgScanForOption( "--fg-root=", argc, argv);
252 // Check in one of the user configuration files.
254 root = fgScanForOption( "--fg-root=" );
256 // Next check if fg-root is set as an env variable
257 if ( root.empty() ) {
258 char *envp = ::getenv( "FG_ROOT" );
259 if ( envp != NULL ) {
264 // Otherwise, default to a random compiled-in location if we can't
265 // find fg-root any other way.
266 if ( root.empty() ) {
267 #if defined( __CYGWIN__ )
268 root = "/FlightGear";
269 #elif defined( WIN32 )
270 root = "\\FlightGear";
271 #elif defined(__APPLE__)
273 The following code looks for the base package inside the application
274 bundle, in the standard Contents/Resources location.
276 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
278 // look for a 'data' subdir
279 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
281 // now convert down to a path, and the a c-string
282 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
283 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
285 CFRelease(resourcesUrl);
293 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
294 globals->set_fg_root(root);
300 // Read in configuration (files and command line options) but only set
302 bool fgInitFGAircraft ( int argc, char **argv ) {
305 // First parse command line options looking for --aircraft=, this
306 // will override anything specified in a config file
307 aircraft = fgScanForOption( "--aircraft=", argc, argv );
308 if ( aircraft.empty() ) {
309 // check synonym option
310 aircraft = fgScanForOption( "--vehicle=", argc, argv );
313 // Check in one of the user configuration files.
314 if ( aircraft.empty() ) {
315 aircraft = fgScanForOption( "--aircraft=" );
317 if ( aircraft.empty() ) {
318 aircraft = fgScanForOption( "--vehicle=" );
321 // if an aircraft was specified, set the property name
322 if ( !aircraft.empty() ) {
323 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
324 fgSetString("/sim/aircraft", aircraft.c_str() );
326 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
333 // Return the current base package version
334 string fgBasePackageVersion() {
335 SGPath base_path( globals->get_fg_root() );
336 base_path.append("version");
338 sg_gzifstream in( base_path.str() );
339 if ( !in.is_open() ) {
340 SGPath old_path( globals->get_fg_root() );
341 old_path.append( "Thanks" );
342 sg_gzifstream old( old_path.str() );
343 if ( !old.is_open() ) {
346 return "[old version]";
357 // Initialize the localization
358 SGPropertyNode *fgInitLocale(const char *language) {
359 SGPropertyNode *c_node = NULL, *d_node = NULL;
360 SGPropertyNode *intl = fgGetNode("/sim/intl");
362 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
364 // localization not defined
369 // Select the proper language from the list
371 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
372 for (unsigned int i = 0; i < locale.size(); i++) {
374 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
375 for (unsigned int j = 0; j < lang.size(); j++) {
377 if (!strcmp(lang[j]->getStringValue(), language)) {
386 d_node = intl->getChild("locale");
390 // Check for localized font
391 SGPropertyNode *font_n = c_node->getNode("font", true);
392 if ( !strcmp(font_n->getStringValue(), "") )
393 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
397 // Load the default strings
399 SGPath d_path( globals->get_fg_root() );
401 const char *d_path_str = d_node->getStringValue("strings");
403 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
407 d_path.append(d_path_str);
408 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
410 SGPropertyNode *strings = c_node->getNode("strings");
412 readProperties(d_path.str(), strings);
413 } catch (const sg_exception &) {
414 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
419 // Load the language specific strings
421 if (c_node != d_node) {
422 SGPath c_path( globals->get_fg_root() );
424 const char *c_path_str = c_node->getStringValue("strings");
426 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
430 c_path.append(c_path_str);
431 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
434 readProperties(c_path.str(), strings);
435 } catch (const sg_exception &) {
436 SG_LOG(SG_GENERAL, SG_ALERT,
437 "Unable to read the localized strings from " << c_path.str());
447 // Initialize the localization routines
448 bool fgDetectLanguage() {
449 const char *language = ::getenv("LANG");
451 if (language == NULL) {
452 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
456 SGPropertyNode *locale = fgInitLocale(language);
458 SG_LOG(SG_GENERAL, SG_ALERT,
459 "No internationalization settings specified in preferences.xml" );
464 globals->set_locale( locale );
469 // Attempt to locate and parse the various non-XML config files in order
470 // from least precidence to greatest precidence
472 do_options (int argc, char ** argv)
474 // Check for $fg_root/system.fgfsrc
475 SGPath config( globals->get_fg_root() );
476 config.append( "system.fgfsrc" );
477 fgParseOptions(config.str());
479 #if defined( unix ) || defined( __CYGWIN__ )
480 config.concat( "." );
481 config.concat( hostname );
482 fgParseOptions(config.str());
485 // Check for ~/.fgfsrc
486 if ( homedir != NULL ) {
487 config.set( homedir );
488 config.append( ".fgfsrc" );
489 fgParseOptions(config.str());
492 #if defined( unix ) || defined( __CYGWIN__ )
493 // Check for ~/.fgfsrc.hostname
494 config.concat( "." );
495 config.concat( hostname );
496 fgParseOptions(config.str());
499 // Parse remaining command line options
500 // These will override anything specified in a config file
501 fgParseArgs(argc, argv);
505 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
506 SGPropertyNode *cache, int depth = 0 )
508 const int MAXDEPTH = 1;
511 ulDir *dirp = ulOpenDir(path.str().c_str());
513 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
518 while ((dire = ulReadDir(dirp)) != NULL) {
520 if (depth > MAXDEPTH)
523 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
524 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
528 next.append(dire->d_name);
530 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
531 if ( ! result.empty() )
535 int len = strlen(dire->d_name);
536 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
542 if (!cache->getChild("aircraft", i++, false))
545 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
547 n = entry->getNode("file", true);
548 n->setStringValue(dire->d_name);
549 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
551 n = entry->getNode("path", true);
552 n->setStringValue(path.str().c_str());
553 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
555 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
567 // Read in configuration (file and command line)
568 bool fgInitConfig ( int argc, char **argv ) {
570 // First, set some sane default values
573 // Read global preferences from $FG_ROOT/preferences.xml
574 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
575 fgLoadProps("preferences.xml", globals->get_props());
576 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
578 // Detect the required language as early as possible
579 if ( !fgDetectLanguage() ) {
583 SGPropertyNode autosave;
585 char *envp = ::getenv( "APPDATA" );
587 SGPath config( envp );
588 config.append( "flightgear.org" );
590 if ( homedir != NULL ) {
591 SGPath config( homedir );
592 config.append( ".fgfs" );
594 const char *fg_home = getenv("FG_HOME");
598 // Set /sim/fg-home and don't allow malign code to override it until
599 // Nasal security is set up. Use FG_HOME if necessary.
600 SGPropertyNode *home = fgGetNode("/sim", true);
601 home->removeChild("fg-home", 0, false);
602 home = home->getChild("fg-home", 0, true);
603 home->setStringValue(config.c_str());
604 home->setAttribute(SGPropertyNode::WRITE, false);
606 config.append( "autosave.xml" );
607 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
609 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
611 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
613 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
615 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
618 // Scan user config files and command line for a specified aircraft.
619 fgInitFGAircraft(argc, argv);
621 string aircraft = fgGetString( "/sim/aircraft", "" );
622 if ( aircraft.size() > 0 ) {
623 SGPath aircraft_search( globals->get_fg_root() );
624 aircraft_search.append( "Aircraft" );
626 string aircraft_set = aircraft + "-set.xml";
629 // check if the *-set.xml file is already in the cache
630 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
631 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
632 for (unsigned int i = 0; i < cache.size(); i++) {
633 const char *name = cache[i]->getStringValue("file", "");
634 if (aircraft_set == name) {
635 const char *path = cache[i]->getStringValue("path", "");
645 if (result.empty()) {
646 // prepare cache for rescan
647 SGPropertyNode *n = cache_root->getNode("fg-root", true);
648 n->setStringValue(globals->get_fg_root().c_str());
649 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
650 cache_root->removeChildren("aircraft");
652 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
655 if ( !result.empty() ) {
656 fgSetString( "/sim/aircraft-dir", result.c_str() );
657 SGPath full_name( result );
658 full_name.append( aircraft_set );
660 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
661 << " from " << full_name.str());
663 readProperties( full_name.str(), globals->get_props() );
664 } catch ( const sg_exception &e ) {
665 string message = "Error reading default aircraft: ";
666 message += e.getFormattedMessage();
667 SG_LOG(SG_INPUT, SG_ALERT, message);
671 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
677 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
680 copyProperties(&autosave, globals->get_props());
682 // parse options after loading aircraft to ensure any user
683 // overrides of defaults are honored.
684 do_options(argc, argv);
695 // This function is never used, but maybe useful in the future ???
698 // Preset lon/lat given an airport id
699 static bool fgSetPosFromAirportID( const string& id ) {
703 SG_LOG( SG_GENERAL, SG_INFO,
704 "Attempting to set starting position from airport code " << id );
706 if ( fgFindAirportID( id, &a ) ) {
708 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
709 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
711 // other code depends on the actual postition being set so set
713 fgSetDouble("/position/longitude-deg", a->longitude );
714 fgSetDouble("/position/latitude-deg", a->latitude );
716 SG_LOG( SG_GENERAL, SG_INFO,
717 "Position for " << id << " is (" << a->longitude
718 << ", " << a->latitude << ")" );
728 // Set current tower position lon/lat given an airport id
729 static bool fgSetTowerPosFromAirportID( const string& id) {
730 const FGAirport *a = fgFindAirportID( id);
732 SGGeod tower = a->getTowerLocation();
733 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
734 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
735 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
743 struct FGTowerLocationListener : SGPropertyChangeListener {
744 void valueChanged(SGPropertyNode* node) {
745 const string id(node->getStringValue());
746 fgSetTowerPosFromAirportID(id);
750 void fgInitTowerLocationListener() {
751 fgGetNode("/sim/tower/airport-id", true)
752 ->addChangeListener( new FGTowerLocationListener(), true );
755 // Set current_options lon/lat given an airport id and heading (degrees)
756 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
760 // set initial position from runway and heading
761 SG_LOG( SG_GENERAL, SG_INFO,
762 "Attempting to set starting position from airport code "
763 << id << " heading " << tgt_hdg );
765 const FGAirport* apt = fgFindAirportID(id);
766 if (!apt) return false;
767 FGRunway r = apt->findBestRunwayForHeading(tgt_hdg);
768 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
770 double lat2, lon2, az2;
771 double heading = r._heading;
772 double azimuth = heading + 180.0;
773 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
775 SG_LOG( SG_GENERAL, SG_INFO,
776 "runway = " << r._lon << ", " << r._lat
777 << " length = " << r._length * SG_FEET_TO_METER
778 << " heading = " << azimuth );
780 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
781 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
782 &lat2, &lon2, &az2 );
784 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
786 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
787 odist *= SG_NM_TO_METER;
788 double oaz = azimuth;
789 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
790 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
793 while ( oaz >= 360.0 ) { oaz -= 360.0; }
794 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
800 fgSetDouble("/sim/presets/longitude-deg", lon2 );
801 fgSetDouble("/sim/presets/latitude-deg", lat2 );
802 fgSetDouble("/sim/presets/heading-deg", heading );
804 // other code depends on the actual values being set ...
805 fgSetDouble("/position/longitude-deg", lon2 );
806 fgSetDouble("/position/latitude-deg", lat2 );
807 fgSetDouble("/orientation/heading-deg", heading );
809 SG_LOG( SG_GENERAL, SG_INFO,
810 "Position for " << id << " is ("
812 << lat2 << ") new heading is "
818 // Set current_options lon/lat given an airport id and parkig position name
819 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
823 // can't see an easy way around this const_cast at the moment
824 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
826 SG_LOG( SG_GENERAL, SG_ALERT,
827 "Failed to find airport " << id );
830 FGAirportDynamics* dcs = apt->getDynamics();
832 SG_LOG( SG_GENERAL, SG_ALERT,
833 "Failed to find parking position " << parkpos <<
834 " at airport " << id );
838 int park_index = dcs->getNrOfParkings() - 1;
839 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
840 if (park_index < 0) {
841 SG_LOG( SG_GENERAL, SG_ALERT,
842 "Failed to find parking position " << parkpos <<
843 " at airport " << id );
846 FGParking* parking = dcs->getParking(park_index);
848 double lat = parking->getLatitude();
849 double lon = parking->getLongitude();
850 double hdg = parking->getHeading();
853 fgSetDouble("/sim/presets/longitude-deg", lon );
854 fgSetDouble("/sim/presets/latitude-deg", lat );
855 fgSetDouble("/sim/presets/heading-deg", hdg );
857 // other code depends on the actual values being set ...
858 fgSetDouble("/position/longitude-deg", lon );
859 fgSetDouble("/position/latitude-deg", lat );
860 fgSetDouble("/orientation/heading-deg", hdg );
862 SG_LOG( SG_GENERAL, SG_INFO,
863 "Position for " << id << " is ("
865 << lat << ") new heading is "
872 // Set current_options lon/lat given an airport id and runway number
873 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
877 // set initial position from airport and runway number
878 SG_LOG( SG_GENERAL, SG_INFO,
879 "Attempting to set starting position for "
880 << id << ":" << rwy );
882 const FGAirport* apt = fgFindAirportID(id);
884 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
888 if (!apt->hasRunwayWithIdent(rwy)) {
889 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
890 "Failed to find runway " << rwy <<
891 " at airport " << id << ". Using default runway." );
895 FGRunway r(apt->getRunwayByIdent(rwy));
896 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
898 double lat2, lon2, az2;
899 double heading = r._heading;
900 double azimuth = heading + 180.0;
901 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
903 SG_LOG( SG_GENERAL, SG_INFO,
904 "runway = " << r._lon << ", " << r._lat
905 << " length = " << r._length * SG_FEET_TO_METER
906 << " heading = " << azimuth );
908 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
909 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
910 &lat2, &lon2, &az2 );
912 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
915 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
916 odist *= SG_NM_TO_METER;
917 double oaz = azimuth;
918 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
920 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
921 heading = fgGetDouble("/sim/presets/heading-deg");
923 while ( oaz >= 360.0 ) { oaz -= 360.0; }
924 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
930 fgSetDouble("/sim/presets/longitude-deg", lon2 );
931 fgSetDouble("/sim/presets/latitude-deg", lat2 );
932 fgSetDouble("/sim/presets/heading-deg", heading );
934 // other code depends on the actual values being set ...
935 fgSetDouble("/position/longitude-deg", lon2 );
936 fgSetDouble("/position/latitude-deg", lat2 );
937 fgSetDouble("/orientation/heading-deg", heading );
939 SG_LOG( SG_GENERAL, SG_INFO,
940 "Position for " << id << " is ("
942 << lat2 << ") new heading is "
949 static void fgSetDistOrAltFromGlideSlope() {
950 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
951 string apt_id = fgGetString("/sim/presets/airport-id");
952 double gs = fgGetDouble("/sim/presets/glideslope-deg")
953 * SG_DEGREES_TO_RADIANS ;
954 double od = fgGetDouble("/sim/presets/offset-distance-nm");
955 double alt = fgGetDouble("/sim/presets/altitude-ft");
957 double apt_elev = 0.0;
958 if ( ! apt_id.empty() ) {
959 apt_elev = fgGetAirportElev( apt_id );
960 if ( apt_elev < -9990.0 ) {
967 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
968 // set altitude from glideslope and offset-distance
969 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
970 alt = fabs(od*tan(gs)) + apt_elev;
971 fgSetDouble("/sim/presets/altitude-ft", alt);
972 fgSetBool("/sim/presets/onground", false);
973 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
975 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
976 // set offset-distance from glideslope and altitude
977 od = (alt - apt_elev) / tan(gs);
978 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
979 fgSetDouble("/sim/presets/offset-distance-nm", od);
980 fgSetBool("/sim/presets/onground", false);
981 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
983 } else if( fabs(gs) > 0.01 ) {
984 SG_LOG( SG_GENERAL, SG_ALERT,
985 "Glideslope given but not altitude or offset-distance." );
986 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
987 fgSetDouble("/sim/presets/glideslope-deg", 0);
988 fgSetBool("/sim/presets/onground", true);
993 // Set current_options lon/lat given an airport id and heading (degrees)
994 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
996 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
998 // set initial position from runway and heading
1000 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1001 << id << ":" << freq );
1003 double lon = nav->get_lon();
1004 double lat = nav->get_lat();
1006 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1008 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1010 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1012 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1013 double olat, olon, az2;
1014 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1021 fgSetDouble("/sim/presets/longitude-deg", lon );
1022 fgSetDouble("/sim/presets/latitude-deg", lat );
1024 // other code depends on the actual values being set ...
1025 fgSetDouble("/position/longitude-deg", lon );
1026 fgSetDouble("/position/latitude-deg", lat );
1027 fgSetDouble("/orientation/heading-deg",
1028 fgGetDouble("/sim/presets/heading-deg") );
1030 SG_LOG( SG_GENERAL, SG_INFO,
1031 "Position for " << id << ":" << freq << " is ("
1032 << lon << ", "<< lat << ")" );
1036 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1037 << id << ":" << freq );
1042 // Set current_options lon/lat given an aircraft carrier id
1043 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1045 // set initial position from runway and heading
1049 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1050 double lon = geodPos.getLongitudeDeg();
1051 double lat = geodPos.getLatitudeDeg();
1052 double alt = geodPos.getElevationFt();
1054 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1055 << carrier << " at lat = " << lat << ", lon = " << lon
1056 << ", alt = " << alt << ", heading = " << heading);
1058 fgSetDouble("/sim/presets/longitude-deg", lon);
1059 fgSetDouble("/sim/presets/latitude-deg", lat);
1060 fgSetDouble("/sim/presets/altitude-ft", alt);
1061 fgSetDouble("/sim/presets/heading-deg", heading);
1062 fgSetDouble("/position/longitude-deg", lon);
1063 fgSetDouble("/position/latitude-deg", lat);
1064 fgSetDouble("/position/altitude-ft", alt);
1065 fgSetDouble("/orientation/heading-deg", heading);
1067 fgSetString("/sim/presets/speed-set", "UVW");
1068 fgSetDouble("/velocities/uBody-fps", uvw(0));
1069 fgSetDouble("/velocities/vBody-fps", uvw(1));
1070 fgSetDouble("/velocities/wBody-fps", uvw(2));
1071 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1072 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1073 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1075 fgSetBool("/sim/presets/onground", true);
1079 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1085 // Set current_options lon/lat given an airport id and heading (degrees)
1086 static bool fgSetPosFromFix( const string& id ) {
1089 // set initial position from runway and heading
1090 if ( globals->get_fixlist()->query( id.c_str(), fix ) ) {
1091 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1094 double lon = fix->get_lon();
1095 double lat = fix->get_lat();
1097 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1099 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1101 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1103 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1104 double olat, olon, az2;
1105 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1112 fgSetDouble("/sim/presets/longitude-deg", lon );
1113 fgSetDouble("/sim/presets/latitude-deg", lat );
1115 // other code depends on the actual values being set ...
1116 fgSetDouble("/position/longitude-deg", lon );
1117 fgSetDouble("/position/latitude-deg", lat );
1118 fgSetDouble("/orientation/heading-deg",
1119 fgGetDouble("/sim/presets/heading-deg") );
1121 SG_LOG( SG_GENERAL, SG_INFO,
1122 "Position for " << id << " is ("
1123 << lon << ", "<< lat << ")" );
1127 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1135 * Initialize vor/ndb/ils/fix list management and query systems (as
1136 * well as simple airport db list)
1141 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1143 SGPath aptdb( globals->get_fg_root() );
1144 aptdb.append( "Airports/apt.dat" );
1146 SGPath p_metar( globals->get_fg_root() );
1147 p_metar.append( "Airports/metar.dat" );
1149 FGAirportList *airports = new FGAirportList();
1150 globals->set_airports( airports );
1152 fgAirportDBLoad( airports, aptdb.str(), p_metar.str() );
1154 FGNavList *navlist = new FGNavList;
1155 FGNavList *loclist = new FGNavList;
1156 FGNavList *gslist = new FGNavList;
1157 FGNavList *dmelist = new FGNavList;
1158 FGNavList *mkrlist = new FGNavList;
1159 FGNavList *tacanlist = new FGNavList;
1160 FGNavList *carrierlist = new FGNavList;
1161 FGTACANList *channellist = new FGTACANList;
1163 globals->set_navlist( navlist );
1164 globals->set_loclist( loclist );
1165 globals->set_gslist( gslist );
1166 globals->set_dmelist( dmelist );
1167 globals->set_mkrlist( mkrlist );
1168 globals->set_tacanlist( tacanlist );
1169 globals->set_carrierlist( carrierlist );
1170 globals->set_channellist( channellist );
1172 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1173 SG_LOG( SG_GENERAL, SG_ALERT,
1174 "Problems loading one or more navigational database" );
1177 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1178 // align all the localizers with their corresponding runways
1179 // since data sources are good for cockpit navigation
1180 // purposes, but not always to the error tolerances needed to
1181 // exactly place these items.
1183 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1185 fgNavDBAlignLOCwithRunway( airports, loclist, threshold );
1188 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1189 SGPath p_fix( globals->get_fg_root() );
1190 p_fix.append( "Navaids/fix.dat" );
1191 FGFixList *fixlist = new FGFixList;
1192 fixlist->init( p_fix );
1193 globals->set_fixlist( fixlist );
1195 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1196 SGPath p_awy( globals->get_fg_root() );
1197 p_awy.append( "Navaids/awy.dat" );
1198 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1199 //cerr << "Loading Airways" << endl;
1200 awyNet->load (p_awy );
1202 //cerr << "initializing airways" << endl;
1203 globals->set_airwaynet( awyNet );
1209 // Set the initial position based on presets (or defaults)
1210 bool fgInitPosition() {
1211 // cout << "fgInitPosition()" << endl;
1212 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1213 * SG_DEGREES_TO_RADIANS ;
1214 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1215 double alt = fgGetDouble("/sim/presets/altitude-ft");
1217 bool set_pos = false;
1219 // If glideslope is specified, then calculate offset-distance or
1220 // altitude relative to glide slope if either of those was not
1222 if ( fabs( gs ) > 0.01 ) {
1223 fgSetDistOrAltFromGlideSlope();
1227 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1228 // If not, check for an airport-id and use that.
1229 // If not, default to the middle of the KSFO field.
1230 // The default values for lon/lat are deliberately out of range
1231 // so that the airport-id can take effect; valid lon/lat will
1232 // override airport-id, however.
1233 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1234 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1235 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1236 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1241 string apt = fgGetString("/sim/presets/airport-id");
1242 string rwy_no = fgGetString("/sim/presets/runway");
1243 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1244 string vor = fgGetString("/sim/presets/vor-id");
1245 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1246 string ndb = fgGetString("/sim/presets/ndb-id");
1247 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1248 string carrier = fgGetString("/sim/presets/carrier");
1249 string parkpos = fgGetString("/sim/presets/parkpos");
1250 string fix = fgGetString("/sim/presets/fix");
1251 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1252 double hdg = hdg_preset->getDoubleValue();
1254 // save some start parameters, so that we can later say what the
1255 // user really requested. TODO generalize that and move it to options.cxx
1256 static bool start_options_saved = false;
1257 if (!start_options_saved) {
1258 start_options_saved = true;
1259 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1261 opt->setDoubleValue("latitude-deg", lat_deg);
1262 opt->setDoubleValue("longitude-deg", lon_deg);
1263 opt->setDoubleValue("heading-deg", hdg);
1264 opt->setStringValue("airport", apt.c_str());
1265 opt->setStringValue("runway", rwy_no.c_str());
1269 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1271 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1272 // An airport + parking position is requested
1273 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1274 // set tower position
1275 fgSetString("/sim/tower/airport-id", apt.c_str());
1280 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1281 // An airport + runway is requested
1282 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1283 // set tower position (a little off the heading for single
1285 fgSetString("/sim/tower/airport-id", apt.c_str());
1290 if ( !set_pos && !apt.empty() ) {
1291 // An airport is requested (find runway closest to hdg)
1292 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1293 // set tower position (a little off the heading for single
1295 fgSetString("/sim/tower/airport-id", apt.c_str());
1300 if (hdg_preset->getDoubleValue() > 9990.0)
1301 hdg_preset->setDoubleValue(hdg);
1303 if ( !set_pos && !vor.empty() ) {
1304 // a VOR is requested
1305 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1310 if ( !set_pos && !ndb.empty() ) {
1311 // an NDB is requested
1312 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1317 if ( !set_pos && !carrier.empty() ) {
1318 // an aircraft carrier is requested
1319 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1324 if ( !set_pos && !fix.empty() ) {
1325 // a Fix is requested
1326 if ( fgSetPosFromFix( fix ) ) {
1332 // No lon/lat specified, no airport specified, default to
1333 // middle of KSFO field.
1334 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1335 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1338 fgSetDouble( "/position/longitude-deg",
1339 fgGetDouble("/sim/presets/longitude-deg") );
1340 fgSetDouble( "/position/latitude-deg",
1341 fgGetDouble("/sim/presets/latitude-deg") );
1342 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1344 // determine if this should be an on-ground or in-air start
1345 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1346 fgSetBool("/sim/presets/onground", false);
1348 fgSetBool("/sim/presets/onground", true);
1355 // General house keeping initializations
1356 bool fgInitGeneral() {
1359 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1360 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1362 root = globals->get_fg_root();
1363 if ( ! root.length() ) {
1364 // No root path set? Then bail ...
1365 SG_LOG( SG_GENERAL, SG_ALERT,
1366 "Cannot continue without a path to the base package "
1367 << "being defined." );
1370 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1372 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1374 char buf[512], *cwd = getcwd(buf, 511);
1376 SGPropertyNode *curr = fgGetNode("/sim", true);
1377 curr->removeChild("fg-current", 0, false);
1378 curr = curr->getChild("fg-current", 0, true);
1379 curr->setStringValue(cwd ? cwd : "");
1380 curr->setAttribute(SGPropertyNode::WRITE, false);
1385 // Initialize the flight model subsystem. This just creates the
1386 // object. The actual fdm initialization is delayed until we get a
1387 // proper scenery elevation hit. This is checked for in main.cxx
1391 if ( cur_fdm_state ) {
1392 delete cur_fdm_state;
1396 double dt = 1.0 / fgGetInt("/sim/model-hz");
1397 string model = fgGetString("/sim/flight-model");
1399 if ( model == "larcsim" ) {
1400 cur_fdm_state = new FGLaRCsim( dt );
1401 } else if ( model == "jsb" ) {
1402 cur_fdm_state = new FGJSBsim( dt );
1404 } else if ( model == "ada" ) {
1405 cur_fdm_state = new FGADA( dt );
1406 } else if ( model == "acms" ) {
1407 cur_fdm_state = new FGACMS( dt );
1408 } else if ( model == "balloon" ) {
1409 cur_fdm_state = new FGBalloonSim( dt );
1410 } else if ( model == "magic" ) {
1411 cur_fdm_state = new FGMagicCarpet( dt );
1413 } else if ( model == "ufo" ) {
1414 cur_fdm_state = new FGUFO( dt );
1415 } else if ( model == "external" ) {
1416 // external is a synonym for "--fdm=null" and is
1417 // maintained here for backwards compatibility
1418 cur_fdm_state = new FGNullFDM( dt );
1419 } else if ( model.find("network") == 0 ) {
1420 string host = "localhost";
1424 string net_options = model.substr(8);
1425 string::size_type begin, end;
1428 end = net_options.find( ",", begin );
1429 if ( end != string::npos ) {
1430 host = net_options.substr(begin, end - begin);
1434 end = net_options.find( ",", begin );
1435 if ( end != string::npos ) {
1436 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1440 end = net_options.find( ",", begin );
1441 if ( end != string::npos ) {
1442 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1446 end = net_options.find( ",", begin );
1447 if ( end != string::npos ) {
1448 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1451 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1452 } else if ( model.find("pipe") == 0 ) {
1453 // /* old */ string pipe_path = model.substr(5);
1454 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1455 string pipe_path = "";
1456 string pipe_protocol = "";
1457 string pipe_options = model.substr(5);
1458 string::size_type begin, end;
1461 end = pipe_options.find( ",", begin );
1462 if ( end != string::npos ) {
1463 pipe_path = pipe_options.substr(begin, end - begin);
1466 // protocol (last option)
1467 pipe_protocol = pipe_options.substr(begin);
1468 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1469 } else if ( model == "null" ) {
1470 cur_fdm_state = new FGNullFDM( dt );
1471 } else if ( model == "yasim" ) {
1472 cur_fdm_state = new YASim( dt );
1474 throw sg_throwable(string("Unrecognized flight model '") + model
1475 + "', cannot init flight dynamics model.");
1479 // Initialize view parameters
1481 // force update of model so that viewer can get some data...
1482 globals->get_aircraft_model()->update(0);
1483 // run update for current view so that data is current...
1484 globals->get_viewmgr()->update(0);
1488 SGTime *fgInitTime() {
1490 static const SGPropertyNode *longitude
1491 = fgGetNode("/position/longitude-deg");
1492 static const SGPropertyNode *latitude
1493 = fgGetNode("/position/latitude-deg");
1494 static const SGPropertyNode *cur_time_override
1495 = fgGetNode("/sim/time/cur-time-override", true);
1497 SGPath zone( globals->get_fg_root() );
1498 zone.append( "Timezone" );
1499 SGTime *t = new SGTime( longitude->getDoubleValue()
1500 * SGD_DEGREES_TO_RADIANS,
1501 latitude->getDoubleValue()
1502 * SGD_DEGREES_TO_RADIANS,
1504 cur_time_override->getLongValue() );
1506 globals->set_warp_delta( 0 );
1508 t->update( 0.0, 0.0,
1509 cur_time_override->getLongValue(),
1510 globals->get_warp() );
1516 // set up a time offset (aka warp) if one is specified
1517 void fgInitTimeOffset() {
1518 static const SGPropertyNode *longitude
1519 = fgGetNode("/position/longitude-deg");
1520 static const SGPropertyNode *latitude
1521 = fgGetNode("/position/latitude-deg");
1522 static const SGPropertyNode *cur_time_override
1523 = fgGetNode("/sim/time/cur-time-override", true);
1525 // Handle potential user specified time offsets
1526 int orig_warp = globals->get_warp();
1527 SGTime *t = globals->get_time_params();
1528 time_t cur_time = t->get_cur_time();
1529 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1530 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1531 time_t aircraftLocalTime =
1532 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1534 // Okay, we now have several possible scenarios
1535 int offset = fgGetInt("/sim/startup/time-offset");
1536 string offset_type = fgGetString("/sim/startup/time-offset-type");
1539 if ( offset_type == "real" ) {
1541 } else if ( offset_type == "dawn" ) {
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 == "morning" ) {
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 == "noon" ) {
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 == "afternoon" ) {
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 == "dusk" ) {
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 == "evening" ) {
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 == "midnight" ) {
1584 warp = fgTimeSecondsUntilSunAngle( cur_time,
1585 longitude->getDoubleValue()
1586 * SGD_DEGREES_TO_RADIANS,
1587 latitude->getDoubleValue()
1588 * SGD_DEGREES_TO_RADIANS,
1590 } else if ( offset_type == "system-offset" ) {
1593 } else if ( offset_type == "gmt-offset" ) {
1594 warp = offset - (currGMT - systemLocalTime);
1596 } else if ( offset_type == "latitude-offset" ) {
1597 warp = offset - (aircraftLocalTime - systemLocalTime);
1599 } else if ( offset_type == "system" ) {
1600 warp = offset - (systemLocalTime - currGMT) - cur_time;
1601 } else if ( offset_type == "gmt" ) {
1602 warp = offset - cur_time;
1603 } else if ( offset_type == "latitude" ) {
1604 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1606 SG_LOG( SG_GENERAL, SG_ALERT,
1607 "FG_TIME::Unsupported offset type " << offset_type );
1610 globals->set_warp( orig_warp + warp );
1611 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1612 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1613 cur_time_override->getLongValue(),
1614 globals->get_warp() );
1616 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1617 << globals->get_warp() );
1621 // This is the top level init routine which calls all the other
1622 // initialization routines. If you are adding a subsystem to flight
1623 // gear, its initialization call should located in this routine.
1624 // Returns non-zero if a problem encountered.
1625 bool fgInitSubsystems() {
1626 // static const SGPropertyNode *longitude
1627 // = fgGetNode("/sim/presets/longitude-deg");
1628 // static const SGPropertyNode *latitude
1629 // = fgGetNode("/sim/presets/latitude-deg");
1630 // static const SGPropertyNode *altitude
1631 // = fgGetNode("/sim/presets/altitude-ft");
1632 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1633 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1635 ////////////////////////////////////////////////////////////////////
1636 // Initialize the event manager subsystem.
1637 ////////////////////////////////////////////////////////////////////
1639 globals->get_event_mgr()->init();
1640 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1642 ////////////////////////////////////////////////////////////////////
1643 // Initialize the property interpolator subsystem. Put into the INIT
1644 // group because the "nasal" subsystem may need it at GENERAL take-down.
1645 ////////////////////////////////////////////////////////////////////
1646 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1649 ////////////////////////////////////////////////////////////////////
1650 // Add the FlightGear property utilities.
1651 ////////////////////////////////////////////////////////////////////
1652 globals->add_subsystem("properties", new FGProperties);
1654 ////////////////////////////////////////////////////////////////////
1655 // Initialize the material property subsystem.
1656 ////////////////////////////////////////////////////////////////////
1658 SGPath mpath( globals->get_fg_root() );
1659 mpath.append( "materials.xml" );
1660 string season = fgGetString("/sim/startup/season", "summer");
1661 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1662 globals->get_props()) ) {
1663 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1668 ////////////////////////////////////////////////////////////////////
1669 // Initialize the scenery management subsystem.
1670 ////////////////////////////////////////////////////////////////////
1672 if ( globals->get_tile_mgr()->init() ) {
1673 // Load the local scenery data
1674 double visibility_meters = fgGetDouble("/environment/visibility-m");
1676 globals->get_tile_mgr()->update( visibility_meters );
1678 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1682 globals->get_scenery()->get_scene_graph()
1683 ->addChild(simgear::Particles::getCommonRoot());
1685 ////////////////////////////////////////////////////////////////////
1686 // Initialize the flight model subsystem.
1687 ////////////////////////////////////////////////////////////////////
1691 // allocates structures so must happen before any of the flight
1692 // model or control parameters are set
1693 fgAircraftInit(); // In the future this might not be the case.
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the weather subsystem.
1698 ////////////////////////////////////////////////////////////////////
1700 // Initialize the weather modeling subsystem
1701 globals->add_subsystem("environment", new FGEnvironmentMgr);
1704 ////////////////////////////////////////////////////////////////////
1705 // Initialize the aircraft systems and instrumentation (before the
1707 ////////////////////////////////////////////////////////////////////
1709 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1710 globals->add_subsystem("systems", new FGSystemMgr);
1712 ////////////////////////////////////////////////////////////////////
1713 // Initialize the XML Autopilot subsystem.
1714 ////////////////////////////////////////////////////////////////////
1716 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1717 globals->add_subsystem( "route-manager", new FGRouteMgr );
1720 ////////////////////////////////////////////////////////////////////
1721 // Initialize the view manager subsystem.
1722 ////////////////////////////////////////////////////////////////////
1726 ////////////////////////////////////////////////////////////////////
1727 // Create and register the logger.
1728 ////////////////////////////////////////////////////////////////////
1730 globals->add_subsystem("logger", new FGLogger);
1732 ////////////////////////////////////////////////////////////////////
1733 // Create and register the XML GUI.
1734 ////////////////////////////////////////////////////////////////////
1736 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1739 ////////////////////////////////////////////////////////////////////
1740 // Initialize the local time subsystem.
1741 ////////////////////////////////////////////////////////////////////
1743 // update the current timezone each 30 minutes
1744 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1745 &fgUpdateLocalTime, 30*60 );
1746 fgInitTimeOffset(); // the environment subsystem needs this
1749 ////////////////////////////////////////////////////////////////////
1750 // Initialize the lighting subsystem.
1751 ////////////////////////////////////////////////////////////////////
1753 globals->add_subsystem("lighting", new FGLight);
1755 //////////////////////////////////////////////////////////////////////
1756 // Initialize the 2D cloud subsystem.
1757 ////////////////////////////////////////////////////////////////////
1758 fgGetBool("/sim/rendering/bump-mapping", false);
1760 #ifdef ENABLE_AUDIO_SUPPORT
1761 ////////////////////////////////////////////////////////////////////
1762 // Initialize the sound subsystem.
1763 ////////////////////////////////////////////////////////////////////
1765 init_volume = fgGetFloat("/sim/sound/volume");
1766 fgSetFloat("/sim/sound/volume", 0.0f);
1767 globals->set_soundmgr(new SGSoundMgr);
1768 globals->get_soundmgr()->init();
1769 globals->get_soundmgr()->bind();
1772 ////////////////////////////////////////////////////////////////////
1773 // Initialize the sound-effects subsystem.
1774 ////////////////////////////////////////////////////////////////////
1776 globals->add_subsystem("fx", new FGFX);
1777 globals->add_subsystem("voice", new FGVoiceMgr);
1780 ////////////////////////////////////////////////////////////////////
1781 // Initialise the ATC Manager
1782 ////////////////////////////////////////////////////////////////////
1784 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1785 globals->set_ATC_mgr(new FGATCMgr);
1786 globals->get_ATC_mgr()->init();
1788 ////////////////////////////////////////////////////////////////////
1789 // Initialise the AI Manager
1790 ////////////////////////////////////////////////////////////////////
1792 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1793 globals->set_AI_mgr(new FGAIMgr);
1794 globals->get_AI_mgr()->init();
1796 ////////////////////////////////////////////////////////////////////
1797 // Initialise the AI Model Manager
1798 ////////////////////////////////////////////////////////////////////
1799 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1800 globals->add_subsystem("ai_model", new FGAIManager);
1801 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1804 // It's probably a good idea to initialize the top level traffic manager
1805 // After the AI and ATC systems have been initialized properly.
1806 // AI Traffic manager
1807 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1810 ////////////////////////////////////////////////////////////////////
1811 // Initialize the cockpit subsystem
1812 ////////////////////////////////////////////////////////////////////
1813 if( fgCockpitInit( ¤t_aircraft )) {
1814 // Cockpit initialized ok.
1816 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1821 ////////////////////////////////////////////////////////////////////
1822 // Initialize I/O subsystem.
1823 ////////////////////////////////////////////////////////////////////
1825 globals->get_io()->init();
1826 globals->get_io()->bind();
1829 ////////////////////////////////////////////////////////////////////
1830 // Add a new 2D panel.
1831 ////////////////////////////////////////////////////////////////////
1833 string panel_path = fgGetString("/sim/panel/path",
1834 "Panels/Default/default.xml");
1836 globals->set_current_panel( fgReadPanel(panel_path) );
1837 if (globals->get_current_panel() == 0) {
1838 SG_LOG( SG_INPUT, SG_ALERT,
1839 "Error reading new panel from " << panel_path );
1841 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1842 globals->get_current_panel()->init();
1843 globals->get_current_panel()->bind();
1847 ////////////////////////////////////////////////////////////////////
1848 // Initialize the controls subsystem.
1849 ////////////////////////////////////////////////////////////////////
1851 globals->get_controls()->init();
1852 globals->get_controls()->bind();
1855 ////////////////////////////////////////////////////////////////////
1856 // Initialize the input subsystem.
1857 ////////////////////////////////////////////////////////////////////
1859 globals->add_subsystem("input", new FGInput);
1862 ////////////////////////////////////////////////////////////////////
1863 // Initialize the replay subsystem
1864 ////////////////////////////////////////////////////////////////////
1865 globals->add_subsystem("replay", new FGReplay);
1867 ////////////////////////////////////////////////////////////////////
1868 // Bind and initialize subsystems.
1869 ////////////////////////////////////////////////////////////////////
1871 globals->get_subsystem_mgr()->bind();
1872 globals->get_subsystem_mgr()->init();
1874 ////////////////////////////////////////////////////////////////////
1875 // Initialize multiplayer subsystem
1876 ////////////////////////////////////////////////////////////////////
1878 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1879 globals->get_multiplayer_mgr()->init();
1881 ////////////////////////////////////////////////////////////////////////
1882 // Initialize the Nasal interpreter.
1883 // Do this last, so that the loaded scripts see initialized state
1884 ////////////////////////////////////////////////////////////////////////
1885 FGNasalSys* nasal = new FGNasalSys();
1886 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1889 // initialize methods that depend on other subsystems.
1890 globals->get_subsystem_mgr()->postinit();
1892 ////////////////////////////////////////////////////////////////////////
1893 // End of subsystem initialization.
1894 ////////////////////////////////////////////////////////////////////
1896 SG_LOG( SG_GENERAL, SG_INFO, endl);
1898 // Save the initial state for future
1900 globals->saveInitialState();
1906 void fgReInitSubsystems()
1908 // static const SGPropertyNode *longitude
1909 // = fgGetNode("/sim/presets/longitude-deg");
1910 // static const SGPropertyNode *latitude
1911 // = fgGetNode("/sim/presets/latitude-deg");
1912 static const SGPropertyNode *altitude
1913 = fgGetNode("/sim/presets/altitude-ft");
1914 static const SGPropertyNode *master_freeze
1915 = fgGetNode("/sim/freeze/master");
1917 SG_LOG( SG_GENERAL, SG_INFO,
1918 "fgReInitSubsystems(): /position/altitude = "
1919 << altitude->getDoubleValue() );
1921 bool freeze = master_freeze->getBoolValue();
1923 fgSetBool("/sim/freeze/master", true);
1925 fgSetBool("/sim/crashed", false);
1927 // Force reupdating the positions of the ai 3d models. They are used for
1928 // initializing ground level for the FDM.
1929 globals->get_subsystem("ai_model")->reinit();
1931 // Initialize the FDM
1934 // allocates structures so must happen before any of the flight
1935 // model or control parameters are set
1936 fgAircraftInit(); // In the future this might not be the case.
1938 // reload offsets from config defaults
1939 globals->get_viewmgr()->reinit();
1943 globals->get_controls()->reset_all();
1945 fgUpdateLocalTime();
1947 // re-init to proper time of day setting
1951 fgSetBool("/sim/freeze/master", false);
1953 fgSetBool("/sim/sceneryloaded",false);
1957 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1959 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1961 bool freeze = master_freeze->getBoolValue();
1963 master_freeze->setBoolValue(true);
1965 fgSetBool("/sim/signals/reinit", true);
1966 cur_fdm_state->unbind();
1968 // in case user has changed window size as
1969 // restoreInitialState() overwrites these
1970 int xsize = fgGetInt("/sim/startup/xsize");
1971 int ysize = fgGetInt("/sim/startup/ysize");
1973 globals->restoreInitialState();
1975 // update our position based on current presets
1978 // We don't know how to resize the window, so keep the last values
1979 // for xsize and ysize, and don't use the one set initially
1980 fgSetInt("/sim/startup/xsize", xsize);
1981 fgSetInt("/sim/startup/ysize", ysize);
1983 SGTime *t = globals->get_time_params();
1986 globals->set_time_params(t);
1988 fgReInitSubsystems();
1990 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1991 globals->get_renderer()->resize(xsize, ysize);
1992 fgSetBool("/sim/signals/reinit", false);
1995 master_freeze->setBoolValue(false);