1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 // For BC 5.01 this must be included before OpenGL includes.
29 #ifdef SG_MATH_EXCEPTION_CLASH
35 #include <string.h> // strcmp()
37 #if defined( unix ) || defined( __CYGWIN__ )
38 # include <unistd.h> // for gethostname()
40 #if defined( _MSC_VER) || defined(__MINGW32__)
41 # include <direct.h> // for getcwd()
42 # define getcwd _getcwd
45 // work around a stdc++ lib bug in some versions of linux, but doesn't
46 // seem to hurt to have this here for all versions of Linux.
48 # define _G_NO_EXTERN_TEMPLATES
51 #include <simgear/compiler.h>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/math/point3d.hxx>
60 #include <simgear/math/polar3d.hxx>
61 #include <simgear/math/sg_geodesy.hxx>
62 #include <simgear/misc/sg_path.hxx>
63 #include <simgear/misc/interpolator.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/scene/model/particles.hxx>
66 #include <simgear/timing/sg_time.hxx>
67 #include <simgear/timing/lowleveltime.h>
69 #include <Aircraft/aircraft.hxx>
70 #include <Aircraft/replay.hxx>
71 #include <Airports/apt_loader.hxx>
72 #include <Airports/runways.hxx>
73 #include <Airports/simple.hxx>
74 #include <AIModel/AIManager.hxx>
75 #include <ATCDCL/ATCmgr.hxx>
76 #include <ATCDCL/AIMgr.hxx>
77 #include <Autopilot/route_mgr.hxx>
78 #include <Autopilot/xmlauto.hxx>
79 #include <Cockpit/cockpit.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/panel_io.hxx>
83 #include <FDM/SP/ADA.hxx>
84 #include <FDM/SP/ACMS.hxx>
86 #include <FDM/Balloon.h>
87 #include <FDM/ExternalNet/ExternalNet.hxx>
88 #include <FDM/ExternalPipe/ExternalPipe.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim/LaRCsim.hxx>
91 #include <FDM/MagicCarpet.hxx>
92 #include <FDM/UFO.hxx>
93 #include <FDM/NullFDM.hxx>
94 #include <FDM/YASim/YASim.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Include/general.hxx>
97 #include <Input/input.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <AIModel/submodel.hxx>
101 #include <AIModel/AIManager.hxx>
102 #include <Navaids/navdb.hxx>
103 #include <Navaids/navlist.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/fg_fx.hxx>
108 #include <Sound/beacon.hxx>
109 #include <Sound/morse.hxx>
110 #include <Sound/voice.hxx>
111 #include <Systems/system_mgr.hxx>
112 #include <Time/light.hxx>
113 #include <Time/sunsolver.hxx>
114 #include <Time/tmp.hxx>
115 #include <Traffic/TrafficMgr.hxx>
116 #include <MultiPlayer/multiplaymgr.hxx>
118 #include <Environment/environment_mgr.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "viewmgr.hxx"
130 #if defined(FX) && defined(XMESA)
131 #include <GL/xmesa.h>
134 SG_USING_STD(string);
138 extern const char *default_root;
142 // Scan the command line options for the specified option and return
144 static string fgScanForOption( const string& option, int argc, char **argv ) {
147 if (hostname == NULL)
150 gethostname(_hostname, 256);
151 hostname = strdup(_hostname);
152 free_hostname = true;
155 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
157 int len = option.length();
160 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
162 string arg = argv[i];
163 if ( arg.find( option ) == 0 ) {
164 return arg.substr( len );
174 // Scan the user config files for the specified option and return
176 static string fgScanForOption( const string& option, const string& path ) {
177 sg_gzifstream in( path );
178 if ( !in.is_open() ) {
182 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
184 int len = option.length();
188 while ( ! in.eof() ) {
191 while ( in.get(c) && c != '\0' ) {
196 #if defined( macintosh )
197 getline( in, line, '\r' );
199 getline( in, line, '\n' );
202 // catch extraneous (DOS) line ending character
203 if ( line[line.length() - 1] < 32 ) {
204 line = line.substr( 0, line.length()-1 );
207 if ( line.find( option ) == 0 ) {
208 return line.substr( len );
217 // Scan the user config files for the specified option and return
219 static string fgScanForOption( const string& option ) {
222 #if defined( unix ) || defined( __CYGWIN__ )
223 // Next check home directory for .fgfsrc.hostname file
225 if ( homedir != NULL ) {
226 SGPath config( homedir );
227 config.append( ".fgfsrc" );
228 config.concat( "." );
229 config.concat( hostname );
230 arg = fgScanForOption( option, config.str() );
235 // Next check home directory for .fgfsrc file
237 if ( homedir != NULL ) {
238 SGPath config( homedir );
239 config.append( ".fgfsrc" );
240 arg = fgScanForOption( option, config.str() );
245 // Check for $fg_root/system.fgfsrc
246 SGPath config( globals->get_fg_root() );
247 config.append( "system.fgfsrc" );
248 arg = fgScanForOption( option, config.str() );
255 // Read in configuration (files and command line options) but only set
257 bool fgInitFGRoot ( int argc, char **argv ) {
260 // First parse command line options looking for --fg-root=, this
261 // will override anything specified in a config file
262 root = fgScanForOption( "--fg-root=", argc, argv);
264 // Check in one of the user configuration files.
266 root = fgScanForOption( "--fg-root=" );
268 // Next check if fg-root is set as an env variable
269 if ( root.empty() ) {
270 char *envp = ::getenv( "FG_ROOT" );
271 if ( envp != NULL ) {
276 // Otherwise, default to a random compiled-in location if we can't
277 // find fg-root any other way.
278 if ( root.empty() ) {
279 #if defined( __CYGWIN__ )
280 root = "/FlightGear";
281 #elif defined( WIN32 )
282 root = "\\FlightGear";
283 #elif defined(OSX_BUNDLE)
284 /* the following code looks for the base package directly inside
285 the application bundle. This can be changed fairly easily by
286 fiddling with the code below. And yes, I know it's ugly and verbose.
288 CFBundleRef appBundle = CFBundleGetMainBundle();
289 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
290 CFRelease(appBundle);
292 // look for a 'data' subdir directly inside the bundle : is there
293 // a better place? maybe in Resources? I don't know ...
294 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
296 // now convert down to a path, and the a c-string
297 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
298 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
301 CFRelease(appBundle);
309 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
310 globals->set_fg_root(root);
316 // Read in configuration (files and command line options) but only set
318 bool fgInitFGAircraft ( int argc, char **argv ) {
321 // First parse command line options looking for --aircraft=, this
322 // will override anything specified in a config file
323 aircraft = fgScanForOption( "--aircraft=", argc, argv );
324 if ( aircraft.empty() ) {
325 // check synonym option
326 aircraft = fgScanForOption( "--vehicle=", argc, argv );
329 // Check in one of the user configuration files.
330 if ( aircraft.empty() ) {
331 aircraft = fgScanForOption( "--aircraft=" );
333 if ( aircraft.empty() ) {
334 aircraft = fgScanForOption( "--vehicle=" );
337 // if an aircraft was specified, set the property name
338 if ( !aircraft.empty() ) {
339 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
340 fgSetString("/sim/aircraft", aircraft.c_str() );
342 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
349 // Return the current base package version
350 string fgBasePackageVersion() {
351 SGPath base_path( globals->get_fg_root() );
352 base_path.append("version");
354 sg_gzifstream in( base_path.str() );
355 if ( !in.is_open() ) {
356 SGPath old_path( globals->get_fg_root() );
357 old_path.append( "Thanks" );
358 sg_gzifstream old( old_path.str() );
359 if ( !old.is_open() ) {
362 return "[old version]";
373 // Initialize the localization
374 SGPropertyNode *fgInitLocale(const char *language) {
375 SGPropertyNode *c_node = NULL, *d_node = NULL;
376 SGPropertyNode *intl = fgGetNode("/sim/intl");
378 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
380 // localization not defined
385 // Select the proper language from the list
387 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
388 for (unsigned int i = 0; i < locale.size(); i++) {
390 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
391 for (unsigned int j = 0; j < lang.size(); j++) {
393 if (!strcmp(lang[j]->getStringValue(), language)) {
402 d_node = intl->getChild("locale");
406 // Check for localized font
407 SGPropertyNode *font_n = c_node->getNode("font", true);
408 if ( !strcmp(font_n->getStringValue(), "") )
409 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
413 // Load the default strings
415 SGPath d_path( globals->get_fg_root() );
417 const char *d_path_str = d_node->getStringValue("strings");
419 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
423 d_path.append(d_path_str);
424 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
426 SGPropertyNode *strings = c_node->getNode("strings");
428 readProperties(d_path.str(), strings);
429 } catch (const sg_exception &e) {
430 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
435 // Load the language specific strings
437 if (c_node != d_node) {
438 SGPath c_path( globals->get_fg_root() );
440 const char *c_path_str = c_node->getStringValue("strings");
442 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
446 c_path.append(c_path_str);
447 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
450 readProperties(c_path.str(), strings);
451 } catch (const sg_exception &e) {
452 SG_LOG(SG_GENERAL, SG_ALERT,
453 "Unable to read the localized strings from " << c_path.str());
463 // Initialize the localization routines
464 bool fgDetectLanguage() {
465 const char *language = ::getenv("LANG");
467 if (language == NULL) {
468 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
472 SGPropertyNode *locale = fgInitLocale(language);
474 SG_LOG(SG_GENERAL, SG_ALERT,
475 "No internationalization settings specified in preferences.xml" );
480 globals->set_locale( locale );
485 // Attempt to locate and parse the various non-XML config files in order
486 // from least precidence to greatest precidence
488 do_options (int argc, char ** argv)
490 // Check for $fg_root/system.fgfsrc
491 SGPath config( globals->get_fg_root() );
492 config.append( "system.fgfsrc" );
493 fgParseOptions(config.str());
495 #if defined( unix ) || defined( __CYGWIN__ )
496 config.concat( "." );
497 config.concat( hostname );
498 fgParseOptions(config.str());
501 // Check for ~/.fgfsrc
502 if ( homedir != NULL ) {
503 config.set( homedir );
504 config.append( ".fgfsrc" );
505 fgParseOptions(config.str());
508 #if defined( unix ) || defined( __CYGWIN__ )
509 // Check for ~/.fgfsrc.hostname
510 config.concat( "." );
511 config.concat( hostname );
512 fgParseOptions(config.str());
515 // Parse remaining command line options
516 // These will override anything specified in a config file
517 fgParseArgs(argc, argv);
521 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
522 SGPropertyNode *cache, int depth = 0 )
524 const int MAXDEPTH = 1;
527 ulDir *dirp = ulOpenDir(path.str().c_str());
529 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
534 while ((dire = ulReadDir(dirp)) != NULL) {
536 if (depth > MAXDEPTH)
539 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
540 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
544 next.append(dire->d_name);
546 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
547 if ( ! result.empty() )
551 int len = strlen(dire->d_name);
552 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
558 if (!cache->getChild("aircraft", i++, false))
561 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
563 n = entry->getNode("file", true);
564 n->setStringValue(dire->d_name);
565 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
567 n = entry->getNode("path", true);
568 n->setStringValue(path.str().c_str());
569 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
571 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
583 // Read in configuration (file and command line)
584 bool fgInitConfig ( int argc, char **argv ) {
586 // First, set some sane default values
589 // Read global preferences from $FG_ROOT/preferences.xml
590 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
591 fgLoadProps("preferences.xml", globals->get_props());
592 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
594 // Detect the required language as early as possible
595 if ( !fgDetectLanguage() ) {
599 SGPropertyNode autosave;
601 char *envp = ::getenv( "APPDATA" );
603 SGPath config( envp );
604 config.append( "flightgear.org" );
606 if ( homedir != NULL ) {
607 SGPath config( homedir );
608 config.append( ".fgfs" );
610 fgSetString("/sim/fg-home", config.c_str());
611 config.append( "autosave.xml" );
612 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
614 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
616 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
618 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
620 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
623 // Scan user config files and command line for a specified aircraft.
624 fgInitFGAircraft(argc, argv);
626 string aircraft = fgGetString( "/sim/aircraft", "" );
627 if ( aircraft.size() > 0 ) {
628 SGPath aircraft_search( globals->get_fg_root() );
629 aircraft_search.append( "Aircraft" );
631 string aircraft_set = aircraft + "-set.xml";
634 // check if the *-set.xml file is already in the cache
635 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
636 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
637 for (unsigned int i = 0; i < cache.size(); i++) {
638 const char *name = cache[i]->getStringValue("file", "");
639 if (aircraft_set == name) {
640 const char *path = cache[i]->getStringValue("path", "");
650 if (result.empty()) {
651 // prepare cache for rescan
652 SGPropertyNode *n = cache_root->getNode("fg-root", true);
653 n->setStringValue(globals->get_fg_root().c_str());
654 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
655 cache_root->removeChildren("aircraft");
657 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
660 if ( !result.empty() ) {
661 fgSetString( "/sim/aircraft-dir", result.c_str() );
662 SGPath full_name( result );
663 full_name.append( aircraft_set );
665 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
666 << " from " << full_name.str());
668 readProperties( full_name.str(), globals->get_props() );
669 } catch ( const sg_exception &e ) {
670 string message = "Error reading default aircraft: ";
671 message += e.getFormattedMessage();
672 SG_LOG(SG_INPUT, SG_ALERT, message);
676 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
682 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
685 copyProperties(&autosave, globals->get_props());
687 // parse options after loading aircraft to ensure any user
688 // overrides of defaults are honored.
689 do_options(argc, argv);
700 // This function is never used, but maybe useful in the future ???
703 // Preset lon/lat given an airport id
704 static bool fgSetPosFromAirportID( const string& id ) {
708 SG_LOG( SG_GENERAL, SG_INFO,
709 "Attempting to set starting position from airport code " << id );
711 if ( fgFindAirportID( id, &a ) ) {
713 fgSetDouble("/sim/presets/longitude-deg", a->longitude );
714 fgSetDouble("/sim/presets/latitude-deg", a->latitude );
716 // other code depends on the actual postition being set so set
718 fgSetDouble("/position/longitude-deg", a->longitude );
719 fgSetDouble("/position/latitude-deg", a->latitude );
721 SG_LOG( SG_GENERAL, SG_INFO,
722 "Position for " << id << " is (" << a->longitude
723 << ", " << a->latitude << ")" );
733 // Set current tower position lon/lat given an airport id
734 static bool fgSetTowerPosFromAirportID( const string& id) {
735 const FGAirport *a = fgFindAirportID( id);
737 SGGeod tower = a->getTowerLocation();
738 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
739 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
740 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
748 struct FGTowerLocationListener : SGPropertyChangeListener {
749 void valueChanged(SGPropertyNode* node) {
750 const string id(node->getStringValue());
751 fgSetTowerPosFromAirportID(id);
755 void fgInitTowerLocationListener() {
756 fgGetNode("/sim/tower/airport-id", true)
757 ->addChangeListener( new FGTowerLocationListener(), true );
760 // Set current_options lon/lat given an airport id and heading (degrees)
761 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
767 // set initial position from runway and heading
768 SG_LOG( SG_GENERAL, SG_INFO,
769 "Attempting to set starting position from airport code "
770 << id << " heading " << tgt_hdg );
772 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
773 SG_LOG( SG_GENERAL, SG_ALERT,
774 "Failed to find a good runway for " << id << '\n' );
777 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
779 double lat2, lon2, az2;
780 double heading = r._heading;
781 double azimuth = heading + 180.0;
782 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
784 SG_LOG( SG_GENERAL, SG_INFO,
785 "runway = " << r._lon << ", " << r._lat
786 << " length = " << r._length * SG_FEET_TO_METER
787 << " heading = " << azimuth );
789 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
790 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
791 &lat2, &lon2, &az2 );
793 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
795 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
796 odist *= SG_NM_TO_METER;
797 double oaz = azimuth;
798 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
799 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
802 while ( oaz >= 360.0 ) { oaz -= 360.0; }
803 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
809 fgSetDouble("/sim/presets/longitude-deg", lon2 );
810 fgSetDouble("/sim/presets/latitude-deg", lat2 );
811 fgSetDouble("/sim/presets/heading-deg", heading );
813 // other code depends on the actual values being set ...
814 fgSetDouble("/position/longitude-deg", lon2 );
815 fgSetDouble("/position/latitude-deg", lat2 );
816 fgSetDouble("/orientation/heading-deg", heading );
818 SG_LOG( SG_GENERAL, SG_INFO,
819 "Position for " << id << " is ("
821 << lat2 << ") new heading is "
827 // Set current_options lon/lat given an airport id and parkig position name
828 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
832 // can't see an easy way around this const_cast at the moment
833 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
835 SG_LOG( SG_GENERAL, SG_ALERT,
836 "Failed to find airport " << id );
839 FGAirportDynamics* dcs = apt->getDynamics();
841 SG_LOG( SG_GENERAL, SG_ALERT,
842 "Failed to find parking position " << parkpos <<
843 " at airport " << id );
847 int park_index = dcs->getNrOfParkings() - 1;
848 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
849 if (park_index < 0) {
850 SG_LOG( SG_GENERAL, SG_ALERT,
851 "Failed to find parking position " << parkpos <<
852 " at airport " << id );
855 FGParking* parking = dcs->getParking(park_index);
857 double lat = parking->getLatitude();
858 double lon = parking->getLongitude();
859 double hdg = parking->getHeading();
862 fgSetDouble("/sim/presets/longitude-deg", lon );
863 fgSetDouble("/sim/presets/latitude-deg", lat );
864 fgSetDouble("/sim/presets/heading-deg", hdg );
866 // other code depends on the actual values being set ...
867 fgSetDouble("/position/longitude-deg", lon );
868 fgSetDouble("/position/latitude-deg", lat );
869 fgSetDouble("/orientation/heading-deg", hdg );
871 SG_LOG( SG_GENERAL, SG_INFO,
872 "Position for " << id << " is ("
874 << lat << ") new heading is "
881 // Set current_options lon/lat given an airport id and runway number
882 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
888 // set initial position from airport and runway number
889 SG_LOG( SG_GENERAL, SG_INFO,
890 "Attempting to set starting position for "
891 << id << ":" << rwy );
893 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
894 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
895 "Failed to find runway " << rwy <<
896 " at airport " << id << ". Using default runway." );
899 fgSetString("/sim/atc/runway", r._rwy_no.c_str());
901 double lat2, lon2, az2;
902 double heading = r._heading;
903 double azimuth = heading + 180.0;
904 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
906 SG_LOG( SG_GENERAL, SG_INFO,
907 "runway = " << r._lon << ", " << r._lat
908 << " length = " << r._length * SG_FEET_TO_METER
909 << " heading = " << azimuth );
911 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, r._length * SG_FEET_TO_METER * 0.5
912 - fgGetDouble("/sim/airport/runways/start-offset-m", 5.0),
913 &lat2, &lon2, &az2 );
915 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
918 double odist = fgGetDouble("/sim/presets/offset-distance-nm");
919 odist *= SG_NM_TO_METER;
920 double oaz = azimuth;
921 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON )
923 oaz = fgGetDouble("/sim/presets/offset-azimuth-deg") + 180;
924 heading = fgGetDouble("/sim/presets/heading-deg");
926 while ( oaz >= 360.0 ) { oaz -= 360.0; }
927 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
933 fgSetDouble("/sim/presets/longitude-deg", lon2 );
934 fgSetDouble("/sim/presets/latitude-deg", lat2 );
935 fgSetDouble("/sim/presets/heading-deg", heading );
937 // other code depends on the actual values being set ...
938 fgSetDouble("/position/longitude-deg", lon2 );
939 fgSetDouble("/position/latitude-deg", lat2 );
940 fgSetDouble("/orientation/heading-deg", heading );
942 SG_LOG( SG_GENERAL, SG_INFO,
943 "Position for " << id << " is ("
945 << lat2 << ") new heading is "
952 static void fgSetDistOrAltFromGlideSlope() {
953 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
954 string apt_id = fgGetString("/sim/presets/airport-id");
955 double gs = fgGetDouble("/sim/presets/glideslope-deg")
956 * SG_DEGREES_TO_RADIANS ;
957 double od = fgGetDouble("/sim/presets/offset-distance-nm");
958 double alt = fgGetDouble("/sim/presets/altitude-ft");
960 double apt_elev = 0.0;
961 if ( ! apt_id.empty() ) {
962 apt_elev = fgGetAirportElev( apt_id );
963 if ( apt_elev < -9990.0 ) {
970 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
971 // set altitude from glideslope and offset-distance
972 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
973 alt = fabs(od*tan(gs)) + apt_elev;
974 fgSetDouble("/sim/presets/altitude-ft", alt);
975 fgSetBool("/sim/presets/onground", false);
976 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
978 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
979 // set offset-distance from glideslope and altitude
980 od = (alt - apt_elev) / tan(gs);
981 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
982 fgSetDouble("/sim/presets/offset-distance-nm", od);
983 fgSetBool("/sim/presets/onground", false);
984 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
986 } else if( fabs(gs) > 0.01 ) {
987 SG_LOG( SG_GENERAL, SG_ALERT,
988 "Glideslope given but not altitude or offset-distance." );
989 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
990 fgSetDouble("/sim/presets/glideslope-deg", 0);
991 fgSetBool("/sim/presets/onground", true);
996 // Set current_options lon/lat given an airport id and heading (degrees)
997 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
999 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
1001 // set initial position from runway and heading
1002 if ( nav != NULL ) {
1003 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1004 << id << ":" << freq );
1006 double lon = nav->get_lon();
1007 double lat = nav->get_lat();
1009 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1011 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1013 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1015 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1016 double olat, olon, az2;
1017 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1024 fgSetDouble("/sim/presets/longitude-deg", lon );
1025 fgSetDouble("/sim/presets/latitude-deg", lat );
1027 // other code depends on the actual values being set ...
1028 fgSetDouble("/position/longitude-deg", lon );
1029 fgSetDouble("/position/latitude-deg", lat );
1030 fgSetDouble("/orientation/heading-deg",
1031 fgGetDouble("/sim/presets/heading-deg") );
1033 SG_LOG( SG_GENERAL, SG_INFO,
1034 "Position for " << id << ":" << freq << " is ("
1035 << lon << ", "<< lat << ")" );
1039 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1040 << id << ":" << freq );
1045 // Set current_options lon/lat given an aircraft carrier id
1046 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1048 // set initial position from runway and heading
1052 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1053 double lon = geodPos.getLongitudeDeg();
1054 double lat = geodPos.getLatitudeDeg();
1055 double alt = geodPos.getElevationFt();
1057 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1058 << carrier << " at lat = " << lat << ", lon = " << lon
1059 << ", alt = " << alt << ", heading = " << heading);
1061 fgSetDouble("/sim/presets/longitude-deg", lon);
1062 fgSetDouble("/sim/presets/latitude-deg", lat);
1063 fgSetDouble("/sim/presets/altitude-ft", alt);
1064 fgSetDouble("/sim/presets/heading-deg", heading);
1065 fgSetDouble("/position/longitude-deg", lon);
1066 fgSetDouble("/position/latitude-deg", lat);
1067 fgSetDouble("/position/altitude-ft", alt);
1068 fgSetDouble("/orientation/heading-deg", heading);
1070 fgSetString("/sim/presets/speed-set", "UVW");
1071 fgSetDouble("/velocities/uBody-fps", uvw(0));
1072 fgSetDouble("/velocities/vBody-fps", uvw(1));
1073 fgSetDouble("/velocities/wBody-fps", uvw(2));
1074 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1075 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1076 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1078 fgSetBool("/sim/presets/onground", true);
1082 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1088 // Set current_options lon/lat given an airport id and heading (degrees)
1089 static bool fgSetPosFromFix( const string& id ) {
1092 // set initial position from runway and heading
1093 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1094 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1097 double lon = fix.get_lon();
1098 double lat = fix.get_lat();
1100 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON )
1102 double odist = fgGetDouble("/sim/presets/offset-distance-nm")
1104 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth-deg"))
1106 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1107 double olat, olon, az2;
1108 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1115 fgSetDouble("/sim/presets/longitude-deg", lon );
1116 fgSetDouble("/sim/presets/latitude-deg", lat );
1118 // other code depends on the actual values being set ...
1119 fgSetDouble("/position/longitude-deg", lon );
1120 fgSetDouble("/position/latitude-deg", lat );
1121 fgSetDouble("/orientation/heading-deg",
1122 fgGetDouble("/sim/presets/heading-deg") );
1124 SG_LOG( SG_GENERAL, SG_INFO,
1125 "Position for " << id << " is ("
1126 << lon << ", "<< lat << ")" );
1130 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1138 * Initialize vor/ndb/ils/fix list management and query systems (as
1139 * well as simple airport db list)
1144 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1146 SGPath aptdb( globals->get_fg_root() );
1147 aptdb.append( "Airports/apt.dat" );
1149 SGPath p_metar( globals->get_fg_root() );
1150 p_metar.append( "Airports/metar.dat" );
1152 FGAirportList *airports = new FGAirportList();
1153 globals->set_airports( airports );
1154 FGRunwayList *runways = new FGRunwayList();
1155 globals->set_runways( runways );
1157 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1159 FGNavList *navlist = new FGNavList;
1160 FGNavList *loclist = new FGNavList;
1161 FGNavList *gslist = new FGNavList;
1162 FGNavList *dmelist = new FGNavList;
1163 FGNavList *mkrlist = new FGNavList;
1164 FGNavList *tacanlist = new FGNavList;
1165 FGNavList *carrierlist = new FGNavList;
1166 FGTACANList *channellist = new FGTACANList;
1168 globals->set_navlist( navlist );
1169 globals->set_loclist( loclist );
1170 globals->set_gslist( gslist );
1171 globals->set_dmelist( dmelist );
1172 globals->set_mkrlist( mkrlist );
1173 globals->set_tacanlist( tacanlist );
1174 globals->set_carrierlist( carrierlist );
1175 globals->set_channellist( channellist );
1177 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1178 SG_LOG( SG_GENERAL, SG_ALERT,
1179 "Problems loading one or more navigational database" );
1182 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1183 // align all the localizers with their corresponding runways
1184 // since data sources are good for cockpit navigation
1185 // purposes, but not always to the error tolerances needed to
1186 // exactly place these items.
1188 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1190 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1193 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1194 SGPath p_fix( globals->get_fg_root() );
1195 p_fix.append( "Navaids/fix.dat" );
1196 FGFixList *fixlist = new FGFixList;
1197 fixlist->init( p_fix );
1198 globals->set_fixlist( fixlist );
1200 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1201 SGPath p_awy( globals->get_fg_root() );
1202 p_awy.append( "Navaids/awy.dat" );
1203 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1204 //cerr << "Loading Airways" << endl;
1205 awyNet->load (p_awy );
1207 //cerr << "initializing airways" << endl;
1208 globals->set_airwaynet( awyNet );
1214 // Set the initial position based on presets (or defaults)
1215 bool fgInitPosition() {
1216 // cout << "fgInitPosition()" << endl;
1217 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1218 * SG_DEGREES_TO_RADIANS ;
1219 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1220 double alt = fgGetDouble("/sim/presets/altitude-ft");
1222 bool set_pos = false;
1224 // If glideslope is specified, then calculate offset-distance or
1225 // altitude relative to glide slope if either of those was not
1227 if ( fabs( gs ) > 0.01 ) {
1228 fgSetDistOrAltFromGlideSlope();
1232 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1233 // If not, check for an airport-id and use that.
1234 // If not, default to the middle of the KSFO field.
1235 // The default values for lon/lat are deliberately out of range
1236 // so that the airport-id can take effect; valid lon/lat will
1237 // override airport-id, however.
1238 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1239 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1240 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1241 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1246 string apt = fgGetString("/sim/presets/airport-id");
1247 string rwy_no = fgGetString("/sim/presets/runway");
1248 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1249 string vor = fgGetString("/sim/presets/vor-id");
1250 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1251 string ndb = fgGetString("/sim/presets/ndb-id");
1252 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1253 string carrier = fgGetString("/sim/presets/carrier");
1254 string parkpos = fgGetString("/sim/presets/parkpos");
1255 string fix = fgGetString("/sim/presets/fix");
1256 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1257 double hdg = hdg_preset->getDoubleValue();
1259 // save some start parameters, so that we can later say what the
1260 // user really requested. TODO generalize that and move it to options.cxx
1261 static bool start_options_saved = false;
1262 if (!start_options_saved) {
1263 start_options_saved = true;
1264 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1266 opt->setDoubleValue("latitude-deg", lat_deg);
1267 opt->setDoubleValue("longitude-deg", lon_deg);
1268 opt->setDoubleValue("heading-deg", hdg);
1269 opt->setStringValue("airport", apt.c_str());
1270 opt->setStringValue("runway", rwy_no.c_str());
1274 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1276 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1277 // An airport + parking position is requested
1278 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1279 // set tower position
1280 fgSetString("/sim/tower/airport-id", apt.c_str());
1285 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1286 // An airport + runway is requested
1287 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1288 // set tower position (a little off the heading for single
1290 fgSetString("/sim/tower/airport-id", apt.c_str());
1295 if ( !set_pos && !apt.empty() ) {
1296 // An airport is requested (find runway closest to hdg)
1297 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1298 // set tower position (a little off the heading for single
1300 fgSetString("/sim/tower/airport-id", apt.c_str());
1305 if (hdg_preset->getDoubleValue() > 9990.0)
1306 hdg_preset->setDoubleValue(hdg);
1308 if ( !set_pos && !vor.empty() ) {
1309 // a VOR is requested
1310 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1315 if ( !set_pos && !ndb.empty() ) {
1316 // an NDB is requested
1317 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1322 if ( !set_pos && !carrier.empty() ) {
1323 // an aircraft carrier is requested
1324 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1329 if ( !set_pos && !fix.empty() ) {
1330 // a Fix is requested
1331 if ( fgSetPosFromFix( fix ) ) {
1337 // No lon/lat specified, no airport specified, default to
1338 // middle of KSFO field.
1339 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1340 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1343 fgSetDouble( "/position/longitude-deg",
1344 fgGetDouble("/sim/presets/longitude-deg") );
1345 fgSetDouble( "/position/latitude-deg",
1346 fgGetDouble("/sim/presets/latitude-deg") );
1347 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1349 // determine if this should be an on-ground or in-air start
1350 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1351 fgSetBool("/sim/presets/onground", false);
1353 fgSetBool("/sim/presets/onground", true);
1360 // General house keeping initializations
1361 bool fgInitGeneral() {
1364 #if defined(FX) && defined(XMESA)
1365 char *mesa_win_state;
1368 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1369 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1371 root = globals->get_fg_root();
1372 if ( ! root.length() ) {
1373 // No root path set? Then bail ...
1374 SG_LOG( SG_GENERAL, SG_ALERT,
1375 "Cannot continue without a path to the base package "
1376 << "being defined." );
1379 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1381 #if defined(FX) && defined(XMESA)
1382 // initialize full screen flag
1383 globals->set_fullscreen(false);
1384 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1385 // Test for the MESA_GLX_FX env variable
1386 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1387 // test if we are fullscreen mesa/glide
1388 if ( (mesa_win_state[0] == 'f') ||
1389 (mesa_win_state[0] == 'F') ) {
1390 globals->set_fullscreen(true);
1396 char buf[512], *cwd = getcwd(buf, 512);
1397 fgSetString("/sim/fg-current", cwd ? cwd : "");
1402 // Initialize the flight model subsystem. This just creates the
1403 // object. The actual fdm initialization is delayed until we get a
1404 // proper scenery elevation hit. This is checked for in main.cxx
1408 if ( cur_fdm_state ) {
1409 delete cur_fdm_state;
1413 double dt = 1.0 / fgGetInt("/sim/model-hz");
1414 string model = fgGetString("/sim/flight-model");
1416 if ( model == "larcsim" ) {
1417 cur_fdm_state = new FGLaRCsim( dt );
1418 } else if ( model == "jsb" ) {
1419 cur_fdm_state = new FGJSBsim( dt );
1421 } else if ( model == "ada" ) {
1422 cur_fdm_state = new FGADA( dt );
1423 } else if ( model == "acms" ) {
1424 cur_fdm_state = new FGACMS( dt );
1426 } else if ( model == "balloon" ) {
1427 cur_fdm_state = new FGBalloonSim( dt );
1428 } else if ( model == "magic" ) {
1429 cur_fdm_state = new FGMagicCarpet( dt );
1430 } else if ( model == "ufo" ) {
1431 cur_fdm_state = new FGUFO( dt );
1432 } else if ( model == "external" ) {
1433 // external is a synonym for "--fdm=null" and is
1434 // maintained here for backwards compatibility
1435 cur_fdm_state = new FGNullFDM( dt );
1436 } else if ( model.find("network") == 0 ) {
1437 string host = "localhost";
1441 string net_options = model.substr(8);
1442 string::size_type begin, end;
1445 end = net_options.find( ",", begin );
1446 if ( end != string::npos ) {
1447 host = net_options.substr(begin, end - begin);
1451 end = net_options.find( ",", begin );
1452 if ( end != string::npos ) {
1453 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1457 end = net_options.find( ",", begin );
1458 if ( end != string::npos ) {
1459 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1463 end = net_options.find( ",", begin );
1464 if ( end != string::npos ) {
1465 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1468 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1469 } else if ( model.find("pipe") == 0 ) {
1470 // /* old */ string pipe_path = model.substr(5);
1471 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1472 string pipe_path = "";
1473 string pipe_protocol = "";
1474 string pipe_options = model.substr(5);
1475 string::size_type begin, end;
1478 end = pipe_options.find( ",", begin );
1479 if ( end != string::npos ) {
1480 pipe_path = pipe_options.substr(begin, end - begin);
1483 // protocol (last option)
1484 pipe_protocol = pipe_options.substr(begin);
1485 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1486 } else if ( model == "null" ) {
1487 cur_fdm_state = new FGNullFDM( dt );
1488 } else if ( model == "yasim" ) {
1489 cur_fdm_state = new YASim( dt );
1491 throw sg_throwable(string("Unrecognized flight model '") + model
1492 + "', cannot init flight dynamics model.");
1496 // Initialize view parameters
1498 // force update of model so that viewer can get some data...
1499 globals->get_aircraft_model()->update(0);
1500 // run update for current view so that data is current...
1501 globals->get_viewmgr()->update(0);
1505 SGTime *fgInitTime() {
1507 static const SGPropertyNode *longitude
1508 = fgGetNode("/position/longitude-deg");
1509 static const SGPropertyNode *latitude
1510 = fgGetNode("/position/latitude-deg");
1511 static const SGPropertyNode *cur_time_override
1512 = fgGetNode("/sim/time/cur-time-override", true);
1514 SGPath zone( globals->get_fg_root() );
1515 zone.append( "Timezone" );
1516 SGTime *t = new SGTime( longitude->getDoubleValue()
1517 * SGD_DEGREES_TO_RADIANS,
1518 latitude->getDoubleValue()
1519 * SGD_DEGREES_TO_RADIANS,
1521 cur_time_override->getLongValue() );
1523 globals->set_warp_delta( 0 );
1525 t->update( 0.0, 0.0,
1526 cur_time_override->getLongValue(),
1527 globals->get_warp() );
1533 // set up a time offset (aka warp) if one is specified
1534 void fgInitTimeOffset() {
1535 static const SGPropertyNode *longitude
1536 = fgGetNode("/position/longitude-deg");
1537 static const SGPropertyNode *latitude
1538 = fgGetNode("/position/latitude-deg");
1539 static const SGPropertyNode *cur_time_override
1540 = fgGetNode("/sim/time/cur-time-override", true);
1542 // Handle potential user specified time offsets
1543 int orig_warp = globals->get_warp();
1544 SGTime *t = globals->get_time_params();
1545 time_t cur_time = t->get_cur_time();
1546 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1547 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1548 time_t aircraftLocalTime =
1549 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1551 // Okay, we now have several possible scenarios
1552 int offset = fgGetInt("/sim/startup/time-offset");
1553 string offset_type = fgGetString("/sim/startup/time-offset-type");
1556 if ( offset_type == "real" ) {
1558 } else if ( offset_type == "dawn" ) {
1559 warp = fgTimeSecondsUntilSunAngle( cur_time,
1560 longitude->getDoubleValue()
1561 * SGD_DEGREES_TO_RADIANS,
1562 latitude->getDoubleValue()
1563 * SGD_DEGREES_TO_RADIANS,
1565 } else if ( offset_type == "morning" ) {
1566 warp = fgTimeSecondsUntilSunAngle( cur_time,
1567 longitude->getDoubleValue()
1568 * SGD_DEGREES_TO_RADIANS,
1569 latitude->getDoubleValue()
1570 * SGD_DEGREES_TO_RADIANS,
1572 } else if ( offset_type == "noon" ) {
1573 warp = fgTimeSecondsUntilSunAngle( cur_time,
1574 longitude->getDoubleValue()
1575 * SGD_DEGREES_TO_RADIANS,
1576 latitude->getDoubleValue()
1577 * SGD_DEGREES_TO_RADIANS,
1579 } else if ( offset_type == "afternoon" ) {
1580 warp = fgTimeSecondsUntilSunAngle( cur_time,
1581 longitude->getDoubleValue()
1582 * SGD_DEGREES_TO_RADIANS,
1583 latitude->getDoubleValue()
1584 * SGD_DEGREES_TO_RADIANS,
1586 } else if ( offset_type == "dusk" ) {
1587 warp = fgTimeSecondsUntilSunAngle( cur_time,
1588 longitude->getDoubleValue()
1589 * SGD_DEGREES_TO_RADIANS,
1590 latitude->getDoubleValue()
1591 * SGD_DEGREES_TO_RADIANS,
1593 } else if ( offset_type == "evening" ) {
1594 warp = fgTimeSecondsUntilSunAngle( cur_time,
1595 longitude->getDoubleValue()
1596 * SGD_DEGREES_TO_RADIANS,
1597 latitude->getDoubleValue()
1598 * SGD_DEGREES_TO_RADIANS,
1600 } else if ( offset_type == "midnight" ) {
1601 warp = fgTimeSecondsUntilSunAngle( cur_time,
1602 longitude->getDoubleValue()
1603 * SGD_DEGREES_TO_RADIANS,
1604 latitude->getDoubleValue()
1605 * SGD_DEGREES_TO_RADIANS,
1607 } else if ( offset_type == "system-offset" ) {
1610 } else if ( offset_type == "gmt-offset" ) {
1611 warp = offset - (currGMT - systemLocalTime);
1613 } else if ( offset_type == "latitude-offset" ) {
1614 warp = offset - (aircraftLocalTime - systemLocalTime);
1616 } else if ( offset_type == "system" ) {
1617 warp = offset - (systemLocalTime - currGMT) - cur_time;
1618 } else if ( offset_type == "gmt" ) {
1619 warp = offset - cur_time;
1620 } else if ( offset_type == "latitude" ) {
1621 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1623 SG_LOG( SG_GENERAL, SG_ALERT,
1624 "FG_TIME::Unsupported offset type " << offset_type );
1627 globals->set_warp( orig_warp + warp );
1628 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1629 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1630 cur_time_override->getLongValue(),
1631 globals->get_warp() );
1633 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1634 << globals->get_warp() );
1638 // This is the top level init routine which calls all the other
1639 // initialization routines. If you are adding a subsystem to flight
1640 // gear, its initialization call should located in this routine.
1641 // Returns non-zero if a problem encountered.
1642 bool fgInitSubsystems() {
1643 // static const SGPropertyNode *longitude
1644 // = fgGetNode("/sim/presets/longitude-deg");
1645 // static const SGPropertyNode *latitude
1646 // = fgGetNode("/sim/presets/latitude-deg");
1647 // static const SGPropertyNode *altitude
1648 // = fgGetNode("/sim/presets/altitude-ft");
1649 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1650 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1652 ////////////////////////////////////////////////////////////////////
1653 // Initialize the event manager subsystem.
1654 ////////////////////////////////////////////////////////////////////
1656 globals->get_event_mgr()->init();
1657 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1659 ////////////////////////////////////////////////////////////////////
1660 // Initialize the property interpolator subsystem. Put into the INIT
1661 // group because the "nasal" subsystem may need it at GENERAL take-down.
1662 ////////////////////////////////////////////////////////////////////
1663 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1666 ////////////////////////////////////////////////////////////////////
1667 // Add the FlightGear property utilities.
1668 ////////////////////////////////////////////////////////////////////
1669 globals->add_subsystem("properties", new FGProperties);
1671 ////////////////////////////////////////////////////////////////////
1672 // Initialize the material property subsystem.
1673 ////////////////////////////////////////////////////////////////////
1675 SGPath mpath( globals->get_fg_root() );
1676 mpath.append( "materials.xml" );
1677 string season = fgGetString("/sim/startup/season", "summer");
1678 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str(),
1679 globals->get_props()) ) {
1680 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1685 ////////////////////////////////////////////////////////////////////
1686 // Initialize the scenery management subsystem.
1687 ////////////////////////////////////////////////////////////////////
1689 if ( globals->get_tile_mgr()->init() ) {
1690 // Load the local scenery data
1691 double visibility_meters = fgGetDouble("/environment/visibility-m");
1693 globals->get_tile_mgr()->update( visibility_meters );
1695 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1699 globals->get_scenery()->get_scene_graph()
1700 ->addChild(simgear::Particles::getCommonRoot());
1702 ////////////////////////////////////////////////////////////////////
1703 // Initialize the flight model subsystem.
1704 ////////////////////////////////////////////////////////////////////
1708 // allocates structures so must happen before any of the flight
1709 // model or control parameters are set
1710 fgAircraftInit(); // In the future this might not be the case.
1713 ////////////////////////////////////////////////////////////////////
1714 // Initialize the weather subsystem.
1715 ////////////////////////////////////////////////////////////////////
1717 // Initialize the weather modeling subsystem
1718 globals->add_subsystem("environment", new FGEnvironmentMgr);
1721 ////////////////////////////////////////////////////////////////////
1722 // Initialize the aircraft systems and instrumentation (before the
1724 ////////////////////////////////////////////////////////////////////
1726 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1727 globals->add_subsystem("systems", new FGSystemMgr);
1729 ////////////////////////////////////////////////////////////////////
1730 // Initialize the XML Autopilot subsystem.
1731 ////////////////////////////////////////////////////////////////////
1733 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1734 globals->add_subsystem( "route-manager", new FGRouteMgr );
1737 ////////////////////////////////////////////////////////////////////
1738 // Initialize the view manager subsystem.
1739 ////////////////////////////////////////////////////////////////////
1743 ////////////////////////////////////////////////////////////////////
1744 // Create and register the logger.
1745 ////////////////////////////////////////////////////////////////////
1747 globals->add_subsystem("logger", new FGLogger);
1749 ////////////////////////////////////////////////////////////////////
1750 // Create and register the XML GUI.
1751 ////////////////////////////////////////////////////////////////////
1753 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1756 ////////////////////////////////////////////////////////////////////
1757 // Initialize the local time subsystem.
1758 ////////////////////////////////////////////////////////////////////
1760 // update the current timezone each 30 minutes
1761 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1762 &fgUpdateLocalTime, 30*60 );
1763 fgInitTimeOffset(); // the environment subsystem needs this
1766 ////////////////////////////////////////////////////////////////////
1767 // Initialize the lighting subsystem.
1768 ////////////////////////////////////////////////////////////////////
1770 globals->add_subsystem("lighting", new FGLight);
1772 //////////////////////////////////////////////////////////////////////
1773 // Initialize the 2D cloud subsystem.
1774 ////////////////////////////////////////////////////////////////////
1775 fgGetBool("/sim/rendering/bump-mapping", false);
1777 #ifdef ENABLE_AUDIO_SUPPORT
1778 ////////////////////////////////////////////////////////////////////
1779 // Initialize the sound subsystem.
1780 ////////////////////////////////////////////////////////////////////
1782 init_volume = fgGetFloat("/sim/sound/volume");
1783 fgSetFloat("/sim/sound/volume", 0.0f);
1784 globals->set_soundmgr(new SGSoundMgr);
1785 globals->get_soundmgr()->init();
1786 globals->get_soundmgr()->bind();
1789 ////////////////////////////////////////////////////////////////////
1790 // Initialize the sound-effects subsystem.
1791 ////////////////////////////////////////////////////////////////////
1793 globals->add_subsystem("fx", new FGFX);
1794 globals->add_subsystem("voice", new FGVoiceMgr);
1797 ////////////////////////////////////////////////////////////////////
1798 // Initialise the ATC Manager
1799 ////////////////////////////////////////////////////////////////////
1801 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1802 globals->set_ATC_mgr(new FGATCMgr);
1803 globals->get_ATC_mgr()->init();
1805 ////////////////////////////////////////////////////////////////////
1806 // Initialise the AI Manager
1807 ////////////////////////////////////////////////////////////////////
1809 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1810 globals->set_AI_mgr(new FGAIMgr);
1811 globals->get_AI_mgr()->init();
1813 ////////////////////////////////////////////////////////////////////
1814 // Initialise the AI Model Manager
1815 ////////////////////////////////////////////////////////////////////
1816 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1817 globals->add_subsystem("ai_model", new FGAIManager);
1818 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1821 // It's probably a good idea to initialize the top level traffic manager
1822 // After the AI and ATC systems have been initialized properly.
1823 // AI Traffic manager
1824 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1827 ////////////////////////////////////////////////////////////////////
1828 // Initialize the cockpit subsystem
1829 ////////////////////////////////////////////////////////////////////
1830 if( fgCockpitInit( ¤t_aircraft )) {
1831 // Cockpit initialized ok.
1833 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1838 ////////////////////////////////////////////////////////////////////
1839 // Initialize I/O subsystem.
1840 ////////////////////////////////////////////////////////////////////
1842 globals->get_io()->init();
1843 globals->get_io()->bind();
1846 ////////////////////////////////////////////////////////////////////
1847 // Add a new 2D panel.
1848 ////////////////////////////////////////////////////////////////////
1850 string panel_path = fgGetString("/sim/panel/path",
1851 "Panels/Default/default.xml");
1853 globals->set_current_panel( fgReadPanel(panel_path) );
1854 if (globals->get_current_panel() == 0) {
1855 SG_LOG( SG_INPUT, SG_ALERT,
1856 "Error reading new panel from " << panel_path );
1858 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1859 globals->get_current_panel()->init();
1860 globals->get_current_panel()->bind();
1864 ////////////////////////////////////////////////////////////////////
1865 // Initialize the controls subsystem.
1866 ////////////////////////////////////////////////////////////////////
1868 globals->get_controls()->init();
1869 globals->get_controls()->bind();
1872 ////////////////////////////////////////////////////////////////////
1873 // Initialize the input subsystem.
1874 ////////////////////////////////////////////////////////////////////
1876 globals->add_subsystem("input", new FGInput);
1879 ////////////////////////////////////////////////////////////////////
1880 // Initialize the replay subsystem
1881 ////////////////////////////////////////////////////////////////////
1882 globals->add_subsystem("replay", new FGReplay);
1884 ////////////////////////////////////////////////////////////////////
1885 // Bind and initialize subsystems.
1886 ////////////////////////////////////////////////////////////////////
1888 globals->get_subsystem_mgr()->bind();
1889 globals->get_subsystem_mgr()->init();
1891 ////////////////////////////////////////////////////////////////////
1892 // Initialize multiplayer subsystem
1893 ////////////////////////////////////////////////////////////////////
1895 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1896 globals->get_multiplayer_mgr()->init();
1898 ////////////////////////////////////////////////////////////////////////
1899 // Initialize the Nasal interpreter.
1900 // Do this last, so that the loaded scripts see initialized state
1901 ////////////////////////////////////////////////////////////////////////
1902 FGNasalSys* nasal = new FGNasalSys();
1903 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1906 // initialize methods that depend on other subsystems.
1907 globals->get_subsystem_mgr()->postinit();
1909 ////////////////////////////////////////////////////////////////////////
1910 // End of subsystem initialization.
1911 ////////////////////////////////////////////////////////////////////
1913 SG_LOG( SG_GENERAL, SG_INFO, endl);
1915 // Save the initial state for future
1917 globals->saveInitialState();
1923 void fgReInitSubsystems()
1925 // static const SGPropertyNode *longitude
1926 // = fgGetNode("/sim/presets/longitude-deg");
1927 // static const SGPropertyNode *latitude
1928 // = fgGetNode("/sim/presets/latitude-deg");
1929 static const SGPropertyNode *altitude
1930 = fgGetNode("/sim/presets/altitude-ft");
1931 static const SGPropertyNode *master_freeze
1932 = fgGetNode("/sim/freeze/master");
1934 SG_LOG( SG_GENERAL, SG_INFO,
1935 "fgReInitSubsystems(): /position/altitude = "
1936 << altitude->getDoubleValue() );
1938 bool freeze = master_freeze->getBoolValue();
1940 fgSetBool("/sim/freeze/master", true);
1942 fgSetBool("/sim/crashed", false);
1944 // Force reupdating the positions of the ai 3d models. They are used for
1945 // initializing ground level for the FDM.
1946 globals->get_subsystem("ai_model")->reinit();
1948 // Initialize the FDM
1951 // allocates structures so must happen before any of the flight
1952 // model or control parameters are set
1953 fgAircraftInit(); // In the future this might not be the case.
1955 // reload offsets from config defaults
1956 globals->get_viewmgr()->reinit();
1960 globals->get_controls()->reset_all();
1962 fgUpdateLocalTime();
1964 // re-init to proper time of day setting
1968 fgSetBool("/sim/freeze/master", false);
1970 fgSetBool("/sim/sceneryloaded",false);