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()
35 #if defined( _MSC_VER) || defined(__MINGW32__)
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
42 // work around a stdc++ lib bug in some versions of linux, but doesn't
43 // seem to hurt to have this here for all versions of Linux.
45 # define _G_NO_EXTERN_TEMPLATES
48 #include <simgear/compiler.h>
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/structure/exception.hxx>
55 #include <simgear/structure/event_mgr.hxx>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/interpolator.hxx>
58 #include <simgear/scene/material/matlib.hxx>
59 #include <simgear/scene/model/particles.hxx>
60 #include <simgear/sound/soundmgr_openal.hxx>
61 #include <simgear/timing/sg_time.hxx>
62 #include <simgear/timing/lowleveltime.h>
64 #include <Aircraft/aircraft.hxx>
65 #include <Aircraft/controls.hxx>
66 #include <Aircraft/replay.hxx>
67 #include <Airports/apt_loader.hxx>
68 #include <Airports/runways.hxx>
69 #include <Airports/simple.hxx>
70 #include <Airports/dynamics.hxx>
72 #include <AIModel/AIManager.hxx>
73 #include <ATCDCL/ATCmgr.hxx>
74 #include <ATCDCL/AIMgr.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/xmlauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <FDM/SP/ADA.hxx>
82 #include <FDM/SP/ACMS.hxx>
83 #include <FDM/SP/MagicCarpet.hxx>
84 #include <FDM/SP/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/UFO.hxx>
91 #include <FDM/NullFDM.hxx>
92 #include <FDM/YASim/YASim.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Model/acmodel.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Navaids/fix.hxx>
103 #include <Navaids/fixlist.hxx>
104 #include <Scenery/scenery.hxx>
105 #include <Scenery/tilemgr.hxx>
106 #include <Scripting/NasalSys.hxx>
107 #include <Sound/voice.hxx>
108 #include <Systems/system_mgr.hxx>
109 #include <Time/light.hxx>
110 #include <Time/sunsolver.hxx>
111 #include <Time/tmp.hxx>
112 #include <Traffic/TrafficMgr.hxx>
113 #include <MultiPlayer/multiplaymgr.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"
128 #include "ATCDCL/commlist.hxx"
131 # include <CoreFoundation/CoreFoundation.h>
136 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__ )
267 root = "/FlightGear";
268 #elif defined( WIN32 )
269 root = "\\FlightGear";
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 ( !strcmp(dire->d_name, aircraft.c_str()) ) {
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;
583 #if defined( _MSC_VER ) || defined( __MINGW32__ )
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 (aircraft_set == name) {
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);
801 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
802 parking->getHeading());
807 // Set current_options lon/lat given an airport id and runway number
808 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
812 // set initial position from airport and runway number
813 SG_LOG( SG_GENERAL, SG_INFO,
814 "Attempting to set starting position for "
815 << id << ":" << rwy );
817 const FGAirport* apt = fgFindAirportID(id);
819 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
823 if (!apt->hasRunwayWithIdent(rwy)) {
824 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
825 "Failed to find runway " << rwy <<
826 " at airport " << id << ". Using default runway." );
830 FGRunway* r(apt->getRunwayByIdent(rwy));
831 fgSetString("/sim/atc/runway", r->ident().c_str());
832 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
833 fgApplyStartOffset(startPos, r->headingDeg());
838 static void fgSetDistOrAltFromGlideSlope() {
839 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
840 string apt_id = fgGetString("/sim/presets/airport-id");
841 double gs = fgGetDouble("/sim/presets/glideslope-deg")
842 * SG_DEGREES_TO_RADIANS ;
843 double od = fgGetDouble("/sim/presets/offset-distance-nm");
844 double alt = fgGetDouble("/sim/presets/altitude-ft");
846 double apt_elev = 0.0;
847 if ( ! apt_id.empty() ) {
848 apt_elev = fgGetAirportElev( apt_id );
849 if ( apt_elev < -9990.0 ) {
856 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
857 // set altitude from glideslope and offset-distance
858 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
859 alt = fabs(od*tan(gs)) + apt_elev;
860 fgSetDouble("/sim/presets/altitude-ft", alt);
861 fgSetBool("/sim/presets/onground", false);
862 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
864 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
865 // set offset-distance from glideslope and altitude
866 od = (alt - apt_elev) / tan(gs);
867 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
868 fgSetDouble("/sim/presets/offset-distance-nm", od);
869 fgSetBool("/sim/presets/onground", false);
870 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
872 } else if( fabs(gs) > 0.01 ) {
873 SG_LOG( SG_GENERAL, SG_ALERT,
874 "Glideslope given but not altitude or offset-distance." );
875 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
876 fgSetDouble("/sim/presets/glideslope-deg", 0);
877 fgSetBool("/sim/presets/onground", true);
882 // Set current_options lon/lat given an airport id and heading (degrees)
883 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
885 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
888 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
889 << id << ":" << freq );
893 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
897 // Set current_options lon/lat given an aircraft carrier id
898 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
900 // set initial position from runway and heading
904 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
905 double lon = geodPos.getLongitudeDeg();
906 double lat = geodPos.getLatitudeDeg();
907 double alt = geodPos.getElevationFt();
909 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
910 << carrier << " at lat = " << lat << ", lon = " << lon
911 << ", alt = " << alt << ", heading = " << heading);
913 fgSetDouble("/sim/presets/longitude-deg", lon);
914 fgSetDouble("/sim/presets/latitude-deg", lat);
915 fgSetDouble("/sim/presets/altitude-ft", alt);
916 fgSetDouble("/sim/presets/heading-deg", heading);
917 fgSetDouble("/position/longitude-deg", lon);
918 fgSetDouble("/position/latitude-deg", lat);
919 fgSetDouble("/position/altitude-ft", alt);
920 fgSetDouble("/orientation/heading-deg", heading);
922 fgSetString("/sim/presets/speed-set", "UVW");
923 fgSetDouble("/velocities/uBody-fps", uvw(0));
924 fgSetDouble("/velocities/vBody-fps", uvw(1));
925 fgSetDouble("/velocities/wBody-fps", uvw(2));
926 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
927 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
928 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
930 fgSetBool("/sim/presets/onground", true);
934 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
940 // Set current_options lon/lat given an airport id and heading (degrees)
941 static bool fgSetPosFromFix( const string& id )
943 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
944 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
946 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
950 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
955 * Initialize vor/ndb/ils/fix list management and query systems (as
956 * well as simple airport db list)
961 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
963 SGPath aptdb( globals->get_fg_root() );
964 aptdb.append( "Airports/apt.dat" );
966 SGPath p_metar( globals->get_fg_root() );
967 p_metar.append( "Airports/metar.dat" );
969 // Initialise the frequency search map BEFORE reading
970 // the airport database:
971 current_commlist = new FGCommList;
972 current_commlist->init( globals->get_fg_root() );
973 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
975 FGNavList *navlist = new FGNavList;
976 FGNavList *loclist = new FGNavList;
977 FGNavList *gslist = new FGNavList;
978 FGNavList *dmelist = new FGNavList;
979 FGNavList *tacanlist = new FGNavList;
980 FGNavList *carrierlist = new FGNavList;
981 FGTACANList *channellist = new FGTACANList;
983 globals->set_navlist( navlist );
984 globals->set_loclist( loclist );
985 globals->set_gslist( gslist );
986 globals->set_dmelist( dmelist );
987 globals->set_tacanlist( tacanlist );
988 globals->set_carrierlist( carrierlist );
989 globals->set_channellist( channellist );
991 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
992 SG_LOG( SG_GENERAL, SG_ALERT,
993 "Problems loading one or more navigational database" );
996 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
997 SGPath p_fix( globals->get_fg_root() );
998 p_fix.append( "Navaids/fix.dat" );
1000 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1002 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1003 SGPath p_awy( globals->get_fg_root() );
1004 p_awy.append( "Navaids/awy.dat" );
1005 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1006 //cerr << "Loading Airways" << endl;
1007 awyNet->load (p_awy );
1009 //cerr << "initializing airways" << endl;
1010 globals->set_airwaynet( awyNet );
1016 // Set the initial position based on presets (or defaults)
1017 bool fgInitPosition() {
1018 // cout << "fgInitPosition()" << endl;
1019 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1020 * SG_DEGREES_TO_RADIANS ;
1021 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1022 double alt = fgGetDouble("/sim/presets/altitude-ft");
1024 bool set_pos = false;
1026 // If glideslope is specified, then calculate offset-distance or
1027 // altitude relative to glide slope if either of those was not
1029 if ( fabs( gs ) > 0.01 ) {
1030 fgSetDistOrAltFromGlideSlope();
1034 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1035 // If not, check for an airport-id and use that.
1036 // If not, default to the middle of the KSFO field.
1037 // The default values for lon/lat are deliberately out of range
1038 // so that the airport-id can take effect; valid lon/lat will
1039 // override airport-id, however.
1040 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1041 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1042 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1043 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1048 string apt = fgGetString("/sim/presets/airport-id");
1049 string rwy_no = fgGetString("/sim/presets/runway");
1050 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1051 string vor = fgGetString("/sim/presets/vor-id");
1052 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1053 string ndb = fgGetString("/sim/presets/ndb-id");
1054 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1055 string carrier = fgGetString("/sim/presets/carrier");
1056 string parkpos = fgGetString("/sim/presets/parkpos");
1057 string fix = fgGetString("/sim/presets/fix");
1058 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1059 double hdg = hdg_preset->getDoubleValue();
1061 // save some start parameters, so that we can later say what the
1062 // user really requested. TODO generalize that and move it to options.cxx
1063 static bool start_options_saved = false;
1064 if (!start_options_saved) {
1065 start_options_saved = true;
1066 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1068 opt->setDoubleValue("latitude-deg", lat_deg);
1069 opt->setDoubleValue("longitude-deg", lon_deg);
1070 opt->setDoubleValue("heading-deg", hdg);
1071 opt->setStringValue("airport", apt.c_str());
1072 opt->setStringValue("runway", rwy_no.c_str());
1076 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1078 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1079 // An airport + parking position is requested
1080 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1081 // set tower position
1082 fgSetString("/sim/tower/airport-id", apt.c_str());
1087 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1088 // An airport + runway is requested
1089 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1090 // set tower position (a little off the heading for single
1092 fgSetString("/sim/tower/airport-id", apt.c_str());
1097 if ( !set_pos && !apt.empty() ) {
1098 // An airport is requested (find runway closest to hdg)
1099 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1100 // set tower position (a little off the heading for single
1102 fgSetString("/sim/tower/airport-id", apt.c_str());
1107 if (hdg_preset->getDoubleValue() > 9990.0)
1108 hdg_preset->setDoubleValue(hdg);
1110 if ( !set_pos && !vor.empty() ) {
1111 // a VOR is requested
1112 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1117 if ( !set_pos && !ndb.empty() ) {
1118 // an NDB is requested
1119 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1124 if ( !set_pos && !carrier.empty() ) {
1125 // an aircraft carrier is requested
1126 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1131 if ( !set_pos && !fix.empty() ) {
1132 // a Fix is requested
1133 if ( fgSetPosFromFix( fix ) ) {
1139 // No lon/lat specified, no airport specified, default to
1140 // middle of KSFO field.
1141 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1142 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1145 fgSetDouble( "/position/longitude-deg",
1146 fgGetDouble("/sim/presets/longitude-deg") );
1147 fgSetDouble( "/position/latitude-deg",
1148 fgGetDouble("/sim/presets/latitude-deg") );
1149 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1151 // determine if this should be an on-ground or in-air start
1152 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1153 fgSetBool("/sim/presets/onground", false);
1155 fgSetBool("/sim/presets/onground", true);
1162 // General house keeping initializations
1163 bool fgInitGeneral() {
1166 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1167 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1169 root = globals->get_fg_root();
1170 if ( ! root.length() ) {
1171 // No root path set? Then bail ...
1172 SG_LOG( SG_GENERAL, SG_ALERT,
1173 "Cannot continue without a path to the base package "
1174 << "being defined." );
1177 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1179 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1181 char buf[512], *cwd = getcwd(buf, 511);
1183 SGPropertyNode *curr = fgGetNode("/sim", true);
1184 curr->removeChild("fg-current", 0, false);
1185 curr = curr->getChild("fg-current", 0, true);
1186 curr->setStringValue(cwd ? cwd : "");
1187 curr->setAttribute(SGPropertyNode::WRITE, false);
1189 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1190 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1195 // Initialize the flight model subsystem. This just creates the
1196 // object. The actual fdm initialization is delayed until we get a
1197 // proper scenery elevation hit. This is checked for in main.cxx
1201 if ( cur_fdm_state ) {
1202 delete cur_fdm_state;
1206 double dt = 1.0 / fgGetInt("/sim/model-hz");
1207 string model = fgGetString("/sim/flight-model");
1209 if ( model == "larcsim" ) {
1210 cur_fdm_state = new FGLaRCsim( dt );
1211 } else if ( model == "jsb" ) {
1212 cur_fdm_state = new FGJSBsim( dt );
1214 } else if ( model == "ada" ) {
1215 cur_fdm_state = new FGADA( dt );
1216 } else if ( model == "acms" ) {
1217 cur_fdm_state = new FGACMS( dt );
1218 } else if ( model == "balloon" ) {
1219 cur_fdm_state = new FGBalloonSim( dt );
1220 } else if ( model == "magic" ) {
1221 cur_fdm_state = new FGMagicCarpet( dt );
1223 } else if ( model == "ufo" ) {
1224 cur_fdm_state = new FGUFO( dt );
1225 } else if ( model == "external" ) {
1226 // external is a synonym for "--fdm=null" and is
1227 // maintained here for backwards compatibility
1228 cur_fdm_state = new FGNullFDM( dt );
1229 } else if ( model.find("network") == 0 ) {
1230 string host = "localhost";
1234 string net_options = model.substr(8);
1235 string::size_type begin, end;
1238 end = net_options.find( ",", begin );
1239 if ( end != string::npos ) {
1240 host = net_options.substr(begin, end - begin);
1244 end = net_options.find( ",", begin );
1245 if ( end != string::npos ) {
1246 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1250 end = net_options.find( ",", begin );
1251 if ( end != string::npos ) {
1252 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1256 end = net_options.find( ",", begin );
1257 if ( end != string::npos ) {
1258 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1261 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1262 } else if ( model.find("pipe") == 0 ) {
1263 // /* old */ string pipe_path = model.substr(5);
1264 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1265 string pipe_path = "";
1266 string pipe_protocol = "";
1267 string pipe_options = model.substr(5);
1268 string::size_type begin, end;
1271 end = pipe_options.find( ",", begin );
1272 if ( end != string::npos ) {
1273 pipe_path = pipe_options.substr(begin, end - begin);
1276 // protocol (last option)
1277 pipe_protocol = pipe_options.substr(begin);
1278 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1279 } else if ( model == "null" ) {
1280 cur_fdm_state = new FGNullFDM( dt );
1281 } else if ( model == "yasim" ) {
1282 cur_fdm_state = new YASim( dt );
1284 throw sg_exception(string("Unrecognized flight model '") + model
1285 + "', cannot init flight dynamics model.");
1289 // Initialize view parameters
1291 // force update of model so that viewer can get some data...
1292 globals->get_aircraft_model()->update(0);
1293 // run update for current view so that data is current...
1294 globals->get_viewmgr()->update(0);
1298 SGTime *fgInitTime() {
1300 static const SGPropertyNode *longitude
1301 = fgGetNode("/position/longitude-deg");
1302 static const SGPropertyNode *latitude
1303 = fgGetNode("/position/latitude-deg");
1304 static const SGPropertyNode *cur_time_override
1305 = fgGetNode("/sim/time/cur-time-override", true);
1307 SGPath zone( globals->get_fg_root() );
1308 zone.append( "Timezone" );
1309 SGTime *t = new SGTime( longitude->getDoubleValue()
1310 * SGD_DEGREES_TO_RADIANS,
1311 latitude->getDoubleValue()
1312 * SGD_DEGREES_TO_RADIANS,
1314 cur_time_override->getLongValue() );
1316 globals->set_warp_delta( 0 );
1318 t->update( 0.0, 0.0,
1319 cur_time_override->getLongValue(),
1320 globals->get_warp() );
1326 // set up a time offset (aka warp) if one is specified
1327 void fgInitTimeOffset() {
1328 static const SGPropertyNode *longitude
1329 = fgGetNode("/position/longitude-deg");
1330 static const SGPropertyNode *latitude
1331 = fgGetNode("/position/latitude-deg");
1332 static const SGPropertyNode *cur_time_override
1333 = fgGetNode("/sim/time/cur-time-override", true);
1335 // Handle potential user specified time offsets
1336 int orig_warp = globals->get_warp();
1337 SGTime *t = globals->get_time_params();
1338 time_t cur_time = t->get_cur_time();
1339 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1340 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1341 time_t aircraftLocalTime =
1342 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1344 // Okay, we now have several possible scenarios
1345 int offset = fgGetInt("/sim/startup/time-offset");
1346 string offset_type = fgGetString("/sim/startup/time-offset-type");
1349 if ( offset_type == "real" ) {
1351 } else if ( offset_type == "dawn" ) {
1352 warp = fgTimeSecondsUntilSunAngle( cur_time,
1353 longitude->getDoubleValue()
1354 * SGD_DEGREES_TO_RADIANS,
1355 latitude->getDoubleValue()
1356 * SGD_DEGREES_TO_RADIANS,
1358 } else if ( offset_type == "morning" ) {
1359 warp = fgTimeSecondsUntilSunAngle( cur_time,
1360 longitude->getDoubleValue()
1361 * SGD_DEGREES_TO_RADIANS,
1362 latitude->getDoubleValue()
1363 * SGD_DEGREES_TO_RADIANS,
1365 } else if ( offset_type == "noon" ) {
1366 warp = fgTimeSecondsUntilSunAngle( cur_time,
1367 longitude->getDoubleValue()
1368 * SGD_DEGREES_TO_RADIANS,
1369 latitude->getDoubleValue()
1370 * SGD_DEGREES_TO_RADIANS,
1372 } else if ( offset_type == "afternoon" ) {
1373 warp = fgTimeSecondsUntilSunAngle( cur_time,
1374 longitude->getDoubleValue()
1375 * SGD_DEGREES_TO_RADIANS,
1376 latitude->getDoubleValue()
1377 * SGD_DEGREES_TO_RADIANS,
1379 } else if ( offset_type == "dusk" ) {
1380 warp = fgTimeSecondsUntilSunAngle( cur_time,
1381 longitude->getDoubleValue()
1382 * SGD_DEGREES_TO_RADIANS,
1383 latitude->getDoubleValue()
1384 * SGD_DEGREES_TO_RADIANS,
1386 } else if ( offset_type == "evening" ) {
1387 warp = fgTimeSecondsUntilSunAngle( cur_time,
1388 longitude->getDoubleValue()
1389 * SGD_DEGREES_TO_RADIANS,
1390 latitude->getDoubleValue()
1391 * SGD_DEGREES_TO_RADIANS,
1393 } else if ( offset_type == "midnight" ) {
1394 warp = fgTimeSecondsUntilSunAngle( cur_time,
1395 longitude->getDoubleValue()
1396 * SGD_DEGREES_TO_RADIANS,
1397 latitude->getDoubleValue()
1398 * SGD_DEGREES_TO_RADIANS,
1400 } else if ( offset_type == "system-offset" ) {
1403 } else if ( offset_type == "gmt-offset" ) {
1404 warp = offset - (currGMT - systemLocalTime);
1406 } else if ( offset_type == "latitude-offset" ) {
1407 warp = offset - (aircraftLocalTime - systemLocalTime);
1409 } else if ( offset_type == "system" ) {
1410 warp = offset - (systemLocalTime - currGMT) - cur_time;
1411 } else if ( offset_type == "gmt" ) {
1412 warp = offset - cur_time;
1413 } else if ( offset_type == "latitude" ) {
1414 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1416 SG_LOG( SG_GENERAL, SG_ALERT,
1417 "FG_TIME::Unsupported offset type " << offset_type );
1420 globals->set_warp( orig_warp + warp );
1421 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1422 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1423 cur_time_override->getLongValue(),
1424 globals->get_warp() );
1426 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1427 << globals->get_warp() );
1431 // This is the top level init routine which calls all the other
1432 // initialization routines. If you are adding a subsystem to flight
1433 // gear, its initialization call should located in this routine.
1434 // Returns non-zero if a problem encountered.
1435 bool fgInitSubsystems() {
1436 // static const SGPropertyNode *longitude
1437 // = fgGetNode("/sim/presets/longitude-deg");
1438 // static const SGPropertyNode *latitude
1439 // = fgGetNode("/sim/presets/latitude-deg");
1440 // static const SGPropertyNode *altitude
1441 // = fgGetNode("/sim/presets/altitude-ft");
1442 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1443 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1445 ////////////////////////////////////////////////////////////////////
1446 // Initialize the event manager subsystem.
1447 ////////////////////////////////////////////////////////////////////
1449 globals->get_event_mgr()->init();
1450 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1452 ////////////////////////////////////////////////////////////////////
1453 // Initialize the property interpolator subsystem. Put into the INIT
1454 // group because the "nasal" subsystem may need it at GENERAL take-down.
1455 ////////////////////////////////////////////////////////////////////
1456 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1459 ////////////////////////////////////////////////////////////////////
1460 // Add the FlightGear property utilities.
1461 ////////////////////////////////////////////////////////////////////
1462 globals->add_subsystem("properties", new FGProperties);
1464 ////////////////////////////////////////////////////////////////////
1465 // Initialize the material property subsystem.
1466 ////////////////////////////////////////////////////////////////////
1468 SGPath mpath( globals->get_fg_root() );
1469 mpath.append( "materials.xml" );
1470 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1471 globals->get_props()) ) {
1472 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1477 ////////////////////////////////////////////////////////////////////
1478 // Initialize the scenery management subsystem.
1479 ////////////////////////////////////////////////////////////////////
1481 if ( globals->get_tile_mgr()->init() ) {
1482 // Load the local scenery data
1483 double visibility_meters = fgGetDouble("/environment/visibility-m");
1485 globals->get_tile_mgr()->update( visibility_meters );
1487 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1491 globals->get_scenery()->get_scene_graph()
1492 ->addChild(simgear::Particles::getCommonRoot());
1493 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1495 ////////////////////////////////////////////////////////////////////
1496 // Initialize the flight model subsystem.
1497 ////////////////////////////////////////////////////////////////////
1501 // allocates structures so must happen before any of the flight
1502 // model or control parameters are set
1503 fgAircraftInit(); // In the future this might not be the case.
1506 ////////////////////////////////////////////////////////////////////
1507 // Initialize the weather subsystem.
1508 ////////////////////////////////////////////////////////////////////
1510 // Initialize the weather modeling subsystem
1511 globals->add_subsystem("environment", new FGEnvironmentMgr);
1513 ////////////////////////////////////////////////////////////////////
1514 // Initialize the ridge lift simulation.
1515 ////////////////////////////////////////////////////////////////////
1517 // Initialize the ridgelift subsystem
1518 globals->add_subsystem("ridgelift", new FGRidgeLift);
1520 ////////////////////////////////////////////////////////////////////
1521 // Initialize the aircraft systems and instrumentation (before the
1523 ////////////////////////////////////////////////////////////////////
1525 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1526 globals->add_subsystem("systems", new FGSystemMgr);
1528 ////////////////////////////////////////////////////////////////////
1529 // Initialize the XML Autopilot subsystem.
1530 ////////////////////////////////////////////////////////////////////
1532 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1533 globals->add_subsystem( "route-manager", new FGRouteMgr );
1535 ////////////////////////////////////////////////////////////////////
1536 // Initialize the view manager subsystem.
1537 ////////////////////////////////////////////////////////////////////
1541 ////////////////////////////////////////////////////////////////////
1542 // Initialize the Input-Output subsystem
1543 ////////////////////////////////////////////////////////////////////
1544 globals->add_subsystem( "io", new FGIO );
1546 ////////////////////////////////////////////////////////////////////
1547 // Create and register the logger.
1548 ////////////////////////////////////////////////////////////////////
1550 globals->add_subsystem("logger", new FGLogger);
1552 ////////////////////////////////////////////////////////////////////
1553 // Create and register the XML GUI.
1554 ////////////////////////////////////////////////////////////////////
1556 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1559 ////////////////////////////////////////////////////////////////////
1560 // Initialize the local time subsystem.
1561 ////////////////////////////////////////////////////////////////////
1563 // update the current timezone each 30 minutes
1564 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1565 &fgUpdateLocalTime, 30*60 );
1566 fgInitTimeOffset(); // the environment subsystem needs this
1569 ////////////////////////////////////////////////////////////////////
1570 // Initialize the lighting subsystem.
1571 ////////////////////////////////////////////////////////////////////
1573 globals->add_subsystem("lighting", new FGLight);
1575 //////////////////////////////////////////////////////////////////////
1576 // Initialize the 2D cloud subsystem.
1577 ////////////////////////////////////////////////////////////////////
1578 fgGetBool("/sim/rendering/bump-mapping", false);
1580 #ifdef ENABLE_AUDIO_SUPPORT
1581 ////////////////////////////////////////////////////////////////////
1582 // Initialize the sound-effects subsystem.
1583 ////////////////////////////////////////////////////////////////////
1584 globals->add_subsystem("voice", new FGVoiceMgr);
1587 ////////////////////////////////////////////////////////////////////
1588 // Initialise the ATC Manager
1589 ////////////////////////////////////////////////////////////////////
1591 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1592 globals->set_ATC_mgr(new FGATCMgr);
1593 globals->get_ATC_mgr()->init();
1595 ////////////////////////////////////////////////////////////////////
1596 // Initialise the AI Manager
1597 ////////////////////////////////////////////////////////////////////
1599 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1600 globals->set_AI_mgr(new FGAIMgr);
1601 globals->get_AI_mgr()->init();
1603 ////////////////////////////////////////////////////////////////////
1604 // Initialise the AI Model Manager
1605 ////////////////////////////////////////////////////////////////////
1606 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1607 globals->add_subsystem("ai_model", new FGAIManager);
1608 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1611 // It's probably a good idea to initialize the top level traffic manager
1612 // After the AI and ATC systems have been initialized properly.
1613 // AI Traffic manager
1614 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1617 ////////////////////////////////////////////////////////////////////
1618 // Initialize the cockpit subsystem
1619 ////////////////////////////////////////////////////////////////////
1620 if( fgCockpitInit( ¤t_aircraft )) {
1621 // Cockpit initialized ok.
1623 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1628 ////////////////////////////////////////////////////////////////////
1629 // Add a new 2D panel.
1630 ////////////////////////////////////////////////////////////////////
1632 string panel_path = fgGetString("/sim/panel/path",
1633 "Panels/Default/default.xml");
1635 globals->set_current_panel( fgReadPanel(panel_path) );
1636 if (globals->get_current_panel() == 0) {
1637 SG_LOG( SG_INPUT, SG_ALERT,
1638 "Error reading new panel from " << panel_path );
1640 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1641 globals->get_current_panel()->init();
1642 globals->get_current_panel()->bind();
1646 ////////////////////////////////////////////////////////////////////
1647 // Initialize the controls subsystem.
1648 ////////////////////////////////////////////////////////////////////
1650 globals->get_controls()->init();
1651 globals->get_controls()->bind();
1654 ////////////////////////////////////////////////////////////////////
1655 // Initialize the input subsystem.
1656 ////////////////////////////////////////////////////////////////////
1658 globals->add_subsystem("input", new FGInput);
1661 ////////////////////////////////////////////////////////////////////
1662 // Initialize the replay subsystem
1663 ////////////////////////////////////////////////////////////////////
1664 globals->add_subsystem("replay", new FGReplay);
1667 ////////////////////////////////////////////////////////////////////
1668 // Bind and initialize subsystems.
1669 ////////////////////////////////////////////////////////////////////
1671 globals->get_subsystem_mgr()->bind();
1672 globals->get_subsystem_mgr()->init();
1674 ////////////////////////////////////////////////////////////////////
1675 // Initialize multiplayer subsystem
1676 ////////////////////////////////////////////////////////////////////
1678 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1679 globals->get_multiplayer_mgr()->init();
1681 ////////////////////////////////////////////////////////////////////////
1682 // Initialize the Nasal interpreter.
1683 // Do this last, so that the loaded scripts see initialized state
1684 ////////////////////////////////////////////////////////////////////////
1685 FGNasalSys* nasal = new FGNasalSys();
1686 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1689 // initialize methods that depend on other subsystems.
1690 globals->get_subsystem_mgr()->postinit();
1692 ////////////////////////////////////////////////////////////////////////
1693 // End of subsystem initialization.
1694 ////////////////////////////////////////////////////////////////////
1696 SG_LOG( SG_GENERAL, SG_INFO, endl);
1698 // Save the initial state for future
1700 globals->saveInitialState();
1706 void fgReInitSubsystems()
1708 // static const SGPropertyNode *longitude
1709 // = fgGetNode("/sim/presets/longitude-deg");
1710 // static const SGPropertyNode *latitude
1711 // = fgGetNode("/sim/presets/latitude-deg");
1712 static const SGPropertyNode *altitude
1713 = fgGetNode("/sim/presets/altitude-ft");
1714 static const SGPropertyNode *master_freeze
1715 = fgGetNode("/sim/freeze/master");
1717 SG_LOG( SG_GENERAL, SG_INFO,
1718 "fgReInitSubsystems(): /position/altitude = "
1719 << altitude->getDoubleValue() );
1721 bool freeze = master_freeze->getBoolValue();
1723 fgSetBool("/sim/freeze/master", true);
1725 fgSetBool("/sim/crashed", false);
1727 // Force reupdating the positions of the ai 3d models. They are used for
1728 // initializing ground level for the FDM.
1729 globals->get_subsystem("ai_model")->reinit();
1731 // Initialize the FDM
1734 // allocates structures so must happen before any of the flight
1735 // model or control parameters are set
1736 fgAircraftInit(); // In the future this might not be the case.
1738 // reload offsets from config defaults
1739 globals->get_viewmgr()->reinit();
1743 globals->get_controls()->reset_all();
1745 fgUpdateLocalTime();
1747 // re-init to proper time of day setting
1751 fgSetBool("/sim/freeze/master", false);
1753 fgSetBool("/sim/sceneryloaded",false);
1757 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1759 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1761 bool freeze = master_freeze->getBoolValue();
1763 master_freeze->setBoolValue(true);
1765 fgSetBool("/sim/signals/reinit", true);
1766 cur_fdm_state->unbind();
1768 // in case user has changed window size as
1769 // restoreInitialState() overwrites these
1770 int xsize = fgGetInt("/sim/startup/xsize");
1771 int ysize = fgGetInt("/sim/startup/ysize");
1773 // viewports also needs to be saved/restored as
1774 // restoreInitialState() overwrites these
1775 SGPropertyNode *guiNode = new SGPropertyNode;
1776 SGPropertyNode *cameraNode = new SGPropertyNode;
1777 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1778 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1779 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1781 globals->restoreInitialState();
1783 // update our position based on current presets
1786 // We don't know how to resize the window, so keep the last values
1787 // for xsize and ysize, and don't use the one set initially
1788 fgSetInt("/sim/startup/xsize", xsize);
1789 fgSetInt("/sim/startup/ysize", ysize);
1791 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1792 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1797 SGTime *t = globals->get_time_params();
1800 globals->set_time_params(t);
1802 fgReInitSubsystems();
1804 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1805 globals->get_renderer()->resize(xsize, ysize);
1806 fgSetBool("/sim/signals/reinit", false);
1809 master_freeze->setBoolValue(false);