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., 675 Mass Ave, Cambridge, MA 02139, USA.
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
36 #include <string.h> // strcmp()
39 #if defined( unix ) || defined( __CYGWIN__ )
40 # include <unistd.h> // for gethostname()
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
46 # define _G_NO_EXTERN_TEMPLATES
49 #include <simgear/compiler.h>
53 #include <simgear/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/math/point3d.hxx>
58 #include <simgear/math/polar3d.hxx>
59 #include <simgear/math/sg_geodesy.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/timing/sg_time.hxx>
64 #include <simgear/timing/lowleveltime.h>
66 #include <Aircraft/aircraft.hxx>
67 #include <Aircraft/replay.hxx>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/AIMgr.hxx>
75 #include <Autopilot/auto_gui.hxx>
76 #include <Autopilot/route_mgr.hxx>
77 #include <Autopilot/xmlauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
85 #include <FDM/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/MagicCarpet.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Systems/system_mgr.hxx>
110 #include <Time/light.hxx>
111 #include <Time/sunsolver.hxx>
112 #include <Time/tmp.hxx>
113 #include <Traffic/TrafficMgr.hxx>
116 #include <MultiPlayer/multiplaymgr.hxx>
119 #include <Environment/environment_mgr.hxx>
121 #include "fg_init.hxx"
123 #include "fg_commands.hxx"
124 #include "fg_props.hxx"
125 #include "options.hxx"
126 #include "globals.hxx"
127 #include "logger.hxx"
128 #include "viewmgr.hxx"
131 #if defined(FX) && defined(XMESA)
132 #include <GL/xmesa.h>
135 SG_USING_STD(string);
139 extern const char *default_root;
143 // Scan the command line options for the specified option and return
145 static string fgScanForOption( const string& option, int argc, char **argv ) {
148 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
150 int len = option.length();
153 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
155 string arg = argv[i];
156 if ( arg.find( option ) == 0 ) {
157 return arg.substr( len );
167 // Scan the user config files for the specified option and return
169 static string fgScanForOption( const string& option, const string& path ) {
170 sg_gzifstream in( path );
171 if ( !in.is_open() ) {
175 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
177 int len = option.length();
181 while ( ! in.eof() ) {
184 while ( in.get(c) && c != '\0' ) {
189 #if defined( macintosh )
190 getline( in, line, '\r' );
192 getline( in, line, '\n' );
195 // catch extraneous (DOS) line ending character
196 if ( line[line.length() - 1] < 32 ) {
197 line = line.substr( 0, line.length()-1 );
200 if ( line.find( option ) == 0 ) {
201 return line.substr( len );
211 // Read in configuration (files and command line options) but only set
213 bool fgInitFGRoot ( int argc, char **argv ) {
216 // First parse command line options looking for --fg-root=, this
217 // will override anything specified in a config file
218 root = fgScanForOption( "--fg-root=", argc, argv);
220 if (hostname == NULL)
223 gethostname(_hostname, 256);
224 hostname = strdup(_hostname);
225 free_hostname = true;
228 #if defined( unix ) || defined( __CYGWIN__ )
229 // Next check home directory for .fgfsrc.hostname file
230 if ( root.empty() ) {
231 if ( homedir != NULL ) {
232 SGPath config( homedir );
233 config.append( ".fgfsrc" );
234 config.concat( "." );
235 config.concat( hostname );
236 root = fgScanForOption( "--fg-root=", config.str() );
241 // Next check home directory for .fgfsrc file
242 if ( root.empty() ) {
243 if ( homedir != NULL ) {
244 SGPath config( homedir );
245 config.append( ".fgfsrc" );
246 root = fgScanForOption( "--fg-root=", config.str() );
250 // Next check if fg-root is set as an env variable
251 if ( root.empty() ) {
252 char *envp = ::getenv( "FG_ROOT" );
253 if ( envp != NULL ) {
258 // Otherwise, default to a random compiled-in location if we can't
259 // find fg-root any other way.
260 if ( root.empty() ) {
261 #if defined( __CYGWIN__ )
262 root = "/FlightGear";
263 #elif defined( WIN32 )
264 root = "\\FlightGear";
265 #elif defined(OSX_BUNDLE)
266 /* the following code looks for the base package directly inside
267 the application bundle. This can be changed fairly easily by
268 fiddling with the code below. And yes, I know it's ugly and verbose.
270 CFBundleRef appBundle = CFBundleGetMainBundle();
271 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
272 CFRelease(appBundle);
274 // look for a 'data' subdir directly inside the bundle : is there
275 // a better place? maybe in Resources? I don't know ...
276 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
278 // now convert down to a path, and the a c-string
279 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
280 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
283 CFRelease(appBundle);
291 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
292 globals->set_fg_root(root);
298 // Read in configuration (files and command line options) but only set
300 bool fgInitFGAircraft ( int argc, char **argv ) {
304 // First parse command line options looking for --aircraft=, this
305 // will override anything specified in a config file
306 aircraft = fgScanForOption( "--aircraft=", argc, argv );
308 #if defined( unix ) || defined( __CYGWIN__ )
309 // Next check home directory for .fgfsrc.hostname file
310 if ( aircraft.empty() ) {
311 if ( homedir != NULL ) {
312 SGPath config( homedir );
313 config.append( ".fgfsrc" );
314 config.concat( "." );
315 config.concat( hostname );
316 aircraft = fgScanForOption( "--aircraft=", config.str() );
321 // Next check home directory for .fgfsrc file
322 if ( aircraft.empty() ) {
323 if ( homedir != NULL ) {
324 SGPath config( homedir );
325 config.append( ".fgfsrc" );
326 aircraft = fgScanForOption( "--aircraft=", config.str() );
330 if ( aircraft.empty() ) {
331 // Check for $fg_root/system.fgfsrc
332 SGPath sysconf( globals->get_fg_root() );
333 sysconf.append( "system.fgfsrc" );
334 aircraft = fgScanForOption( "--aircraft=", sysconf.str() );
336 // if an aircraft was specified, set the property name
337 if ( !aircraft.empty() ) {
338 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
339 fgSetString("/sim/aircraft", aircraft.c_str() );
341 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
348 // Return the current base package version
349 string fgBasePackageVersion() {
350 SGPath base_path( globals->get_fg_root() );
351 base_path.append("version");
353 sg_gzifstream in( base_path.str() );
354 if ( !in.is_open() ) {
355 SGPath old_path( globals->get_fg_root() );
356 old_path.append( "Thanks" );
357 sg_gzifstream old( old_path.str() );
358 if ( !old.is_open() ) {
361 return "[old version]";
372 // Initialize the localization
373 SGPropertyNode *fgInitLocale(const char *language) {
374 SGPropertyNode *c_node = NULL, *d_node = NULL;
375 SGPropertyNode *intl = fgGetNode("/sim/intl");
377 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
379 // localization not defined
384 // Select the proper language from the list
386 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
387 for (unsigned int i = 0; i < locale.size(); i++) {
389 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
390 for (unsigned int j = 0; j < lang.size(); j++) {
392 if (!strcmp(lang[j]->getStringValue(), language)) {
401 d_node = intl->getChild("locale");
405 // Check for localized font
406 SGPropertyNode *font_n = c_node->getNode("font", true);
407 if ( !strcmp(font_n->getStringValue(), "") )
408 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
412 // Load the default strings
414 SGPath d_path( globals->get_fg_root() );
416 const char *d_path_str = d_node->getStringValue("strings");
418 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
422 d_path.append(d_path_str);
423 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
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, "Incorrect path in configuration file.");
446 c_path.append(c_path_str);
447 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
451 readProperties(c_path.str(), strings);
452 } catch (const sg_exception &e) {
453 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
463 // Initialize the localization routines
464 bool fgDetectLanguage() {
465 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 ) {
523 ulDir *dirp = ulOpenDir(path.str().c_str());
525 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
529 while ((dire = ulReadDir(dirp)) != NULL) {
531 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
532 && strcmp("..", dire->d_name) )
535 next.append(dire->d_name);
537 string result = fgFindAircraftPath( next, aircraft );
538 if ( ! result.empty() ) {
542 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
553 // Read in configuration (file and command line)
554 bool fgInitConfig ( int argc, char **argv ) {
556 // First, set some sane default values
559 // Read global preferences from $FG_ROOT/preferences.xml
560 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
561 fgLoadProps("preferences.xml", globals->get_props());
562 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
564 // Detect the required language as early as possible
565 if ( !fgDetectLanguage() ) {
569 // Scan user config files and command line for a specified aircraft.
570 fgInitFGAircraft(argc, argv);
572 string aircraft = fgGetString( "/sim/aircraft", "" );
573 if ( aircraft.size() > 0 ) {
574 SGPath aircraft_search( globals->get_fg_root() );
575 aircraft_search.append( "Aircraft" );
577 string aircraft_set = aircraft + "-set.xml";
579 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
580 if ( !result.empty() ) {
581 fgSetString( "/sim/aircraft-dir", result.c_str() );
582 SGPath full_name( result );
583 full_name.append( aircraft_set );
585 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
586 << " from " << full_name.str());
588 readProperties( full_name.str(), globals->get_props() );
589 } catch ( const sg_exception &e ) {
590 string message = "Error reading default aircraft: ";
591 message += e.getFormattedMessage();
592 SG_LOG(SG_INPUT, SG_ALERT, message);
596 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
602 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
606 char *envp = ::getenv( "APPDATA" );
608 SGPath config( env );
609 config.append( "flightgear.org" );
611 if ( homedir != NULL ) {
612 SGPath config( homedir );
613 config.append( ".fgfs" );
615 config.append( "preferences.xml" );
616 SG_LOG(SG_INPUT, SG_INFO, "Reading user preferences");
618 fgLoadProps(config.str().c_str(), globals->get_props(), false,
619 SGPropertyNode::USERARCHIVE);
621 SG_LOG(SG_INPUT, SG_BULK, "First time reading user preferences.");
623 SG_LOG(SG_INPUT, SG_BULK, "Finished Reading user preferences");
626 // parse options after loading aircraft to ensure any user
627 // overrides of defaults are honored.
628 do_options(argc, argv);
634 // find basic airport location info from airport database
635 bool fgFindAirportID( const string& id, FGAirport *a ) {
636 const FGAirport* result;
638 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
640 result = globals->get_airports()->search( id );
642 if ( result == NULL ) {
643 SG_LOG( SG_GENERAL, SG_ALERT,
644 "Failed to find " << id << " in apt.dat.gz" );
653 SG_LOG( SG_GENERAL, SG_INFO,
654 "Position for " << id << " is ("
655 << a->getLongitude() << ", "
656 << a->getLatitude() << ")" );
662 // get airport elevation
663 static double fgGetAirportElev( const string& id ) {
667 SG_LOG( SG_GENERAL, SG_INFO,
668 "Finding elevation for airport: " << id );
670 if ( fgFindAirportID( id, &a ) ) {
671 return a.getElevation();
680 // This function is never used, but maybe useful in the future ???
683 // Preset lon/lat given an airport id
684 static bool fgSetPosFromAirportID( const string& id ) {
688 SG_LOG( SG_GENERAL, SG_INFO,
689 "Attempting to set starting position from airport code " << id );
691 if ( fgFindAirportID( id, &a ) ) {
693 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
694 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
696 // other code depends on the actual postition being set so set
698 fgSetDouble("/position/longitude-deg", a.longitude );
699 fgSetDouble("/position/latitude-deg", a.latitude );
701 SG_LOG( SG_GENERAL, SG_INFO,
702 "Position for " << id << " is (" << a.longitude
703 << ", " << a.latitude << ")" );
713 // Set current tower position lon/lat given an airport id
714 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
716 // tower height hard coded for now...
717 float towerheight=50.0f;
719 // make a little off the heading for 1 runway airports...
720 float fudge_lon = fabs(sin(hdg)) * .003f;
721 float fudge_lat = .003f - fudge_lon;
723 if ( fgFindAirportID( id, &a ) ) {
724 fgSetDouble("/sim/tower/longitude-deg", a.getLongitude() + fudge_lon);
725 fgSetDouble("/sim/tower/latitude-deg", a.getLatitude() + fudge_lat);
726 fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
734 struct FGTowerLocationListener : SGPropertyChangeListener {
735 void valueChanged(SGPropertyNode* node) {
736 const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
737 const string id(node->getStringValue());
738 fgSetTowerPosFromAirportID(id, hdg);
742 static void fgInitTowerLocationListener() {
743 fgGetNode("/sim/tower/airport-id", true)
744 ->addChangeListener( new FGTowerLocationListener() );
747 // Set current_options lon/lat given an airport id and heading (degrees)
748 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
752 // set initial position from runway and heading
754 SG_LOG( SG_GENERAL, SG_INFO,
755 "Attempting to set starting position from airport code "
756 << id << " heading " << tgt_hdg );
758 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
759 SG_LOG( SG_GENERAL, SG_ALERT,
760 "Failed to find a good runway for " << id << '\n' );
767 double lat2, lon2, az2;
768 double heading = r._heading;
769 double azimuth = heading + 180.0;
770 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
772 SG_LOG( SG_GENERAL, SG_INFO,
773 "runway = " << r._lon << ", " << r._lat
774 << " length = " << r._length * SG_FEET_TO_METER
775 << " heading = " << azimuth );
777 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
778 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
779 &lat2, &lon2, &az2 );
781 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
783 double odist = fgGetDouble("/sim/presets/offset-distance");
784 odist *= SG_NM_TO_METER;
785 double oaz = azimuth;
786 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
787 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
790 while ( oaz >= 360.0 ) { oaz -= 360.0; }
791 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
797 fgSetDouble("/sim/presets/longitude-deg", lon2 );
798 fgSetDouble("/sim/presets/latitude-deg", lat2 );
799 fgSetDouble("/sim/presets/heading-deg", heading );
801 // other code depends on the actual values being set ...
802 fgSetDouble("/position/longitude-deg", lon2 );
803 fgSetDouble("/position/latitude-deg", lat2 );
804 fgSetDouble("/orientation/heading-deg", heading );
806 SG_LOG( SG_GENERAL, SG_INFO,
807 "Position for " << id << " is ("
809 << lat2 << ") new heading is "
816 // Set current_options lon/lat given an airport id and runway number
817 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
821 // set initial position from airport and runway number
823 SG_LOG( SG_GENERAL, SG_INFO,
824 "Attempting to set starting position for "
825 << id << ":" << rwy );
827 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
828 SG_LOG( SG_GENERAL, SG_ALERT,
829 "Failed to find runway " << rwy <<
830 " at airport " << id );
837 double lat2, lon2, az2;
838 double heading = r._heading;
839 double azimuth = heading + 180.0;
840 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
842 SG_LOG( SG_GENERAL, SG_INFO,
843 "runway = " << r._lon << ", " << r._lat
844 << " length = " << r._length * SG_FEET_TO_METER
845 << " heading = " << azimuth );
847 geo_direct_wgs_84 ( 0, r._lat, r._lon,
849 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
850 &lat2, &lon2, &az2 );
852 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
855 double odist = fgGetDouble("/sim/presets/offset-distance");
856 odist *= SG_NM_TO_METER;
857 double oaz = azimuth;
858 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
860 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
861 heading = fgGetDouble("/sim/presets/heading-deg");
863 while ( oaz >= 360.0 ) { oaz -= 360.0; }
864 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
870 fgSetDouble("/sim/presets/longitude-deg", lon2 );
871 fgSetDouble("/sim/presets/latitude-deg", lat2 );
872 fgSetDouble("/sim/presets/heading-deg", heading );
874 // other code depends on the actual values being set ...
875 fgSetDouble("/position/longitude-deg", lon2 );
876 fgSetDouble("/position/latitude-deg", lat2 );
877 fgSetDouble("/orientation/heading-deg", heading );
879 SG_LOG( SG_GENERAL, SG_INFO,
880 "Position for " << id << " is ("
882 << lat2 << ") new heading is "
889 static void fgSetDistOrAltFromGlideSlope() {
890 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
891 string apt_id = fgGetString("/sim/presets/airport-id");
892 double gs = fgGetDouble("/sim/presets/glideslope-deg")
893 * SG_DEGREES_TO_RADIANS ;
894 double od = fgGetDouble("/sim/presets/offset-distance");
895 double alt = fgGetDouble("/sim/presets/altitude-ft");
897 double apt_elev = 0.0;
898 if ( ! apt_id.empty() ) {
899 apt_elev = fgGetAirportElev( apt_id );
900 if ( apt_elev < -9990.0 ) {
907 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
908 // set altitude from glideslope and offset-distance
909 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
910 alt = fabs(od*tan(gs)) + apt_elev;
911 fgSetDouble("/sim/presets/altitude-ft", alt);
912 fgSetBool("/sim/presets/onground", false);
913 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
915 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
916 // set offset-distance from glideslope and altitude
917 od = (alt - apt_elev) / tan(gs);
918 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
919 fgSetDouble("/sim/presets/offset-distance", od);
920 fgSetBool("/sim/presets/onground", false);
921 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
923 } else if( fabs(gs) > 0.01 ) {
924 SG_LOG( SG_GENERAL, SG_ALERT,
925 "Glideslope given but not altitude or offset-distance." );
926 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
927 fgSetDouble("/sim/presets/glideslope-deg", 0);
928 fgSetBool("/sim/presets/onground", true);
933 // Set current_options lon/lat given an airport id and heading (degrees)
934 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
936 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
938 // set initial position from runway and heading
940 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
941 << id << ":" << freq );
943 double lon = nav->get_lon();
944 double lat = nav->get_lat();
946 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
948 double odist = fgGetDouble("/sim/presets/offset-distance")
950 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
952 while ( oaz >= 360.0 ) { oaz -= 360.0; }
953 double olat, olon, az2;
954 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
961 fgSetDouble("/sim/presets/longitude-deg", lon );
962 fgSetDouble("/sim/presets/latitude-deg", lat );
964 // other code depends on the actual values being set ...
965 fgSetDouble("/position/longitude-deg", lon );
966 fgSetDouble("/position/latitude-deg", lat );
967 fgSetDouble("/orientation/heading-deg",
968 fgGetDouble("/sim/presets/heading-deg") );
970 SG_LOG( SG_GENERAL, SG_INFO,
971 "Position for " << id << ":" << freq << " is ("
972 << lon << ", "<< lat << ")" );
976 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
977 << id << ":" << freq );
982 // Set current_options lon/lat given an aircraft carrier id
983 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
985 // set initial position from runway and heading
989 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
990 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
991 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
992 double alt = geodPos.elev() * SG_METER_TO_FEET;
994 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
995 << carrier << " at lat = " << lat << ", lon = " << lon
996 << ", alt = " << alt << ", heading = " << heading);
998 fgSetDouble("/sim/presets/longitude-deg", lon);
999 fgSetDouble("/sim/presets/latitude-deg", lat);
1000 fgSetDouble("/sim/presets/altitude-ft", alt);
1001 fgSetDouble("/sim/presets/heading-deg", heading);
1002 fgSetDouble("/position/longitude-deg", lon);
1003 fgSetDouble("/position/latitude-deg", lat);
1004 fgSetDouble("/position/altitude-ft", alt);
1005 fgSetDouble("/orientation/heading-deg", heading);
1007 fgSetString("/sim/presets/speed-set", "UVW");
1008 fgSetDouble("/velocities/uBody-fps", uvw[0]);
1009 fgSetDouble("/velocities/vBody-fps", uvw[1]);
1010 fgSetDouble("/velocities/wBody-fps", uvw[2]);
1011 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
1012 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
1013 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
1015 fgSetBool("/sim/presets/onground", true);
1019 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1025 // Set current_options lon/lat given an airport id and heading (degrees)
1026 static bool fgSetPosFromFix( const string& id ) {
1029 // set initial position from runway and heading
1030 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1031 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1034 double lon = fix.get_lon();
1035 double lat = fix.get_lat();
1037 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1039 double odist = fgGetDouble("/sim/presets/offset-distance")
1041 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1043 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1044 double olat, olon, az2;
1045 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1052 fgSetDouble("/sim/presets/longitude-deg", lon );
1053 fgSetDouble("/sim/presets/latitude-deg", lat );
1055 // other code depends on the actual values being set ...
1056 fgSetDouble("/position/longitude-deg", lon );
1057 fgSetDouble("/position/latitude-deg", lat );
1058 fgSetDouble("/orientation/heading-deg",
1059 fgGetDouble("/sim/presets/heading-deg") );
1061 SG_LOG( SG_GENERAL, SG_INFO,
1062 "Position for " << id << " is ("
1063 << lon << ", "<< lat << ")" );
1067 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1073 static void parseWaypoints() {
1074 string_list *waypoints = globals->get_initial_waypoints();
1076 vector<string>::iterator i;
1077 for (i = waypoints->begin();
1078 i != waypoints->end();
1083 // Now were done using the way points we can deallocate the
1085 while (waypoints->begin() != waypoints->end()) {
1086 waypoints->pop_back();
1089 globals->set_initial_waypoints(0);
1098 * Initialize vor/ndb/ils/fix list management and query systems (as
1099 * well as simple airport db list)
1104 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1106 SGPath aptdb( globals->get_fg_root() );
1107 aptdb.append( "Airports/apt.dat" );
1109 SGPath p_metar( globals->get_fg_root() );
1110 p_metar.append( "Airports/metar.dat" );
1112 FGAirportList *airports = new FGAirportList();
1113 globals->set_airports( airports );
1114 FGRunwayList *runways = new FGRunwayList();
1115 globals->set_runways( runways );
1117 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1119 FGNavList *navlist = new FGNavList;
1120 FGNavList *loclist = new FGNavList;
1121 FGNavList *gslist = new FGNavList;
1122 FGNavList *dmelist = new FGNavList;
1123 FGNavList *mkrlist = new FGNavList;
1124 FGNavList *tacanlist = new FGNavList;
1125 FGNavList *carrierlist = new FGNavList;
1126 FGTACANList *channellist = new FGTACANList;
1128 globals->set_navlist( navlist );
1129 globals->set_loclist( loclist );
1130 globals->set_gslist( gslist );
1131 globals->set_dmelist( dmelist );
1132 globals->set_mkrlist( mkrlist );
1133 globals->set_tacanlist( tacanlist );
1134 globals->set_carrierlist( carrierlist );
1135 globals->set_channellist( channellist );
1137 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1138 SG_LOG( SG_GENERAL, SG_ALERT,
1139 "Problems loading one or more navigational database" );
1142 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1143 // align all the localizers with their corresponding runways
1144 // since data sources are good for cockpit navigation
1145 // purposes, but not always to the error tolerances needed to
1146 // exactly place these items.
1148 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1150 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1153 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1154 SGPath p_fix( globals->get_fg_root() );
1155 p_fix.append( "Navaids/fix.dat" );
1156 FGFixList *fixlist = new FGFixList;
1157 fixlist->init( p_fix );
1158 globals->set_fixlist( fixlist );
1164 // Set the initial position based on presets (or defaults)
1165 bool fgInitPosition() {
1166 // cout << "fgInitPosition()" << endl;
1167 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1168 * SG_DEGREES_TO_RADIANS ;
1169 double od = fgGetDouble("/sim/presets/offset-distance");
1170 double alt = fgGetDouble("/sim/presets/altitude-ft");
1172 bool set_pos = false;
1174 // If glideslope is specified, then calculate offset-distance or
1175 // altitude relative to glide slope if either of those was not
1177 if ( fabs( gs ) > 0.01 ) {
1178 fgSetDistOrAltFromGlideSlope();
1182 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1183 // If not, check for an airport-id and use that.
1184 // If not, default to the middle of the KSFO field.
1185 // The default values for lon/lat are deliberately out of range
1186 // so that the airport-id can take effect; valid lon/lat will
1187 // override airport-id, however.
1188 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1189 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1190 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1191 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1196 string apt = fgGetString("/sim/presets/airport-id");
1197 string rwy_no = fgGetString("/sim/presets/runway");
1198 double hdg = fgGetDouble("/sim/presets/heading-deg");
1199 string vor = fgGetString("/sim/presets/vor-id");
1200 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1201 string ndb = fgGetString("/sim/presets/ndb-id");
1202 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1203 string carrier = fgGetString("/sim/presets/carrier");
1204 string parkpos = fgGetString("/sim/presets/parkpos");
1205 string fix = fgGetString("/sim/presets/fix");
1207 fgSetDouble( "/orientation/heading-deg", hdg );
1208 fgInitTowerLocationListener();
1210 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1211 // An airport + runway is requested
1212 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1213 // set tower position (a little off the heading for single
1215 fgSetString("/sim/tower/airport-id", apt.c_str());
1220 if ( !set_pos && !apt.empty() ) {
1221 // An airport is requested (find runway closest to hdg)
1222 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1223 // set tower position (a little off the heading for single
1225 fgSetString("/sim/tower/airport-id", apt.c_str());
1230 if ( !set_pos && !vor.empty() ) {
1231 // a VOR is requested
1232 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1237 if ( !set_pos && !ndb.empty() ) {
1238 // an NDB is requested
1239 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1244 if ( !set_pos && !carrier.empty() ) {
1245 // an aircraft carrier is requested
1246 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1251 if ( !set_pos && !fix.empty() ) {
1252 // a Fix is requested
1253 if ( fgSetPosFromFix( fix ) ) {
1259 // No lon/lat specified, no airport specified, default to
1260 // middle of KSFO field.
1261 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1262 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1265 fgSetDouble( "/position/longitude-deg",
1266 fgGetDouble("/sim/presets/longitude-deg") );
1267 fgSetDouble( "/position/latitude-deg",
1268 fgGetDouble("/sim/presets/latitude-deg") );
1270 // determine if this should be an on-ground or in-air start
1271 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1272 fgSetBool("/sim/presets/onground", false);
1274 fgSetBool("/sim/presets/onground", true);
1281 // General house keeping initializations
1282 bool fgInitGeneral() {
1285 #if defined(FX) && defined(XMESA)
1286 char *mesa_win_state;
1289 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1290 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1292 root = globals->get_fg_root();
1293 if ( ! root.length() ) {
1294 // No root path set? Then bail ...
1295 SG_LOG( SG_GENERAL, SG_ALERT,
1296 "Cannot continue without a path to the base package "
1297 << "being defined." );
1300 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1302 #if defined(FX) && defined(XMESA)
1303 // initialize full screen flag
1304 globals->set_fullscreen(false);
1305 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1306 // Test for the MESA_GLX_FX env variable
1307 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1308 // test if we are fullscreen mesa/glide
1309 if ( (mesa_win_state[0] == 'f') ||
1310 (mesa_win_state[0] == 'F') ) {
1311 globals->set_fullscreen(true);
1321 // Initialize the flight model subsystem. This just creates the
1322 // object. The actual fdm initialization is delayed until we get a
1323 // proper scenery elevation hit. This is checked for in main.cxx
1327 if ( cur_fdm_state ) {
1328 delete cur_fdm_state;
1332 double dt = 1.0 / fgGetInt("/sim/model-hz");
1333 string model = fgGetString("/sim/flight-model");
1336 if ( model == "larcsim" ) {
1337 cur_fdm_state = new FGLaRCsim( dt );
1338 } else if ( model == "jsb" ) {
1339 cur_fdm_state = new FGJSBsim( dt );
1341 } else if ( model == "ada" ) {
1342 cur_fdm_state = new FGADA( dt );
1343 } else if ( model == "acms" ) {
1344 cur_fdm_state = new FGACMS( dt );
1346 } else if ( model == "balloon" ) {
1347 cur_fdm_state = new FGBalloonSim( dt );
1348 } else if ( model == "magic" ) {
1349 cur_fdm_state = new FGMagicCarpet( dt );
1350 } else if ( model == "ufo" ) {
1351 cur_fdm_state = new FGUFO( dt );
1352 } else if ( model == "external" ) {
1353 // external is a synonym for "--fdm=null" and is
1354 // maintained here for backwards compatibility
1355 cur_fdm_state = new FGNullFDM( dt );
1356 } else if ( model.find("network") == 0 ) {
1357 string host = "localhost";
1361 string net_options = model.substr(8);
1362 string::size_type begin, end;
1365 end = net_options.find( ",", begin );
1366 if ( end != string::npos ) {
1367 host = net_options.substr(begin, end - begin);
1371 end = net_options.find( ",", begin );
1372 if ( end != string::npos ) {
1373 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1377 end = net_options.find( ",", begin );
1378 if ( end != string::npos ) {
1379 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1383 end = net_options.find( ",", begin );
1384 if ( end != string::npos ) {
1385 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1388 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1389 } else if ( model.find("pipe") == 0 ) {
1390 // /* old */ string pipe_path = model.substr(5);
1391 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1392 string pipe_path = "";
1393 string pipe_protocol = "";
1394 string pipe_options = model.substr(5);
1395 string::size_type begin, end;
1398 end = pipe_options.find( ",", begin );
1399 if ( end != string::npos ) {
1400 pipe_path = pipe_options.substr(begin, end - begin);
1403 // protocol (last option)
1404 pipe_protocol = pipe_options.substr(begin);
1405 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1406 } else if ( model == "null" ) {
1407 cur_fdm_state = new FGNullFDM( dt );
1408 } else if ( model == "yasim" ) {
1409 cur_fdm_state = new YASim( dt );
1411 SG_LOG(SG_GENERAL, SG_ALERT,
1412 "Unrecognized flight model '" << model
1413 << "', cannot init flight dynamics model.");
1417 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1422 static void printMat(const sgVec4 *mat, char *name="")
1425 SG_LOG(SG_GENERAL, SG_BULK, name );
1426 for(i=0; i<4; i++) {
1427 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1428 << " " << mat[i][2] << " " << mat[i][3] );
1432 // Initialize view parameters
1434 // force update of model so that viewer can get some data...
1435 globals->get_aircraft_model()->update(0);
1436 // run update for current view so that data is current...
1437 globals->get_viewmgr()->update(0);
1439 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1440 printMat(globals->get_current_view()->get_UP(),"UP");
1441 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1446 SGTime *fgInitTime() {
1448 static const SGPropertyNode *longitude
1449 = fgGetNode("/position/longitude-deg");
1450 static const SGPropertyNode *latitude
1451 = fgGetNode("/position/latitude-deg");
1452 static const SGPropertyNode *cur_time_override
1453 = fgGetNode("/sim/time/cur-time-override", true);
1455 SGPath zone( globals->get_fg_root() );
1456 zone.append( "Timezone" );
1457 SGTime *t = new SGTime( longitude->getDoubleValue()
1458 * SGD_DEGREES_TO_RADIANS,
1459 latitude->getDoubleValue()
1460 * SGD_DEGREES_TO_RADIANS,
1462 cur_time_override->getLongValue() );
1464 globals->set_warp_delta( 0 );
1466 t->update( 0.0, 0.0,
1467 cur_time_override->getLongValue(),
1468 globals->get_warp() );
1474 // set up a time offset (aka warp) if one is specified
1475 void fgInitTimeOffset() {
1476 static const SGPropertyNode *longitude
1477 = fgGetNode("/position/longitude-deg");
1478 static const SGPropertyNode *latitude
1479 = fgGetNode("/position/latitude-deg");
1480 static const SGPropertyNode *cur_time_override
1481 = fgGetNode("/sim/time/cur-time-override", true);
1483 // Handle potential user specified time offsets
1484 int orig_warp = globals->get_warp();
1485 SGTime *t = globals->get_time_params();
1486 time_t cur_time = t->get_cur_time();
1487 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1488 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1489 time_t aircraftLocalTime =
1490 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1492 // Okay, we now have several possible scenarios
1493 int offset = fgGetInt("/sim/startup/time-offset");
1494 string offset_type = fgGetString("/sim/startup/time-offset-type");
1497 if ( offset_type == "real" ) {
1499 } else if ( offset_type == "dawn" ) {
1500 warp = fgTimeSecondsUntilSunAngle( cur_time,
1501 longitude->getDoubleValue()
1502 * SGD_DEGREES_TO_RADIANS,
1503 latitude->getDoubleValue()
1504 * SGD_DEGREES_TO_RADIANS,
1506 } else if ( offset_type == "morning" ) {
1507 warp = fgTimeSecondsUntilSunAngle( cur_time,
1508 longitude->getDoubleValue()
1509 * SGD_DEGREES_TO_RADIANS,
1510 latitude->getDoubleValue()
1511 * SGD_DEGREES_TO_RADIANS,
1513 } else if ( offset_type == "noon" ) {
1514 warp = fgTimeSecondsUntilSunAngle( cur_time,
1515 longitude->getDoubleValue()
1516 * SGD_DEGREES_TO_RADIANS,
1517 latitude->getDoubleValue()
1518 * SGD_DEGREES_TO_RADIANS,
1520 } else if ( offset_type == "afternoon" ) {
1521 warp = fgTimeSecondsUntilSunAngle( cur_time,
1522 longitude->getDoubleValue()
1523 * SGD_DEGREES_TO_RADIANS,
1524 latitude->getDoubleValue()
1525 * SGD_DEGREES_TO_RADIANS,
1527 } else if ( offset_type == "dusk" ) {
1528 warp = fgTimeSecondsUntilSunAngle( cur_time,
1529 longitude->getDoubleValue()
1530 * SGD_DEGREES_TO_RADIANS,
1531 latitude->getDoubleValue()
1532 * SGD_DEGREES_TO_RADIANS,
1534 } else if ( offset_type == "evening" ) {
1535 warp = fgTimeSecondsUntilSunAngle( cur_time,
1536 longitude->getDoubleValue()
1537 * SGD_DEGREES_TO_RADIANS,
1538 latitude->getDoubleValue()
1539 * SGD_DEGREES_TO_RADIANS,
1541 } else if ( offset_type == "midnight" ) {
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 == "system-offset" ) {
1550 } else if ( offset_type == "gmt-offset" ) {
1551 warp = offset - (currGMT - systemLocalTime);
1552 } else if ( offset_type == "latitude-offset" ) {
1553 warp = offset - (aircraftLocalTime - systemLocalTime);
1554 } else if ( offset_type == "system" ) {
1555 warp = offset - cur_time;
1556 } else if ( offset_type == "gmt" ) {
1557 warp = offset - currGMT;
1558 } else if ( offset_type == "latitude" ) {
1559 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1561 SG_LOG( SG_GENERAL, SG_ALERT,
1562 "FG_TIME::Unsupported offset type " << offset_type );
1565 globals->set_warp( orig_warp + warp );
1566 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1567 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1568 cur_time_override->getLongValue(),
1569 globals->get_warp() );
1571 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1572 << globals->get_warp() );
1576 // This is the top level init routine which calls all the other
1577 // initialization routines. If you are adding a subsystem to flight
1578 // gear, its initialization call should located in this routine.
1579 // Returns non-zero if a problem encountered.
1580 bool fgInitSubsystems() {
1581 // static const SGPropertyNode *longitude
1582 // = fgGetNode("/sim/presets/longitude-deg");
1583 // static const SGPropertyNode *latitude
1584 // = fgGetNode("/sim/presets/latitude-deg");
1585 // static const SGPropertyNode *altitude
1586 // = fgGetNode("/sim/presets/altitude-ft");
1588 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1589 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1591 ////////////////////////////////////////////////////////////////////
1592 // Initialize the event manager subsystem.
1593 ////////////////////////////////////////////////////////////////////
1595 globals->get_event_mgr()->init();
1596 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1598 ////////////////////////////////////////////////////////////////////
1599 // Initialize the property interpolator subsystem
1600 ////////////////////////////////////////////////////////////////////
1601 globals->add_subsystem("interpolator", new SGInterpolator);
1604 ////////////////////////////////////////////////////////////////////
1605 // Add the FlightGear property utilities.
1606 ////////////////////////////////////////////////////////////////////
1607 globals->add_subsystem("properties", new FGProperties);
1609 ////////////////////////////////////////////////////////////////////
1610 // Initialize the material property subsystem.
1611 ////////////////////////////////////////////////////////////////////
1613 SGPath mpath( globals->get_fg_root() );
1614 mpath.append( "materials.xml" );
1615 string season = fgGetString("/sim/startup/season", "summer");
1616 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1617 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1622 ////////////////////////////////////////////////////////////////////
1623 // Initialize the scenery management subsystem.
1624 ////////////////////////////////////////////////////////////////////
1626 if ( globals->get_tile_mgr()->init() ) {
1627 // Load the local scenery data
1628 double visibility_meters = fgGetDouble("/environment/visibility-m");
1630 globals->get_tile_mgr()->update( visibility_meters );
1632 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1636 // cause refresh of viewer scenery timestamps every 15 seconds...
1637 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1638 globals->get_tile_mgr(),
1639 &FGTileMgr::refresh_view_timestamps,
1643 ////////////////////////////////////////////////////////////////////
1644 // Initialize the flight model subsystem.
1645 ////////////////////////////////////////////////////////////////////
1649 // allocates structures so must happen before any of the flight
1650 // model or control parameters are set
1651 fgAircraftInit(); // In the future this might not be the case.
1654 ////////////////////////////////////////////////////////////////////
1655 // Initialize the XML Autopilot subsystem.
1656 ////////////////////////////////////////////////////////////////////
1658 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1659 globals->add_subsystem( "route-manager", new FGRouteMgr );
1662 ////////////////////////////////////////////////////////////////////
1663 // Initialize the view manager subsystem.
1664 ////////////////////////////////////////////////////////////////////
1668 ////////////////////////////////////////////////////////////////////
1669 // Create and register the logger.
1670 ////////////////////////////////////////////////////////////////////
1672 globals->add_subsystem("logger", new FGLogger);
1674 ////////////////////////////////////////////////////////////////////
1675 // Create and register the XML GUI.
1676 ////////////////////////////////////////////////////////////////////
1678 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1681 ////////////////////////////////////////////////////////////////////
1682 // Initialize the local time subsystem.
1683 ////////////////////////////////////////////////////////////////////
1685 // update the current timezone each 30 minutes
1686 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1687 &fgUpdateLocalTime, 30*60 );
1688 fgInitTimeOffset(); // the environment subsystem needs this
1691 ////////////////////////////////////////////////////////////////////
1692 // Initialize the weather subsystem.
1693 ////////////////////////////////////////////////////////////////////
1695 // Initialize the weather modeling subsystem
1696 globals->add_subsystem("environment", new FGEnvironmentMgr);
1699 ////////////////////////////////////////////////////////////////////
1700 // Initialize the lighting subsystem.
1701 ////////////////////////////////////////////////////////////////////
1703 globals->add_subsystem("lighting", new FGLight);
1705 //////////////////////////////////////////////////////////////////////
1706 // Initialize the 2D cloud subsystem.
1707 ////////////////////////////////////////////////////////////////////
1708 fgGetBool("/sim/rendering/bump-mapping", false);
1710 #ifdef ENABLE_AUDIO_SUPPORT
1711 ////////////////////////////////////////////////////////////////////
1712 // Initialize the sound subsystem.
1713 ////////////////////////////////////////////////////////////////////
1715 init_volume = fgGetFloat("/sim/sound/volume");
1716 fgSetFloat("/sim/sound/volume", 0.0f);
1717 globals->set_soundmgr(new SGSoundMgr);
1718 globals->get_soundmgr()->init();
1719 globals->get_soundmgr()->bind();
1722 ////////////////////////////////////////////////////////////////////
1723 // Initialize the sound-effects subsystem.
1724 ////////////////////////////////////////////////////////////////////
1726 globals->add_subsystem("fx", new FGFX);
1730 ////////////////////////////////////////////////////////////////////
1731 // Initialise ATC display system
1732 ////////////////////////////////////////////////////////////////////
1734 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1735 globals->set_ATC_display(new FGATCDisplay);
1736 globals->get_ATC_display()->init();
1738 ////////////////////////////////////////////////////////////////////
1739 // Initialise the ATC Manager
1740 ////////////////////////////////////////////////////////////////////
1742 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1743 globals->set_ATC_mgr(new FGATCMgr);
1744 globals->get_ATC_mgr()->init();
1746 ////////////////////////////////////////////////////////////////////
1747 // Initialise the AI Manager
1748 ////////////////////////////////////////////////////////////////////
1750 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1751 globals->set_AI_mgr(new FGAIMgr);
1752 globals->get_AI_mgr()->init();
1754 ////////////////////////////////////////////////////////////////////
1755 // Initialise the AI Model Manager
1756 ////////////////////////////////////////////////////////////////////
1757 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1758 globals->add_subsystem("ai_model", new FGAIManager);
1759 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1762 // It's probably a good idea to initialize the top level traffic manager
1763 // After the AI and ATC systems have been initialized properly.
1764 // AI Traffic manager
1765 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1766 FGTrafficManager *dispatcher =
1767 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1768 SGPath path = globals->get_fg_root();
1769 path.append("/Traffic/fgtraffic.xml");
1772 //globals->get_subsystem("Traffic Manager")->init();
1774 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1775 globals->add_subsystem("systems", new FGSystemMgr);
1779 ////////////////////////////////////////////////////////////////////
1780 // Initialize the cockpit subsystem
1781 ////////////////////////////////////////////////////////////////////
1782 if( fgCockpitInit( ¤t_aircraft )) {
1783 // Cockpit initialized ok.
1785 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1790 ////////////////////////////////////////////////////////////////////
1791 // Initialize the autopilot subsystem.
1792 ////////////////////////////////////////////////////////////////////
1794 // FIXME: these should go in the
1795 // GUI initialization code, not here.
1796 // fgAPAdjustInit();
1797 NewTgtAirportInit();
1801 ////////////////////////////////////////////////////////////////////
1802 // Initialize I/O subsystem.
1803 ////////////////////////////////////////////////////////////////////
1805 globals->get_io()->init();
1806 globals->get_io()->bind();
1809 ////////////////////////////////////////////////////////////////////
1810 // Add a new 2D panel.
1811 ////////////////////////////////////////////////////////////////////
1813 string panel_path = fgGetString("/sim/panel/path",
1814 "Panels/Default/default.xml");
1816 globals->set_current_panel( fgReadPanel(panel_path) );
1817 if (globals->get_current_panel() == 0) {
1818 SG_LOG( SG_INPUT, SG_ALERT,
1819 "Error reading new panel from " << panel_path );
1821 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1822 globals->get_current_panel()->init();
1823 globals->get_current_panel()->bind();
1827 ////////////////////////////////////////////////////////////////////
1828 // Initialize the controls subsystem.
1829 ////////////////////////////////////////////////////////////////////
1831 globals->get_controls()->init();
1832 globals->get_controls()->bind();
1835 ////////////////////////////////////////////////////////////////////
1836 // Initialize the input subsystem.
1837 ////////////////////////////////////////////////////////////////////
1839 globals->add_subsystem("input", new FGInput);
1842 ////////////////////////////////////////////////////////////////////
1843 // Initialize the replay subsystem
1844 ////////////////////////////////////////////////////////////////////
1845 globals->add_subsystem("replay", new FGReplay);
1847 ////////////////////////////////////////////////////////////////////
1848 // Bind and initialize subsystems.
1849 ////////////////////////////////////////////////////////////////////
1851 globals->get_subsystem_mgr()->bind();
1852 globals->get_subsystem_mgr()->init();
1854 #ifdef FG_MPLAYER_AS
1855 ////////////////////////////////////////////////////////////////////
1856 // Initialize multiplayer subsystem
1857 ////////////////////////////////////////////////////////////////////
1859 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1860 globals->get_multiplayer_mgr()->init();
1863 ////////////////////////////////////////////////////////////////////////
1864 // Initialize the Nasal interpreter.
1865 // Do this last, so that the loaded scripts see initialized state
1866 ////////////////////////////////////////////////////////////////////////
1867 FGNasalSys* nasal = new FGNasalSys();
1868 globals->add_subsystem("nasal", nasal);
1871 ////////////////////////////////////////////////////////////////////
1872 // At this point we could try and parse the waypoint options
1873 ///////////////////////////////////////////////////////////////////
1876 // initialize methods that depend on other subsystems.
1877 globals->get_subsystem_mgr()->postinit();
1879 ////////////////////////////////////////////////////////////////////////
1880 // End of subsystem initialization.
1881 ////////////////////////////////////////////////////////////////////
1883 SG_LOG( SG_GENERAL, SG_INFO, endl);
1885 // Save the initial state for future
1887 globals->saveInitialState();
1893 void fgReInitSubsystems()
1895 // static const SGPropertyNode *longitude
1896 // = fgGetNode("/sim/presets/longitude-deg");
1897 // static const SGPropertyNode *latitude
1898 // = fgGetNode("/sim/presets/latitude-deg");
1899 static const SGPropertyNode *altitude
1900 = fgGetNode("/sim/presets/altitude-ft");
1901 static const SGPropertyNode *master_freeze
1902 = fgGetNode("/sim/freeze/master");
1904 SG_LOG( SG_GENERAL, SG_INFO,
1905 "fgReInitSubsystems(): /position/altitude = "
1906 << altitude->getDoubleValue() );
1908 bool freeze = master_freeze->getBoolValue();
1910 fgSetBool("/sim/freeze/master", true);
1912 fgSetBool("/sim/crashed", false);
1914 // Force reupdating the positions of the ai 3d models. They are used for
1915 // initializing ground level for the FDM.
1916 globals->get_subsystem("ai_model")->reinit();
1918 // Initialize the FDM
1921 // allocates structures so must happen before any of the flight
1922 // model or control parameters are set
1923 fgAircraftInit(); // In the future this might not be the case.
1925 // reload offsets from config defaults
1926 globals->get_viewmgr()->reinit();
1930 globals->get_controls()->reset_all();
1932 fgUpdateLocalTime();
1934 // re-init to proper time of day setting
1938 fgSetBool("/sim/freeze/master", false);
1940 fgSetBool("/sim/sceneryloaded",false);