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/xmlauto.hxx>
87 #include <Autopilot/autobrake.hxx>
89 #include <Cockpit/cockpit.hxx>
90 #include <Cockpit/panel.hxx>
91 #include <Cockpit/panel_io.hxx>
94 #include <FDM/SP/ADA.hxx>
95 #include <FDM/SP/ACMS.hxx>
96 #include <FDM/SP/MagicCarpet.hxx>
97 #include <FDM/SP/Balloon.h>
99 #include <FDM/ExternalNet/ExternalNet.hxx>
100 #include <FDM/ExternalPipe/ExternalPipe.hxx>
101 #include <FDM/JSBSim/JSBSim.hxx>
102 #include <FDM/LaRCsim/LaRCsim.hxx>
103 #include <FDM/UFO.hxx>
104 #include <FDM/NullFDM.hxx>
105 #include <FDM/YASim/YASim.hxx>
106 #include <GUI/new_gui.hxx>
107 #include <Include/general.hxx>
108 #include <Input/input.hxx>
109 #include <Instrumentation/instrument_mgr.hxx>
110 #include <Model/acmodel.hxx>
111 #include <AIModel/submodel.hxx>
112 #include <AIModel/AIManager.hxx>
113 #include <Navaids/navdb.hxx>
114 #include <Navaids/navlist.hxx>
115 #include <Navaids/fix.hxx>
116 #include <Navaids/fixlist.hxx>
117 #include <Scenery/scenery.hxx>
118 #include <Scenery/tilemgr.hxx>
119 #include <Scripting/NasalSys.hxx>
120 #include <Sound/voice.hxx>
121 #include <Systems/system_mgr.hxx>
122 #include <Time/light.hxx>
123 #include <Time/sunsolver.hxx>
124 #include <Time/tmp.hxx>
125 #include <Traffic/TrafficMgr.hxx>
126 #include <MultiPlayer/multiplaymgr.hxx>
128 #include <Environment/environment_mgr.hxx>
129 #include <Environment/ridge_lift.hxx>
131 #include "fg_init.hxx"
133 #include "fg_commands.hxx"
134 #include "fg_props.hxx"
135 #include "options.hxx"
136 #include "globals.hxx"
137 #include "logger.hxx"
138 #include "renderer.hxx"
139 #include "viewmgr.hxx"
144 # include <CoreFoundation/CoreFoundation.h>
148 using namespace boost::algorithm;
150 extern const char *default_root;
153 // Scan the command line options for the specified option and return
155 static string fgScanForOption( const string& option, int argc, char **argv ) {
158 if (hostname == NULL)
161 gethostname(_hostname, 256);
162 hostname = strdup(_hostname);
163 free_hostname = true;
166 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
168 int len = option.length();
171 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
173 string arg = argv[i];
174 if ( arg.find( option ) == 0 ) {
175 return arg.substr( len );
185 // Scan the user config files for the specified option and return
187 static string fgScanForOption( const string& option, const string& path ) {
188 sg_gzifstream in( path );
189 if ( !in.is_open() ) {
193 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
195 int len = option.length();
198 while ( ! in.eof() ) {
200 getline( in, line, '\n' );
202 // catch extraneous (DOS) line ending character
203 if ( line[line.length() - 1] < 32 ) {
204 line = line.substr( 0, line.length()-1 );
207 if ( line.find( option ) == 0 ) {
208 return line.substr( len );
217 // Scan the user config files for the specified option and return
219 static string fgScanForOption( const string& option ) {
222 #if defined( unix ) || defined( __CYGWIN__ )
223 // Next check home directory for .fgfsrc.hostname file
225 if ( homedir != NULL ) {
226 SGPath config( homedir );
227 config.append( ".fgfsrc" );
228 config.concat( "." );
229 config.concat( hostname );
230 arg = fgScanForOption( option, config.str() );
235 // Next check home directory for .fgfsrc file
237 if ( homedir != NULL ) {
238 SGPath config( homedir );
239 config.append( ".fgfsrc" );
240 arg = fgScanForOption( option, config.str() );
245 // Check for $fg_root/system.fgfsrc
246 SGPath config( globals->get_fg_root() );
247 config.append( "system.fgfsrc" );
248 arg = fgScanForOption( option, config.str() );
255 // Read in configuration (files and command line options) but only set
257 bool fgInitFGRoot ( int argc, char **argv ) {
260 // First parse command line options looking for --fg-root=, this
261 // will override anything specified in a config file
262 root = fgScanForOption( "--fg-root=", argc, argv);
264 // Check in one of the user configuration files.
266 root = fgScanForOption( "--fg-root=" );
268 // Next check if fg-root is set as an env variable
269 if ( root.empty() ) {
270 char *envp = ::getenv( "FG_ROOT" );
271 if ( envp != NULL ) {
276 // Otherwise, default to a random compiled-in location if we can't
277 // find fg-root any other way.
278 if ( root.empty() ) {
279 #if defined( __CYGWIN__ )
281 #elif defined( _WIN32 )
283 #elif defined(__APPLE__)
285 The following code looks for the base package inside the application
286 bundle, in the standard Contents/Resources location.
288 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
290 // look for a 'data' subdir
291 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
293 // now convert down to a path, and the a c-string
294 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
295 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
297 CFRelease(resourcesUrl);
305 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
306 globals->set_fg_root(root);
312 // Read in configuration (files and command line options) but only set
314 bool fgInitFGAircraft ( int argc, char **argv ) {
317 // First parse command line options looking for --aircraft=, this
318 // will override anything specified in a config file
319 aircraft = fgScanForOption( "--aircraft=", argc, argv );
320 if ( aircraft.empty() ) {
321 // check synonym option
322 aircraft = fgScanForOption( "--vehicle=", argc, argv );
325 // Check in one of the user configuration files.
326 if ( aircraft.empty() ) {
327 aircraft = fgScanForOption( "--aircraft=" );
329 if ( aircraft.empty() ) {
330 aircraft = fgScanForOption( "--vehicle=" );
333 // if an aircraft was specified, set the property name
334 if ( !aircraft.empty() ) {
335 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
336 fgSetString("/sim/aircraft", aircraft.c_str() );
338 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
345 // Return the current base package version
346 string fgBasePackageVersion() {
347 SGPath base_path( globals->get_fg_root() );
348 base_path.append("version");
350 sg_gzifstream in( base_path.str() );
351 if ( !in.is_open() ) {
352 SGPath old_path( globals->get_fg_root() );
353 old_path.append( "Thanks" );
354 sg_gzifstream old( old_path.str() );
355 if ( !old.is_open() ) {
358 return "[old version]";
369 // Initialize the localization
370 SGPropertyNode *fgInitLocale(const char *language) {
371 SGPropertyNode *c_node = NULL, *d_node = NULL;
372 SGPropertyNode *intl = fgGetNode("/sim/intl");
374 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
376 // localization not defined
381 // Select the proper language from the list
383 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
384 for (unsigned int i = 0; i < locale.size(); i++) {
386 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
387 for (unsigned int j = 0; j < lang.size(); j++) {
389 if (!strcmp(lang[j]->getStringValue(), language)) {
398 d_node = intl->getChild("locale");
402 // Check for localized font
403 SGPropertyNode *font_n = c_node->getNode("font", true);
404 if ( !strcmp(font_n->getStringValue(), "") )
405 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
409 // Load the default strings
411 SGPath d_path( globals->get_fg_root() );
413 const char *d_path_str = d_node->getStringValue("strings");
415 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
419 d_path.append(d_path_str);
420 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
422 SGPropertyNode *strings = c_node->getNode("strings");
424 readProperties(d_path.str(), strings);
425 } catch (const sg_exception &) {
426 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
431 // Load the language specific strings
433 if (c_node != d_node) {
434 SGPath c_path( globals->get_fg_root() );
436 const char *c_path_str = c_node->getStringValue("strings");
438 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
442 c_path.append(c_path_str);
443 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
446 readProperties(c_path.str(), strings);
447 } catch (const sg_exception &) {
448 SG_LOG(SG_GENERAL, SG_ALERT,
449 "Unable to read the localized strings from " << c_path.str());
459 // Initialize the localization routines
460 bool fgDetectLanguage() {
461 const char *language = ::getenv("LANG");
463 if (language == NULL) {
464 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
468 SGPropertyNode *locale = fgInitLocale(language);
470 SG_LOG(SG_GENERAL, SG_ALERT,
471 "No internationalization settings specified in preferences.xml" );
476 globals->set_locale( locale );
481 // Attempt to locate and parse the various non-XML config files in order
482 // from least precidence to greatest precidence
484 do_options (int argc, char ** argv)
486 // Check for $fg_root/system.fgfsrc
487 SGPath config( globals->get_fg_root() );
488 config.append( "system.fgfsrc" );
489 fgParseOptions(config.str());
491 #if defined( unix ) || defined( __CYGWIN__ )
492 config.concat( "." );
493 config.concat( hostname );
494 fgParseOptions(config.str());
497 // Check for ~/.fgfsrc
498 if ( homedir != NULL ) {
499 config.set( homedir );
500 config.append( ".fgfsrc" );
501 fgParseOptions(config.str());
504 #if defined( unix ) || defined( __CYGWIN__ )
505 // Check for ~/.fgfsrc.hostname
506 config.concat( "." );
507 config.concat( hostname );
508 fgParseOptions(config.str());
511 // Parse remaining command line options
512 // These will override anything specified in a config file
513 fgParseArgs(argc, argv);
517 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
518 SGPropertyNode *cache, int depth = 0 )
520 const int MAXDEPTH = 1;
523 ulDir *dirp = ulOpenDir(path.str().c_str());
525 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
530 while ((dire = ulReadDir(dirp)) != NULL) {
532 if (depth > MAXDEPTH)
535 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
536 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
540 next.append(dire->d_name);
542 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
543 if ( ! result.empty() )
547 int len = strlen(dire->d_name);
548 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
554 if (!cache->getChild("aircraft", i++, false))
557 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
559 n = entry->getNode("file", true);
560 n->setStringValue(dire->d_name);
561 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
563 n = entry->getNode("path", true);
564 n->setStringValue(path.str().c_str());
565 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
567 if ( boost::equals(dire->d_name, aircraft.c_str(), is_iequal()) ) {
579 // Read in configuration (file and command line)
580 bool fgInitConfig ( int argc, char **argv ) {
582 // First, set some sane default values
585 // Read global preferences from $FG_ROOT/preferences.xml
586 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
587 fgLoadProps("preferences.xml", globals->get_props());
588 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
590 // Detect the required language as early as possible
591 if ( !fgDetectLanguage() ) {
595 SGPropertyNode autosave;
597 char *envp = ::getenv( "APPDATA" );
599 SGPath config( envp );
600 config.append( "flightgear.org" );
602 if ( homedir != NULL ) {
603 SGPath config( homedir );
604 config.append( ".fgfs" );
606 const char *fg_home = getenv("FG_HOME");
610 SGPath home_export(config.str());
611 home_export.append("Export/dummy");
612 home_export.create_dir(0777);
614 // Set /sim/fg-home and don't allow malign code to override it until
615 // Nasal security is set up. Use FG_HOME if necessary.
616 SGPropertyNode *home = fgGetNode("/sim", true);
617 home->removeChild("fg-home", 0, false);
618 home = home->getChild("fg-home", 0, true);
619 home->setStringValue(config.c_str());
620 home->setAttribute(SGPropertyNode::WRITE, false);
622 config.append( "autosave.xml" );
623 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
625 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
627 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
629 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
631 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
634 // Scan user config files and command line for a specified aircraft.
635 fgInitFGAircraft(argc, argv);
637 string aircraft = fgGetString( "/sim/aircraft", "" );
638 if ( aircraft.size() > 0 ) {
639 SGPath aircraft_search( globals->get_fg_root() );
640 aircraft_search.append( "Aircraft" );
642 string aircraft_set = aircraft + "-set.xml";
645 // check if the *-set.xml file is already in the cache
646 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
647 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
648 for (unsigned int i = 0; i < cache.size(); i++) {
649 const char *name = cache[i]->getStringValue("file", "");
650 if (boost::equals(aircraft_set, name, is_iequal())) {
651 const char *path = cache[i]->getStringValue("path", "");
661 if (result.empty()) {
662 // prepare cache for rescan
663 SGPropertyNode *n = cache_root->getNode("fg-root", true);
664 n->setStringValue(globals->get_fg_root().c_str());
665 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
666 cache_root->removeChildren("aircraft");
668 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
671 if ( !result.empty() ) {
672 fgSetString( "/sim/aircraft-dir", result.c_str() );
673 SGPath full_name( result );
674 full_name.append( aircraft_set );
676 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
677 << " from " << full_name.str());
679 readProperties( full_name.str(), globals->get_props() );
680 } catch ( const sg_exception &e ) {
681 string message = "Error reading default aircraft: ";
682 message += e.getFormattedMessage();
683 SG_LOG(SG_INPUT, SG_ALERT, message);
687 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
693 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
696 copyProperties(&autosave, globals->get_props());
698 // parse options after loading aircraft to ensure any user
699 // overrides of defaults are honored.
700 do_options(argc, argv);
705 // Set current tower position lon/lat given an airport id
706 static bool fgSetTowerPosFromAirportID( const string& id) {
707 const FGAirport *a = fgFindAirportID( id);
709 SGGeod tower = a->getTowerLocation();
710 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
711 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
712 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
720 struct FGTowerLocationListener : SGPropertyChangeListener {
721 void valueChanged(SGPropertyNode* node) {
722 const string id(node->getStringValue());
723 fgSetTowerPosFromAirportID(id);
727 void fgInitTowerLocationListener() {
728 fgGetNode("/sim/tower/airport-id", true)
729 ->addChangeListener( new FGTowerLocationListener(), true );
732 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
734 SGGeod startPos(aStartPos);
735 if (aTargetHeading == HUGE_VAL) {
736 aTargetHeading = aHeading;
739 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
740 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
741 offsetDistance *= SG_NM_TO_METER;
742 double offsetAzimuth = aHeading;
743 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
744 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
745 aHeading = aTargetHeading;
750 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
755 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
756 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
757 fgSetDouble("/sim/presets/heading-deg", aHeading );
759 // other code depends on the actual values being set ...
760 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
761 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
762 fgSetDouble("/orientation/heading-deg", aHeading );
765 // Set current_options lon/lat given an airport id and heading (degrees)
766 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
770 // set initial position from runway and heading
771 SG_LOG( SG_GENERAL, SG_INFO,
772 "Attempting to set starting position from airport code "
773 << id << " heading " << tgt_hdg );
775 const FGAirport* apt = fgFindAirportID(id);
776 if (!apt) return false;
777 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
778 fgSetString("/sim/atc/runway", r->ident().c_str());
780 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
781 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
785 // Set current_options lon/lat given an airport id and parkig position name
786 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
790 // can't see an easy way around this const_cast at the moment
791 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
793 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
796 FGAirportDynamics* dcs = apt->getDynamics();
798 SG_LOG( SG_GENERAL, SG_ALERT,
799 "Failed to find parking position " << parkpos <<
800 " at airport " << id );
804 int park_index = dcs->getNrOfParkings() - 1;
805 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
806 if (park_index < 0) {
807 SG_LOG( SG_GENERAL, SG_ALERT,
808 "Failed to find parking position " << parkpos <<
809 " at airport " << id );
812 FGParking* parking = dcs->getParking(park_index);
813 parking->setAvailable(false);
815 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
816 parking->getHeading());
821 // Set current_options lon/lat given an airport id and runway number
822 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
826 // set initial position from airport and runway number
827 SG_LOG( SG_GENERAL, SG_INFO,
828 "Attempting to set starting position for "
829 << id << ":" << rwy );
831 const FGAirport* apt = fgFindAirportID(id);
833 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
837 if (!apt->hasRunwayWithIdent(rwy)) {
838 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
839 "Failed to find runway " << rwy <<
840 " at airport " << id << ". Using default runway." );
844 FGRunway* r(apt->getRunwayByIdent(rwy));
845 fgSetString("/sim/atc/runway", r->ident().c_str());
846 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
847 fgApplyStartOffset(startPos, r->headingDeg());
852 static void fgSetDistOrAltFromGlideSlope() {
853 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
854 string apt_id = fgGetString("/sim/presets/airport-id");
855 double gs = fgGetDouble("/sim/presets/glideslope-deg")
856 * SG_DEGREES_TO_RADIANS ;
857 double od = fgGetDouble("/sim/presets/offset-distance-nm");
858 double alt = fgGetDouble("/sim/presets/altitude-ft");
860 double apt_elev = 0.0;
861 if ( ! apt_id.empty() ) {
862 apt_elev = fgGetAirportElev( apt_id );
863 if ( apt_elev < -9990.0 ) {
870 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
871 // set altitude from glideslope and offset-distance
872 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
873 alt = fabs(od*tan(gs)) + apt_elev;
874 fgSetDouble("/sim/presets/altitude-ft", alt);
875 fgSetBool("/sim/presets/onground", false);
876 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
878 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
879 // set offset-distance from glideslope and altitude
880 od = (alt - apt_elev) / tan(gs);
881 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
882 fgSetDouble("/sim/presets/offset-distance-nm", od);
883 fgSetBool("/sim/presets/onground", false);
884 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
886 } else if( fabs(gs) > 0.01 ) {
887 SG_LOG( SG_GENERAL, SG_ALERT,
888 "Glideslope given but not altitude or offset-distance." );
889 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
890 fgSetDouble("/sim/presets/glideslope-deg", 0);
891 fgSetBool("/sim/presets/onground", true);
896 // Set current_options lon/lat given an airport id and heading (degrees)
897 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
899 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
902 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
903 << id << ":" << freq );
907 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
911 // Set current_options lon/lat given an aircraft carrier id
912 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
914 // set initial position from runway and heading
918 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
919 double lon = geodPos.getLongitudeDeg();
920 double lat = geodPos.getLatitudeDeg();
921 double alt = geodPos.getElevationFt();
923 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
924 << carrier << " at lat = " << lat << ", lon = " << lon
925 << ", alt = " << alt << ", heading = " << heading);
927 fgSetDouble("/sim/presets/longitude-deg", lon);
928 fgSetDouble("/sim/presets/latitude-deg", lat);
929 fgSetDouble("/sim/presets/altitude-ft", alt);
930 fgSetDouble("/sim/presets/heading-deg", heading);
931 fgSetDouble("/position/longitude-deg", lon);
932 fgSetDouble("/position/latitude-deg", lat);
933 fgSetDouble("/position/altitude-ft", alt);
934 fgSetDouble("/orientation/heading-deg", heading);
936 fgSetString("/sim/presets/speed-set", "UVW");
937 fgSetDouble("/velocities/uBody-fps", uvw(0));
938 fgSetDouble("/velocities/vBody-fps", uvw(1));
939 fgSetDouble("/velocities/wBody-fps", uvw(2));
940 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
941 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
942 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
944 fgSetBool("/sim/presets/onground", true);
948 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
954 // Set current_options lon/lat given an airport id and heading (degrees)
955 static bool fgSetPosFromFix( const string& id )
957 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
958 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
960 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
964 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
969 * Initialize vor/ndb/ils/fix list management and query systems (as
970 * well as simple airport db list)
975 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
977 SGPath aptdb( globals->get_fg_root() );
978 aptdb.append( "Airports/apt.dat" );
980 SGPath p_metar( globals->get_fg_root() );
981 p_metar.append( "Airports/metar.dat" );
983 // Initialise the frequency search map BEFORE reading
984 // the airport database:
988 current_commlist = new FGCommList;
989 current_commlist->init( globals->get_fg_root() );
990 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
992 FGNavList *navlist = new FGNavList;
993 FGNavList *loclist = new FGNavList;
994 FGNavList *gslist = new FGNavList;
995 FGNavList *dmelist = new FGNavList;
996 FGNavList *tacanlist = new FGNavList;
997 FGNavList *carrierlist = new FGNavList;
998 FGTACANList *channellist = new FGTACANList;
1000 globals->set_navlist( navlist );
1001 globals->set_loclist( loclist );
1002 globals->set_gslist( gslist );
1003 globals->set_dmelist( dmelist );
1004 globals->set_tacanlist( tacanlist );
1005 globals->set_carrierlist( carrierlist );
1006 globals->set_channellist( channellist );
1008 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1009 SG_LOG( SG_GENERAL, SG_ALERT,
1010 "Problems loading one or more navigational database" );
1013 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1014 SGPath p_fix( globals->get_fg_root() );
1015 p_fix.append( "Navaids/fix.dat" );
1017 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1019 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1020 SGPath p_awy( globals->get_fg_root() );
1021 p_awy.append( "Navaids/awy.dat" );
1022 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1023 //cerr << "Loading Airways" << endl;
1024 awyNet->load (p_awy );
1026 //cerr << "initializing airways" << endl;
1027 globals->set_airwaynet( awyNet );
1033 // Set the initial position based on presets (or defaults)
1034 bool fgInitPosition() {
1035 // cout << "fgInitPosition()" << endl;
1036 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1037 * SG_DEGREES_TO_RADIANS ;
1038 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1039 double alt = fgGetDouble("/sim/presets/altitude-ft");
1041 bool set_pos = false;
1043 // If glideslope is specified, then calculate offset-distance or
1044 // altitude relative to glide slope if either of those was not
1046 if ( fabs( gs ) > 0.01 ) {
1047 fgSetDistOrAltFromGlideSlope();
1051 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1052 // If not, check for an airport-id and use that.
1053 // If not, default to the middle of the KSFO field.
1054 // The default values for lon/lat are deliberately out of range
1055 // so that the airport-id can take effect; valid lon/lat will
1056 // override airport-id, however.
1057 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1058 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1059 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1060 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1065 string apt = fgGetString("/sim/presets/airport-id");
1066 string rwy_no = fgGetString("/sim/presets/runway");
1067 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1068 string vor = fgGetString("/sim/presets/vor-id");
1069 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1070 string ndb = fgGetString("/sim/presets/ndb-id");
1071 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1072 string carrier = fgGetString("/sim/presets/carrier");
1073 string parkpos = fgGetString("/sim/presets/parkpos");
1074 string fix = fgGetString("/sim/presets/fix");
1075 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1076 double hdg = hdg_preset->getDoubleValue();
1078 // save some start parameters, so that we can later say what the
1079 // user really requested. TODO generalize that and move it to options.cxx
1080 static bool start_options_saved = false;
1081 if (!start_options_saved) {
1082 start_options_saved = true;
1083 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1085 opt->setDoubleValue("latitude-deg", lat_deg);
1086 opt->setDoubleValue("longitude-deg", lon_deg);
1087 opt->setDoubleValue("heading-deg", hdg);
1088 opt->setStringValue("airport", apt.c_str());
1089 opt->setStringValue("runway", rwy_no.c_str());
1093 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1095 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1096 // An airport + parking position is requested
1097 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1098 // set tower position
1099 fgSetString("/sim/tower/airport-id", apt.c_str());
1104 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1105 // An airport + runway is requested
1106 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1107 // set tower position (a little off the heading for single
1109 fgSetString("/sim/tower/airport-id", apt.c_str());
1114 if ( !set_pos && !apt.empty() ) {
1115 // An airport is requested (find runway closest to hdg)
1116 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1117 // set tower position (a little off the heading for single
1119 fgSetString("/sim/tower/airport-id", apt.c_str());
1124 if (hdg_preset->getDoubleValue() > 9990.0)
1125 hdg_preset->setDoubleValue(hdg);
1127 if ( !set_pos && !vor.empty() ) {
1128 // a VOR is requested
1129 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1134 if ( !set_pos && !ndb.empty() ) {
1135 // an NDB is requested
1136 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1141 if ( !set_pos && !carrier.empty() ) {
1142 // an aircraft carrier is requested
1143 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1148 if ( !set_pos && !fix.empty() ) {
1149 // a Fix is requested
1150 if ( fgSetPosFromFix( fix ) ) {
1156 // No lon/lat specified, no airport specified, default to
1157 // middle of KSFO field.
1158 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1159 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1162 fgSetDouble( "/position/longitude-deg",
1163 fgGetDouble("/sim/presets/longitude-deg") );
1164 fgSetDouble( "/position/latitude-deg",
1165 fgGetDouble("/sim/presets/latitude-deg") );
1166 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1168 // determine if this should be an on-ground or in-air start
1169 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1170 fgSetBool("/sim/presets/onground", false);
1172 fgSetBool("/sim/presets/onground", true);
1179 // General house keeping initializations
1180 bool fgInitGeneral() {
1183 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1184 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1186 root = globals->get_fg_root();
1187 if ( ! root.length() ) {
1188 // No root path set? Then bail ...
1189 SG_LOG( SG_GENERAL, SG_ALERT,
1190 "Cannot continue without a path to the base package "
1191 << "being defined." );
1194 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1196 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1198 char buf[512], *cwd = getcwd(buf, 511);
1200 SGPropertyNode *curr = fgGetNode("/sim", true);
1201 curr->removeChild("fg-current", 0, false);
1202 curr = curr->getChild("fg-current", 0, true);
1203 curr->setStringValue(cwd ? cwd : "");
1204 curr->setAttribute(SGPropertyNode::WRITE, false);
1206 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1207 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1212 // Initialize the flight model subsystem. This just creates the
1213 // object. The actual fdm initialization is delayed until we get a
1214 // proper scenery elevation hit. This is checked for in main.cxx
1218 if ( cur_fdm_state ) {
1219 delete cur_fdm_state;
1223 double dt = 1.0 / fgGetInt("/sim/model-hz");
1224 string model = fgGetString("/sim/flight-model");
1226 if ( model == "larcsim" ) {
1227 cur_fdm_state = new FGLaRCsim( dt );
1228 } else if ( model == "jsb" ) {
1229 cur_fdm_state = new FGJSBsim( dt );
1231 } else if ( model == "ada" ) {
1232 cur_fdm_state = new FGADA( dt );
1233 } else if ( model == "acms" ) {
1234 cur_fdm_state = new FGACMS( dt );
1235 } else if ( model == "balloon" ) {
1236 cur_fdm_state = new FGBalloonSim( dt );
1237 } else if ( model == "magic" ) {
1238 cur_fdm_state = new FGMagicCarpet( dt );
1240 } else if ( model == "ufo" ) {
1241 cur_fdm_state = new FGUFO( dt );
1242 } else if ( model == "external" ) {
1243 // external is a synonym for "--fdm=null" and is
1244 // maintained here for backwards compatibility
1245 cur_fdm_state = new FGNullFDM( dt );
1246 } else if ( model.find("network") == 0 ) {
1247 string host = "localhost";
1251 string net_options = model.substr(8);
1252 string::size_type begin, end;
1255 end = net_options.find( ",", begin );
1256 if ( end != string::npos ) {
1257 host = net_options.substr(begin, end - begin);
1261 end = net_options.find( ",", begin );
1262 if ( end != string::npos ) {
1263 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1267 end = net_options.find( ",", begin );
1268 if ( end != string::npos ) {
1269 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1273 end = net_options.find( ",", begin );
1274 if ( end != string::npos ) {
1275 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1278 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1279 } else if ( model.find("pipe") == 0 ) {
1280 // /* old */ string pipe_path = model.substr(5);
1281 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1282 string pipe_path = "";
1283 string pipe_protocol = "";
1284 string pipe_options = model.substr(5);
1285 string::size_type begin, end;
1288 end = pipe_options.find( ",", begin );
1289 if ( end != string::npos ) {
1290 pipe_path = pipe_options.substr(begin, end - begin);
1293 // protocol (last option)
1294 pipe_protocol = pipe_options.substr(begin);
1295 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1296 } else if ( model == "null" ) {
1297 cur_fdm_state = new FGNullFDM( dt );
1298 } else if ( model == "yasim" ) {
1299 cur_fdm_state = new YASim( dt );
1301 throw sg_exception(string("Unrecognized flight model '") + model
1302 + "', cannot init flight dynamics model.");
1306 // Initialize view parameters
1308 // force update of model so that viewer can get some data...
1309 globals->get_aircraft_model()->update(0);
1310 // run update for current view so that data is current...
1311 globals->get_viewmgr()->update(0);
1315 SGTime *fgInitTime() {
1317 static const SGPropertyNode *longitude
1318 = fgGetNode("/position/longitude-deg");
1319 static const SGPropertyNode *latitude
1320 = fgGetNode("/position/latitude-deg");
1321 static const SGPropertyNode *cur_time_override
1322 = fgGetNode("/sim/time/cur-time-override", true);
1324 SGPath zone( globals->get_fg_root() );
1325 zone.append( "Timezone" );
1326 SGTime *t = new SGTime( longitude->getDoubleValue()
1327 * SGD_DEGREES_TO_RADIANS,
1328 latitude->getDoubleValue()
1329 * SGD_DEGREES_TO_RADIANS,
1331 cur_time_override->getLongValue() );
1333 globals->set_warp_delta( 0 );
1335 t->update( 0.0, 0.0,
1336 cur_time_override->getLongValue(),
1337 globals->get_warp() );
1343 // set up a time offset (aka warp) if one is specified
1344 void fgInitTimeOffset() {
1345 static const SGPropertyNode *longitude
1346 = fgGetNode("/position/longitude-deg");
1347 static const SGPropertyNode *latitude
1348 = fgGetNode("/position/latitude-deg");
1349 static const SGPropertyNode *cur_time_override
1350 = fgGetNode("/sim/time/cur-time-override", true);
1352 // Handle potential user specified time offsets
1353 int orig_warp = globals->get_warp();
1354 SGTime *t = globals->get_time_params();
1355 time_t cur_time = t->get_cur_time();
1356 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1357 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1358 time_t aircraftLocalTime =
1359 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1361 // Okay, we now have several possible scenarios
1362 int offset = fgGetInt("/sim/startup/time-offset");
1363 string offset_type = fgGetString("/sim/startup/time-offset-type");
1366 if ( offset_type == "real" ) {
1368 } else if ( offset_type == "dawn" ) {
1369 warp = fgTimeSecondsUntilSunAngle( cur_time,
1370 longitude->getDoubleValue()
1371 * SGD_DEGREES_TO_RADIANS,
1372 latitude->getDoubleValue()
1373 * SGD_DEGREES_TO_RADIANS,
1375 } else if ( offset_type == "morning" ) {
1376 warp = fgTimeSecondsUntilSunAngle( cur_time,
1377 longitude->getDoubleValue()
1378 * SGD_DEGREES_TO_RADIANS,
1379 latitude->getDoubleValue()
1380 * SGD_DEGREES_TO_RADIANS,
1382 } else if ( offset_type == "noon" ) {
1383 warp = fgTimeSecondsUntilSunAngle( cur_time,
1384 longitude->getDoubleValue()
1385 * SGD_DEGREES_TO_RADIANS,
1386 latitude->getDoubleValue()
1387 * SGD_DEGREES_TO_RADIANS,
1389 } else if ( offset_type == "afternoon" ) {
1390 warp = fgTimeSecondsUntilSunAngle( cur_time,
1391 longitude->getDoubleValue()
1392 * SGD_DEGREES_TO_RADIANS,
1393 latitude->getDoubleValue()
1394 * SGD_DEGREES_TO_RADIANS,
1396 } else if ( offset_type == "dusk" ) {
1397 warp = fgTimeSecondsUntilSunAngle( cur_time,
1398 longitude->getDoubleValue()
1399 * SGD_DEGREES_TO_RADIANS,
1400 latitude->getDoubleValue()
1401 * SGD_DEGREES_TO_RADIANS,
1403 } else if ( offset_type == "evening" ) {
1404 warp = fgTimeSecondsUntilSunAngle( cur_time,
1405 longitude->getDoubleValue()
1406 * SGD_DEGREES_TO_RADIANS,
1407 latitude->getDoubleValue()
1408 * SGD_DEGREES_TO_RADIANS,
1410 } else if ( offset_type == "midnight" ) {
1411 warp = fgTimeSecondsUntilSunAngle( cur_time,
1412 longitude->getDoubleValue()
1413 * SGD_DEGREES_TO_RADIANS,
1414 latitude->getDoubleValue()
1415 * SGD_DEGREES_TO_RADIANS,
1417 } else if ( offset_type == "system-offset" ) {
1420 } else if ( offset_type == "gmt-offset" ) {
1421 warp = offset - (currGMT - systemLocalTime);
1423 } else if ( offset_type == "latitude-offset" ) {
1424 warp = offset - (aircraftLocalTime - systemLocalTime);
1426 } else if ( offset_type == "system" ) {
1427 warp = offset - (systemLocalTime - currGMT) - cur_time;
1428 } else if ( offset_type == "gmt" ) {
1429 warp = offset - cur_time;
1430 } else if ( offset_type == "latitude" ) {
1431 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1433 SG_LOG( SG_GENERAL, SG_ALERT,
1434 "FG_TIME::Unsupported offset type " << offset_type );
1437 globals->set_warp( orig_warp + warp );
1438 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1439 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1440 cur_time_override->getLongValue(),
1441 globals->get_warp() );
1443 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1444 << globals->get_warp() );
1448 // This is the top level init routine which calls all the other
1449 // initialization routines. If you are adding a subsystem to flight
1450 // gear, its initialization call should located in this routine.
1451 // Returns non-zero if a problem encountered.
1452 bool fgInitSubsystems() {
1453 // static const SGPropertyNode *longitude
1454 // = fgGetNode("/sim/presets/longitude-deg");
1455 // static const SGPropertyNode *latitude
1456 // = fgGetNode("/sim/presets/latitude-deg");
1457 // static const SGPropertyNode *altitude
1458 // = fgGetNode("/sim/presets/altitude-ft");
1460 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1461 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1463 ////////////////////////////////////////////////////////////////////
1464 // Initialize the event manager subsystem.
1465 ////////////////////////////////////////////////////////////////////
1467 globals->get_event_mgr()->init();
1468 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1470 ////////////////////////////////////////////////////////////////////
1471 // Initialize the property interpolator subsystem. Put into the INIT
1472 // group because the "nasal" subsystem may need it at GENERAL take-down.
1473 ////////////////////////////////////////////////////////////////////
1474 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1477 ////////////////////////////////////////////////////////////////////
1478 // Add the FlightGear property utilities.
1479 ////////////////////////////////////////////////////////////////////
1480 globals->add_subsystem("properties", new FGProperties);
1482 ////////////////////////////////////////////////////////////////////
1483 // Initialize the material property subsystem.
1484 ////////////////////////////////////////////////////////////////////
1486 SGPath mpath( globals->get_fg_root() );
1487 mpath.append( "materials.xml" );
1488 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1489 globals->get_props()) ) {
1490 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1495 ////////////////////////////////////////////////////////////////////
1496 // Initialize the scenery management subsystem.
1497 ////////////////////////////////////////////////////////////////////
1499 if ( globals->get_tile_mgr()->init() ) {
1500 // Load the local scenery data
1501 double visibility_meters = fgGetDouble("/environment/visibility-m");
1503 globals->get_tile_mgr()->update( visibility_meters );
1505 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1509 globals->get_scenery()->get_scene_graph()
1510 ->addChild(simgear::Particles::getCommonRoot());
1511 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1513 ////////////////////////////////////////////////////////////////////
1514 // Initialize the flight model subsystem.
1515 ////////////////////////////////////////////////////////////////////
1519 // allocates structures so must happen before any of the flight
1520 // model or control parameters are set
1521 fgAircraftInit(); // In the future this might not be the case.
1524 ////////////////////////////////////////////////////////////////////
1525 // Initialize the weather subsystem.
1526 ////////////////////////////////////////////////////////////////////
1528 // Initialize the weather modeling subsystem
1529 globals->add_subsystem("environment", new FGEnvironmentMgr);
1531 ////////////////////////////////////////////////////////////////////
1532 // Initialize the ridge lift simulation.
1533 ////////////////////////////////////////////////////////////////////
1535 // Initialize the ridgelift subsystem
1536 globals->add_subsystem("ridgelift", new FGRidgeLift);
1538 ////////////////////////////////////////////////////////////////////
1539 // Initialize the aircraft systems and instrumentation (before the
1541 ////////////////////////////////////////////////////////////////////
1543 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1544 globals->add_subsystem("systems", new FGSystemMgr);
1546 ////////////////////////////////////////////////////////////////////
1547 // Initialize the XML Autopilot subsystem.
1548 ////////////////////////////////////////////////////////////////////
1550 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilotGroup );
1551 globals->add_subsystem( "route-manager", new FGRouteMgr );
1552 globals->add_subsystem( "autobrake", new FGAutoBrake );
1554 ////////////////////////////////////////////////////////////////////
1555 // Initialize the view manager subsystem.
1556 ////////////////////////////////////////////////////////////////////
1560 ////////////////////////////////////////////////////////////////////
1561 // Initialize the Input-Output subsystem
1562 ////////////////////////////////////////////////////////////////////
1563 globals->add_subsystem( "io", new FGIO );
1565 ////////////////////////////////////////////////////////////////////
1566 // Create and register the logger.
1567 ////////////////////////////////////////////////////////////////////
1569 globals->add_subsystem("logger", new FGLogger);
1571 ////////////////////////////////////////////////////////////////////
1572 // Create and register the XML GUI.
1573 ////////////////////////////////////////////////////////////////////
1575 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1578 ////////////////////////////////////////////////////////////////////
1579 // Initialize the local time subsystem.
1580 ////////////////////////////////////////////////////////////////////
1582 // update the current timezone each 30 minutes
1583 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1584 &fgUpdateLocalTime, 30*60 );
1585 fgInitTimeOffset(); // the environment subsystem needs this
1588 ////////////////////////////////////////////////////////////////////
1589 // Initialize the lighting subsystem.
1590 ////////////////////////////////////////////////////////////////////
1592 globals->add_subsystem("lighting", new FGLight);
1594 //////////////////////////////////////////////////////////////////////
1595 // Initialize the 2D cloud subsystem.
1596 ////////////////////////////////////////////////////////////////////
1597 fgGetBool("/sim/rendering/bump-mapping", false);
1599 #ifdef ENABLE_AUDIO_SUPPORT
1600 ////////////////////////////////////////////////////////////////////
1601 // Initialize the sound-effects subsystem.
1602 ////////////////////////////////////////////////////////////////////
1603 globals->add_subsystem("voice", new FGVoiceMgr);
1606 ////////////////////////////////////////////////////////////////////
1607 // Initialise the ATC Manager
1608 ////////////////////////////////////////////////////////////////////
1611 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1612 globals->set_ATC_mgr(new FGATCMgr);
1613 globals->get_ATC_mgr()->init();
1615 ////////////////////////////////////////////////////////////////////
1616 // Initialise the AI Manager
1617 ////////////////////////////////////////////////////////////////////
1619 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1620 globals->set_AI_mgr(new FGAIMgr);
1621 globals->get_AI_mgr()->init();
1623 ////////////////////////////////////////////////////////////////////
1624 // Initialise the AI Model Manager
1625 ////////////////////////////////////////////////////////////////////
1626 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1627 globals->add_subsystem("ai_model", new FGAIManager);
1628 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1631 // It's probably a good idea to initialize the top level traffic manager
1632 // After the AI and ATC systems have been initialized properly.
1633 // AI Traffic manager
1634 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1637 ////////////////////////////////////////////////////////////////////
1638 // Initialize the cockpit subsystem
1639 ////////////////////////////////////////////////////////////////////
1640 if( fgCockpitInit( ¤t_aircraft )) {
1641 // Cockpit initialized ok.
1643 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1648 ////////////////////////////////////////////////////////////////////
1649 // Add a new 2D panel.
1650 ////////////////////////////////////////////////////////////////////
1652 string panel_path = fgGetString("/sim/panel/path",
1653 "Panels/Default/default.xml");
1655 globals->set_current_panel( fgReadPanel(panel_path) );
1656 if (globals->get_current_panel() == 0) {
1657 SG_LOG( SG_INPUT, SG_ALERT,
1658 "Error reading new panel from " << panel_path );
1660 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1661 globals->get_current_panel()->init();
1662 globals->get_current_panel()->bind();
1666 ////////////////////////////////////////////////////////////////////
1667 // Initialize the controls subsystem.
1668 ////////////////////////////////////////////////////////////////////
1670 globals->get_controls()->init();
1671 globals->get_controls()->bind();
1674 ////////////////////////////////////////////////////////////////////
1675 // Initialize the input subsystem.
1676 ////////////////////////////////////////////////////////////////////
1678 globals->add_subsystem("input", new FGInput);
1681 ////////////////////////////////////////////////////////////////////
1682 // Initialize the replay subsystem
1683 ////////////////////////////////////////////////////////////////////
1684 globals->add_subsystem("replay", new FGReplay);
1687 ////////////////////////////////////////////////////////////////////
1688 // Bind and initialize subsystems.
1689 ////////////////////////////////////////////////////////////////////
1691 globals->get_subsystem_mgr()->bind();
1692 globals->get_subsystem_mgr()->init();
1694 ////////////////////////////////////////////////////////////////////
1695 // Initialize multiplayer subsystem
1696 ////////////////////////////////////////////////////////////////////
1698 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1699 globals->get_multiplayer_mgr()->init();
1701 ////////////////////////////////////////////////////////////////////////
1702 // Initialize the Nasal interpreter.
1703 // Do this last, so that the loaded scripts see initialized state
1704 ////////////////////////////////////////////////////////////////////////
1705 FGNasalSys* nasal = new FGNasalSys();
1706 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1709 // initialize methods that depend on other subsystems.
1710 globals->get_subsystem_mgr()->postinit();
1712 ////////////////////////////////////////////////////////////////////////
1713 // End of subsystem initialization.
1714 ////////////////////////////////////////////////////////////////////
1716 SG_LOG( SG_GENERAL, SG_INFO, endl);
1718 // Save the initial state for future
1720 globals->saveInitialState();
1726 void fgReInitSubsystems()
1728 // static const SGPropertyNode *longitude
1729 // = fgGetNode("/sim/presets/longitude-deg");
1730 // static const SGPropertyNode *latitude
1731 // = fgGetNode("/sim/presets/latitude-deg");
1732 static const SGPropertyNode *altitude
1733 = fgGetNode("/sim/presets/altitude-ft");
1734 static const SGPropertyNode *master_freeze
1735 = fgGetNode("/sim/freeze/master");
1737 SG_LOG( SG_GENERAL, SG_INFO,
1738 "fgReInitSubsystems(): /position/altitude = "
1739 << altitude->getDoubleValue() );
1741 bool freeze = master_freeze->getBoolValue();
1743 fgSetBool("/sim/freeze/master", true);
1745 fgSetBool("/sim/crashed", false);
1747 // Force reupdating the positions of the ai 3d models. They are used for
1748 // initializing ground level for the FDM.
1749 globals->get_subsystem("ai_model")->reinit();
1751 // Initialize the FDM
1754 // allocates structures so must happen before any of the flight
1755 // model or control parameters are set
1756 fgAircraftInit(); // In the future this might not be the case.
1758 // reload offsets from config defaults
1759 globals->get_viewmgr()->reinit();
1763 globals->get_controls()->reset_all();
1765 fgUpdateLocalTime();
1767 // re-init to proper time of day setting
1771 fgSetBool("/sim/freeze/master", false);
1773 fgSetBool("/sim/sceneryloaded",false);
1777 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1779 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1781 bool freeze = master_freeze->getBoolValue();
1783 master_freeze->setBoolValue(true);
1785 fgSetBool("/sim/signals/reinit", true);
1786 cur_fdm_state->unbind();
1788 // in case user has changed window size as
1789 // restoreInitialState() overwrites these
1790 int xsize = fgGetInt("/sim/startup/xsize");
1791 int ysize = fgGetInt("/sim/startup/ysize");
1793 // viewports also needs to be saved/restored as
1794 // restoreInitialState() overwrites these
1795 SGPropertyNode *guiNode = new SGPropertyNode;
1796 SGPropertyNode *cameraNode = new SGPropertyNode;
1797 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1798 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1799 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1801 globals->restoreInitialState();
1803 // update our position based on current presets
1806 // We don't know how to resize the window, so keep the last values
1807 // for xsize and ysize, and don't use the one set initially
1808 fgSetInt("/sim/startup/xsize", xsize);
1809 fgSetInt("/sim/startup/ysize", ysize);
1811 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1812 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1817 SGTime *t = globals->get_time_params();
1820 globals->set_time_params(t);
1822 fgReInitSubsystems();
1824 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1825 globals->get_renderer()->resize(xsize, ysize);
1826 fgSetBool("/sim/signals/reinit", false);
1829 master_freeze->setBoolValue(false);