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 <FDM/UIUCModel/uiuc_aircraftdir.h>
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 <Replay/replay.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/fg_fx.hxx>
108 #include <Sound/beacon.hxx>
109 #include <Sound/morse.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/moonpos.hxx>
113 #include <Time/sunpos.hxx>
114 #include <Time/sunsolver.hxx>
115 #include <Time/tmp.hxx>
116 #include <Traffic/TrafficMgr.hxx>
119 #include <MultiPlayer/multiplaytxmgr.hxx>
120 #include <MultiPlayer/multiplayrxmgr.hxx>
123 #include <Environment/environment_mgr.hxx>
125 #include "fg_init.hxx"
127 #include "fg_commands.hxx"
128 #include "fg_props.hxx"
129 #include "options.hxx"
130 #include "globals.hxx"
131 #include "logger.hxx"
132 #include "viewmgr.hxx"
134 #if defined(FX) && defined(XMESA)
135 #include <GL/xmesa.h>
138 SG_USING_STD(string);
142 extern const char *default_root;
146 // Scan the command line options for the specified option and return
148 static string fgScanForOption( const string& option, int argc, char **argv ) {
151 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
153 int len = option.length();
156 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
158 string arg = argv[i];
159 if ( arg.find( option ) == 0 ) {
160 return arg.substr( len );
170 // Scan the user config files for the specified option and return
172 static string fgScanForOption( const string& option, const string& path ) {
173 sg_gzifstream in( path );
174 if ( !in.is_open() ) {
178 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
180 int len = option.length();
184 while ( ! in.eof() ) {
187 while ( in.get(c) && c != '\0' ) {
192 #if defined( macintosh )
193 getline( in, line, '\r' );
195 getline( in, line, '\n' );
198 // catch extraneous (DOS) line ending character
199 if ( line[line.length() - 1] < 32 ) {
200 line = line.substr( 0, line.length()-1 );
203 if ( line.find( option ) == 0 ) {
204 return line.substr( len );
214 // Read in configuration (files and command line options) but only set
216 bool fgInitFGRoot ( int argc, char **argv ) {
220 // First parse command line options looking for --fg-root=, this
221 // will override anything specified in a config file
222 root = fgScanForOption( "--fg-root=", argc, argv);
224 #if defined( unix ) || defined( __CYGWIN__ )
225 // Next check home directory for .fgfsrc.hostname file
226 if ( root.empty() ) {
227 envp = ::getenv( "HOME" );
228 if ( envp != NULL ) {
229 SGPath config( envp );
230 config.append( ".fgfsrc" );
232 gethostname( name, 256 );
233 config.concat( "." );
234 config.concat( name );
235 root = fgScanForOption( "--fg-root=", config.str() );
240 // Next check home directory for .fgfsrc file
241 if ( root.empty() ) {
242 envp = ::getenv( "HOME" );
243 if ( envp != NULL ) {
244 SGPath config( envp );
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 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 envp = ::getenv( "HOME" );
312 if ( envp != NULL ) {
313 SGPath config( envp );
314 config.append( ".fgfsrc" );
316 gethostname( name, 256 );
317 config.concat( "." );
318 config.concat( name );
319 aircraft = fgScanForOption( "--aircraft=", config.str() );
324 // Next check home directory for .fgfsrc file
325 if ( aircraft.empty() ) {
326 envp = ::getenv( "HOME" );
327 if ( envp != NULL ) {
328 SGPath config( envp );
329 config.append( ".fgfsrc" );
330 aircraft = fgScanForOption( "--aircraft=", config.str() );
334 if ( aircraft.empty() ) {
335 // Check for $fg_root/system.fgfsrc
336 SGPath sysconf( globals->get_fg_root() );
337 sysconf.append( "system.fgfsrc" );
338 aircraft = fgScanForOption( "--aircraft=", sysconf.str() );
340 // if an aircraft was specified, set the property name
341 if ( !aircraft.empty() ) {
342 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
343 fgSetString("/sim/aircraft", aircraft.c_str() );
345 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
352 // Return the current base package version
353 string fgBasePackageVersion() {
354 SGPath base_path( globals->get_fg_root() );
355 base_path.append("version");
357 sg_gzifstream in( base_path.str() );
358 if ( !in.is_open() ) {
359 SGPath old_path( globals->get_fg_root() );
360 old_path.append( "Thanks" );
361 sg_gzifstream old( old_path.str() );
362 if ( !old.is_open() ) {
365 return "[old version]";
376 // Initialize the localization
377 SGPropertyNode *fgInitLocale(const char *language) {
378 SGPropertyNode *c_node = NULL, *d_node = NULL;
379 SGPropertyNode *intl = fgGetNode("/sim/intl");
381 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
383 // localization not defined
388 // Select the proper language from the list
390 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
391 for (unsigned int i = 0; i < locale.size(); i++) {
393 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
394 for (unsigned int j = 0; j < lang.size(); j++) {
396 if (!strcmp(lang[j]->getStringValue(), language)) {
405 d_node = intl->getChild("locale");
409 // Check for localized font
410 SGPropertyNode *font_n = c_node->getNode("font", true);
411 if ( !strcmp(font_n->getStringValue(), "") )
412 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
416 // Load the default strings
418 SGPath d_path( globals->get_fg_root() );
420 const char *d_path_str = d_node->getStringValue("strings");
422 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
426 d_path.append(d_path_str);
427 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
430 SGPropertyNode *strings = c_node->getNode("strings");
432 readProperties(d_path.str(), strings);
433 } catch (const sg_exception &e) {
434 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
439 // Load the language specific strings
441 if (c_node != d_node) {
442 SGPath c_path( globals->get_fg_root() );
444 const char *c_path_str = c_node->getStringValue("strings");
446 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
450 c_path.append(c_path_str);
451 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
455 readProperties(c_path.str(), strings);
456 } catch (const sg_exception &e) {
457 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
467 // Initialize the localization routines
468 bool fgDetectLanguage() {
469 char *language = ::getenv("LANG");
471 if (language == NULL) {
472 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
476 SGPropertyNode *locale = fgInitLocale(language);
478 SG_LOG(SG_GENERAL, SG_ALERT,
479 "No internationalization settings specified in preferences.xml" );
484 globals->set_locale( locale );
489 // Attempt to locate and parse the various non-XML config files in order
490 // from least precidence to greatest precidence
492 do_options (int argc, char ** argv)
494 // Check for $fg_root/system.fgfsrc
495 SGPath config( globals->get_fg_root() );
496 config.append( "system.fgfsrc" );
497 fgParseOptions(config.str());
499 #if defined( unix ) || defined( __CYGWIN__ )
501 // Check for $fg_root/system.fgfsrc.hostname
502 gethostname( name, 256 );
503 config.concat( "." );
504 config.concat( name );
505 fgParseOptions(config.str());
508 // Check for ~/.fgfsrc
509 char* envp = ::getenv( "HOME" );
510 if ( envp != NULL ) {
512 config.append( ".fgfsrc" );
513 fgParseOptions(config.str());
516 #if defined( unix ) || defined( __CYGWIN__ )
517 // Check for ~/.fgfsrc.hostname
518 gethostname( name, 256 );
519 config.concat( "." );
520 config.concat( name );
521 fgParseOptions(config.str());
524 // Parse remaining command line options
525 // These will override anything specified in a config file
526 fgParseArgs(argc, argv);
530 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
532 ulDir *dirp = ulOpenDir(path.str().c_str());
534 cerr << "Unable to open aircraft directory." << endl;
538 while ((dire = ulReadDir(dirp)) != NULL) {
540 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
541 && strcmp("..", dire->d_name) )
544 next.append(dire->d_name);
546 string result = fgFindAircraftPath( next, aircraft );
547 if ( ! result.empty() ) {
551 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
562 // Read in configuration (file and command line)
563 bool fgInitConfig ( int argc, char **argv ) {
565 // First, set some sane default values
568 // Read global preferences from $FG_ROOT/preferences.xml
569 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
570 fgLoadProps("preferences.xml", globals->get_props());
571 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
573 // Detect the required language as early as possible
574 if ( !fgDetectLanguage() ) {
578 // Scan user config files and command line for a specified aircraft.
579 fgInitFGAircraft(argc, argv);
581 string aircraft = fgGetString( "/sim/aircraft", "" );
582 if ( aircraft.size() > 0 ) {
583 SGPath aircraft_search( globals->get_fg_root() );
584 aircraft_search.append( "Aircraft" );
586 string aircraft_set = aircraft + "-set.xml";
588 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
589 if ( !result.empty() ) {
590 fgSetString( "/sim/aircraft-dir", result.c_str() );
591 SGPath full_name( result );
592 full_name.append( aircraft_set );
594 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
595 << " from " << full_name.str());
597 readProperties( full_name.str(), globals->get_props() );
598 } catch ( const sg_exception &e ) {
599 string message = "Error reading default aircraft: ";
600 message += e.getFormattedMessage();
601 SG_LOG(SG_INPUT, SG_ALERT, message);
605 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
611 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
614 // parse options after loading aircraft to ensure any user
615 // overrides of defaults are honored.
616 do_options(argc, argv);
622 // find basic airport location info from airport database
623 bool fgFindAirportID( const string& id, FGAirport *a ) {
626 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
628 result = globals->get_airports()->search( id );
630 if ( result.getId().empty() ) {
631 SG_LOG( SG_GENERAL, SG_ALERT,
632 "Failed to find " << id << " in basic.dat.gz" );
641 SG_LOG( SG_GENERAL, SG_INFO,
642 "Position for " << id << " is ("
643 << a->getLongitude() << ", "
644 << a->getLatitude() << ")" );
650 // get airport elevation
651 static double fgGetAirportElev( const string& id ) {
655 SG_LOG( SG_GENERAL, SG_INFO,
656 "Finding elevation for airport: " << id );
658 if ( fgFindAirportID( id, &a ) ) {
659 return a.getElevation();
668 // This function is never used, but maybe useful in the future ???
671 // Preset lon/lat given an airport id
672 static bool fgSetPosFromAirportID( const string& id ) {
676 SG_LOG( SG_GENERAL, SG_INFO,
677 "Attempting to set starting position from airport code " << id );
679 if ( fgFindAirportID( id, &a ) ) {
681 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
682 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
684 // other code depends on the actual postition being set so set
686 fgSetDouble("/position/longitude-deg", a.longitude );
687 fgSetDouble("/position/latitude-deg", a.latitude );
689 SG_LOG( SG_GENERAL, SG_INFO,
690 "Position for " << id << " is (" << a.longitude
691 << ", " << a.latitude << ")" );
701 // Set current tower position lon/lat given an airport id
702 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
704 // tower height hard coded for now...
705 float towerheight=50.0f;
707 // make a little off the heading for 1 runway airports...
708 float fudge_lon = fabs(sin(hdg)) * .003f;
709 float fudge_lat = .003f - fudge_lon;
711 if ( fgFindAirportID( id, &a ) ) {
712 fgSetDouble("/sim/tower/longitude-deg", a.getLongitude() + fudge_lon);
713 fgSetDouble("/sim/tower/latitude-deg", a.getLatitude() + fudge_lat);
714 fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
723 // Set current_options lon/lat given an airport id and heading (degrees)
724 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
728 // set initial position from runway and heading
730 SG_LOG( SG_GENERAL, SG_INFO,
731 "Attempting to set starting position from airport code "
732 << id << " heading " << tgt_hdg );
734 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
735 SG_LOG( SG_GENERAL, SG_ALERT,
736 "Failed to find a good runway for " << id << '\n' );
743 double lat2, lon2, az2;
744 double heading = r._heading;
745 double azimuth = heading + 180.0;
746 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
748 SG_LOG( SG_GENERAL, SG_INFO,
749 "runway = " << r._lon << ", " << r._lat
750 << " length = " << r._length * SG_FEET_TO_METER
751 << " heading = " << azimuth );
753 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
754 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
755 &lat2, &lon2, &az2 );
757 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
759 double odist = fgGetDouble("/sim/presets/offset-distance");
760 odist *= SG_NM_TO_METER;
761 double oaz = azimuth;
762 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
763 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
766 while ( oaz >= 360.0 ) { oaz -= 360.0; }
767 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
773 fgSetDouble("/sim/presets/longitude-deg", lon2 );
774 fgSetDouble("/sim/presets/latitude-deg", lat2 );
775 fgSetDouble("/sim/presets/heading-deg", heading );
777 // other code depends on the actual values being set ...
778 fgSetDouble("/position/longitude-deg", lon2 );
779 fgSetDouble("/position/latitude-deg", lat2 );
780 fgSetDouble("/orientation/heading-deg", heading );
782 SG_LOG( SG_GENERAL, SG_INFO,
783 "Position for " << id << " is ("
785 << lat2 << ") new heading is "
792 // Set current_options lon/lat given an airport id and runway number
793 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
797 // set initial position from airport and runway number
799 SG_LOG( SG_GENERAL, SG_INFO,
800 "Attempting to set starting position for "
801 << id << ":" << rwy );
803 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
804 SG_LOG( SG_GENERAL, SG_ALERT,
805 "Failed to find runway " << rwy <<
806 " at airport " << id );
813 double lat2, lon2, az2;
814 double heading = r._heading;
815 double azimuth = heading + 180.0;
816 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
818 SG_LOG( SG_GENERAL, SG_INFO,
819 "runway = " << r._lon << ", " << r._lat
820 << " length = " << r._length * SG_FEET_TO_METER
821 << " heading = " << azimuth );
823 geo_direct_wgs_84 ( 0, r._lat, r._lon,
825 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
826 &lat2, &lon2, &az2 );
828 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
831 double odist = fgGetDouble("/sim/presets/offset-distance");
832 odist *= SG_NM_TO_METER;
833 double oaz = azimuth;
834 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
836 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
837 heading = fgGetDouble("/sim/presets/heading-deg");
839 while ( oaz >= 360.0 ) { oaz -= 360.0; }
840 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
846 fgSetDouble("/sim/presets/longitude-deg", lon2 );
847 fgSetDouble("/sim/presets/latitude-deg", lat2 );
848 fgSetDouble("/sim/presets/heading-deg", heading );
850 // other code depends on the actual values being set ...
851 fgSetDouble("/position/longitude-deg", lon2 );
852 fgSetDouble("/position/latitude-deg", lat2 );
853 fgSetDouble("/orientation/heading-deg", heading );
855 SG_LOG( SG_GENERAL, SG_INFO,
856 "Position for " << id << " is ("
858 << lat2 << ") new heading is "
865 static void fgSetDistOrAltFromGlideSlope() {
866 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
867 string apt_id = fgGetString("/sim/presets/airport-id");
868 double gs = fgGetDouble("/sim/presets/glideslope-deg")
869 * SG_DEGREES_TO_RADIANS ;
870 double od = fgGetDouble("/sim/presets/offset-distance");
871 double alt = fgGetDouble("/sim/presets/altitude-ft");
873 double apt_elev = 0.0;
874 if ( ! apt_id.empty() ) {
875 apt_elev = fgGetAirportElev( apt_id );
876 if ( apt_elev < -9990.0 ) {
883 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
884 // set altitude from glideslope and offset-distance
885 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
886 alt = fabs(od*tan(gs)) + apt_elev;
887 fgSetDouble("/sim/presets/altitude-ft", alt);
888 fgSetBool("/sim/presets/onground", false);
889 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
891 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
892 // set offset-distance from glideslope and altitude
893 od = (alt - apt_elev) / tan(gs);
894 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
895 fgSetDouble("/sim/presets/offset-distance", od);
896 fgSetBool("/sim/presets/onground", false);
897 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
899 } else if( fabs(gs) > 0.01 ) {
900 SG_LOG( SG_GENERAL, SG_ALERT,
901 "Glideslope given but not altitude or offset-distance." );
902 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
903 fgSetDouble("/sim/presets/glideslope-deg", 0);
904 fgSetBool("/sim/presets/onground", true);
909 // Set current_options lon/lat given an airport id and heading (degrees)
910 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
912 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
914 // set initial position from runway and heading
916 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
917 << id << ":" << freq );
919 double lon = nav->get_lon();
920 double lat = nav->get_lat();
922 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
924 double odist = fgGetDouble("/sim/presets/offset-distance")
926 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
928 while ( oaz >= 360.0 ) { oaz -= 360.0; }
929 double olat, olon, az2;
930 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
937 fgSetDouble("/sim/presets/longitude-deg", lon );
938 fgSetDouble("/sim/presets/latitude-deg", lat );
940 // other code depends on the actual values being set ...
941 fgSetDouble("/position/longitude-deg", lon );
942 fgSetDouble("/position/latitude-deg", lat );
943 fgSetDouble("/orientation/heading-deg",
944 fgGetDouble("/sim/presets/heading-deg") );
946 SG_LOG( SG_GENERAL, SG_INFO,
947 "Position for " << id << ":" << freq << " is ("
948 << lon << ", "<< lat << ")" );
952 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
953 << id << ":" << freq );
958 // Set current_options lon/lat given an aircraft carrier id
959 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
961 // set initial position from runway and heading
965 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
966 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
967 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
968 double alt = geodPos.elev() * SG_METER_TO_FEET;
970 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
971 << carrier << " at lat = " << lat << ", lon = " << lon
972 << ", alt = " << alt << ", heading = " << heading);
974 fgSetDouble("/sim/presets/longitude-deg", lon);
975 fgSetDouble("/sim/presets/latitude-deg", lat);
976 fgSetDouble("/sim/presets/altitude-ft", alt);
977 fgSetDouble("/sim/presets/heading-deg", heading);
978 fgSetDouble("/position/longitude-deg", lon);
979 fgSetDouble("/position/latitude-deg", lat);
980 fgSetDouble("/position/altitude-ft", alt);
981 fgSetDouble("/orientation/heading-deg", heading);
983 fgSetString("/sim/presets/speed-set", "UVW");
984 fgSetDouble("/velocities/uBody-fps", uvw[0]);
985 fgSetDouble("/velocities/vBody-fps", uvw[1]);
986 fgSetDouble("/velocities/wBody-fps", uvw[2]);
987 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
988 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
989 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
991 fgSetBool("/sim/presets/onground", true);
995 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carroer = "
1001 // Set current_options lon/lat given an airport id and heading (degrees)
1002 static bool fgSetPosFromFix( const string& id ) {
1005 // set initial position from runway and heading
1006 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1007 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1010 double lon = fix.get_lon();
1011 double lat = fix.get_lat();
1013 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1015 double odist = fgGetDouble("/sim/presets/offset-distance")
1017 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1019 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1020 double olat, olon, az2;
1021 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1028 fgSetDouble("/sim/presets/longitude-deg", lon );
1029 fgSetDouble("/sim/presets/latitude-deg", lat );
1031 // other code depends on the actual values being set ...
1032 fgSetDouble("/position/longitude-deg", lon );
1033 fgSetDouble("/position/latitude-deg", lat );
1034 fgSetDouble("/orientation/heading-deg",
1035 fgGetDouble("/sim/presets/heading-deg") );
1037 SG_LOG( SG_GENERAL, SG_INFO,
1038 "Position for " << id << " is ("
1039 << lon << ", "<< lat << ")" );
1043 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1049 static void parseWaypoints() {
1050 string_list *waypoints = globals->get_initial_waypoints();
1052 vector<string>::iterator i;
1053 for (i = waypoints->begin();
1054 i != waypoints->end();
1059 // Now were done using the way points we can deallocate the
1061 while (waypoints->begin() != waypoints->end()) {
1062 waypoints->pop_back();
1065 globals->set_initial_waypoints(0);
1074 * Initialize vor/ndb/ils/fix list management and query systems (as
1075 * well as simple airport db list)
1080 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1082 SGPath aptdb( globals->get_fg_root() );
1083 aptdb.append( "Airports/apt.dat" );
1085 SGPath p_metar( globals->get_fg_root() );
1086 p_metar.append( "Airports/metar.dat" );
1088 FGAirportList *airports = new FGAirportList();
1089 globals->set_airports( airports );
1090 FGRunwayList *runways = new FGRunwayList();
1091 globals->set_runways( runways );
1093 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1095 FGNavList *navlist = new FGNavList;
1096 FGNavList *loclist = new FGNavList;
1097 FGNavList *gslist = new FGNavList;
1098 FGNavList *dmelist = new FGNavList;
1099 FGNavList *mkrlist = new FGNavList;
1101 globals->set_navlist( navlist );
1102 globals->set_loclist( loclist );
1103 globals->set_gslist( gslist );
1104 globals->set_dmelist( dmelist );
1105 globals->set_mkrlist( mkrlist );
1107 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist) ) {
1108 SG_LOG( SG_GENERAL, SG_ALERT,
1109 "Problems loading one or more navigational database" );
1112 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1113 // align all the localizers with their corresponding runways
1114 // since data sources are good for cockpit navigation
1115 // purposes, but not always to the error tolerances needed to
1116 // exactly place these items.
1118 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1120 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1123 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1124 SGPath p_fix( globals->get_fg_root() );
1125 p_fix.append( "Navaids/fix.dat" );
1126 FGFixList *fixlist = new FGFixList;
1127 fixlist->init( p_fix );
1128 globals->set_fixlist( fixlist );
1134 // Set the initial position based on presets (or defaults)
1135 bool fgInitPosition() {
1136 // cout << "fgInitPosition()" << endl;
1137 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1138 * SG_DEGREES_TO_RADIANS ;
1139 double od = fgGetDouble("/sim/presets/offset-distance");
1140 double alt = fgGetDouble("/sim/presets/altitude-ft");
1142 bool set_pos = false;
1144 // If glideslope is specified, then calculate offset-distance or
1145 // altitude relative to glide slope if either of those was not
1147 if ( fabs( gs ) > 0.01 ) {
1148 fgSetDistOrAltFromGlideSlope();
1152 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1153 // If not, check for an airport-id and use that.
1154 // If not, default to the middle of the KSFO field.
1155 // The default values for lon/lat are deliberately out of range
1156 // so that the airport-id can take effect; valid lon/lat will
1157 // override airport-id, however.
1158 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1159 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1160 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1161 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1166 string apt = fgGetString("/sim/presets/airport-id");
1167 string rwy_no = fgGetString("/sim/presets/runway");
1168 double hdg = fgGetDouble("/sim/presets/heading-deg");
1169 string vor = fgGetString("/sim/presets/vor-id");
1170 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1171 string ndb = fgGetString("/sim/presets/ndb-id");
1172 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1173 string carrier = fgGetString("/sim/presets/carrier");
1174 string parkpos = fgGetString("/sim/presets/parkpos");
1175 string fix = fgGetString("/sim/presets/fix");
1177 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1178 // An airport + runway is requested
1179 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1180 // set tower position (a little off the heading for single
1182 fgSetTowerPosFromAirportID( apt, hdg );
1187 if ( !set_pos && !apt.empty() ) {
1188 // An airport is requested (find runway closest to hdg)
1189 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1190 // set tower position (a little off the heading for single
1192 fgSetTowerPosFromAirportID( apt, hdg );
1197 if ( !set_pos && !vor.empty() ) {
1198 // a VOR is requested
1199 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1204 if ( !set_pos && !ndb.empty() ) {
1205 // an NDB is requested
1206 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1211 if ( !set_pos && !carrier.empty() ) {
1212 // an aircraft carrier is requested
1213 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1218 if ( !set_pos && !fix.empty() ) {
1219 // a Fix is requested
1220 if ( fgSetPosFromFix( fix ) ) {
1226 // No lon/lat specified, no airport specified, default to
1227 // middle of KSFO field.
1228 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1229 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1232 fgSetDouble( "/position/longitude-deg",
1233 fgGetDouble("/sim/presets/longitude-deg") );
1234 fgSetDouble( "/position/latitude-deg",
1235 fgGetDouble("/sim/presets/latitude-deg") );
1236 fgSetDouble( "/orientation/heading-deg",
1237 fgGetDouble("/sim/presets/heading-deg") );
1239 // determine if this should be an on-ground or in-air start
1240 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1241 fgSetBool("/sim/presets/onground", false);
1243 fgSetBool("/sim/presets/onground", true);
1250 // General house keeping initializations
1251 bool fgInitGeneral() {
1254 #if defined(FX) && defined(XMESA)
1255 char *mesa_win_state;
1258 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1259 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1261 root = globals->get_fg_root();
1262 if ( ! root.length() ) {
1263 // No root path set? Then bail ...
1264 SG_LOG( SG_GENERAL, SG_ALERT,
1265 "Cannot continue without a path to the base package "
1266 << "being defined." );
1269 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1271 #if defined(FX) && defined(XMESA)
1272 // initialize full screen flag
1273 globals->set_fullscreen(false);
1274 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1275 // Test for the MESA_GLX_FX env variable
1276 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1277 // test if we are fullscreen mesa/glide
1278 if ( (mesa_win_state[0] == 'f') ||
1279 (mesa_win_state[0] == 'F') ) {
1280 globals->set_fullscreen(true);
1290 // Initialize the flight model subsystem. This just creates the
1291 // object. The actual fdm initialization is delayed until we get a
1292 // proper scenery elevation hit. This is checked for in main.cxx
1296 if ( cur_fdm_state ) {
1297 delete cur_fdm_state;
1301 double dt = 1.0 / fgGetInt("/sim/model-hz");
1302 aircraft_dir = fgGetString("/sim/aircraft-dir");
1303 const string &model = fgGetString("/sim/flight-model");
1306 if ( model == "larcsim" ) {
1307 cur_fdm_state = new FGLaRCsim( dt );
1308 } else if ( model == "jsb" ) {
1309 cur_fdm_state = new FGJSBsim( dt );
1310 #ifdef ENABLE_SP_FMDS
1311 } else if ( model == "ada" ) {
1312 cur_fdm_state = new FGADA( dt );
1313 } else if ( model == "acms" ) {
1314 cur_fdm_state = new FGACMS( dt );
1316 } else if ( model == "balloon" ) {
1317 cur_fdm_state = new FGBalloonSim( dt );
1318 } else if ( model == "magic" ) {
1319 cur_fdm_state = new FGMagicCarpet( dt );
1320 } else if ( model == "ufo" ) {
1321 cur_fdm_state = new FGUFO( dt );
1322 } else if ( model == "external" ) {
1323 // external is a synonym for "--fdm=null" and is
1324 // maintained here for backwards compatibility
1325 cur_fdm_state = new FGNullFDM( dt );
1326 } else if ( model.find("network") == 0 ) {
1327 string host = "localhost";
1331 string net_options = model.substr(8);
1332 string::size_type begin, end;
1335 end = net_options.find( ",", begin );
1336 if ( end != string::npos ) {
1337 host = net_options.substr(begin, end - begin);
1341 end = net_options.find( ",", begin );
1342 if ( end != string::npos ) {
1343 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1347 end = net_options.find( ",", begin );
1348 if ( end != string::npos ) {
1349 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1353 end = net_options.find( ",", begin );
1354 if ( end != string::npos ) {
1355 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1358 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1359 } else if ( model.find("pipe") == 0 ) {
1360 // /* old */ string pipe_path = model.substr(5);
1361 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1362 string pipe_path = "";
1363 string pipe_protocol = "";
1364 string pipe_options = model.substr(5);
1365 string::size_type begin, end;
1368 end = pipe_options.find( ",", begin );
1369 if ( end != string::npos ) {
1370 pipe_path = pipe_options.substr(begin, end - begin);
1373 // protocol (last option)
1374 pipe_protocol = pipe_options.substr(begin);
1375 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1376 } else if ( model == "null" ) {
1377 cur_fdm_state = new FGNullFDM( dt );
1378 } else if ( model == "yasim" ) {
1379 cur_fdm_state = new YASim( dt );
1381 SG_LOG(SG_GENERAL, SG_ALERT,
1382 "Unrecognized flight model '" << model
1383 << "', cannot init flight dynamics model.");
1387 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1392 static void printMat(const sgVec4 *mat, char *name="")
1395 SG_LOG(SG_GENERAL, SG_BULK, name );
1396 for(i=0; i<4; i++) {
1397 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1398 << " " << mat[i][2] << " " << mat[i][3] );
1402 // Initialize view parameters
1404 // force update of model so that viewer can get some data...
1405 globals->get_aircraft_model()->update(0);
1406 // run update for current view so that data is current...
1407 globals->get_viewmgr()->update(0);
1409 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1410 printMat(globals->get_current_view()->get_UP(),"UP");
1411 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1416 SGTime *fgInitTime() {
1418 static const SGPropertyNode *longitude
1419 = fgGetNode("/position/longitude-deg");
1420 static const SGPropertyNode *latitude
1421 = fgGetNode("/position/latitude-deg");
1422 static const SGPropertyNode *cur_time_override
1423 = fgGetNode("/sim/time/cur-time-override", true);
1425 SGPath zone( globals->get_fg_root() );
1426 zone.append( "Timezone" );
1427 SGTime *t = new SGTime( longitude->getDoubleValue()
1428 * SGD_DEGREES_TO_RADIANS,
1429 latitude->getDoubleValue()
1430 * SGD_DEGREES_TO_RADIANS,
1432 cur_time_override->getLongValue() );
1434 globals->set_warp_delta( 0 );
1436 t->update( 0.0, 0.0,
1437 cur_time_override->getLongValue(),
1438 globals->get_warp() );
1444 // set up a time offset (aka warp) if one is specified
1445 void fgInitTimeOffset() {
1446 static const SGPropertyNode *longitude
1447 = fgGetNode("/position/longitude-deg");
1448 static const SGPropertyNode *latitude
1449 = fgGetNode("/position/latitude-deg");
1450 static const SGPropertyNode *cur_time_override
1451 = fgGetNode("/sim/time/cur-time-override", true);
1453 // Handle potential user specified time offsets
1454 int orig_warp = globals->get_warp();
1455 SGTime *t = globals->get_time_params();
1456 time_t cur_time = t->get_cur_time();
1457 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1458 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1459 time_t aircraftLocalTime =
1460 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1462 // Okay, we now have several possible scenarios
1463 int offset = fgGetInt("/sim/startup/time-offset");
1464 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1467 if ( offset_type == "real" ) {
1469 } else if ( offset_type == "dawn" ) {
1470 warp = fgTimeSecondsUntilSunAngle( cur_time,
1471 longitude->getDoubleValue()
1472 * SGD_DEGREES_TO_RADIANS,
1473 latitude->getDoubleValue()
1474 * SGD_DEGREES_TO_RADIANS,
1476 } else if ( offset_type == "morning" ) {
1477 warp = fgTimeSecondsUntilSunAngle( cur_time,
1478 longitude->getDoubleValue()
1479 * SGD_DEGREES_TO_RADIANS,
1480 latitude->getDoubleValue()
1481 * SGD_DEGREES_TO_RADIANS,
1483 } else if ( offset_type == "noon" ) {
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 == "afternoon" ) {
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 == "dusk" ) {
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 == "evening" ) {
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 == "midnight" ) {
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 == "system-offset" ) {
1520 } else if ( offset_type == "gmt-offset" ) {
1521 warp = offset - (currGMT - systemLocalTime);
1522 } else if ( offset_type == "latitude-offset" ) {
1523 warp = offset - (aircraftLocalTime - systemLocalTime);
1524 } else if ( offset_type == "system" ) {
1525 warp = offset - cur_time;
1526 } else if ( offset_type == "gmt" ) {
1527 warp = offset - currGMT;
1528 } else if ( offset_type == "latitude" ) {
1529 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1531 SG_LOG( SG_GENERAL, SG_ALERT,
1532 "FG_TIME::Unsupported offset type " << offset_type );
1535 globals->set_warp( orig_warp + warp );
1536 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1537 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1538 cur_time_override->getLongValue(),
1539 globals->get_warp() );
1541 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1542 << globals->get_warp() );
1546 // This is the top level init routine which calls all the other
1547 // initialization routines. If you are adding a subsystem to flight
1548 // gear, its initialization call should located in this routine.
1549 // Returns non-zero if a problem encountered.
1550 bool fgInitSubsystems() {
1551 // static const SGPropertyNode *longitude
1552 // = fgGetNode("/sim/presets/longitude-deg");
1553 // static const SGPropertyNode *latitude
1554 // = fgGetNode("/sim/presets/latitude-deg");
1555 // static const SGPropertyNode *altitude
1556 // = fgGetNode("/sim/presets/altitude-ft");
1558 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1559 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1561 ////////////////////////////////////////////////////////////////////
1562 // Initialize the event manager subsystem.
1563 ////////////////////////////////////////////////////////////////////
1565 globals->get_event_mgr()->init();
1566 globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1568 ////////////////////////////////////////////////////////////////////
1569 // Initialize the property interpolator subsystem
1570 ////////////////////////////////////////////////////////////////////
1571 globals->add_subsystem("interpolator", new SGInterpolator);
1574 ////////////////////////////////////////////////////////////////////
1575 // Add the FlightGear property utilities.
1576 ////////////////////////////////////////////////////////////////////
1577 globals->add_subsystem("properties", new FGProperties);
1579 ////////////////////////////////////////////////////////////////////
1580 // Initialize the material property subsystem.
1581 ////////////////////////////////////////////////////////////////////
1583 SGPath mpath( globals->get_fg_root() );
1584 mpath.append( "materials.xml" );
1585 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1586 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1591 ////////////////////////////////////////////////////////////////////
1592 // Initialize the scenery management subsystem.
1593 ////////////////////////////////////////////////////////////////////
1595 if ( globals->get_tile_mgr()->init() ) {
1596 // Load the local scenery data
1597 double visibility_meters = fgGetDouble("/environment/visibility-m");
1599 globals->get_tile_mgr()->update( visibility_meters );
1601 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1605 // cause refresh of viewer scenery timestamps every 15 seconds...
1606 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1607 globals->get_tile_mgr(),
1608 &FGTileMgr::refresh_view_timestamps,
1611 SG_LOG( SG_GENERAL, SG_DEBUG,
1612 "Current terrain elevation after tile mgr init " <<
1613 globals->get_scenery()->get_cur_elev() );
1616 ////////////////////////////////////////////////////////////////////
1617 // Initialize the flight model subsystem.
1618 ////////////////////////////////////////////////////////////////////
1622 // allocates structures so must happen before any of the flight
1623 // model or control parameters are set
1624 fgAircraftInit(); // In the future this might not be the case.
1627 ////////////////////////////////////////////////////////////////////
1628 // Initialize the XML Autopilot subsystem.
1629 ////////////////////////////////////////////////////////////////////
1631 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1632 globals->add_subsystem( "route-manager", new FGRouteMgr );
1635 ////////////////////////////////////////////////////////////////////
1636 // Initialize the view manager subsystem.
1637 ////////////////////////////////////////////////////////////////////
1641 ////////////////////////////////////////////////////////////////////
1642 // Create and register the logger.
1643 ////////////////////////////////////////////////////////////////////
1645 globals->add_subsystem("logger", new FGLogger);
1647 ////////////////////////////////////////////////////////////////////
1648 // Create and register the XML GUI.
1649 ////////////////////////////////////////////////////////////////////
1651 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1654 ////////////////////////////////////////////////////////////////////
1655 // Initialize the local time subsystem.
1656 ////////////////////////////////////////////////////////////////////
1658 // update the current timezone each 30 minutes
1659 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1660 &fgUpdateLocalTime, 30*60 );
1661 fgInitTimeOffset(); // the environment subsystem needs this
1664 ////////////////////////////////////////////////////////////////////
1665 // Initialize the weather subsystem.
1666 ////////////////////////////////////////////////////////////////////
1668 // Initialize the weather modeling subsystem
1669 globals->add_subsystem("environment", new FGEnvironmentMgr);
1672 ////////////////////////////////////////////////////////////////////
1673 // Initialize the lighting subsystem.
1674 ////////////////////////////////////////////////////////////////////
1676 globals->add_subsystem("lighting", new FGLight);
1678 //////////////////////////////////////////////////////////////////////
1679 // Initialize the 2D cloud subsystem.
1680 ////////////////////////////////////////////////////////////////////
1681 fgGetBool("/sim/rendering/bump-mapping", false);
1683 #ifdef ENABLE_AUDIO_SUPPORT
1684 ////////////////////////////////////////////////////////////////////
1685 // Initialize the sound subsystem.
1686 ////////////////////////////////////////////////////////////////////
1688 init_volume = fgGetFloat("/sim/sound/volume");
1689 fgSetFloat("/sim/sound/volume", 0.0f);
1690 globals->set_soundmgr(new SGSoundMgr);
1691 globals->get_soundmgr()->init();
1692 globals->get_soundmgr()->bind();
1695 ////////////////////////////////////////////////////////////////////
1696 // Initialize the sound-effects subsystem.
1697 ////////////////////////////////////////////////////////////////////
1699 globals->add_subsystem("fx", new FGFX);
1703 ////////////////////////////////////////////////////////////////////
1704 // Initialise ATC display system
1705 ////////////////////////////////////////////////////////////////////
1707 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1708 globals->set_ATC_display(new FGATCDisplay);
1709 globals->get_ATC_display()->init();
1711 ////////////////////////////////////////////////////////////////////
1712 // Initialise the ATC Manager
1713 ////////////////////////////////////////////////////////////////////
1715 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1716 globals->set_ATC_mgr(new FGATCMgr);
1717 globals->get_ATC_mgr()->init();
1719 ////////////////////////////////////////////////////////////////////
1720 // Initialise the AI Manager
1721 ////////////////////////////////////////////////////////////////////
1723 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1724 globals->set_AI_mgr(new FGAIMgr);
1725 globals->get_AI_mgr()->init();
1727 ////////////////////////////////////////////////////////////////////
1728 // Initialise the AI Model Manager
1729 ////////////////////////////////////////////////////////////////////
1730 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1731 globals->add_subsystem("ai_model", new FGAIManager);
1732 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1735 // It's probably a good idea to initialize the top level traffic manager
1736 // After the AI and ATC systems have been initialized properly.
1737 // AI Traffic manager
1738 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1739 FGTrafficManager *dispatcher =
1740 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1741 SGPath path = globals->get_fg_root();
1742 path.append("/Traffic/fgtraffic.xml");
1745 //globals->get_subsystem("Traffic Manager")->init();
1747 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1748 globals->add_subsystem("systems", new FGSystemMgr);
1752 ////////////////////////////////////////////////////////////////////
1753 // Initialize the cockpit subsystem
1754 ////////////////////////////////////////////////////////////////////
1755 if( fgCockpitInit( ¤t_aircraft )) {
1756 // Cockpit initialized ok.
1758 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1763 ////////////////////////////////////////////////////////////////////
1764 // Initialize the autopilot subsystem.
1765 ////////////////////////////////////////////////////////////////////
1767 // FIXME: these should go in the
1768 // GUI initialization code, not here.
1769 // fgAPAdjustInit();
1770 NewTgtAirportInit();
1774 ////////////////////////////////////////////////////////////////////
1775 // Initialize I/O subsystem.
1776 ////////////////////////////////////////////////////////////////////
1778 globals->get_io()->init();
1779 globals->get_io()->bind();
1782 ////////////////////////////////////////////////////////////////////
1783 // Add a new 2D panel.
1784 ////////////////////////////////////////////////////////////////////
1786 string panel_path = fgGetString("/sim/panel/path",
1787 "Panels/Default/default.xml");
1789 globals->set_current_panel( fgReadPanel(panel_path) );
1790 if (globals->get_current_panel() == 0) {
1791 SG_LOG( SG_INPUT, SG_ALERT,
1792 "Error reading new panel from " << panel_path );
1794 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1795 globals->get_current_panel()->init();
1796 globals->get_current_panel()->bind();
1800 ////////////////////////////////////////////////////////////////////
1801 // Initialize the controls subsystem.
1802 ////////////////////////////////////////////////////////////////////
1804 globals->get_controls()->init();
1805 globals->get_controls()->bind();
1808 ////////////////////////////////////////////////////////////////////
1809 // Initialize the input subsystem.
1810 ////////////////////////////////////////////////////////////////////
1812 globals->add_subsystem("input", new FGInput);
1815 ////////////////////////////////////////////////////////////////////
1816 // Initialize the replay subsystem
1817 ////////////////////////////////////////////////////////////////////
1818 globals->add_subsystem("replay", new FGReplay);
1820 ////////////////////////////////////////////////////////////////////
1821 // Bind and initialize subsystems.
1822 ////////////////////////////////////////////////////////////////////
1824 globals->get_subsystem_mgr()->bind();
1825 globals->get_subsystem_mgr()->init();
1827 #ifdef FG_MPLAYER_AS
1828 ////////////////////////////////////////////////////////////////////
1829 // Initialize multiplayer subsystem
1830 ////////////////////////////////////////////////////////////////////
1832 globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1833 globals->get_multiplayer_tx_mgr()->init();
1835 globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1836 globals->get_multiplayer_rx_mgr()->init();
1839 ////////////////////////////////////////////////////////////////////////
1840 // Initialize the Nasal interpreter.
1841 // Do this last, so that the loaded scripts see initialized state
1842 ////////////////////////////////////////////////////////////////////////
1843 FGNasalSys* nasal = new FGNasalSys();
1844 globals->add_subsystem("nasal", nasal);
1847 ////////////////////////////////////////////////////////////////////
1848 // At this point we could try and parse the waypoint options
1849 ///////////////////////////////////////////////////////////////////
1852 // initialize methods that depend on other subsystems.
1853 globals->get_subsystem_mgr()->postinit();
1855 ////////////////////////////////////////////////////////////////////////
1856 // End of subsystem initialization.
1857 ////////////////////////////////////////////////////////////////////
1859 SG_LOG( SG_GENERAL, SG_INFO, endl);
1861 // Save the initial state for future
1863 globals->saveInitialState();
1869 void fgReInitSubsystems()
1871 // static const SGPropertyNode *longitude
1872 // = fgGetNode("/sim/presets/longitude-deg");
1873 // static const SGPropertyNode *latitude
1874 // = fgGetNode("/sim/presets/latitude-deg");
1875 static const SGPropertyNode *altitude
1876 = fgGetNode("/sim/presets/altitude-ft");
1877 static const SGPropertyNode *master_freeze
1878 = fgGetNode("/sim/freeze/master");
1880 SG_LOG( SG_GENERAL, SG_INFO,
1881 "fgReInitSubsystems(): /position/altitude = "
1882 << altitude->getDoubleValue() );
1884 bool freeze = master_freeze->getBoolValue();
1886 fgSetBool("/sim/freeze/master", true);
1888 fgSetBool("/sim/crashed", false);
1890 // Initialize the FDM
1893 // allocates structures so must happen before any of the flight
1894 // model or control parameters are set
1895 fgAircraftInit(); // In the future this might not be the case.
1897 // reload offsets from config defaults
1898 globals->get_viewmgr()->reinit();
1902 globals->get_controls()->reset_all();
1904 fgUpdateLocalTime();
1906 // re-init to proper time of day setting
1910 fgSetBool("/sim/freeze/master", false);
1912 fgSetBool("/sim/sceneryloaded",false);