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/sunpos.hxx>
113 #include <Time/sunsolver.hxx>
114 #include <Time/tmp.hxx>
115 #include <Traffic/TrafficMgr.hxx>
118 #include <MultiPlayer/multiplaytxmgr.hxx>
119 #include <MultiPlayer/multiplayrxmgr.hxx>
122 #include <Environment/environment_mgr.hxx>
124 #include "fg_init.hxx"
126 #include "fg_commands.hxx"
127 #include "fg_props.hxx"
128 #include "options.hxx"
129 #include "globals.hxx"
130 #include "logger.hxx"
131 #include "viewmgr.hxx"
133 #if defined(FX) && defined(XMESA)
134 #include <GL/xmesa.h>
137 SG_USING_STD(string);
141 extern const char *default_root;
145 // Scan the command line options for the specified option and return
147 static string fgScanForOption( const string& option, int argc, char **argv ) {
150 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
152 int len = option.length();
155 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
157 string arg = argv[i];
158 if ( arg.find( option ) == 0 ) {
159 return arg.substr( len );
169 // Scan the user config files for the specified option and return
171 static string fgScanForOption( const string& option, const string& path ) {
172 sg_gzifstream in( path );
173 if ( !in.is_open() ) {
177 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
179 int len = option.length();
183 while ( ! in.eof() ) {
186 while ( in.get(c) && c != '\0' ) {
191 #if defined( macintosh )
192 getline( in, line, '\r' );
194 getline( in, line, '\n' );
197 // catch extraneous (DOS) line ending character
198 if ( line[line.length() - 1] < 32 ) {
199 line = line.substr( 0, line.length()-1 );
202 if ( line.find( option ) == 0 ) {
203 return line.substr( len );
213 // Read in configuration (files and command line options) but only set
215 bool fgInitFGRoot ( int argc, char **argv ) {
219 // First parse command line options looking for --fg-root=, this
220 // will override anything specified in a config file
221 root = fgScanForOption( "--fg-root=", argc, argv);
223 #if defined( unix ) || defined( __CYGWIN__ )
224 // Next check home directory for .fgfsrc.hostname file
225 if ( root.empty() ) {
226 envp = ::getenv( "HOME" );
227 if ( envp != NULL ) {
228 SGPath config( envp );
229 config.append( ".fgfsrc" );
231 gethostname( name, 256 );
232 config.concat( "." );
233 config.concat( name );
234 root = fgScanForOption( "--fg-root=", config.str() );
239 // Next check home directory for .fgfsrc file
240 if ( root.empty() ) {
241 envp = ::getenv( "HOME" );
242 if ( envp != NULL ) {
243 SGPath config( envp );
244 config.append( ".fgfsrc" );
245 root = fgScanForOption( "--fg-root=", config.str() );
249 // Next check if fg-root is set as an env variable
250 if ( root.empty() ) {
251 envp = ::getenv( "FG_ROOT" );
252 if ( envp != NULL ) {
257 // Otherwise, default to a random compiled-in location if we can't
258 // find fg-root any other way.
259 if ( root.empty() ) {
260 #if defined( __CYGWIN__ )
261 root = "/FlightGear";
262 #elif defined( WIN32 )
263 root = "\\FlightGear";
264 #elif defined(OSX_BUNDLE)
265 /* the following code looks for the base package directly inside
266 the application bundle. This can be changed fairly easily by
267 fiddling with the code below. And yes, I know it's ugly and verbose.
269 CFBundleRef appBundle = CFBundleGetMainBundle();
270 CFURLRef appUrl = CFBundleCopyBundleURL(appBundle);
271 CFRelease(appBundle);
273 // look for a 'data' subdir directly inside the bundle : is there
274 // a better place? maybe in Resources? I don't know ...
275 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, appUrl, CFSTR("data"), true);
277 // now convert down to a path, and the a c-string
278 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
279 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
282 CFRelease(appBundle);
290 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
291 globals->set_fg_root(root);
297 // Read in configuration (files and command line options) but only set
299 bool fgInitFGAircraft ( int argc, char **argv ) {
303 // First parse command line options looking for --aircraft=, this
304 // will override anything specified in a config file
305 aircraft = fgScanForOption( "--aircraft=", argc, argv );
307 #if defined( unix ) || defined( __CYGWIN__ )
308 // Next check home directory for .fgfsrc.hostname file
309 if ( aircraft.empty() ) {
310 envp = ::getenv( "HOME" );
311 if ( envp != NULL ) {
312 SGPath config( envp );
313 config.append( ".fgfsrc" );
315 gethostname( name, 256 );
316 config.concat( "." );
317 config.concat( name );
318 aircraft = fgScanForOption( "--aircraft=", config.str() );
323 // Next check home directory for .fgfsrc file
324 if ( aircraft.empty() ) {
325 envp = ::getenv( "HOME" );
326 if ( envp != NULL ) {
327 SGPath config( envp );
328 config.append( ".fgfsrc" );
329 aircraft = fgScanForOption( "--aircraft=", config.str() );
333 if ( aircraft.empty() ) {
334 // Check for $fg_root/system.fgfsrc
335 SGPath sysconf( globals->get_fg_root() );
336 sysconf.append( "system.fgfsrc" );
337 aircraft = fgScanForOption( "--aircraft=", sysconf.str() );
339 // if an aircraft was specified, set the property name
340 if ( !aircraft.empty() ) {
341 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
342 fgSetString("/sim/aircraft", aircraft.c_str() );
344 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
351 // Return the current base package version
352 string fgBasePackageVersion() {
353 SGPath base_path( globals->get_fg_root() );
354 base_path.append("version");
356 sg_gzifstream in( base_path.str() );
357 if ( !in.is_open() ) {
358 SGPath old_path( globals->get_fg_root() );
359 old_path.append( "Thanks" );
360 sg_gzifstream old( old_path.str() );
361 if ( !old.is_open() ) {
364 return "[old version]";
375 // Initialize the localization
376 SGPropertyNode *fgInitLocale(const char *language) {
377 SGPropertyNode *c_node = NULL, *d_node = NULL;
378 SGPropertyNode *intl = fgGetNode("/sim/intl");
380 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
382 // localization not defined
387 // Select the proper language from the list
389 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
390 for (unsigned int i = 0; i < locale.size(); i++) {
392 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
393 for (unsigned int j = 0; j < lang.size(); j++) {
395 if (!strcmp(lang[j]->getStringValue(), language)) {
404 d_node = intl->getChild("locale");
408 // Check for localized font
409 SGPropertyNode *font_n = c_node->getNode("font", true);
410 if ( !strcmp(font_n->getStringValue(), "") )
411 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
415 // Load the default strings
417 SGPath d_path( globals->get_fg_root() );
419 const char *d_path_str = d_node->getStringValue("strings");
421 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
425 d_path.append(d_path_str);
426 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
429 SGPropertyNode *strings = c_node->getNode("strings");
431 readProperties(d_path.str(), strings);
432 } catch (const sg_exception &e) {
433 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
438 // Load the language specific strings
440 if (c_node != d_node) {
441 SGPath c_path( globals->get_fg_root() );
443 const char *c_path_str = c_node->getStringValue("strings");
445 SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
449 c_path.append(c_path_str);
450 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
454 readProperties(c_path.str(), strings);
455 } catch (const sg_exception &e) {
456 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
466 // Initialize the localization routines
467 bool fgDetectLanguage() {
468 char *language = ::getenv("LANG");
470 if (language == NULL) {
471 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
475 SGPropertyNode *locale = fgInitLocale(language);
477 SG_LOG(SG_GENERAL, SG_ALERT,
478 "No internationalization settings specified in preferences.xml" );
483 globals->set_locale( locale );
488 // Attempt to locate and parse the various non-XML config files in order
489 // from least precidence to greatest precidence
491 do_options (int argc, char ** argv)
493 // Check for $fg_root/system.fgfsrc
494 SGPath config( globals->get_fg_root() );
495 config.append( "system.fgfsrc" );
496 fgParseOptions(config.str());
498 #if defined( unix ) || defined( __CYGWIN__ )
500 // Check for $fg_root/system.fgfsrc.hostname
501 gethostname( name, 256 );
502 config.concat( "." );
503 config.concat( name );
504 fgParseOptions(config.str());
507 // Check for ~/.fgfsrc
508 char* envp = ::getenv( "HOME" );
509 if ( envp != NULL ) {
511 config.append( ".fgfsrc" );
512 fgParseOptions(config.str());
515 #if defined( unix ) || defined( __CYGWIN__ )
516 // Check for ~/.fgfsrc.hostname
517 gethostname( name, 256 );
518 config.concat( "." );
519 config.concat( name );
520 fgParseOptions(config.str());
523 // Parse remaining command line options
524 // These will override anything specified in a config file
525 fgParseArgs(argc, argv);
529 static string fgFindAircraftPath( const SGPath &path, const string &aircraft ) {
531 ulDir *dirp = ulOpenDir(path.str().c_str());
533 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
537 while ((dire = ulReadDir(dirp)) != NULL) {
539 if ( strcmp("CVS", dire->d_name) && strcmp(".", dire->d_name)
540 && strcmp("..", dire->d_name) )
543 next.append(dire->d_name);
545 string result = fgFindAircraftPath( next, aircraft );
546 if ( ! result.empty() ) {
550 } else if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
561 // Read in configuration (file and command line)
562 bool fgInitConfig ( int argc, char **argv ) {
564 // First, set some sane default values
567 // Read global preferences from $FG_ROOT/preferences.xml
568 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
569 fgLoadProps("preferences.xml", globals->get_props());
570 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
572 // Detect the required language as early as possible
573 if ( !fgDetectLanguage() ) {
577 // Scan user config files and command line for a specified aircraft.
578 fgInitFGAircraft(argc, argv);
580 string aircraft = fgGetString( "/sim/aircraft", "" );
581 if ( aircraft.size() > 0 ) {
582 SGPath aircraft_search( globals->get_fg_root() );
583 aircraft_search.append( "Aircraft" );
585 string aircraft_set = aircraft + "-set.xml";
587 string result = fgFindAircraftPath( aircraft_search, aircraft_set );
588 if ( !result.empty() ) {
589 fgSetString( "/sim/aircraft-dir", result.c_str() );
590 SGPath full_name( result );
591 full_name.append( aircraft_set );
593 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
594 << " from " << full_name.str());
596 readProperties( full_name.str(), globals->get_props() );
597 } catch ( const sg_exception &e ) {
598 string message = "Error reading default aircraft: ";
599 message += e.getFormattedMessage();
600 SG_LOG(SG_INPUT, SG_ALERT, message);
604 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
610 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
613 // parse options after loading aircraft to ensure any user
614 // overrides of defaults are honored.
615 do_options(argc, argv);
621 // find basic airport location info from airport database
622 bool fgFindAirportID( const string& id, FGAirport *a ) {
623 const FGAirport* result;
625 SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
627 result = globals->get_airports()->search( id );
629 if ( result == NULL ) {
630 SG_LOG( SG_GENERAL, SG_ALERT,
631 "Failed to find " << id << " in apt.dat.gz" );
640 SG_LOG( SG_GENERAL, SG_INFO,
641 "Position for " << id << " is ("
642 << a->getLongitude() << ", "
643 << a->getLatitude() << ")" );
649 // get airport elevation
650 static double fgGetAirportElev( const string& id ) {
654 SG_LOG( SG_GENERAL, SG_INFO,
655 "Finding elevation for airport: " << id );
657 if ( fgFindAirportID( id, &a ) ) {
658 return a.getElevation();
667 // This function is never used, but maybe useful in the future ???
670 // Preset lon/lat given an airport id
671 static bool fgSetPosFromAirportID( const string& id ) {
675 SG_LOG( SG_GENERAL, SG_INFO,
676 "Attempting to set starting position from airport code " << id );
678 if ( fgFindAirportID( id, &a ) ) {
680 fgSetDouble("/sim/presets/longitude-deg", a.longitude );
681 fgSetDouble("/sim/presets/latitude-deg", a.latitude );
683 // other code depends on the actual postition being set so set
685 fgSetDouble("/position/longitude-deg", a.longitude );
686 fgSetDouble("/position/latitude-deg", a.latitude );
688 SG_LOG( SG_GENERAL, SG_INFO,
689 "Position for " << id << " is (" << a.longitude
690 << ", " << a.latitude << ")" );
700 // Set current tower position lon/lat given an airport id
701 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
703 // tower height hard coded for now...
704 float towerheight=50.0f;
706 // make a little off the heading for 1 runway airports...
707 float fudge_lon = fabs(sin(hdg)) * .003f;
708 float fudge_lat = .003f - fudge_lon;
710 if ( fgFindAirportID( id, &a ) ) {
711 fgSetDouble("/sim/tower/longitude-deg", a.getLongitude() + fudge_lon);
712 fgSetDouble("/sim/tower/latitude-deg", a.getLatitude() + fudge_lat);
713 fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
722 // Set current_options lon/lat given an airport id and heading (degrees)
723 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
727 // set initial position from runway and heading
729 SG_LOG( SG_GENERAL, SG_INFO,
730 "Attempting to set starting position from airport code "
731 << id << " heading " << tgt_hdg );
733 if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
734 SG_LOG( SG_GENERAL, SG_ALERT,
735 "Failed to find a good runway for " << id << '\n' );
742 double lat2, lon2, az2;
743 double heading = r._heading;
744 double azimuth = heading + 180.0;
745 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
747 SG_LOG( SG_GENERAL, SG_INFO,
748 "runway = " << r._lon << ", " << r._lat
749 << " length = " << r._length * SG_FEET_TO_METER
750 << " heading = " << azimuth );
752 geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth,
753 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
754 &lat2, &lon2, &az2 );
756 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
758 double odist = fgGetDouble("/sim/presets/offset-distance");
759 odist *= SG_NM_TO_METER;
760 double oaz = azimuth;
761 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
762 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
765 while ( oaz >= 360.0 ) { oaz -= 360.0; }
766 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
772 fgSetDouble("/sim/presets/longitude-deg", lon2 );
773 fgSetDouble("/sim/presets/latitude-deg", lat2 );
774 fgSetDouble("/sim/presets/heading-deg", heading );
776 // other code depends on the actual values being set ...
777 fgSetDouble("/position/longitude-deg", lon2 );
778 fgSetDouble("/position/latitude-deg", lat2 );
779 fgSetDouble("/orientation/heading-deg", heading );
781 SG_LOG( SG_GENERAL, SG_INFO,
782 "Position for " << id << " is ("
784 << lat2 << ") new heading is "
791 // Set current_options lon/lat given an airport id and runway number
792 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
796 // set initial position from airport and runway number
798 SG_LOG( SG_GENERAL, SG_INFO,
799 "Attempting to set starting position for "
800 << id << ":" << rwy );
802 if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
803 SG_LOG( SG_GENERAL, SG_ALERT,
804 "Failed to find runway " << rwy <<
805 " at airport " << id );
812 double lat2, lon2, az2;
813 double heading = r._heading;
814 double azimuth = heading + 180.0;
815 while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
817 SG_LOG( SG_GENERAL, SG_INFO,
818 "runway = " << r._lon << ", " << r._lat
819 << " length = " << r._length * SG_FEET_TO_METER
820 << " heading = " << azimuth );
822 geo_direct_wgs_84 ( 0, r._lat, r._lon,
824 r._length * SG_FEET_TO_METER * 0.5 - 5.0,
825 &lat2, &lon2, &az2 );
827 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
830 double odist = fgGetDouble("/sim/presets/offset-distance");
831 odist *= SG_NM_TO_METER;
832 double oaz = azimuth;
833 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
835 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
836 heading = fgGetDouble("/sim/presets/heading-deg");
838 while ( oaz >= 360.0 ) { oaz -= 360.0; }
839 geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
845 fgSetDouble("/sim/presets/longitude-deg", lon2 );
846 fgSetDouble("/sim/presets/latitude-deg", lat2 );
847 fgSetDouble("/sim/presets/heading-deg", heading );
849 // other code depends on the actual values being set ...
850 fgSetDouble("/position/longitude-deg", lon2 );
851 fgSetDouble("/position/latitude-deg", lat2 );
852 fgSetDouble("/orientation/heading-deg", heading );
854 SG_LOG( SG_GENERAL, SG_INFO,
855 "Position for " << id << " is ("
857 << lat2 << ") new heading is "
864 static void fgSetDistOrAltFromGlideSlope() {
865 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
866 string apt_id = fgGetString("/sim/presets/airport-id");
867 double gs = fgGetDouble("/sim/presets/glideslope-deg")
868 * SG_DEGREES_TO_RADIANS ;
869 double od = fgGetDouble("/sim/presets/offset-distance");
870 double alt = fgGetDouble("/sim/presets/altitude-ft");
872 double apt_elev = 0.0;
873 if ( ! apt_id.empty() ) {
874 apt_elev = fgGetAirportElev( apt_id );
875 if ( apt_elev < -9990.0 ) {
882 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
883 // set altitude from glideslope and offset-distance
884 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
885 alt = fabs(od*tan(gs)) + apt_elev;
886 fgSetDouble("/sim/presets/altitude-ft", alt);
887 fgSetBool("/sim/presets/onground", false);
888 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
890 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
891 // set offset-distance from glideslope and altitude
892 od = (alt - apt_elev) / tan(gs);
893 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
894 fgSetDouble("/sim/presets/offset-distance", od);
895 fgSetBool("/sim/presets/onground", false);
896 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
898 } else if( fabs(gs) > 0.01 ) {
899 SG_LOG( SG_GENERAL, SG_ALERT,
900 "Glideslope given but not altitude or offset-distance." );
901 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
902 fgSetDouble("/sim/presets/glideslope-deg", 0);
903 fgSetBool("/sim/presets/onground", true);
908 // Set current_options lon/lat given an airport id and heading (degrees)
909 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
911 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
913 // set initial position from runway and heading
915 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
916 << id << ":" << freq );
918 double lon = nav->get_lon();
919 double lat = nav->get_lat();
921 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
923 double odist = fgGetDouble("/sim/presets/offset-distance")
925 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
927 while ( oaz >= 360.0 ) { oaz -= 360.0; }
928 double olat, olon, az2;
929 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
936 fgSetDouble("/sim/presets/longitude-deg", lon );
937 fgSetDouble("/sim/presets/latitude-deg", lat );
939 // other code depends on the actual values being set ...
940 fgSetDouble("/position/longitude-deg", lon );
941 fgSetDouble("/position/latitude-deg", lat );
942 fgSetDouble("/orientation/heading-deg",
943 fgGetDouble("/sim/presets/heading-deg") );
945 SG_LOG( SG_GENERAL, SG_INFO,
946 "Position for " << id << ":" << freq << " is ("
947 << lon << ", "<< lat << ")" );
951 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
952 << id << ":" << freq );
957 // Set current_options lon/lat given an aircraft carrier id
958 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
960 // set initial position from runway and heading
964 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
965 double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
966 double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
967 double alt = geodPos.elev() * SG_METER_TO_FEET;
969 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
970 << carrier << " at lat = " << lat << ", lon = " << lon
971 << ", alt = " << alt << ", heading = " << heading);
973 fgSetDouble("/sim/presets/longitude-deg", lon);
974 fgSetDouble("/sim/presets/latitude-deg", lat);
975 fgSetDouble("/sim/presets/altitude-ft", alt);
976 fgSetDouble("/sim/presets/heading-deg", heading);
977 fgSetDouble("/position/longitude-deg", lon);
978 fgSetDouble("/position/latitude-deg", lat);
979 fgSetDouble("/position/altitude-ft", alt);
980 fgSetDouble("/orientation/heading-deg", heading);
982 fgSetString("/sim/presets/speed-set", "UVW");
983 fgSetDouble("/velocities/uBody-fps", uvw[0]);
984 fgSetDouble("/velocities/vBody-fps", uvw[1]);
985 fgSetDouble("/velocities/wBody-fps", uvw[2]);
986 fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
987 fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
988 fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
990 fgSetBool("/sim/presets/onground", true);
994 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1000 // Set current_options lon/lat given an airport id and heading (degrees)
1001 static bool fgSetPosFromFix( const string& id ) {
1004 // set initial position from runway and heading
1005 if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1006 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1009 double lon = fix.get_lon();
1010 double lat = fix.get_lat();
1012 if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1014 double odist = fgGetDouble("/sim/presets/offset-distance")
1016 double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1018 while ( oaz >= 360.0 ) { oaz -= 360.0; }
1019 double olat, olon, az2;
1020 geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1027 fgSetDouble("/sim/presets/longitude-deg", lon );
1028 fgSetDouble("/sim/presets/latitude-deg", lat );
1030 // other code depends on the actual values being set ...
1031 fgSetDouble("/position/longitude-deg", lon );
1032 fgSetDouble("/position/latitude-deg", lat );
1033 fgSetDouble("/orientation/heading-deg",
1034 fgGetDouble("/sim/presets/heading-deg") );
1036 SG_LOG( SG_GENERAL, SG_INFO,
1037 "Position for " << id << " is ("
1038 << lon << ", "<< lat << ")" );
1042 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1048 static void parseWaypoints() {
1049 string_list *waypoints = globals->get_initial_waypoints();
1051 vector<string>::iterator i;
1052 for (i = waypoints->begin();
1053 i != waypoints->end();
1058 // Now were done using the way points we can deallocate the
1060 while (waypoints->begin() != waypoints->end()) {
1061 waypoints->pop_back();
1064 globals->set_initial_waypoints(0);
1073 * Initialize vor/ndb/ils/fix list management and query systems (as
1074 * well as simple airport db list)
1079 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1081 SGPath aptdb( globals->get_fg_root() );
1082 aptdb.append( "Airports/apt.dat" );
1084 SGPath p_metar( globals->get_fg_root() );
1085 p_metar.append( "Airports/metar.dat" );
1087 FGAirportList *airports = new FGAirportList();
1088 globals->set_airports( airports );
1089 FGRunwayList *runways = new FGRunwayList();
1090 globals->set_runways( runways );
1092 fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1094 FGNavList *navlist = new FGNavList;
1095 FGNavList *loclist = new FGNavList;
1096 FGNavList *gslist = new FGNavList;
1097 FGNavList *dmelist = new FGNavList;
1098 FGNavList *mkrlist = new FGNavList;
1099 FGNavList *tacanlist = new FGNavList;
1100 FGNavList *carrierlist = new FGNavList;
1101 FGTACANList *channellist = new FGTACANList;
1103 globals->set_navlist( navlist );
1104 globals->set_loclist( loclist );
1105 globals->set_gslist( gslist );
1106 globals->set_dmelist( dmelist );
1107 globals->set_mkrlist( mkrlist );
1108 globals->set_tacanlist( tacanlist );
1109 globals->set_carrierlist( carrierlist );
1110 globals->set_channellist( channellist );
1112 if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1113 SG_LOG( SG_GENERAL, SG_ALERT,
1114 "Problems loading one or more navigational database" );
1117 if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1118 // align all the localizers with their corresponding runways
1119 // since data sources are good for cockpit navigation
1120 // purposes, but not always to the error tolerances needed to
1121 // exactly place these items.
1123 = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1125 fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1128 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1129 SGPath p_fix( globals->get_fg_root() );
1130 p_fix.append( "Navaids/fix.dat" );
1131 FGFixList *fixlist = new FGFixList;
1132 fixlist->init( p_fix );
1133 globals->set_fixlist( fixlist );
1139 // Set the initial position based on presets (or defaults)
1140 bool fgInitPosition() {
1141 // cout << "fgInitPosition()" << endl;
1142 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1143 * SG_DEGREES_TO_RADIANS ;
1144 double od = fgGetDouble("/sim/presets/offset-distance");
1145 double alt = fgGetDouble("/sim/presets/altitude-ft");
1147 bool set_pos = false;
1149 // If glideslope is specified, then calculate offset-distance or
1150 // altitude relative to glide slope if either of those was not
1152 if ( fabs( gs ) > 0.01 ) {
1153 fgSetDistOrAltFromGlideSlope();
1157 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1158 // If not, check for an airport-id and use that.
1159 // If not, default to the middle of the KSFO field.
1160 // The default values for lon/lat are deliberately out of range
1161 // so that the airport-id can take effect; valid lon/lat will
1162 // override airport-id, however.
1163 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1164 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1165 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1166 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1171 string apt = fgGetString("/sim/presets/airport-id");
1172 string rwy_no = fgGetString("/sim/presets/runway");
1173 double hdg = fgGetDouble("/sim/presets/heading-deg");
1174 string vor = fgGetString("/sim/presets/vor-id");
1175 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1176 string ndb = fgGetString("/sim/presets/ndb-id");
1177 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1178 string carrier = fgGetString("/sim/presets/carrier");
1179 string parkpos = fgGetString("/sim/presets/parkpos");
1180 string fix = fgGetString("/sim/presets/fix");
1182 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1183 // An airport + runway is requested
1184 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1185 // set tower position (a little off the heading for single
1187 fgSetTowerPosFromAirportID( apt, hdg );
1192 if ( !set_pos && !apt.empty() ) {
1193 // An airport is requested (find runway closest to hdg)
1194 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1195 // set tower position (a little off the heading for single
1197 fgSetTowerPosFromAirportID( apt, hdg );
1202 if ( !set_pos && !vor.empty() ) {
1203 // a VOR is requested
1204 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1209 if ( !set_pos && !ndb.empty() ) {
1210 // an NDB is requested
1211 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1216 if ( !set_pos && !carrier.empty() ) {
1217 // an aircraft carrier is requested
1218 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1223 if ( !set_pos && !fix.empty() ) {
1224 // a Fix is requested
1225 if ( fgSetPosFromFix( fix ) ) {
1231 // No lon/lat specified, no airport specified, default to
1232 // middle of KSFO field.
1233 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1234 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1237 fgSetDouble( "/position/longitude-deg",
1238 fgGetDouble("/sim/presets/longitude-deg") );
1239 fgSetDouble( "/position/latitude-deg",
1240 fgGetDouble("/sim/presets/latitude-deg") );
1241 fgSetDouble( "/orientation/heading-deg",
1242 fgGetDouble("/sim/presets/heading-deg") );
1244 // determine if this should be an on-ground or in-air start
1245 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1246 fgSetBool("/sim/presets/onground", false);
1248 fgSetBool("/sim/presets/onground", true);
1255 // General house keeping initializations
1256 bool fgInitGeneral() {
1259 #if defined(FX) && defined(XMESA)
1260 char *mesa_win_state;
1263 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1264 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1266 root = globals->get_fg_root();
1267 if ( ! root.length() ) {
1268 // No root path set? Then bail ...
1269 SG_LOG( SG_GENERAL, SG_ALERT,
1270 "Cannot continue without a path to the base package "
1271 << "being defined." );
1274 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1276 #if defined(FX) && defined(XMESA)
1277 // initialize full screen flag
1278 globals->set_fullscreen(false);
1279 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1280 // Test for the MESA_GLX_FX env variable
1281 if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1282 // test if we are fullscreen mesa/glide
1283 if ( (mesa_win_state[0] == 'f') ||
1284 (mesa_win_state[0] == 'F') ) {
1285 globals->set_fullscreen(true);
1295 // Initialize the flight model subsystem. This just creates the
1296 // object. The actual fdm initialization is delayed until we get a
1297 // proper scenery elevation hit. This is checked for in main.cxx
1301 if ( cur_fdm_state ) {
1302 delete cur_fdm_state;
1306 double dt = 1.0 / fgGetInt("/sim/model-hz");
1307 aircraft_dir = fgGetString("/sim/aircraft-dir");
1308 const string &model = fgGetString("/sim/flight-model");
1311 if ( model == "larcsim" ) {
1312 cur_fdm_state = new FGLaRCsim( dt );
1313 } else if ( model == "jsb" ) {
1314 cur_fdm_state = new FGJSBsim( dt );
1315 #ifdef ENABLE_SP_FMDS
1316 } else if ( model == "ada" ) {
1317 cur_fdm_state = new FGADA( dt );
1318 } else if ( model == "acms" ) {
1319 cur_fdm_state = new FGACMS( dt );
1321 } else if ( model == "balloon" ) {
1322 cur_fdm_state = new FGBalloonSim( dt );
1323 } else if ( model == "magic" ) {
1324 cur_fdm_state = new FGMagicCarpet( dt );
1325 } else if ( model == "ufo" ) {
1326 cur_fdm_state = new FGUFO( dt );
1327 } else if ( model == "external" ) {
1328 // external is a synonym for "--fdm=null" and is
1329 // maintained here for backwards compatibility
1330 cur_fdm_state = new FGNullFDM( dt );
1331 } else if ( model.find("network") == 0 ) {
1332 string host = "localhost";
1336 string net_options = model.substr(8);
1337 string::size_type begin, end;
1340 end = net_options.find( ",", begin );
1341 if ( end != string::npos ) {
1342 host = net_options.substr(begin, end - begin);
1346 end = net_options.find( ",", begin );
1347 if ( end != string::npos ) {
1348 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1352 end = net_options.find( ",", begin );
1353 if ( end != string::npos ) {
1354 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1358 end = net_options.find( ",", begin );
1359 if ( end != string::npos ) {
1360 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1363 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1364 } else if ( model.find("pipe") == 0 ) {
1365 // /* old */ string pipe_path = model.substr(5);
1366 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1367 string pipe_path = "";
1368 string pipe_protocol = "";
1369 string pipe_options = model.substr(5);
1370 string::size_type begin, end;
1373 end = pipe_options.find( ",", begin );
1374 if ( end != string::npos ) {
1375 pipe_path = pipe_options.substr(begin, end - begin);
1378 // protocol (last option)
1379 pipe_protocol = pipe_options.substr(begin);
1380 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1381 } else if ( model == "null" ) {
1382 cur_fdm_state = new FGNullFDM( dt );
1383 } else if ( model == "yasim" ) {
1384 cur_fdm_state = new YASim( dt );
1386 SG_LOG(SG_GENERAL, SG_ALERT,
1387 "Unrecognized flight model '" << model
1388 << "', cannot init flight dynamics model.");
1392 SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1397 static void printMat(const sgVec4 *mat, char *name="")
1400 SG_LOG(SG_GENERAL, SG_BULK, name );
1401 for(i=0; i<4; i++) {
1402 SG_LOG(SG_GENERAL, SG_BULK, " " << mat[i][0] << " " << mat[i][1]
1403 << " " << mat[i][2] << " " << mat[i][3] );
1407 // Initialize view parameters
1409 // force update of model so that viewer can get some data...
1410 globals->get_aircraft_model()->update(0);
1411 // run update for current view so that data is current...
1412 globals->get_viewmgr()->update(0);
1414 printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1415 printMat(globals->get_current_view()->get_UP(),"UP");
1416 // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1421 SGTime *fgInitTime() {
1423 static const SGPropertyNode *longitude
1424 = fgGetNode("/position/longitude-deg");
1425 static const SGPropertyNode *latitude
1426 = fgGetNode("/position/latitude-deg");
1427 static const SGPropertyNode *cur_time_override
1428 = fgGetNode("/sim/time/cur-time-override", true);
1430 SGPath zone( globals->get_fg_root() );
1431 zone.append( "Timezone" );
1432 SGTime *t = new SGTime( longitude->getDoubleValue()
1433 * SGD_DEGREES_TO_RADIANS,
1434 latitude->getDoubleValue()
1435 * SGD_DEGREES_TO_RADIANS,
1437 cur_time_override->getLongValue() );
1439 globals->set_warp_delta( 0 );
1441 t->update( 0.0, 0.0,
1442 cur_time_override->getLongValue(),
1443 globals->get_warp() );
1449 // set up a time offset (aka warp) if one is specified
1450 void fgInitTimeOffset() {
1451 static const SGPropertyNode *longitude
1452 = fgGetNode("/position/longitude-deg");
1453 static const SGPropertyNode *latitude
1454 = fgGetNode("/position/latitude-deg");
1455 static const SGPropertyNode *cur_time_override
1456 = fgGetNode("/sim/time/cur-time-override", true);
1458 // Handle potential user specified time offsets
1459 int orig_warp = globals->get_warp();
1460 SGTime *t = globals->get_time_params();
1461 time_t cur_time = t->get_cur_time();
1462 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1463 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1464 time_t aircraftLocalTime =
1465 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1467 // Okay, we now have several possible scenarios
1468 int offset = fgGetInt("/sim/startup/time-offset");
1469 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1472 if ( offset_type == "real" ) {
1474 } else if ( offset_type == "dawn" ) {
1475 warp = fgTimeSecondsUntilSunAngle( cur_time,
1476 longitude->getDoubleValue()
1477 * SGD_DEGREES_TO_RADIANS,
1478 latitude->getDoubleValue()
1479 * SGD_DEGREES_TO_RADIANS,
1481 } else if ( offset_type == "morning" ) {
1482 warp = fgTimeSecondsUntilSunAngle( cur_time,
1483 longitude->getDoubleValue()
1484 * SGD_DEGREES_TO_RADIANS,
1485 latitude->getDoubleValue()
1486 * SGD_DEGREES_TO_RADIANS,
1488 } else if ( offset_type == "noon" ) {
1489 warp = fgTimeSecondsUntilSunAngle( cur_time,
1490 longitude->getDoubleValue()
1491 * SGD_DEGREES_TO_RADIANS,
1492 latitude->getDoubleValue()
1493 * SGD_DEGREES_TO_RADIANS,
1495 } else if ( offset_type == "afternoon" ) {
1496 warp = fgTimeSecondsUntilSunAngle( cur_time,
1497 longitude->getDoubleValue()
1498 * SGD_DEGREES_TO_RADIANS,
1499 latitude->getDoubleValue()
1500 * SGD_DEGREES_TO_RADIANS,
1502 } else if ( offset_type == "dusk" ) {
1503 warp = fgTimeSecondsUntilSunAngle( cur_time,
1504 longitude->getDoubleValue()
1505 * SGD_DEGREES_TO_RADIANS,
1506 latitude->getDoubleValue()
1507 * SGD_DEGREES_TO_RADIANS,
1509 } else if ( offset_type == "evening" ) {
1510 warp = fgTimeSecondsUntilSunAngle( cur_time,
1511 longitude->getDoubleValue()
1512 * SGD_DEGREES_TO_RADIANS,
1513 latitude->getDoubleValue()
1514 * SGD_DEGREES_TO_RADIANS,
1516 } else if ( offset_type == "midnight" ) {
1517 warp = fgTimeSecondsUntilSunAngle( cur_time,
1518 longitude->getDoubleValue()
1519 * SGD_DEGREES_TO_RADIANS,
1520 latitude->getDoubleValue()
1521 * SGD_DEGREES_TO_RADIANS,
1523 } else if ( offset_type == "system-offset" ) {
1525 } else if ( offset_type == "gmt-offset" ) {
1526 warp = offset - (currGMT - systemLocalTime);
1527 } else if ( offset_type == "latitude-offset" ) {
1528 warp = offset - (aircraftLocalTime - systemLocalTime);
1529 } else if ( offset_type == "system" ) {
1530 warp = offset - cur_time;
1531 } else if ( offset_type == "gmt" ) {
1532 warp = offset - currGMT;
1533 } else if ( offset_type == "latitude" ) {
1534 warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time;
1536 SG_LOG( SG_GENERAL, SG_ALERT,
1537 "FG_TIME::Unsupported offset type " << offset_type );
1540 globals->set_warp( orig_warp + warp );
1541 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1542 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1543 cur_time_override->getLongValue(),
1544 globals->get_warp() );
1546 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1547 << globals->get_warp() );
1551 // This is the top level init routine which calls all the other
1552 // initialization routines. If you are adding a subsystem to flight
1553 // gear, its initialization call should located in this routine.
1554 // Returns non-zero if a problem encountered.
1555 bool fgInitSubsystems() {
1556 // static const SGPropertyNode *longitude
1557 // = fgGetNode("/sim/presets/longitude-deg");
1558 // static const SGPropertyNode *latitude
1559 // = fgGetNode("/sim/presets/latitude-deg");
1560 // static const SGPropertyNode *altitude
1561 // = fgGetNode("/sim/presets/altitude-ft");
1563 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1564 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1566 ////////////////////////////////////////////////////////////////////
1567 // Initialize the event manager subsystem.
1568 ////////////////////////////////////////////////////////////////////
1570 globals->get_event_mgr()->init();
1571 globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1573 ////////////////////////////////////////////////////////////////////
1574 // Initialize the property interpolator subsystem
1575 ////////////////////////////////////////////////////////////////////
1576 globals->add_subsystem("interpolator", new SGInterpolator);
1579 ////////////////////////////////////////////////////////////////////
1580 // Add the FlightGear property utilities.
1581 ////////////////////////////////////////////////////////////////////
1582 globals->add_subsystem("properties", new FGProperties);
1584 ////////////////////////////////////////////////////////////////////
1585 // Initialize the material property subsystem.
1586 ////////////////////////////////////////////////////////////////////
1588 SGPath mpath( globals->get_fg_root() );
1589 mpath.append( "materials.xml" );
1590 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1591 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1596 ////////////////////////////////////////////////////////////////////
1597 // Initialize the scenery management subsystem.
1598 ////////////////////////////////////////////////////////////////////
1600 if ( globals->get_tile_mgr()->init() ) {
1601 // Load the local scenery data
1602 double visibility_meters = fgGetDouble("/environment/visibility-m");
1604 globals->get_tile_mgr()->update( visibility_meters );
1606 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1610 // cause refresh of viewer scenery timestamps every 15 seconds...
1611 globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1612 globals->get_tile_mgr(),
1613 &FGTileMgr::refresh_view_timestamps,
1617 ////////////////////////////////////////////////////////////////////
1618 // Initialize the flight model subsystem.
1619 ////////////////////////////////////////////////////////////////////
1623 // allocates structures so must happen before any of the flight
1624 // model or control parameters are set
1625 fgAircraftInit(); // In the future this might not be the case.
1628 ////////////////////////////////////////////////////////////////////
1629 // Initialize the XML Autopilot subsystem.
1630 ////////////////////////////////////////////////////////////////////
1632 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1633 globals->add_subsystem( "route-manager", new FGRouteMgr );
1636 ////////////////////////////////////////////////////////////////////
1637 // Initialize the view manager subsystem.
1638 ////////////////////////////////////////////////////////////////////
1642 ////////////////////////////////////////////////////////////////////
1643 // Create and register the logger.
1644 ////////////////////////////////////////////////////////////////////
1646 globals->add_subsystem("logger", new FGLogger);
1648 ////////////////////////////////////////////////////////////////////
1649 // Create and register the XML GUI.
1650 ////////////////////////////////////////////////////////////////////
1652 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1655 ////////////////////////////////////////////////////////////////////
1656 // Initialize the local time subsystem.
1657 ////////////////////////////////////////////////////////////////////
1659 // update the current timezone each 30 minutes
1660 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1661 &fgUpdateLocalTime, 30*60 );
1662 fgInitTimeOffset(); // the environment subsystem needs this
1665 ////////////////////////////////////////////////////////////////////
1666 // Initialize the weather subsystem.
1667 ////////////////////////////////////////////////////////////////////
1669 // Initialize the weather modeling subsystem
1670 globals->add_subsystem("environment", new FGEnvironmentMgr);
1673 ////////////////////////////////////////////////////////////////////
1674 // Initialize the lighting subsystem.
1675 ////////////////////////////////////////////////////////////////////
1677 globals->add_subsystem("lighting", new FGLight);
1679 //////////////////////////////////////////////////////////////////////
1680 // Initialize the 2D cloud subsystem.
1681 ////////////////////////////////////////////////////////////////////
1682 fgGetBool("/sim/rendering/bump-mapping", false);
1684 #ifdef ENABLE_AUDIO_SUPPORT
1685 ////////////////////////////////////////////////////////////////////
1686 // Initialize the sound subsystem.
1687 ////////////////////////////////////////////////////////////////////
1689 init_volume = fgGetFloat("/sim/sound/volume");
1690 fgSetFloat("/sim/sound/volume", 0.0f);
1691 globals->set_soundmgr(new SGSoundMgr);
1692 globals->get_soundmgr()->init();
1693 globals->get_soundmgr()->bind();
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the sound-effects subsystem.
1698 ////////////////////////////////////////////////////////////////////
1700 globals->add_subsystem("fx", new FGFX);
1704 ////////////////////////////////////////////////////////////////////
1705 // Initialise ATC display system
1706 ////////////////////////////////////////////////////////////////////
1708 SG_LOG(SG_GENERAL, SG_INFO, " ATC Display");
1709 globals->set_ATC_display(new FGATCDisplay);
1710 globals->get_ATC_display()->init();
1712 ////////////////////////////////////////////////////////////////////
1713 // Initialise the ATC Manager
1714 ////////////////////////////////////////////////////////////////////
1716 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1717 globals->set_ATC_mgr(new FGATCMgr);
1718 globals->get_ATC_mgr()->init();
1720 ////////////////////////////////////////////////////////////////////
1721 // Initialise the AI Manager
1722 ////////////////////////////////////////////////////////////////////
1724 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1725 globals->set_AI_mgr(new FGAIMgr);
1726 globals->get_AI_mgr()->init();
1728 ////////////////////////////////////////////////////////////////////
1729 // Initialise the AI Model Manager
1730 ////////////////////////////////////////////////////////////////////
1731 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1732 globals->add_subsystem("ai_model", new FGAIManager);
1733 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1736 // It's probably a good idea to initialize the top level traffic manager
1737 // After the AI and ATC systems have been initialized properly.
1738 // AI Traffic manager
1739 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1740 FGTrafficManager *dispatcher =
1741 (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1742 SGPath path = globals->get_fg_root();
1743 path.append("/Traffic/fgtraffic.xml");
1746 //globals->get_subsystem("Traffic Manager")->init();
1748 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1749 globals->add_subsystem("systems", new FGSystemMgr);
1753 ////////////////////////////////////////////////////////////////////
1754 // Initialize the cockpit subsystem
1755 ////////////////////////////////////////////////////////////////////
1756 if( fgCockpitInit( ¤t_aircraft )) {
1757 // Cockpit initialized ok.
1759 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1764 ////////////////////////////////////////////////////////////////////
1765 // Initialize the autopilot subsystem.
1766 ////////////////////////////////////////////////////////////////////
1768 // FIXME: these should go in the
1769 // GUI initialization code, not here.
1770 // fgAPAdjustInit();
1771 NewTgtAirportInit();
1775 ////////////////////////////////////////////////////////////////////
1776 // Initialize I/O subsystem.
1777 ////////////////////////////////////////////////////////////////////
1779 globals->get_io()->init();
1780 globals->get_io()->bind();
1783 ////////////////////////////////////////////////////////////////////
1784 // Add a new 2D panel.
1785 ////////////////////////////////////////////////////////////////////
1787 string panel_path = fgGetString("/sim/panel/path",
1788 "Panels/Default/default.xml");
1790 globals->set_current_panel( fgReadPanel(panel_path) );
1791 if (globals->get_current_panel() == 0) {
1792 SG_LOG( SG_INPUT, SG_ALERT,
1793 "Error reading new panel from " << panel_path );
1795 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1796 globals->get_current_panel()->init();
1797 globals->get_current_panel()->bind();
1801 ////////////////////////////////////////////////////////////////////
1802 // Initialize the controls subsystem.
1803 ////////////////////////////////////////////////////////////////////
1805 globals->get_controls()->init();
1806 globals->get_controls()->bind();
1809 ////////////////////////////////////////////////////////////////////
1810 // Initialize the input subsystem.
1811 ////////////////////////////////////////////////////////////////////
1813 globals->add_subsystem("input", new FGInput);
1816 ////////////////////////////////////////////////////////////////////
1817 // Initialize the replay subsystem
1818 ////////////////////////////////////////////////////////////////////
1819 globals->add_subsystem("replay", new FGReplay);
1821 ////////////////////////////////////////////////////////////////////
1822 // Bind and initialize subsystems.
1823 ////////////////////////////////////////////////////////////////////
1825 globals->get_subsystem_mgr()->bind();
1826 globals->get_subsystem_mgr()->init();
1828 #ifdef FG_MPLAYER_AS
1829 ////////////////////////////////////////////////////////////////////
1830 // Initialize multiplayer subsystem
1831 ////////////////////////////////////////////////////////////////////
1833 globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1834 globals->get_multiplayer_tx_mgr()->init();
1836 globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1837 globals->get_multiplayer_rx_mgr()->init();
1840 ////////////////////////////////////////////////////////////////////////
1841 // Initialize the Nasal interpreter.
1842 // Do this last, so that the loaded scripts see initialized state
1843 ////////////////////////////////////////////////////////////////////////
1844 FGNasalSys* nasal = new FGNasalSys();
1845 globals->add_subsystem("nasal", nasal);
1848 ////////////////////////////////////////////////////////////////////
1849 // At this point we could try and parse the waypoint options
1850 ///////////////////////////////////////////////////////////////////
1853 // initialize methods that depend on other subsystems.
1854 globals->get_subsystem_mgr()->postinit();
1856 ////////////////////////////////////////////////////////////////////////
1857 // End of subsystem initialization.
1858 ////////////////////////////////////////////////////////////////////
1860 SG_LOG( SG_GENERAL, SG_INFO, endl);
1862 // Save the initial state for future
1864 globals->saveInitialState();
1870 void fgReInitSubsystems()
1872 // static const SGPropertyNode *longitude
1873 // = fgGetNode("/sim/presets/longitude-deg");
1874 // static const SGPropertyNode *latitude
1875 // = fgGetNode("/sim/presets/latitude-deg");
1876 static const SGPropertyNode *altitude
1877 = fgGetNode("/sim/presets/altitude-ft");
1878 static const SGPropertyNode *master_freeze
1879 = fgGetNode("/sim/freeze/master");
1881 SG_LOG( SG_GENERAL, SG_INFO,
1882 "fgReInitSubsystems(): /position/altitude = "
1883 << altitude->getDoubleValue() );
1885 bool freeze = master_freeze->getBoolValue();
1887 fgSetBool("/sim/freeze/master", true);
1889 fgSetBool("/sim/crashed", false);
1891 // Force reupdating the positions of the ai 3d models. They are used for
1892 // initializing ground level for the FDM.
1893 globals->get_subsystem("ai_model")->reinit();
1895 // Initialize the FDM
1898 // allocates structures so must happen before any of the flight
1899 // model or control parameters are set
1900 fgAircraftInit(); // In the future this might not be the case.
1902 // reload offsets from config defaults
1903 globals->get_viewmgr()->reinit();
1907 globals->get_controls()->reset_all();
1909 fgUpdateLocalTime();
1911 // re-init to proper time of day setting
1915 fgSetBool("/sim/freeze/master", false);
1917 fgSetBool("/sim/sceneryloaded",false);