1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
40 # include "winsock2.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>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/scene/model/particles.hxx>
63 #include <simgear/sound/soundmgr_openal.hxx>
64 #include <simgear/timing/sg_time.hxx>
65 #include <simgear/timing/lowleveltime.h>
67 #include <Aircraft/aircraft.hxx>
68 #include <Aircraft/controls.hxx>
69 #include <Aircraft/replay.hxx>
70 #include <Airports/apt_loader.hxx>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/dynamics.hxx>
75 #include <AIModel/AIManager.hxx>
78 # include <ATCDCL/ATCmgr.hxx>
79 # include <ATCDCL/AIMgr.hxx>
80 # include "ATCDCL/commlist.hxx"
82 # include "ATC/atcutils.hxx"
85 #include <Autopilot/route_mgr.hxx>
86 #include <Autopilot/autopilotgroup.hxx>
88 #include <Cockpit/cockpit.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Cockpit/panel_io.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Include/general.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Navaids/fix.hxx>
102 #include <Navaids/fixlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/voice.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/sunsolver.hxx>
110 #include <Time/tmp.hxx>
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <FDM/fdm_shell.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Environment/ridge_lift.hxx>
118 #include "fg_init.hxx"
120 #include "fg_commands.hxx"
121 #include "fg_props.hxx"
122 #include "options.hxx"
123 #include "globals.hxx"
124 #include "logger.hxx"
125 #include "renderer.hxx"
126 #include "viewmgr.hxx"
131 # include <CoreFoundation/CoreFoundation.h>
135 using namespace boost::algorithm;
137 extern const char *default_root;
140 // Scan the command line options for the specified option and return
142 static string fgScanForOption( const string& option, int argc, char **argv ) {
145 if (hostname == NULL)
148 gethostname(_hostname, 256);
149 hostname = strdup(_hostname);
150 free_hostname = true;
153 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
155 int len = option.length();
158 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
160 string arg = argv[i];
161 if ( arg.find( option ) == 0 ) {
162 return arg.substr( len );
172 // Scan the user config files for the specified option and return
174 static string fgScanForOption( const string& option, const string& path ) {
175 sg_gzifstream in( path );
176 if ( !in.is_open() ) {
180 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
182 int len = option.length();
185 while ( ! in.eof() ) {
187 getline( in, line, '\n' );
189 // catch extraneous (DOS) line ending character
190 if ( line[line.length() - 1] < 32 ) {
191 line = line.substr( 0, line.length()-1 );
194 if ( line.find( option ) == 0 ) {
195 return line.substr( len );
204 // Scan the user config files for the specified option and return
206 static string fgScanForOption( const string& option ) {
209 #if defined( unix ) || defined( __CYGWIN__ )
210 // Next check home directory for .fgfsrc.hostname file
212 if ( homedir != NULL ) {
213 SGPath config( homedir );
214 config.append( ".fgfsrc" );
215 config.concat( "." );
216 config.concat( hostname );
217 arg = fgScanForOption( option, config.str() );
222 // Next check home directory for .fgfsrc file
224 if ( homedir != NULL ) {
225 SGPath config( homedir );
226 config.append( ".fgfsrc" );
227 arg = fgScanForOption( option, config.str() );
232 // Check for $fg_root/system.fgfsrc
233 SGPath config( globals->get_fg_root() );
234 config.append( "system.fgfsrc" );
235 arg = fgScanForOption( option, config.str() );
242 // Read in configuration (files and command line options) but only set
244 bool fgInitFGRoot ( int argc, char **argv ) {
247 // First parse command line options looking for --fg-root=, this
248 // will override anything specified in a config file
249 root = fgScanForOption( "--fg-root=", argc, argv);
251 // Check in one of the user configuration files.
253 root = fgScanForOption( "--fg-root=" );
255 // Next check if fg-root is set as an env variable
256 if ( root.empty() ) {
257 char *envp = ::getenv( "FG_ROOT" );
258 if ( envp != NULL ) {
263 // Otherwise, default to a random compiled-in location if we can't
264 // find fg-root any other way.
265 if ( root.empty() ) {
266 #if defined( __CYGWIN__ )
268 #elif defined( _WIN32 )
270 #elif defined(__APPLE__)
272 The following code looks for the base package inside the application
273 bundle, in the standard Contents/Resources location.
275 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
277 // look for a 'data' subdir
278 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
280 // now convert down to a path, and the a c-string
281 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
282 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
284 CFRelease(resourcesUrl);
292 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
293 globals->set_fg_root(root);
299 // Read in configuration (files and command line options) but only set
301 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 );
307 if ( aircraft.empty() ) {
308 // check synonym option
309 aircraft = fgScanForOption( "--vehicle=", argc, argv );
312 // Check in one of the user configuration files.
313 if ( aircraft.empty() ) {
314 aircraft = fgScanForOption( "--aircraft=" );
316 if ( aircraft.empty() ) {
317 aircraft = fgScanForOption( "--vehicle=" );
320 // if an aircraft was specified, set the property name
321 if ( !aircraft.empty() ) {
322 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
323 fgSetString("/sim/aircraft", aircraft.c_str() );
325 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
332 // Return the current base package version
333 string fgBasePackageVersion() {
334 SGPath base_path( globals->get_fg_root() );
335 base_path.append("version");
337 sg_gzifstream in( base_path.str() );
338 if ( !in.is_open() ) {
339 SGPath old_path( globals->get_fg_root() );
340 old_path.append( "Thanks" );
341 sg_gzifstream old( old_path.str() );
342 if ( !old.is_open() ) {
345 return "[old version]";
356 // Initialize the localization
357 SGPropertyNode *fgInitLocale(const char *language) {
358 SGPropertyNode *c_node = NULL, *d_node = NULL;
359 SGPropertyNode *intl = fgGetNode("/sim/intl");
361 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
363 // localization not defined
368 // Select the proper language from the list
370 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
371 for (unsigned int i = 0; i < locale.size(); i++) {
373 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
374 for (unsigned int j = 0; j < lang.size(); j++) {
376 if (!strcmp(lang[j]->getStringValue(), language)) {
385 d_node = intl->getChild("locale");
389 // Check for localized font
390 SGPropertyNode *font_n = c_node->getNode("font", true);
391 if ( !strcmp(font_n->getStringValue(), "") )
392 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
396 // Load the default strings
398 SGPath d_path( globals->get_fg_root() );
400 const char *d_path_str = d_node->getStringValue("strings");
402 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
406 d_path.append(d_path_str);
407 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
409 SGPropertyNode *strings = c_node->getNode("strings");
411 readProperties(d_path.str(), strings);
412 } catch (const sg_exception &) {
413 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
418 // Load the language specific strings
420 if (c_node != d_node) {
421 SGPath c_path( globals->get_fg_root() );
423 const char *c_path_str = c_node->getStringValue("strings");
425 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
429 c_path.append(c_path_str);
430 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
433 readProperties(c_path.str(), strings);
434 } catch (const sg_exception &) {
435 SG_LOG(SG_GENERAL, SG_ALERT,
436 "Unable to read the localized strings from " << c_path.str());
446 // Initialize the localization routines
447 bool fgDetectLanguage() {
448 const char *language = ::getenv("LANG");
450 if (language == NULL) {
451 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
455 SGPropertyNode *locale = fgInitLocale(language);
457 SG_LOG(SG_GENERAL, SG_ALERT,
458 "No internationalization settings specified in preferences.xml" );
463 globals->set_locale( locale );
468 // Attempt to locate and parse the various non-XML config files in order
469 // from least precidence to greatest precidence
471 do_options (int argc, char ** argv)
473 // Check for $fg_root/system.fgfsrc
474 SGPath config( globals->get_fg_root() );
475 config.append( "system.fgfsrc" );
476 fgParseOptions(config.str());
478 #if defined( unix ) || defined( __CYGWIN__ )
479 config.concat( "." );
480 config.concat( hostname );
481 fgParseOptions(config.str());
484 // Check for ~/.fgfsrc
485 if ( homedir != NULL ) {
486 config.set( homedir );
487 config.append( ".fgfsrc" );
488 fgParseOptions(config.str());
491 #if defined( unix ) || defined( __CYGWIN__ )
492 // Check for ~/.fgfsrc.hostname
493 config.concat( "." );
494 config.concat( hostname );
495 fgParseOptions(config.str());
498 // Parse remaining command line options
499 // These will override anything specified in a config file
500 fgParseArgs(argc, argv);
504 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
505 SGPropertyNode *cache, int depth = 0 )
507 const int MAXDEPTH = 1;
510 ulDir *dirp = ulOpenDir(path.str().c_str());
512 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
517 while ((dire = ulReadDir(dirp)) != NULL) {
519 if (depth > MAXDEPTH)
522 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
523 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
527 next.append(dire->d_name);
529 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
530 if ( ! result.empty() )
534 int len = strlen(dire->d_name);
535 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
541 if (!cache->getChild("aircraft", i++, false))
544 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
546 n = entry->getNode("file", true);
547 n->setStringValue(dire->d_name);
548 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
550 n = entry->getNode("path", true);
551 n->setStringValue(path.str().c_str());
552 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
554 if ( boost::equals(dire->d_name, aircraft.c_str(), is_iequal()) ) {
566 // Read in configuration (file and command line)
567 bool fgInitConfig ( int argc, char **argv ) {
569 // First, set some sane default values
572 // Read global preferences from $FG_ROOT/preferences.xml
573 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
574 fgLoadProps("preferences.xml", globals->get_props());
575 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
577 // Detect the required language as early as possible
578 if ( !fgDetectLanguage() ) {
582 SGPropertyNode autosave;
584 char *envp = ::getenv( "APPDATA" );
586 SGPath config( envp );
587 config.append( "flightgear.org" );
589 if ( homedir != NULL ) {
590 SGPath config( homedir );
591 config.append( ".fgfs" );
593 const char *fg_home = getenv("FG_HOME");
597 SGPath home_export(config.str());
598 home_export.append("Export/dummy");
599 home_export.create_dir(0777);
601 // Set /sim/fg-home and don't allow malign code to override it until
602 // Nasal security is set up. Use FG_HOME if necessary.
603 SGPropertyNode *home = fgGetNode("/sim", true);
604 home->removeChild("fg-home", 0, false);
605 home = home->getChild("fg-home", 0, true);
606 home->setStringValue(config.c_str());
607 home->setAttribute(SGPropertyNode::WRITE, false);
609 config.append( "autosave.xml" );
610 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
612 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
614 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
616 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
618 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
621 // Scan user config files and command line for a specified aircraft.
622 fgInitFGAircraft(argc, argv);
624 string aircraft = fgGetString( "/sim/aircraft", "" );
625 if ( aircraft.size() > 0 ) {
626 SGPath aircraft_search( globals->get_fg_root() );
627 aircraft_search.append( "Aircraft" );
629 string aircraft_set = aircraft + "-set.xml";
632 // check if the *-set.xml file is already in the cache
633 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
634 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
635 for (unsigned int i = 0; i < cache.size(); i++) {
636 const char *name = cache[i]->getStringValue("file", "");
637 if (boost::equals(aircraft_set, name, is_iequal())) {
638 const char *path = cache[i]->getStringValue("path", "");
648 if (result.empty()) {
649 // prepare cache for rescan
650 SGPropertyNode *n = cache_root->getNode("fg-root", true);
651 n->setStringValue(globals->get_fg_root().c_str());
652 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
653 cache_root->removeChildren("aircraft");
655 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
658 if ( !result.empty() ) {
659 fgSetString( "/sim/aircraft-dir", result.c_str() );
660 SGPath full_name( result );
661 full_name.append( aircraft_set );
663 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
664 << " from " << full_name.str());
666 readProperties( full_name.str(), globals->get_props() );
667 } catch ( const sg_exception &e ) {
668 string message = "Error reading default aircraft: ";
669 message += e.getFormattedMessage();
670 SG_LOG(SG_INPUT, SG_ALERT, message);
674 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
680 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
683 copyProperties(&autosave, globals->get_props());
685 // parse options after loading aircraft to ensure any user
686 // overrides of defaults are honored.
687 do_options(argc, argv);
692 // Set current tower position lon/lat given an airport id
693 static bool fgSetTowerPosFromAirportID( const string& id) {
694 const FGAirport *a = fgFindAirportID( id);
696 SGGeod tower = a->getTowerLocation();
697 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
698 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
699 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
707 struct FGTowerLocationListener : SGPropertyChangeListener {
708 void valueChanged(SGPropertyNode* node) {
709 const string id(node->getStringValue());
710 fgSetTowerPosFromAirportID(id);
714 void fgInitTowerLocationListener() {
715 fgGetNode("/sim/tower/airport-id", true)
716 ->addChangeListener( new FGTowerLocationListener(), true );
719 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
721 SGGeod startPos(aStartPos);
722 if (aTargetHeading == HUGE_VAL) {
723 aTargetHeading = aHeading;
726 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
727 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
728 offsetDistance *= SG_NM_TO_METER;
729 double offsetAzimuth = aHeading;
730 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
731 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
732 aHeading = aTargetHeading;
737 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
742 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
743 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
744 fgSetDouble("/sim/presets/heading-deg", aHeading );
746 // other code depends on the actual values being set ...
747 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
748 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
749 fgSetDouble("/orientation/heading-deg", aHeading );
752 // Set current_options lon/lat given an airport id and heading (degrees)
753 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
757 // set initial position from runway and heading
758 SG_LOG( SG_GENERAL, SG_INFO,
759 "Attempting to set starting position from airport code "
760 << id << " heading " << tgt_hdg );
762 const FGAirport* apt = fgFindAirportID(id);
763 if (!apt) return false;
764 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
765 fgSetString("/sim/atc/runway", r->ident().c_str());
767 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
768 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
772 // Set current_options lon/lat given an airport id and parkig position name
773 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
777 // can't see an easy way around this const_cast at the moment
778 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
780 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
783 FGAirportDynamics* dcs = apt->getDynamics();
785 SG_LOG( SG_GENERAL, SG_ALERT,
786 "Failed to find parking position " << parkpos <<
787 " at airport " << id );
791 int park_index = dcs->getNrOfParkings() - 1;
792 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
793 if (park_index < 0) {
794 SG_LOG( SG_GENERAL, SG_ALERT,
795 "Failed to find parking position " << parkpos <<
796 " at airport " << id );
799 FGParking* parking = dcs->getParking(park_index);
800 parking->setAvailable(false);
802 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
803 parking->getHeading());
808 // Set current_options lon/lat given an airport id and runway number
809 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
813 // set initial position from airport and runway number
814 SG_LOG( SG_GENERAL, SG_INFO,
815 "Attempting to set starting position for "
816 << id << ":" << rwy );
818 const FGAirport* apt = fgFindAirportID(id);
820 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
824 if (!apt->hasRunwayWithIdent(rwy)) {
825 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
826 "Failed to find runway " << rwy <<
827 " at airport " << id << ". Using default runway." );
831 FGRunway* r(apt->getRunwayByIdent(rwy));
832 fgSetString("/sim/atc/runway", r->ident().c_str());
833 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
834 fgApplyStartOffset(startPos, r->headingDeg());
839 static void fgSetDistOrAltFromGlideSlope() {
840 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
841 string apt_id = fgGetString("/sim/presets/airport-id");
842 double gs = fgGetDouble("/sim/presets/glideslope-deg")
843 * SG_DEGREES_TO_RADIANS ;
844 double od = fgGetDouble("/sim/presets/offset-distance-nm");
845 double alt = fgGetDouble("/sim/presets/altitude-ft");
847 double apt_elev = 0.0;
848 if ( ! apt_id.empty() ) {
849 apt_elev = fgGetAirportElev( apt_id );
850 if ( apt_elev < -9990.0 ) {
857 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
858 // set altitude from glideslope and offset-distance
859 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
860 alt = fabs(od*tan(gs)) + apt_elev;
861 fgSetDouble("/sim/presets/altitude-ft", alt);
862 fgSetBool("/sim/presets/onground", false);
863 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
865 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
866 // set offset-distance from glideslope and altitude
867 od = (alt - apt_elev) / tan(gs);
868 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
869 fgSetDouble("/sim/presets/offset-distance-nm", od);
870 fgSetBool("/sim/presets/onground", false);
871 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
873 } else if( fabs(gs) > 0.01 ) {
874 SG_LOG( SG_GENERAL, SG_ALERT,
875 "Glideslope given but not altitude or offset-distance." );
876 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
877 fgSetDouble("/sim/presets/glideslope-deg", 0);
878 fgSetBool("/sim/presets/onground", true);
883 // Set current_options lon/lat given an airport id and heading (degrees)
884 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
886 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
889 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
890 << id << ":" << freq );
894 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
898 // Set current_options lon/lat given an aircraft carrier id
899 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
901 // set initial position from runway and heading
905 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
906 double lon = geodPos.getLongitudeDeg();
907 double lat = geodPos.getLatitudeDeg();
908 double alt = geodPos.getElevationFt();
910 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
911 << carrier << " at lat = " << lat << ", lon = " << lon
912 << ", alt = " << alt << ", heading = " << heading);
914 fgSetDouble("/sim/presets/longitude-deg", lon);
915 fgSetDouble("/sim/presets/latitude-deg", lat);
916 fgSetDouble("/sim/presets/altitude-ft", alt);
917 fgSetDouble("/sim/presets/heading-deg", heading);
918 fgSetDouble("/position/longitude-deg", lon);
919 fgSetDouble("/position/latitude-deg", lat);
920 fgSetDouble("/position/altitude-ft", alt);
921 fgSetDouble("/orientation/heading-deg", heading);
923 fgSetString("/sim/presets/speed-set", "UVW");
924 fgSetDouble("/velocities/uBody-fps", uvw(0));
925 fgSetDouble("/velocities/vBody-fps", uvw(1));
926 fgSetDouble("/velocities/wBody-fps", uvw(2));
927 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
928 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
929 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
931 fgSetBool("/sim/presets/onground", true);
935 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
941 // Set current_options lon/lat given an airport id and heading (degrees)
942 static bool fgSetPosFromFix( const string& id )
944 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
945 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
947 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
951 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
956 * Initialize vor/ndb/ils/fix list management and query systems (as
957 * well as simple airport db list)
962 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
964 SGPath aptdb( globals->get_fg_root() );
965 aptdb.append( "Airports/apt.dat" );
967 SGPath p_metar( globals->get_fg_root() );
968 p_metar.append( "Airports/metar.dat" );
970 // Initialise the frequency search map BEFORE reading
971 // the airport database:
975 current_commlist = new FGCommList;
976 current_commlist->init( globals->get_fg_root() );
977 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
979 FGNavList *navlist = new FGNavList;
980 FGNavList *loclist = new FGNavList;
981 FGNavList *gslist = new FGNavList;
982 FGNavList *dmelist = new FGNavList;
983 FGNavList *tacanlist = new FGNavList;
984 FGNavList *carrierlist = new FGNavList;
985 FGTACANList *channellist = new FGTACANList;
987 globals->set_navlist( navlist );
988 globals->set_loclist( loclist );
989 globals->set_gslist( gslist );
990 globals->set_dmelist( dmelist );
991 globals->set_tacanlist( tacanlist );
992 globals->set_carrierlist( carrierlist );
993 globals->set_channellist( channellist );
995 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
996 SG_LOG( SG_GENERAL, SG_ALERT,
997 "Problems loading one or more navigational database" );
1000 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1001 SGPath p_fix( globals->get_fg_root() );
1002 p_fix.append( "Navaids/fix.dat" );
1004 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1006 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1007 SGPath p_awy( globals->get_fg_root() );
1008 p_awy.append( "Navaids/awy.dat" );
1009 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1010 //cerr << "Loading Airways" << endl;
1011 awyNet->load (p_awy );
1013 //cerr << "initializing airways" << endl;
1014 globals->set_airwaynet( awyNet );
1020 // Set the initial position based on presets (or defaults)
1021 bool fgInitPosition() {
1022 // cout << "fgInitPosition()" << endl;
1023 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1024 * SG_DEGREES_TO_RADIANS ;
1025 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1026 double alt = fgGetDouble("/sim/presets/altitude-ft");
1028 bool set_pos = false;
1030 // If glideslope is specified, then calculate offset-distance or
1031 // altitude relative to glide slope if either of those was not
1033 if ( fabs( gs ) > 0.01 ) {
1034 fgSetDistOrAltFromGlideSlope();
1038 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1039 // If not, check for an airport-id and use that.
1040 // If not, default to the middle of the KSFO field.
1041 // The default values for lon/lat are deliberately out of range
1042 // so that the airport-id can take effect; valid lon/lat will
1043 // override airport-id, however.
1044 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1045 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1046 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1047 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1052 string apt = fgGetString("/sim/presets/airport-id");
1053 string rwy_no = fgGetString("/sim/presets/runway");
1054 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1055 string vor = fgGetString("/sim/presets/vor-id");
1056 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1057 string ndb = fgGetString("/sim/presets/ndb-id");
1058 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1059 string carrier = fgGetString("/sim/presets/carrier");
1060 string parkpos = fgGetString("/sim/presets/parkpos");
1061 string fix = fgGetString("/sim/presets/fix");
1062 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1063 double hdg = hdg_preset->getDoubleValue();
1065 // save some start parameters, so that we can later say what the
1066 // user really requested. TODO generalize that and move it to options.cxx
1067 static bool start_options_saved = false;
1068 if (!start_options_saved) {
1069 start_options_saved = true;
1070 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1072 opt->setDoubleValue("latitude-deg", lat_deg);
1073 opt->setDoubleValue("longitude-deg", lon_deg);
1074 opt->setDoubleValue("heading-deg", hdg);
1075 opt->setStringValue("airport", apt.c_str());
1076 opt->setStringValue("runway", rwy_no.c_str());
1080 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1082 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1083 // An airport + parking position is requested
1084 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1085 // set tower position
1086 fgSetString("/sim/tower/airport-id", apt.c_str());
1091 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1092 // An airport + runway is requested
1093 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1094 // set tower position (a little off the heading for single
1096 fgSetString("/sim/tower/airport-id", apt.c_str());
1101 if ( !set_pos && !apt.empty() ) {
1102 // An airport is requested (find runway closest to hdg)
1103 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1104 // set tower position (a little off the heading for single
1106 fgSetString("/sim/tower/airport-id", apt.c_str());
1111 if (hdg_preset->getDoubleValue() > 9990.0)
1112 hdg_preset->setDoubleValue(hdg);
1114 if ( !set_pos && !vor.empty() ) {
1115 // a VOR is requested
1116 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1121 if ( !set_pos && !ndb.empty() ) {
1122 // an NDB is requested
1123 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1128 if ( !set_pos && !carrier.empty() ) {
1129 // an aircraft carrier is requested
1130 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1135 if ( !set_pos && !fix.empty() ) {
1136 // a Fix is requested
1137 if ( fgSetPosFromFix( fix ) ) {
1143 // No lon/lat specified, no airport specified, default to
1144 // middle of KSFO field.
1145 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1146 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1149 fgSetDouble( "/position/longitude-deg",
1150 fgGetDouble("/sim/presets/longitude-deg") );
1151 fgSetDouble( "/position/latitude-deg",
1152 fgGetDouble("/sim/presets/latitude-deg") );
1153 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1155 // determine if this should be an on-ground or in-air start
1156 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1157 fgSetBool("/sim/presets/onground", false);
1159 fgSetBool("/sim/presets/onground", true);
1166 // General house keeping initializations
1167 bool fgInitGeneral() {
1170 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1171 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1173 root = globals->get_fg_root();
1174 if ( ! root.length() ) {
1175 // No root path set? Then bail ...
1176 SG_LOG( SG_GENERAL, SG_ALERT,
1177 "Cannot continue without a path to the base package "
1178 << "being defined." );
1181 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1183 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1185 char buf[512], *cwd = getcwd(buf, 511);
1187 SGPropertyNode *curr = fgGetNode("/sim", true);
1188 curr->removeChild("fg-current", 0, false);
1189 curr = curr->getChild("fg-current", 0, true);
1190 curr->setStringValue(cwd ? cwd : "");
1191 curr->setAttribute(SGPropertyNode::WRITE, false);
1193 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1194 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1198 // Initialize view parameters
1200 // force update of model so that viewer can get some data...
1201 globals->get_aircraft_model()->update(0);
1202 // run update for current view so that data is current...
1203 globals->get_viewmgr()->update(0);
1207 SGTime *fgInitTime() {
1209 static const SGPropertyNode *longitude
1210 = fgGetNode("/position/longitude-deg");
1211 static const SGPropertyNode *latitude
1212 = fgGetNode("/position/latitude-deg");
1213 static const SGPropertyNode *cur_time_override
1214 = fgGetNode("/sim/time/cur-time-override", true);
1216 SGPath zone( globals->get_fg_root() );
1217 zone.append( "Timezone" );
1218 SGTime *t = new SGTime( longitude->getDoubleValue()
1219 * SGD_DEGREES_TO_RADIANS,
1220 latitude->getDoubleValue()
1221 * SGD_DEGREES_TO_RADIANS,
1223 cur_time_override->getLongValue() );
1225 globals->set_warp_delta( 0 );
1227 t->update( 0.0, 0.0,
1228 cur_time_override->getLongValue(),
1229 globals->get_warp() );
1235 // set up a time offset (aka warp) if one is specified
1236 void fgInitTimeOffset() {
1237 static const SGPropertyNode *longitude
1238 = fgGetNode("/position/longitude-deg");
1239 static const SGPropertyNode *latitude
1240 = fgGetNode("/position/latitude-deg");
1241 static const SGPropertyNode *cur_time_override
1242 = fgGetNode("/sim/time/cur-time-override", true);
1244 // Handle potential user specified time offsets
1245 int orig_warp = globals->get_warp();
1246 SGTime *t = globals->get_time_params();
1247 time_t cur_time = t->get_cur_time();
1248 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1249 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1250 time_t aircraftLocalTime =
1251 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1253 // Okay, we now have several possible scenarios
1254 int offset = fgGetInt("/sim/startup/time-offset");
1255 string offset_type = fgGetString("/sim/startup/time-offset-type");
1258 if ( offset_type == "real" ) {
1260 } else if ( offset_type == "dawn" ) {
1261 warp = fgTimeSecondsUntilSunAngle( cur_time,
1262 longitude->getDoubleValue()
1263 * SGD_DEGREES_TO_RADIANS,
1264 latitude->getDoubleValue()
1265 * SGD_DEGREES_TO_RADIANS,
1267 } else if ( offset_type == "morning" ) {
1268 warp = fgTimeSecondsUntilSunAngle( cur_time,
1269 longitude->getDoubleValue()
1270 * SGD_DEGREES_TO_RADIANS,
1271 latitude->getDoubleValue()
1272 * SGD_DEGREES_TO_RADIANS,
1274 } else if ( offset_type == "noon" ) {
1275 warp = fgTimeSecondsUntilSunAngle( cur_time,
1276 longitude->getDoubleValue()
1277 * SGD_DEGREES_TO_RADIANS,
1278 latitude->getDoubleValue()
1279 * SGD_DEGREES_TO_RADIANS,
1281 } else if ( offset_type == "afternoon" ) {
1282 warp = fgTimeSecondsUntilSunAngle( cur_time,
1283 longitude->getDoubleValue()
1284 * SGD_DEGREES_TO_RADIANS,
1285 latitude->getDoubleValue()
1286 * SGD_DEGREES_TO_RADIANS,
1288 } else if ( offset_type == "dusk" ) {
1289 warp = fgTimeSecondsUntilSunAngle( cur_time,
1290 longitude->getDoubleValue()
1291 * SGD_DEGREES_TO_RADIANS,
1292 latitude->getDoubleValue()
1293 * SGD_DEGREES_TO_RADIANS,
1295 } else if ( offset_type == "evening" ) {
1296 warp = fgTimeSecondsUntilSunAngle( cur_time,
1297 longitude->getDoubleValue()
1298 * SGD_DEGREES_TO_RADIANS,
1299 latitude->getDoubleValue()
1300 * SGD_DEGREES_TO_RADIANS,
1302 } else if ( offset_type == "midnight" ) {
1303 warp = fgTimeSecondsUntilSunAngle( cur_time,
1304 longitude->getDoubleValue()
1305 * SGD_DEGREES_TO_RADIANS,
1306 latitude->getDoubleValue()
1307 * SGD_DEGREES_TO_RADIANS,
1309 } else if ( offset_type == "system-offset" ) {
1312 } else if ( offset_type == "gmt-offset" ) {
1313 warp = offset - (currGMT - systemLocalTime);
1315 } else if ( offset_type == "latitude-offset" ) {
1316 warp = offset - (aircraftLocalTime - systemLocalTime);
1318 } else if ( offset_type == "system" ) {
1319 warp = offset - (systemLocalTime - currGMT) - cur_time;
1320 } else if ( offset_type == "gmt" ) {
1321 warp = offset - cur_time;
1322 } else if ( offset_type == "latitude" ) {
1323 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1325 SG_LOG( SG_GENERAL, SG_ALERT,
1326 "FG_TIME::Unsupported offset type " << offset_type );
1329 globals->set_warp( orig_warp + warp );
1330 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1331 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1332 cur_time_override->getLongValue(),
1333 globals->get_warp() );
1335 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1336 << globals->get_warp() );
1340 // This is the top level init routine which calls all the other
1341 // initialization routines. If you are adding a subsystem to flight
1342 // gear, its initialization call should located in this routine.
1343 // Returns non-zero if a problem encountered.
1344 bool fgInitSubsystems() {
1345 // static const SGPropertyNode *longitude
1346 // = fgGetNode("/sim/presets/longitude-deg");
1347 // static const SGPropertyNode *latitude
1348 // = fgGetNode("/sim/presets/latitude-deg");
1349 // static const SGPropertyNode *altitude
1350 // = fgGetNode("/sim/presets/altitude-ft");
1352 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1353 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1355 ////////////////////////////////////////////////////////////////////
1356 // Initialize the event manager subsystem.
1357 ////////////////////////////////////////////////////////////////////
1359 globals->get_event_mgr()->init();
1360 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1362 ////////////////////////////////////////////////////////////////////
1363 // Initialize the property interpolator subsystem. Put into the INIT
1364 // group because the "nasal" subsystem may need it at GENERAL take-down.
1365 ////////////////////////////////////////////////////////////////////
1366 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1369 ////////////////////////////////////////////////////////////////////
1370 // Add the FlightGear property utilities.
1371 ////////////////////////////////////////////////////////////////////
1372 globals->add_subsystem("properties", new FGProperties);
1374 ////////////////////////////////////////////////////////////////////
1375 // Initialize the material property subsystem.
1376 ////////////////////////////////////////////////////////////////////
1378 SGPath mpath( globals->get_fg_root() );
1379 mpath.append( "materials.xml" );
1380 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1381 globals->get_props()) ) {
1382 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1387 ////////////////////////////////////////////////////////////////////
1388 // Initialize the scenery management subsystem.
1389 ////////////////////////////////////////////////////////////////////
1391 if ( globals->get_tile_mgr()->init() ) {
1392 // Load the local scenery data
1393 double visibility_meters = fgGetDouble("/environment/visibility-m");
1395 globals->get_tile_mgr()->update( visibility_meters );
1397 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1401 globals->get_scenery()->get_scene_graph()
1402 ->addChild(simgear::Particles::getCommonRoot());
1403 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1405 ////////////////////////////////////////////////////////////////////
1406 // Initialize the flight model subsystem.
1407 ////////////////////////////////////////////////////////////////////
1409 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1411 // allocates structures so must happen before any of the flight
1412 // model or control parameters are set
1413 fgAircraftInit(); // In the future this might not be the case.
1416 ////////////////////////////////////////////////////////////////////
1417 // Initialize the weather subsystem.
1418 ////////////////////////////////////////////////////////////////////
1420 // Initialize the weather modeling subsystem
1421 globals->add_subsystem("environment", new FGEnvironmentMgr);
1423 ////////////////////////////////////////////////////////////////////
1424 // Initialize the ridge lift simulation.
1425 ////////////////////////////////////////////////////////////////////
1427 // Initialize the ridgelift subsystem
1428 globals->add_subsystem("ridgelift", new FGRidgeLift);
1430 ////////////////////////////////////////////////////////////////////
1431 // Initialize the aircraft systems and instrumentation (before the
1433 ////////////////////////////////////////////////////////////////////
1435 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1436 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1438 ////////////////////////////////////////////////////////////////////
1439 // Initialize the XML Autopilot subsystem.
1440 ////////////////////////////////////////////////////////////////////
1442 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilotGroup, SGSubsystemMgr::FDM );
1443 globals->add_subsystem( "route-manager", new FGRouteMgr );
1445 ////////////////////////////////////////////////////////////////////
1446 // Initialize the view manager subsystem.
1447 ////////////////////////////////////////////////////////////////////
1451 ////////////////////////////////////////////////////////////////////
1452 // Initialize the Input-Output subsystem
1453 ////////////////////////////////////////////////////////////////////
1454 globals->add_subsystem( "io", new FGIO );
1456 ////////////////////////////////////////////////////////////////////
1457 // Create and register the logger.
1458 ////////////////////////////////////////////////////////////////////
1460 globals->add_subsystem("logger", new FGLogger);
1462 ////////////////////////////////////////////////////////////////////
1463 // Create and register the XML GUI.
1464 ////////////////////////////////////////////////////////////////////
1466 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1469 ////////////////////////////////////////////////////////////////////
1470 // Initialize the local time subsystem.
1471 ////////////////////////////////////////////////////////////////////
1473 // update the current timezone each 30 minutes
1474 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1475 &fgUpdateLocalTime, 30*60 );
1476 fgInitTimeOffset(); // the environment subsystem needs this
1479 ////////////////////////////////////////////////////////////////////
1480 // Initialize the lighting subsystem.
1481 ////////////////////////////////////////////////////////////////////
1483 globals->add_subsystem("lighting", new FGLight);
1485 //////////////////////////////////////////////////////////////////////
1486 // Initialize the 2D cloud subsystem.
1487 ////////////////////////////////////////////////////////////////////
1488 fgGetBool("/sim/rendering/bump-mapping", false);
1490 #ifdef ENABLE_AUDIO_SUPPORT
1491 ////////////////////////////////////////////////////////////////////
1492 // Initialize the sound-effects subsystem.
1493 ////////////////////////////////////////////////////////////////////
1494 globals->add_subsystem("voice", new FGVoiceMgr);
1497 ////////////////////////////////////////////////////////////////////
1498 // Initialise the ATC Manager
1499 ////////////////////////////////////////////////////////////////////
1502 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1503 globals->set_ATC_mgr(new FGATCMgr);
1504 globals->get_ATC_mgr()->init();
1506 ////////////////////////////////////////////////////////////////////
1507 // Initialise the AI Manager
1508 ////////////////////////////////////////////////////////////////////
1510 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1511 globals->set_AI_mgr(new FGAIMgr);
1512 globals->get_AI_mgr()->init();
1514 ////////////////////////////////////////////////////////////////////
1515 // Initialise the AI Model Manager
1516 ////////////////////////////////////////////////////////////////////
1517 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1518 globals->add_subsystem("ai_model", new FGAIManager);
1519 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1522 // It's probably a good idea to initialize the top level traffic manager
1523 // After the AI and ATC systems have been initialized properly.
1524 // AI Traffic manager
1525 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1528 ////////////////////////////////////////////////////////////////////
1529 // Initialize the cockpit subsystem
1530 ////////////////////////////////////////////////////////////////////
1531 if( fgCockpitInit( ¤t_aircraft )) {
1532 // Cockpit initialized ok.
1534 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1539 ////////////////////////////////////////////////////////////////////
1540 // Add a new 2D panel.
1541 ////////////////////////////////////////////////////////////////////
1543 string panel_path = fgGetString("/sim/panel/path",
1544 "Panels/Default/default.xml");
1546 globals->set_current_panel( fgReadPanel(panel_path) );
1547 if (globals->get_current_panel() == 0) {
1548 SG_LOG( SG_INPUT, SG_ALERT,
1549 "Error reading new panel from " << panel_path );
1551 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1552 globals->get_current_panel()->init();
1553 globals->get_current_panel()->bind();
1557 ////////////////////////////////////////////////////////////////////
1558 // Initialize the controls subsystem.
1559 ////////////////////////////////////////////////////////////////////
1561 globals->get_controls()->init();
1562 globals->get_controls()->bind();
1565 ////////////////////////////////////////////////////////////////////
1566 // Initialize the input subsystem.
1567 ////////////////////////////////////////////////////////////////////
1569 globals->add_subsystem("input", new FGInput);
1572 ////////////////////////////////////////////////////////////////////
1573 // Initialize the replay subsystem
1574 ////////////////////////////////////////////////////////////////////
1575 globals->add_subsystem("replay", new FGReplay);
1578 ////////////////////////////////////////////////////////////////////
1579 // Bind and initialize subsystems.
1580 ////////////////////////////////////////////////////////////////////
1582 globals->get_subsystem_mgr()->bind();
1583 globals->get_subsystem_mgr()->init();
1585 ////////////////////////////////////////////////////////////////////
1586 // Initialize multiplayer subsystem
1587 ////////////////////////////////////////////////////////////////////
1589 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1590 globals->get_multiplayer_mgr()->init();
1592 ////////////////////////////////////////////////////////////////////////
1593 // Initialize the Nasal interpreter.
1594 // Do this last, so that the loaded scripts see initialized state
1595 ////////////////////////////////////////////////////////////////////////
1596 FGNasalSys* nasal = new FGNasalSys();
1597 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1600 // initialize methods that depend on other subsystems.
1601 globals->get_subsystem_mgr()->postinit();
1603 ////////////////////////////////////////////////////////////////////////
1604 // End of subsystem initialization.
1605 ////////////////////////////////////////////////////////////////////
1607 SG_LOG( SG_GENERAL, SG_INFO, endl);
1609 // Save the initial state for future
1611 globals->saveInitialState();
1617 void fgReInitSubsystems()
1619 // static const SGPropertyNode *longitude
1620 // = fgGetNode("/sim/presets/longitude-deg");
1621 // static const SGPropertyNode *latitude
1622 // = fgGetNode("/sim/presets/latitude-deg");
1623 static const SGPropertyNode *altitude
1624 = fgGetNode("/sim/presets/altitude-ft");
1625 static const SGPropertyNode *master_freeze
1626 = fgGetNode("/sim/freeze/master");
1628 SG_LOG( SG_GENERAL, SG_INFO,
1629 "fgReInitSubsystems(): /position/altitude = "
1630 << altitude->getDoubleValue() );
1632 bool freeze = master_freeze->getBoolValue();
1634 fgSetBool("/sim/freeze/master", true);
1636 fgSetBool("/sim/crashed", false);
1638 // Force reupdating the positions of the ai 3d models. They are used for
1639 // initializing ground level for the FDM.
1640 globals->get_subsystem("ai_model")->reinit();
1642 // Initialize the FDM
1643 globals->get_subsystem("flight")->reinit();
1645 // allocates structures so must happen before any of the flight
1646 // model or control parameters are set
1647 fgAircraftInit(); // In the future this might not be the case.
1649 // reload offsets from config defaults
1650 globals->get_viewmgr()->reinit();
1654 globals->get_controls()->reset_all();
1656 fgUpdateLocalTime();
1658 // re-init to proper time of day setting
1662 fgSetBool("/sim/freeze/master", false);
1664 fgSetBool("/sim/sceneryloaded",false);
1668 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1670 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1672 bool freeze = master_freeze->getBoolValue();
1674 master_freeze->setBoolValue(true);
1676 fgSetBool("/sim/signals/reinit", true);
1678 globals->get_subsystem("flight")->unbind();
1680 // in case user has changed window size as
1681 // restoreInitialState() overwrites these
1682 int xsize = fgGetInt("/sim/startup/xsize");
1683 int ysize = fgGetInt("/sim/startup/ysize");
1685 // viewports also needs to be saved/restored as
1686 // restoreInitialState() overwrites these
1687 SGPropertyNode *guiNode = new SGPropertyNode;
1688 SGPropertyNode *cameraNode = new SGPropertyNode;
1689 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1690 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1691 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1693 globals->restoreInitialState();
1695 // update our position based on current presets
1698 // We don't know how to resize the window, so keep the last values
1699 // for xsize and ysize, and don't use the one set initially
1700 fgSetInt("/sim/startup/xsize", xsize);
1701 fgSetInt("/sim/startup/ysize", ysize);
1703 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1704 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1709 SGTime *t = globals->get_time_params();
1712 globals->set_time_params(t);
1714 fgReInitSubsystems();
1716 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1717 globals->get_renderer()->resize(xsize, ysize);
1718 fgSetBool("/sim/signals/reinit", false);
1721 master_freeze->setBoolValue(false);