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"
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 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
149 int len = option.length();
152 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
154 string arg = argv[i];
155 if ( arg.find( option ) == 0 ) {
156 return arg.substr( len );
166 // Scan the user config files for the specified option and return
168 static string fgScanForOption( const string& option, const string& path ) {
169 sg_gzifstream in( path );
170 if ( !in.is_open() ) {
174 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
176 int len = option.length();
180 while ( ! in.eof() ) {
183 while ( in.get(c) && c != '\0' ) {
188 #if defined( macintosh )
189 getline( in, line, '\r' );
191 getline( in, line, '\n' );
194 // catch extraneous (DOS) line ending character
195 if ( line[line.length() - 1] < 32 ) {
196 line = line.substr( 0, line.length()-1 );
199 if ( line.find( option ) == 0 ) {
200 return line.substr( len );
210 // Read in configuration (files and command line options) but only set
212 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 defined( unix ) || defined( __CYGWIN__ )
221 // Next check home directory for .fgfsrc.hostname file
222 if ( root.empty() ) {
223 envp = ::getenv( "HOME" );
224 if ( envp != NULL ) {
225 SGPath config( envp );
226 config.append( ".fgfsrc" );
228 gethostname( name, 256 );
229 config.concat( "." );
230 config.concat( name );
231 root = fgScanForOption( "--fg-root=", config.str() );
236 // Next check home directory for .fgfsrc file
237 if ( root.empty() ) {
238 envp = ::getenv( "HOME" );
239 if ( envp != NULL ) {
240 SGPath config( envp );
241 config.append( ".fgfsrc" );
242 root = fgScanForOption( "--fg-root=", config.str() );
246 // Next check if fg-root is set as an env variable
247 if ( root.empty() ) {
248 envp = ::getenv( "FG_ROOT" );
249 if ( envp != NULL ) {
254 // Otherwise, default to a random compiled-in location if we can't
255 // find fg-root any other way.
256 if ( root.empty() ) {
257 #if defined( __CYGWIN__ )
258 root = "/FlightGear";
259 #elif defined( WIN32 )
260 root = "\\FlightGear";
261 #elif defined(OSX_BUNDLE)
262 /* the following code looks for the base package directly inside
263 the application bundle. This can be changed fairly easily by
264 fiddling with the code below. And yes, I know it's ugly and verbose.
266 CFBundleRef appBundle = CFBundleGetMainBundle();
267 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
268 CFRelease(appBundle);
270 // look for a 'data' subdir directly inside the bundle : is there
271 // a better place? maybe in Resources? I don't know ...
272 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
274 // now convert down to a path, and the a c-string
275 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
276 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
279 CFRelease(appBundle);
287 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
288 globals->set_fg_root(root);
294 // Read in configuration (files and command line options) but only set
296 bool fgInitFGAircraft ( int argc, char **argv ) {
300 // First parse command line options looking for --aircraft=, this
301 // will override anything specified in a config file
302 aircraft = fgScanForOption( "--aircraft=", argc, argv );
304 #if defined( unix ) || defined( __CYGWIN__ )
305 // Next check home directory for .fgfsrc.hostname file
306 if ( aircraft.empty() ) {
307 envp = ::getenv( "HOME" );
308 if ( envp != NULL ) {
309 SGPath config( envp );
310 config.append( ".fgfsrc" );
312 gethostname( name, 256 );
313 config.concat( "." );
314 config.concat( name );
315 aircraft = fgScanForOption( "--aircraft=", config.str() );
320 // Next check home directory for .fgfsrc file
321 if ( aircraft.empty() ) {
322 envp = ::getenv( "HOME" );
323 if ( envp != NULL ) {
324 SGPath config( envp );
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__ )
497 // Check for $fg_root/system.fgfsrc.hostname
498 gethostname( name, 256 );
499 config.concat( "." );
500 config.concat( name );
501 fgParseOptions(config.str());
504 // Check for ~/.fgfsrc
505 char* envp = ::getenv( "HOME" );
506 if ( envp != NULL ) {
508 config.append( ".fgfsrc" );
509 fgParseOptions(config.str());
512 #if defined( unix ) || defined( __CYGWIN__ )
513 // Check for ~/.fgfsrc.hostname
514 gethostname( name, 256 );
515 config.concat( "." );
516 config.concat( name );
517 fgParseOptions(config.str());
520 // Parse remaining command line options
521 // These will override anything specified in a config file
522 fgParseArgs(argc, argv);
526 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
528 ulDir *dirp = ulOpenDir(path.str().c_str());
530 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
534 while ((dire = ulReadDir(dirp)) != NULL) {
536 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
537 && strcmp("..", dire->d_name) )
540 next.append(dire->d_name);
542 string result = fgFindAircraftPath( next, aircraft );
543 if ( ! result.empty() ) {
547 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
558 // Read in configuration (file and command line)
559 bool fgInitConfig ( int argc, char **argv ) {
561 // First, set some sane default values
564 // Read global preferences from $FG_ROOT/preferences.xml
565 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
566 fgLoadProps("preferences.xml", globals->get_props());
567 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
569 // Detect the required language as early as possible
570 if ( !fgDetectLanguage() ) {
574 // Scan user config files and command line for a specified aircraft.
575 fgInitFGAircraft(argc, argv);
577 string aircraft = fgGetString( "/sim/aircraft", "" );
578 if ( aircraft.size() > 0 ) {
579 SGPath aircraft_search( globals->get_fg_root() );
580 aircraft_search.append( "Aircraft" );
582 string aircraft_set = aircraft + "-set.xml";
584 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
585 if ( !result.empty() ) {
586 fgSetString( "/sim/aircraft-dir", result.c_str() );
587 SGPath full_name( result );
588 full_name.append( aircraft_set );
590 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
591 << " from " << full_name.str());
593 readProperties( full_name.str(), globals->get_props() );
594 } catch ( const sg_exception &e ) {
595 string message = "Error reading default aircraft: ";
596 message += e.getFormattedMessage();
597 SG_LOG(SG_INPUT, SG_ALERT, message);
601 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
607 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
610 // parse options after loading aircraft to ensure any user
611 // overrides of defaults are honored.
612 do_options(argc, argv);
618 // find basic airport location info from airport database
619 bool fgFindAirportID( const string& id, FGAirport *a ) {
620 const FGAirport* result;
622 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
624 result = globals->get_airports()->search( id );
626 if ( result == NULL ) {
627 SG_LOG( SG_GENERAL, SG_ALERT,
628 "Failed to find " << id << " in apt.dat.gz" );
637 SG_LOG( SG_GENERAL, SG_INFO,
638 "Position for " << id << " is ("
639 << a->getLongitude() << ", "
640 << a->getLatitude() << ")" );
646 // get airport elevation
647 static double fgGetAirportElev( const string& id ) {
651 SG_LOG( SG_GENERAL, SG_INFO,
652 "Finding elevation for airport: " << id );
654 if ( fgFindAirportID( id, &a ) ) {
655 return a.getElevation();
664 // This function is never used, but maybe useful in the future ???
667 // Preset lon/lat given an airport id
668 static bool fgSetPosFromAirportID( const string& id ) {
672 SG_LOG( SG_GENERAL, SG_INFO,
673 "Attempting to set starting position from airport code " << id );
675 if ( fgFindAirportID( id, &a ) ) {
677 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
678 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
680 // other code depends on the actual postition being set so set
682 fgSetDouble("/position/longitude-deg", a.longitude );
683 fgSetDouble("/position/latitude-deg", a.latitude );
685 SG_LOG( SG_GENERAL, SG_INFO,
686 "Position for " << id << " is (" << a.longitude
687 << ", " << a.latitude << ")" );
697 // Set current tower position lon/lat given an airport id
698 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
700 // tower height hard coded for now...
701 float towerheight=50.0f;
703 // make a little off the heading for 1 runway airports...
704 float fudge_lon = fabs(sin(hdg)) * .003f;
705 float fudge_lat = .003f - fudge_lon;
707 if ( fgFindAirportID( id, &a ) ) {
708 fgSetDouble("/sim/tower/longitude-deg", a.getLongitude() + fudge_lon);
709 fgSetDouble("/sim/tower/latitude-deg", a.getLatitude() + fudge_lat);
710 fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
718 struct FGTowerLocationListener : SGPropertyChangeListener {
719 void valueChanged(SGPropertyNode* node) {
720 const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
721 const string id(node->getStringValue());
722 fgSetTowerPosFromAirportID(id, hdg);
726 static void fgInitTowerLocationListener() {
727 fgGetNode("/sim/tower/airport-id", true)
728 ->addChangeListener( new FGTowerLocationListener() );
731 // Set current_options lon/lat given an airport id and heading (degrees)
732 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
736 // set initial position from runway and heading
738 SG_LOG( SG_GENERAL, SG_INFO,
739 "Attempting to set starting position from airport code "
740 << id << " heading " << tgt_hdg );
742 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
743 SG_LOG( SG_GENERAL, SG_ALERT,
744 "Failed to find a good runway for " << id << '\n' );
751 double lat2, lon2, az2;
752 double heading = r._heading;
753 double azimuth = heading + 180.0;
754 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
756 SG_LOG( SG_GENERAL, SG_INFO,
757 "runway = " << r._lon << ", " << r._lat
758 << " length = " << r._length * SG_FEET_TO_METER
759 << " heading = " << azimuth );
761 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
762 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
763 &lat2, &lon2, &az2 );
765 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
767 double odist = fgGetDouble("/sim/presets/offset-distance");
768 odist *= SG_NM_TO_METER;
769 double oaz = azimuth;
770 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
771 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
774 while ( oaz >= 360.0 ) { oaz -= 360.0; }
775 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
781 fgSetDouble("/sim/presets/longitude-deg", lon2 );
782 fgSetDouble("/sim/presets/latitude-deg", lat2 );
783 fgSetDouble("/sim/presets/heading-deg", heading );
785 // other code depends on the actual values being set ...
786 fgSetDouble("/position/longitude-deg", lon2 );
787 fgSetDouble("/position/latitude-deg", lat2 );
788 fgSetDouble("/orientation/heading-deg", heading );
790 SG_LOG( SG_GENERAL, SG_INFO,
791 "Position for " << id << " is ("
793 << lat2 << ") new heading is "
800 // Set current_options lon/lat given an airport id and runway number
801 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
805 // set initial position from airport and runway number
807 SG_LOG( SG_GENERAL, SG_INFO,
808 "Attempting to set starting position for "
809 << id << ":" << rwy );
811 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
812 SG_LOG( SG_GENERAL, SG_ALERT,
813 "Failed to find runway " << rwy <<
814 " at airport " << id );
821 double lat2, lon2, az2;
822 double heading = r._heading;
823 double azimuth = heading + 180.0;
824 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
826 SG_LOG( SG_GENERAL, SG_INFO,
827 "runway = " << r._lon << ", " << r._lat
828 << " length = " << r._length * SG_FEET_TO_METER
829 << " heading = " << azimuth );
831 geo_direct_wgs_84 ( 0, r._lat, r._lon,
833 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
834 &lat2, &lon2, &az2 );
836 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
839 double odist = fgGetDouble("/sim/presets/offset-distance");
840 odist *= SG_NM_TO_METER;
841 double oaz = azimuth;
842 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
844 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
845 heading = fgGetDouble("/sim/presets/heading-deg");
847 while ( oaz >= 360.0 ) { oaz -= 360.0; }
848 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
854 fgSetDouble("/sim/presets/longitude-deg", lon2 );
855 fgSetDouble("/sim/presets/latitude-deg", lat2 );
856 fgSetDouble("/sim/presets/heading-deg", heading );
858 // other code depends on the actual values being set ...
859 fgSetDouble("/position/longitude-deg", lon2 );
860 fgSetDouble("/position/latitude-deg", lat2 );
861 fgSetDouble("/orientation/heading-deg", heading );
863 SG_LOG( SG_GENERAL, SG_INFO,
864 "Position for " << id << " is ("
866 << lat2 << ") new heading is "
873 static void fgSetDistOrAltFromGlideSlope() {
874 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
875 string apt_id = fgGetString("/sim/presets/airport-id");
876 double gs = fgGetDouble("/sim/presets/glideslope-deg")
877 * SG_DEGREES_TO_RADIANS ;
878 double od = fgGetDouble("/sim/presets/offset-distance");
879 double alt = fgGetDouble("/sim/presets/altitude-ft");
881 double apt_elev = 0.0;
882 if ( ! apt_id.empty() ) {
883 apt_elev = fgGetAirportElev( apt_id );
884 if ( apt_elev < -9990.0 ) {
891 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
892 // set altitude from glideslope and offset-distance
893 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
894 alt = fabs(od*tan(gs)) + apt_elev;
895 fgSetDouble("/sim/presets/altitude-ft", alt);
896 fgSetBool("/sim/presets/onground", false);
897 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
899 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
900 // set offset-distance from glideslope and altitude
901 od = (alt - apt_elev) / tan(gs);
902 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
903 fgSetDouble("/sim/presets/offset-distance", od);
904 fgSetBool("/sim/presets/onground", false);
905 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
907 } else if( fabs(gs) > 0.01 ) {
908 SG_LOG( SG_GENERAL, SG_ALERT,
909 "Glideslope given but not altitude or offset-distance." );
910 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
911 fgSetDouble("/sim/presets/glideslope-deg", 0);
912 fgSetBool("/sim/presets/onground", true);
917 // Set current_options lon/lat given an airport id and heading (degrees)
918 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
920 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
922 // set initial position from runway and heading
924 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
925 << id << ":" << freq );
927 double lon = nav->get_lon();
928 double lat = nav->get_lat();
930 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
932 double odist = fgGetDouble("/sim/presets/offset-distance")
934 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
936 while ( oaz >= 360.0 ) { oaz -= 360.0; }
937 double olat, olon, az2;
938 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
945 fgSetDouble("/sim/presets/longitude-deg", lon );
946 fgSetDouble("/sim/presets/latitude-deg", lat );
948 // other code depends on the actual values being set ...
949 fgSetDouble("/position/longitude-deg", lon );
950 fgSetDouble("/position/latitude-deg", lat );
951 fgSetDouble("/orientation/heading-deg",
952 fgGetDouble("/sim/presets/heading-deg") );
954 SG_LOG( SG_GENERAL, SG_INFO,
955 "Position for " << id << ":" << freq << " is ("
956 << lon << ", "<< lat << ")" );
960 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
961 << id << ":" << freq );
966 // Set current_options lon/lat given an aircraft carrier id
967 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
969 // set initial position from runway and heading
973 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
974 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
975 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
976 double alt = geodPos.elev() * SG_METER_TO_FEET;
978 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
979 << carrier << " at lat = " << lat << ", lon = " << lon
980 << ", alt = " << alt << ", heading = " << heading);
982 fgSetDouble("/sim/presets/longitude-deg", lon);
983 fgSetDouble("/sim/presets/latitude-deg", lat);
984 fgSetDouble("/sim/presets/altitude-ft", alt);
985 fgSetDouble("/sim/presets/heading-deg", heading);
986 fgSetDouble("/position/longitude-deg", lon);
987 fgSetDouble("/position/latitude-deg", lat);
988 fgSetDouble("/position/altitude-ft", alt);
989 fgSetDouble("/orientation/heading-deg", heading);
991 fgSetString("/sim/presets/speed-set", "UVW");
992 fgSetDouble("/velocities/uBody-fps", uvw[0]);
993 fgSetDouble("/velocities/vBody-fps", uvw[1]);
994 fgSetDouble("/velocities/wBody-fps", uvw[2]);
995 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
996 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
997 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
999 fgSetBool("/sim/presets/onground", true);
1003 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1009 // Set current_options lon/lat given an airport id and heading (degrees)
1010 static bool fgSetPosFromFix( const string& id ) {
1013 // set initial position from runway and heading
1014 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1015 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1018 double lon = fix.get_lon();
1019 double lat = fix.get_lat();
1021 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1023 double odist = fgGetDouble("/sim/presets/offset-distance")
1025 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1027 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1028 double olat, olon, az2;
1029 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1036 fgSetDouble("/sim/presets/longitude-deg", lon );
1037 fgSetDouble("/sim/presets/latitude-deg", lat );
1039 // other code depends on the actual values being set ...
1040 fgSetDouble("/position/longitude-deg", lon );
1041 fgSetDouble("/position/latitude-deg", lat );
1042 fgSetDouble("/orientation/heading-deg",
1043 fgGetDouble("/sim/presets/heading-deg") );
1045 SG_LOG( SG_GENERAL, SG_INFO,
1046 "Position for " << id << " is ("
1047 << lon << ", "<< lat << ")" );
1051 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1057 static void parseWaypoints() {
1058 string_list *waypoints = globals->get_initial_waypoints();
1060 vector<string>::iterator i;
1061 for (i = waypoints->begin();
1062 i != waypoints->end();
1067 // Now were done using the way points we can deallocate the
1069 while (waypoints->begin() != waypoints->end()) {
1070 waypoints->pop_back();
1073 globals->set_initial_waypoints(0);
1082 * Initialize vor/ndb/ils/fix list management and query systems (as
1083 * well as simple airport db list)
1088 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1090 SGPath aptdb( globals->get_fg_root() );
1091 aptdb.append( "Airports/apt.dat" );
1093 SGPath p_metar( globals->get_fg_root() );
1094 p_metar.append( "Airports/metar.dat" );
1096 FGAirportList *airports = new FGAirportList();
1097 globals->set_airports( airports );
1098 FGRunwayList *runways = new FGRunwayList();
1099 globals->set_runways( runways );
1101 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1103 FGNavList *navlist = new FGNavList;
1104 FGNavList *loclist = new FGNavList;
1105 FGNavList *gslist = new FGNavList;
1106 FGNavList *dmelist = new FGNavList;
1107 FGNavList *mkrlist = new FGNavList;
1108 FGNavList *tacanlist = new FGNavList;
1109 FGNavList *carrierlist = new FGNavList;
1110 FGTACANList *channellist = new FGTACANList;
1112 globals->set_navlist( navlist );
1113 globals->set_loclist( loclist );
1114 globals->set_gslist( gslist );
1115 globals->set_dmelist( dmelist );
1116 globals->set_mkrlist( mkrlist );
1117 globals->set_tacanlist( tacanlist );
1118 globals->set_carrierlist( carrierlist );
1119 globals->set_channellist( channellist );
1121 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1122 SG_LOG( SG_GENERAL, SG_ALERT,
1123 "Problems loading one or more navigational database" );
1126 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1127 // align all the localizers with their corresponding runways
1128 // since data sources are good for cockpit navigation
1129 // purposes, but not always to the error tolerances needed to
1130 // exactly place these items.
1132 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1134 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1137 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1138 SGPath p_fix( globals->get_fg_root() );
1139 p_fix.append( "Navaids/fix.dat" );
1140 FGFixList *fixlist = new FGFixList;
1141 fixlist->init( p_fix );
1142 globals->set_fixlist( fixlist );
1148 // Set the initial position based on presets (or defaults)
1149 bool fgInitPosition() {
1150 // cout << "fgInitPosition()" << endl;
1151 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1152 * SG_DEGREES_TO_RADIANS ;
1153 double od = fgGetDouble("/sim/presets/offset-distance");
1154 double alt = fgGetDouble("/sim/presets/altitude-ft");
1156 bool set_pos = false;
1158 // If glideslope is specified, then calculate offset-distance or
1159 // altitude relative to glide slope if either of those was not
1161 if ( fabs( gs ) > 0.01 ) {
1162 fgSetDistOrAltFromGlideSlope();
1166 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1167 // If not, check for an airport-id and use that.
1168 // If not, default to the middle of the KSFO field.
1169 // The default values for lon/lat are deliberately out of range
1170 // so that the airport-id can take effect; valid lon/lat will
1171 // override airport-id, however.
1172 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1173 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1174 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1175 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1180 string apt = fgGetString("/sim/presets/airport-id");
1181 string rwy_no = fgGetString("/sim/presets/runway");
1182 double hdg = fgGetDouble("/sim/presets/heading-deg");
1183 string vor = fgGetString("/sim/presets/vor-id");
1184 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1185 string ndb = fgGetString("/sim/presets/ndb-id");
1186 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1187 string carrier = fgGetString("/sim/presets/carrier");
1188 string parkpos = fgGetString("/sim/presets/parkpos");
1189 string fix = fgGetString("/sim/presets/fix");
1191 fgSetDouble( "/orientation/heading-deg", hdg );
1192 fgInitTowerLocationListener();
1194 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1195 // An airport + runway is requested
1196 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1197 // set tower position (a little off the heading for single
1199 fgSetString("/sim/tower/airport-id", apt.c_str());
1204 if ( !set_pos && !apt.empty() ) {
1205 // An airport is requested (find runway closest to hdg)
1206 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1207 // set tower position (a little off the heading for single
1209 fgSetString("/sim/tower/airport-id", apt.c_str());
1214 if ( !set_pos && !vor.empty() ) {
1215 // a VOR is requested
1216 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1221 if ( !set_pos && !ndb.empty() ) {
1222 // an NDB is requested
1223 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1228 if ( !set_pos && !carrier.empty() ) {
1229 // an aircraft carrier is requested
1230 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1235 if ( !set_pos && !fix.empty() ) {
1236 // a Fix is requested
1237 if ( fgSetPosFromFix( fix ) ) {
1243 // No lon/lat specified, no airport specified, default to
1244 // middle of KSFO field.
1245 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1246 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1249 fgSetDouble( "/position/longitude-deg",
1250 fgGetDouble("/sim/presets/longitude-deg") );
1251 fgSetDouble( "/position/latitude-deg",
1252 fgGetDouble("/sim/presets/latitude-deg") );
1254 // determine if this should be an on-ground or in-air start
1255 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1256 fgSetBool("/sim/presets/onground", false);
1258 fgSetBool("/sim/presets/onground", true);
1265 // General house keeping initializations
1266 bool fgInitGeneral() {
1269 #if defined(FX) && defined(XMESA)
1270 char *mesa_win_state;
1273 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1274 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1276 root = globals->get_fg_root();
1277 if ( ! root.length() ) {
1278 // No root path set? Then bail ...
1279 SG_LOG( SG_GENERAL, SG_ALERT,
1280 "Cannot continue without a path to the base package "
1281 << "being defined." );
1284 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1286 #if defined(FX) && defined(XMESA)
1287 // initialize full screen flag
1288 globals->set_fullscreen(false);
1289 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1290 // Test for the MESA_GLX_FX env variable
1291 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1292 // test if we are fullscreen mesa/glide
1293 if ( (mesa_win_state[0] == 'f') ||
1294 (mesa_win_state[0] == 'F') ) {
1295 globals->set_fullscreen(true);
1305 // Initialize the flight model subsystem. This just creates the
1306 // object. The actual fdm initialization is delayed until we get a
1307 // proper scenery elevation hit. This is checked for in main.cxx
1311 if ( cur_fdm_state ) {
1312 delete cur_fdm_state;
1316 double dt = 1.0 / fgGetInt("/sim/model-hz");
1317 string model = fgGetString("/sim/flight-model");
1320 if ( model == "larcsim" ) {
1321 cur_fdm_state = new FGLaRCsim( dt );
1322 } else if ( model == "jsb" ) {
1323 cur_fdm_state = new FGJSBsim( dt );
1324 #ifdef ENABLE_SP_FMDS
1325 } else if ( model == "ada" ) {
1326 cur_fdm_state = new FGADA( dt );
1327 } else if ( model == "acms" ) {
1328 cur_fdm_state = new FGACMS( dt );
1330 } else if ( model == "balloon" ) {
1331 cur_fdm_state = new FGBalloonSim( dt );
1332 } else if ( model == "magic" ) {
1333 cur_fdm_state = new FGMagicCarpet( dt );
1334 } else if ( model == "ufo" ) {
1335 cur_fdm_state = new FGUFO( dt );
1336 } else if ( model == "external" ) {
1337 // external is a synonym for "--fdm=null" and is
1338 // maintained here for backwards compatibility
1339 cur_fdm_state = new FGNullFDM( dt );
1340 } else if ( model.find("network") == 0 ) {
1341 string host = "localhost";
1345 string net_options = model.substr(8);
1346 string::size_type begin, end;
1349 end = net_options.find( ",", begin );
1350 if ( end != string::npos ) {
1351 host = net_options.substr(begin, end - begin);
1355 end = net_options.find( ",", begin );
1356 if ( end != string::npos ) {
1357 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1361 end = net_options.find( ",", begin );
1362 if ( end != string::npos ) {
1363 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1367 end = net_options.find( ",", begin );
1368 if ( end != string::npos ) {
1369 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1372 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1373 } else if ( model.find("pipe") == 0 ) {
1374 // /* old */ string pipe_path = model.substr(5);
1375 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1376 string pipe_path = "";
1377 string pipe_protocol = "";
1378 string pipe_options = model.substr(5);
1379 string::size_type begin, end;
1382 end = pipe_options.find( ",", begin );
1383 if ( end != string::npos ) {
1384 pipe_path = pipe_options.substr(begin, end - begin);
1387 // protocol (last option)
1388 pipe_protocol = pipe_options.substr(begin);
1389 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1390 } else if ( model == "null" ) {
1391 cur_fdm_state = new FGNullFDM( dt );
1392 } else if ( model == "yasim" ) {
1393 cur_fdm_state = new YASim( dt );
1395 SG_LOG(SG_GENERAL, SG_ALERT,
1396 "Unrecognized flight model '" << model
1397 << "', cannot init flight dynamics model.");
1401 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1406 static void printMat(const sgVec4 *mat, char *name="")
1409 SG_LOG(SG_GENERAL, SG_BULK, name );
1410 for(i=0; i<4; i++) {
1411 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1412 << " " << mat[i][2] << " " << mat[i][3] );
1416 // Initialize view parameters
1418 // force update of model so that viewer can get some data...
1419 globals->get_aircraft_model()->update(0);
1420 // run update for current view so that data is current...
1421 globals->get_viewmgr()->update(0);
1423 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1424 printMat(globals->get_current_view()->get_UP(),"UP");
1425 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1430 SGTime *fgInitTime() {
1432 static const SGPropertyNode *longitude
1433 = fgGetNode("/position/longitude-deg");
1434 static const SGPropertyNode *latitude
1435 = fgGetNode("/position/latitude-deg");
1436 static const SGPropertyNode *cur_time_override
1437 = fgGetNode("/sim/time/cur-time-override", true);
1439 SGPath zone( globals->get_fg_root() );
1440 zone.append( "Timezone" );
1441 SGTime *t = new SGTime( longitude->getDoubleValue()
1442 * SGD_DEGREES_TO_RADIANS,
1443 latitude->getDoubleValue()
1444 * SGD_DEGREES_TO_RADIANS,
1446 cur_time_override->getLongValue() );
1448 globals->set_warp_delta( 0 );
1450 t->update( 0.0, 0.0,
1451 cur_time_override->getLongValue(),
1452 globals->get_warp() );
1458 // set up a time offset (aka warp) if one is specified
1459 void fgInitTimeOffset() {
1460 static const SGPropertyNode *longitude
1461 = fgGetNode("/position/longitude-deg");
1462 static const SGPropertyNode *latitude
1463 = fgGetNode("/position/latitude-deg");
1464 static const SGPropertyNode *cur_time_override
1465 = fgGetNode("/sim/time/cur-time-override", true);
1467 // Handle potential user specified time offsets
1468 int orig_warp = globals->get_warp();
1469 SGTime *t = globals->get_time_params();
1470 time_t cur_time = t->get_cur_time();
1471 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1472 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1473 time_t aircraftLocalTime =
1474 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1476 // Okay, we now have several possible scenarios
1477 int offset = fgGetInt("/sim/startup/time-offset");
1478 string offset_type = fgGetString("/sim/startup/time-offset-type");
1481 if ( offset_type == "real" ) {
1483 } else if ( offset_type == "dawn" ) {
1484 warp = fgTimeSecondsUntilSunAngle( cur_time,
1485 longitude->getDoubleValue()
1486 * SGD_DEGREES_TO_RADIANS,
1487 latitude->getDoubleValue()
1488 * SGD_DEGREES_TO_RADIANS,
1490 } else if ( offset_type == "morning" ) {
1491 warp = fgTimeSecondsUntilSunAngle( cur_time,
1492 longitude->getDoubleValue()
1493 * SGD_DEGREES_TO_RADIANS,
1494 latitude->getDoubleValue()
1495 * SGD_DEGREES_TO_RADIANS,
1497 } else if ( offset_type == "noon" ) {
1498 warp = fgTimeSecondsUntilSunAngle( cur_time,
1499 longitude->getDoubleValue()
1500 * SGD_DEGREES_TO_RADIANS,
1501 latitude->getDoubleValue()
1502 * SGD_DEGREES_TO_RADIANS,
1504 } else if ( offset_type == "afternoon" ) {
1505 warp = fgTimeSecondsUntilSunAngle( cur_time,
1506 longitude->getDoubleValue()
1507 * SGD_DEGREES_TO_RADIANS,
1508 latitude->getDoubleValue()
1509 * SGD_DEGREES_TO_RADIANS,
1511 } else if ( offset_type == "dusk" ) {
1512 warp = fgTimeSecondsUntilSunAngle( cur_time,
1513 longitude->getDoubleValue()
1514 * SGD_DEGREES_TO_RADIANS,
1515 latitude->getDoubleValue()
1516 * SGD_DEGREES_TO_RADIANS,
1518 } else if ( offset_type == "evening" ) {
1519 warp = fgTimeSecondsUntilSunAngle( cur_time,
1520 longitude->getDoubleValue()
1521 * SGD_DEGREES_TO_RADIANS,
1522 latitude->getDoubleValue()
1523 * SGD_DEGREES_TO_RADIANS,
1525 } else if ( offset_type == "midnight" ) {
1526 warp = fgTimeSecondsUntilSunAngle( cur_time,
1527 longitude->getDoubleValue()
1528 * SGD_DEGREES_TO_RADIANS,
1529 latitude->getDoubleValue()
1530 * SGD_DEGREES_TO_RADIANS,
1532 } else if ( offset_type == "system-offset" ) {
1534 } else if ( offset_type == "gmt-offset" ) {
1535 warp = offset - (currGMT - systemLocalTime);
1536 } else if ( offset_type == "latitude-offset" ) {
1537 warp = offset - (aircraftLocalTime - systemLocalTime);
1538 } else if ( offset_type == "system" ) {
1539 warp = offset - cur_time;
1540 } else if ( offset_type == "gmt" ) {
1541 warp = offset - currGMT;
1542 } else if ( offset_type == "latitude" ) {
1543 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1545 SG_LOG( SG_GENERAL, SG_ALERT,
1546 "FG_TIME::Unsupported offset type " << offset_type );
1549 globals->set_warp( orig_warp + warp );
1550 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1551 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1552 cur_time_override->getLongValue(),
1553 globals->get_warp() );
1555 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1556 << globals->get_warp() );
1560 // This is the top level init routine which calls all the other
1561 // initialization routines. If you are adding a subsystem to flight
1562 // gear, its initialization call should located in this routine.
1563 // Returns non-zero if a problem encountered.
1564 bool fgInitSubsystems() {
1565 // static const SGPropertyNode *longitude
1566 // = fgGetNode("/sim/presets/longitude-deg");
1567 // static const SGPropertyNode *latitude
1568 // = fgGetNode("/sim/presets/latitude-deg");
1569 // static const SGPropertyNode *altitude
1570 // = fgGetNode("/sim/presets/altitude-ft");
1572 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1573 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1575 ////////////////////////////////////////////////////////////////////
1576 // Initialize the event manager subsystem.
1577 ////////////////////////////////////////////////////////////////////
1579 globals->get_event_mgr()->init();
1580 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1582 ////////////////////////////////////////////////////////////////////
1583 // Initialize the property interpolator subsystem
1584 ////////////////////////////////////////////////////////////////////
1585 globals->add_subsystem("interpolator", new SGInterpolator);
1588 ////////////////////////////////////////////////////////////////////
1589 // Add the FlightGear property utilities.
1590 ////////////////////////////////////////////////////////////////////
1591 globals->add_subsystem("properties", new FGProperties);
1593 ////////////////////////////////////////////////////////////////////
1594 // Initialize the material property subsystem.
1595 ////////////////////////////////////////////////////////////////////
1597 SGPath mpath( globals->get_fg_root() );
1598 mpath.append( "materials.xml" );
1599 string season = fgGetString("/sim/startup/season", "summer");
1600 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1601 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1606 ////////////////////////////////////////////////////////////////////
1607 // Initialize the scenery management subsystem.
1608 ////////////////////////////////////////////////////////////////////
1610 if ( globals->get_tile_mgr()->init() ) {
1611 // Load the local scenery data
1612 double visibility_meters = fgGetDouble("/environment/visibility-m");
1614 globals->get_tile_mgr()->update( visibility_meters );
1616 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1620 // cause refresh of viewer scenery timestamps every 15 seconds...
1621 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1622 globals->get_tile_mgr(),
1623 &FGTileMgr::refresh_view_timestamps,
1627 ////////////////////////////////////////////////////////////////////
1628 // Initialize the flight model subsystem.
1629 ////////////////////////////////////////////////////////////////////
1633 // allocates structures so must happen before any of the flight
1634 // model or control parameters are set
1635 fgAircraftInit(); // In the future this might not be the case.
1638 ////////////////////////////////////////////////////////////////////
1639 // Initialize the XML Autopilot subsystem.
1640 ////////////////////////////////////////////////////////////////////
1642 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1643 globals->add_subsystem( "route-manager", new FGRouteMgr );
1646 ////////////////////////////////////////////////////////////////////
1647 // Initialize the view manager subsystem.
1648 ////////////////////////////////////////////////////////////////////
1652 ////////////////////////////////////////////////////////////////////
1653 // Create and register the logger.
1654 ////////////////////////////////////////////////////////////////////
1656 globals->add_subsystem("logger", new FGLogger);
1658 ////////////////////////////////////////////////////////////////////
1659 // Create and register the XML GUI.
1660 ////////////////////////////////////////////////////////////////////
1662 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1665 ////////////////////////////////////////////////////////////////////
1666 // Initialize the local time subsystem.
1667 ////////////////////////////////////////////////////////////////////
1669 // update the current timezone each 30 minutes
1670 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1671 &fgUpdateLocalTime, 30*60 );
1672 fgInitTimeOffset(); // the environment subsystem needs this
1675 ////////////////////////////////////////////////////////////////////
1676 // Initialize the weather subsystem.
1677 ////////////////////////////////////////////////////////////////////
1679 // Initialize the weather modeling subsystem
1680 globals->add_subsystem("environment", new FGEnvironmentMgr);
1683 ////////////////////////////////////////////////////////////////////
1684 // Initialize the lighting subsystem.
1685 ////////////////////////////////////////////////////////////////////
1687 globals->add_subsystem("lighting", new FGLight);
1689 //////////////////////////////////////////////////////////////////////
1690 // Initialize the 2D cloud subsystem.
1691 ////////////////////////////////////////////////////////////////////
1692 fgGetBool("/sim/rendering/bump-mapping", false);
1694 #ifdef ENABLE_AUDIO_SUPPORT
1695 ////////////////////////////////////////////////////////////////////
1696 // Initialize the sound subsystem.
1697 ////////////////////////////////////////////////////////////////////
1699 init_volume = fgGetFloat("/sim/sound/volume");
1700 fgSetFloat("/sim/sound/volume", 0.0f);
1701 globals->set_soundmgr(new SGSoundMgr);
1702 globals->get_soundmgr()->init();
1703 globals->get_soundmgr()->bind();
1706 ////////////////////////////////////////////////////////////////////
1707 // Initialize the sound-effects subsystem.
1708 ////////////////////////////////////////////////////////////////////
1710 globals->add_subsystem("fx", new FGFX);
1714 ////////////////////////////////////////////////////////////////////
1715 // Initialise ATC display system
1716 ////////////////////////////////////////////////////////////////////
1718 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1719 globals->set_ATC_display(new FGATCDisplay);
1720 globals->get_ATC_display()->init();
1722 ////////////////////////////////////////////////////////////////////
1723 // Initialise the ATC Manager
1724 ////////////////////////////////////////////////////////////////////
1726 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1727 globals->set_ATC_mgr(new FGATCMgr);
1728 globals->get_ATC_mgr()->init();
1730 ////////////////////////////////////////////////////////////////////
1731 // Initialise the AI Manager
1732 ////////////////////////////////////////////////////////////////////
1734 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1735 globals->set_AI_mgr(new FGAIMgr);
1736 globals->get_AI_mgr()->init();
1738 ////////////////////////////////////////////////////////////////////
1739 // Initialise the AI Model Manager
1740 ////////////////////////////////////////////////////////////////////
1741 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1742 globals->add_subsystem("ai_model", new FGAIManager);
1743 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1746 // It's probably a good idea to initialize the top level traffic manager
1747 // After the AI and ATC systems have been initialized properly.
1748 // AI Traffic manager
1749 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1750 FGTrafficManager *dispatcher =
1751 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1752 SGPath path = globals->get_fg_root();
1753 path.append("/Traffic/fgtraffic.xml");
1756 //globals->get_subsystem("Traffic Manager")->init();
1758 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1759 globals->add_subsystem("systems", new FGSystemMgr);
1763 ////////////////////////////////////////////////////////////////////
1764 // Initialize the cockpit subsystem
1765 ////////////////////////////////////////////////////////////////////
1766 if( fgCockpitInit( ¤t_aircraft )) {
1767 // Cockpit initialized ok.
1769 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1774 ////////////////////////////////////////////////////////////////////
1775 // Initialize the autopilot subsystem.
1776 ////////////////////////////////////////////////////////////////////
1778 // FIXME: these should go in the
1779 // GUI initialization code, not here.
1780 // fgAPAdjustInit();
1781 NewTgtAirportInit();
1785 ////////////////////////////////////////////////////////////////////
1786 // Initialize I/O subsystem.
1787 ////////////////////////////////////////////////////////////////////
1789 globals->get_io()->init();
1790 globals->get_io()->bind();
1793 ////////////////////////////////////////////////////////////////////
1794 // Add a new 2D panel.
1795 ////////////////////////////////////////////////////////////////////
1797 string panel_path = fgGetString("/sim/panel/path",
1798 "Panels/Default/default.xml");
1800 globals->set_current_panel( fgReadPanel(panel_path) );
1801 if (globals->get_current_panel() == 0) {
1802 SG_LOG( SG_INPUT, SG_ALERT,
1803 "Error reading new panel from " << panel_path );
1805 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1806 globals->get_current_panel()->init();
1807 globals->get_current_panel()->bind();
1811 ////////////////////////////////////////////////////////////////////
1812 // Initialize the controls subsystem.
1813 ////////////////////////////////////////////////////////////////////
1815 globals->get_controls()->init();
1816 globals->get_controls()->bind();
1819 ////////////////////////////////////////////////////////////////////
1820 // Initialize the input subsystem.
1821 ////////////////////////////////////////////////////////////////////
1823 globals->add_subsystem("input", new FGInput);
1826 ////////////////////////////////////////////////////////////////////
1827 // Initialize the replay subsystem
1828 ////////////////////////////////////////////////////////////////////
1829 globals->add_subsystem("replay", new FGReplay);
1831 ////////////////////////////////////////////////////////////////////
1832 // Bind and initialize subsystems.
1833 ////////////////////////////////////////////////////////////////////
1835 globals->get_subsystem_mgr()->bind();
1836 globals->get_subsystem_mgr()->init();
1838 #ifdef FG_MPLAYER_AS
1839 ////////////////////////////////////////////////////////////////////
1840 // Initialize multiplayer subsystem
1841 ////////////////////////////////////////////////////////////////////
1843 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1844 globals->get_multiplayer_mgr()->init();
1847 ////////////////////////////////////////////////////////////////////////
1848 // Initialize the Nasal interpreter.
1849 // Do this last, so that the loaded scripts see initialized state
1850 ////////////////////////////////////////////////////////////////////////
1851 FGNasalSys* nasal = new FGNasalSys();
1852 globals->add_subsystem("nasal", nasal);
1855 ////////////////////////////////////////////////////////////////////
1856 // At this point we could try and parse the waypoint options
1857 ///////////////////////////////////////////////////////////////////
1860 // initialize methods that depend on other subsystems.
1861 globals->get_subsystem_mgr()->postinit();
1863 ////////////////////////////////////////////////////////////////////////
1864 // End of subsystem initialization.
1865 ////////////////////////////////////////////////////////////////////
1867 SG_LOG( SG_GENERAL, SG_INFO, endl);
1869 // Save the initial state for future
1871 globals->saveInitialState();
1877 void fgReInitSubsystems()
1879 // static const SGPropertyNode *longitude
1880 // = fgGetNode("/sim/presets/longitude-deg");
1881 // static const SGPropertyNode *latitude
1882 // = fgGetNode("/sim/presets/latitude-deg");
1883 static const SGPropertyNode *altitude
1884 = fgGetNode("/sim/presets/altitude-ft");
1885 static const SGPropertyNode *master_freeze
1886 = fgGetNode("/sim/freeze/master");
1888 SG_LOG( SG_GENERAL, SG_INFO,
1889 "fgReInitSubsystems(): /position/altitude = "
1890 << altitude->getDoubleValue() );
1892 bool freeze = master_freeze->getBoolValue();
1894 fgSetBool("/sim/freeze/master", true);
1896 fgSetBool("/sim/crashed", false);
1898 // Force reupdating the positions of the ai 3d models. They are used for
1899 // initializing ground level for the FDM.
1900 globals->get_subsystem("ai_model")->reinit();
1902 // Initialize the FDM
1905 // allocates structures so must happen before any of the flight
1906 // model or control parameters are set
1907 fgAircraftInit(); // In the future this might not be the case.
1909 // reload offsets from config defaults
1910 globals->get_viewmgr()->reinit();
1914 globals->get_controls()->reset_all();
1916 fgUpdateLocalTime();
1918 // re-init to proper time of day setting
1922 fgSetBool("/sim/freeze/master", false);
1924 fgSetBool("/sim/sceneryloaded",false);