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/timing/sg_time.hxx>
61 #include <simgear/timing/lowleveltime.h>
63 #include <Aircraft/aircraft.hxx>
64 #include <Aircraft/controls.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/apt_loader.hxx>
67 #include <Airports/runways.hxx>
68 #include <Airports/simple.hxx>
69 #include <Airports/dynamics.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATCDCL/ATCmgr.hxx>
73 #include <ATCDCL/AIMgr.hxx>
74 #include <Autopilot/route_mgr.hxx>
75 #include <Autopilot/xmlauto.hxx>
76 #include <Cockpit/cockpit.hxx>
77 #include <Cockpit/panel.hxx>
78 #include <Cockpit/panel_io.hxx>
80 #include <FDM/SP/ADA.hxx>
81 #include <FDM/SP/ACMS.hxx>
82 #include <FDM/SP/MagicCarpet.hxx>
83 #include <FDM/SP/Balloon.h>
85 #include <FDM/ExternalNet/ExternalNet.hxx>
86 #include <FDM/ExternalPipe/ExternalPipe.hxx>
87 #include <FDM/JSBSim/JSBSim.hxx>
88 #include <FDM/LaRCsim/LaRCsim.hxx>
89 #include <FDM/UFO.hxx>
90 #include <FDM/NullFDM.hxx>
91 #include <FDM/YASim/YASim.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Include/general.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Navaids/fix.hxx>
102 #include <Navaids/fixlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/fg_fx.hxx>
107 #include <Sound/beacon.hxx>
108 #include <Sound/morse.hxx>
109 #include <Sound/voice.hxx>
110 #include <Systems/system_mgr.hxx>
111 #include <Time/light.hxx>
112 #include <Time/sunsolver.hxx>
113 #include <Time/tmp.hxx>
114 #include <Traffic/TrafficMgr.hxx>
115 #include <MultiPlayer/multiplaymgr.hxx>
117 #include <Environment/environment_mgr.hxx>
118 #include <Environment/ridge_lift.hxx>
120 #include "fg_init.hxx"
122 #include "fg_commands.hxx"
123 #include "fg_props.hxx"
124 #include "options.hxx"
125 #include "globals.hxx"
126 #include "logger.hxx"
127 #include "renderer.hxx"
128 #include "viewmgr.hxx"
130 #include "ATCDCL/commlist.hxx"
133 # include <CoreFoundation/CoreFoundation.h>
140 extern const char *default_root;
144 // Scan the command line options for the specified option and return
146 static string fgScanForOption( const string& option, int argc, char **argv ) {
149 if (hostname == NULL)
152 gethostname(_hostname, 256);
153 hostname = strdup(_hostname);
154 free_hostname = true;
157 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
159 int len = option.length();
162 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
164 string arg = argv[i];
165 if ( arg.find( option ) == 0 ) {
166 return arg.substr( len );
176 // Scan the user config files for the specified option and return
178 static string fgScanForOption( const string& option, const string& path ) {
179 sg_gzifstream in( path );
180 if ( !in.is_open() ) {
184 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
186 int len = option.length();
189 while ( ! in.eof() ) {
191 getline( in, line, '\n' );
193 // catch extraneous (DOS) line ending character
194 if ( line[line.length() - 1] < 32 ) {
195 line = line.substr( 0, line.length()-1 );
198 if ( line.find( option ) == 0 ) {
199 return line.substr( len );
208 // Scan the user config files for the specified option and return
210 static string fgScanForOption( const string& option ) {
213 #if defined( unix ) || defined( __CYGWIN__ )
214 // Next check home directory for .fgfsrc.hostname file
216 if ( homedir != NULL ) {
217 SGPath config( homedir );
218 config.append( ".fgfsrc" );
219 config.concat( "." );
220 config.concat( hostname );
221 arg = fgScanForOption( option, config.str() );
226 // Next check home directory for .fgfsrc file
228 if ( homedir != NULL ) {
229 SGPath config( homedir );
230 config.append( ".fgfsrc" );
231 arg = fgScanForOption( option, config.str() );
236 // Check for $fg_root/system.fgfsrc
237 SGPath config( globals->get_fg_root() );
238 config.append( "system.fgfsrc" );
239 arg = fgScanForOption( option, config.str() );
246 // Read in configuration (files and command line options) but only set
248 bool fgInitFGRoot ( int argc, char **argv ) {
251 // First parse command line options looking for --fg-root=, this
252 // will override anything specified in a config file
253 root = fgScanForOption( "--fg-root=", argc, argv);
255 // Check in one of the user configuration files.
257 root = fgScanForOption( "--fg-root=" );
259 // Next check if fg-root is set as an env variable
260 if ( root.empty() ) {
261 char *envp = ::getenv( "FG_ROOT" );
262 if ( envp != NULL ) {
267 // Otherwise, default to a random compiled-in location if we can't
268 // find fg-root any other way.
269 if ( root.empty() ) {
270 #if defined( __CYGWIN__ )
271 root = "/FlightGear";
272 #elif defined( WIN32 )
273 root = "\\FlightGear";
274 #elif defined(__APPLE__)
276 The following code looks for the base package inside the application
277 bundle, in the standard Contents/Resources location.
279 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
281 // look for a 'data' subdir
282 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
284 // now convert down to a path, and the a c-string
285 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
286 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
288 CFRelease(resourcesUrl);
296 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
297 globals->set_fg_root(root);
303 // Read in configuration (files and command line options) but only set
305 bool fgInitFGAircraft ( int argc, char **argv ) {
308 // First parse command line options looking for --aircraft=, this
309 // will override anything specified in a config file
310 aircraft = fgScanForOption( "--aircraft=", argc, argv );
311 if ( aircraft.empty() ) {
312 // check synonym option
313 aircraft = fgScanForOption( "--vehicle=", argc, argv );
316 // Check in one of the user configuration files.
317 if ( aircraft.empty() ) {
318 aircraft = fgScanForOption( "--aircraft=" );
320 if ( aircraft.empty() ) {
321 aircraft = fgScanForOption( "--vehicle=" );
324 // if an aircraft was specified, set the property name
325 if ( !aircraft.empty() ) {
326 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
327 fgSetString("/sim/aircraft", aircraft.c_str() );
329 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
336 // Return the current base package version
337 string fgBasePackageVersion() {
338 SGPath base_path( globals->get_fg_root() );
339 base_path.append("version");
341 sg_gzifstream in( base_path.str() );
342 if ( !in.is_open() ) {
343 SGPath old_path( globals->get_fg_root() );
344 old_path.append( "Thanks" );
345 sg_gzifstream old( old_path.str() );
346 if ( !old.is_open() ) {
349 return "[old version]";
360 // Initialize the localization
361 SGPropertyNode *fgInitLocale(const char *language) {
362 SGPropertyNode *c_node = NULL, *d_node = NULL;
363 SGPropertyNode *intl = fgGetNode("/sim/intl");
365 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
367 // localization not defined
372 // Select the proper language from the list
374 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
375 for (unsigned int i = 0; i < locale.size(); i++) {
377 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
378 for (unsigned int j = 0; j < lang.size(); j++) {
380 if (!strcmp(lang[j]->getStringValue(), language)) {
389 d_node = intl->getChild("locale");
393 // Check for localized font
394 SGPropertyNode *font_n = c_node->getNode("font", true);
395 if ( !strcmp(font_n->getStringValue(), "") )
396 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
400 // Load the default strings
402 SGPath d_path( globals->get_fg_root() );
404 const char *d_path_str = d_node->getStringValue("strings");
406 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
410 d_path.append(d_path_str);
411 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
413 SGPropertyNode *strings = c_node->getNode("strings");
415 readProperties(d_path.str(), strings);
416 } catch (const sg_exception &) {
417 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
422 // Load the language specific strings
424 if (c_node != d_node) {
425 SGPath c_path( globals->get_fg_root() );
427 const char *c_path_str = c_node->getStringValue("strings");
429 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
433 c_path.append(c_path_str);
434 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
437 readProperties(c_path.str(), strings);
438 } catch (const sg_exception &) {
439 SG_LOG(SG_GENERAL, SG_ALERT,
440 "Unable to read the localized strings from " << c_path.str());
450 // Initialize the localization routines
451 bool fgDetectLanguage() {
452 const char *language = ::getenv("LANG");
454 if (language == NULL) {
455 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
459 SGPropertyNode *locale = fgInitLocale(language);
461 SG_LOG(SG_GENERAL, SG_ALERT,
462 "No internationalization settings specified in preferences.xml" );
467 globals->set_locale( locale );
472 // Attempt to locate and parse the various non-XML config files in order
473 // from least precidence to greatest precidence
475 do_options (int argc, char ** argv)
477 // Check for $fg_root/system.fgfsrc
478 SGPath config( globals->get_fg_root() );
479 config.append( "system.fgfsrc" );
480 fgParseOptions(config.str());
482 #if defined( unix ) || defined( __CYGWIN__ )
483 config.concat( "." );
484 config.concat( hostname );
485 fgParseOptions(config.str());
488 // Check for ~/.fgfsrc
489 if ( homedir != NULL ) {
490 config.set( homedir );
491 config.append( ".fgfsrc" );
492 fgParseOptions(config.str());
495 #if defined( unix ) || defined( __CYGWIN__ )
496 // Check for ~/.fgfsrc.hostname
497 config.concat( "." );
498 config.concat( hostname );
499 fgParseOptions(config.str());
502 // Parse remaining command line options
503 // These will override anything specified in a config file
504 fgParseArgs(argc, argv);
508 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
509 SGPropertyNode *cache, int depth = 0 )
511 const int MAXDEPTH = 1;
514 ulDir *dirp = ulOpenDir(path.str().c_str());
516 cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
521 while ((dire = ulReadDir(dirp)) != NULL) {
523 if (depth > MAXDEPTH)
526 if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
527 || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
531 next.append(dire->d_name);
533 result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
534 if ( ! result.empty() )
538 int len = strlen(dire->d_name);
539 if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
545 if (!cache->getChild("aircraft", i++, false))
548 SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
550 n = entry->getNode("file", true);
551 n->setStringValue(dire->d_name);
552 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
554 n = entry->getNode("path", true);
555 n->setStringValue(path.str().c_str());
556 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
558 if ( !strcmp(dire->d_name, aircraft.c_str()) ) {
570 // Read in configuration (file and command line)
571 bool fgInitConfig ( int argc, char **argv ) {
573 // First, set some sane default values
576 // Read global preferences from $FG_ROOT/preferences.xml
577 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
578 fgLoadProps("preferences.xml", globals->get_props());
579 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
581 // Detect the required language as early as possible
582 if ( !fgDetectLanguage() ) {
586 SGPropertyNode autosave;
587 #if defined( _MSC_VER ) || defined( __MINGW32__ )
588 char *envp = ::getenv( "APPDATA" );
590 SGPath config( envp );
591 config.append( "flightgear.org" );
593 if ( homedir != NULL ) {
594 SGPath config( homedir );
595 config.append( ".fgfs" );
597 const char *fg_home = getenv("FG_HOME");
601 SGPath home_export(config.str());
602 home_export.append("Export/dummy");
603 home_export.create_dir(0777);
605 // Set /sim/fg-home and don't allow malign code to override it until
606 // Nasal security is set up. Use FG_HOME if necessary.
607 SGPropertyNode *home = fgGetNode("/sim", true);
608 home->removeChild("fg-home", 0, false);
609 home = home->getChild("fg-home", 0, true);
610 home->setStringValue(config.c_str());
611 home->setAttribute(SGPropertyNode::WRITE, false);
613 config.append( "autosave.xml" );
614 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
616 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
618 SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
620 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
622 SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
625 // Scan user config files and command line for a specified aircraft.
626 fgInitFGAircraft(argc, argv);
628 string aircraft = fgGetString( "/sim/aircraft", "" );
629 if ( aircraft.size() > 0 ) {
630 SGPath aircraft_search( globals->get_fg_root() );
631 aircraft_search.append( "Aircraft" );
633 string aircraft_set = aircraft + "-set.xml";
636 // check if the *-set.xml file is already in the cache
637 if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
638 vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
639 for (unsigned int i = 0; i < cache.size(); i++) {
640 const char *name = cache[i]->getStringValue("file", "");
641 if (aircraft_set == name) {
642 const char *path = cache[i]->getStringValue("path", "");
652 if (result.empty()) {
653 // prepare cache for rescan
654 SGPropertyNode *n = cache_root->getNode("fg-root", true);
655 n->setStringValue(globals->get_fg_root().c_str());
656 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
657 cache_root->removeChildren("aircraft");
659 result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
662 if ( !result.empty() ) {
663 fgSetString( "/sim/aircraft-dir", result.c_str() );
664 SGPath full_name( result );
665 full_name.append( aircraft_set );
667 SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
668 << " from " << full_name.str());
670 readProperties( full_name.str(), globals->get_props() );
671 } catch ( const sg_exception &e ) {
672 string message = "Error reading default aircraft: ";
673 message += e.getFormattedMessage();
674 SG_LOG(SG_INPUT, SG_ALERT, message);
678 SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
684 SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
687 copyProperties(&autosave, globals->get_props());
689 // parse options after loading aircraft to ensure any user
690 // overrides of defaults are honored.
691 do_options(argc, argv);
696 // Set current tower position lon/lat given an airport id
697 static bool fgSetTowerPosFromAirportID( const string& id) {
698 const FGAirport *a = fgFindAirportID( id);
700 SGGeod tower = a->getTowerLocation();
701 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
702 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
703 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
711 struct FGTowerLocationListener : SGPropertyChangeListener {
712 void valueChanged(SGPropertyNode* node) {
713 const string id(node->getStringValue());
714 fgSetTowerPosFromAirportID(id);
718 void fgInitTowerLocationListener() {
719 fgGetNode("/sim/tower/airport-id", true)
720 ->addChangeListener( new FGTowerLocationListener(), true );
723 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
725 SGGeod startPos(aStartPos);
726 if (aTargetHeading == HUGE_VAL) {
727 aTargetHeading = aHeading;
730 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
731 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
732 offsetDistance *= SG_NM_TO_METER;
733 double offsetAzimuth = aHeading;
734 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
735 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
736 aHeading = aTargetHeading;
741 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
746 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
747 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
748 fgSetDouble("/sim/presets/heading-deg", aHeading );
750 // other code depends on the actual values being set ...
751 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
752 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
753 fgSetDouble("/orientation/heading-deg", aHeading );
756 // Set current_options lon/lat given an airport id and heading (degrees)
757 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
761 // set initial position from runway and heading
762 SG_LOG( SG_GENERAL, SG_INFO,
763 "Attempting to set starting position from airport code "
764 << id << " heading " << tgt_hdg );
766 const FGAirport* apt = fgFindAirportID(id);
767 if (!apt) return false;
768 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
769 fgSetString("/sim/atc/runway", r->ident().c_str());
771 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
772 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
776 // Set current_options lon/lat given an airport id and parkig position name
777 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
781 // can't see an easy way around this const_cast at the moment
782 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
784 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
787 FGAirportDynamics* dcs = apt->getDynamics();
789 SG_LOG( SG_GENERAL, SG_ALERT,
790 "Failed to find parking position " << parkpos <<
791 " at airport " << id );
795 int park_index = dcs->getNrOfParkings() - 1;
796 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
797 if (park_index < 0) {
798 SG_LOG( SG_GENERAL, SG_ALERT,
799 "Failed to find parking position " << parkpos <<
800 " at airport " << id );
803 FGParking* parking = dcs->getParking(park_index);
805 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
806 parking->getHeading());
811 // Set current_options lon/lat given an airport id and runway number
812 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
816 // set initial position from airport and runway number
817 SG_LOG( SG_GENERAL, SG_INFO,
818 "Attempting to set starting position for "
819 << id << ":" << rwy );
821 const FGAirport* apt = fgFindAirportID(id);
823 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
827 if (!apt->hasRunwayWithIdent(rwy)) {
828 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
829 "Failed to find runway " << rwy <<
830 " at airport " << id << ". Using default runway." );
834 FGRunway* r(apt->getRunwayByIdent(rwy));
835 fgSetString("/sim/atc/runway", r->ident().c_str());
836 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
837 fgApplyStartOffset(startPos, r->headingDeg());
842 static void fgSetDistOrAltFromGlideSlope() {
843 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
844 string apt_id = fgGetString("/sim/presets/airport-id");
845 double gs = fgGetDouble("/sim/presets/glideslope-deg")
846 * SG_DEGREES_TO_RADIANS ;
847 double od = fgGetDouble("/sim/presets/offset-distance-nm");
848 double alt = fgGetDouble("/sim/presets/altitude-ft");
850 double apt_elev = 0.0;
851 if ( ! apt_id.empty() ) {
852 apt_elev = fgGetAirportElev( apt_id );
853 if ( apt_elev < -9990.0 ) {
860 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
861 // set altitude from glideslope and offset-distance
862 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
863 alt = fabs(od*tan(gs)) + apt_elev;
864 fgSetDouble("/sim/presets/altitude-ft", alt);
865 fgSetBool("/sim/presets/onground", false);
866 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
868 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
869 // set offset-distance from glideslope and altitude
870 od = (alt - apt_elev) / tan(gs);
871 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
872 fgSetDouble("/sim/presets/offset-distance-nm", od);
873 fgSetBool("/sim/presets/onground", false);
874 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
876 } else if( fabs(gs) > 0.01 ) {
877 SG_LOG( SG_GENERAL, SG_ALERT,
878 "Glideslope given but not altitude or offset-distance." );
879 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
880 fgSetDouble("/sim/presets/glideslope-deg", 0);
881 fgSetBool("/sim/presets/onground", true);
886 // Set current_options lon/lat given an airport id and heading (degrees)
887 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
889 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
892 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
893 << id << ":" << freq );
897 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
901 // Set current_options lon/lat given an aircraft carrier id
902 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
904 // set initial position from runway and heading
908 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
909 double lon = geodPos.getLongitudeDeg();
910 double lat = geodPos.getLatitudeDeg();
911 double alt = geodPos.getElevationFt();
913 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
914 << carrier << " at lat = " << lat << ", lon = " << lon
915 << ", alt = " << alt << ", heading = " << heading);
917 fgSetDouble("/sim/presets/longitude-deg", lon);
918 fgSetDouble("/sim/presets/latitude-deg", lat);
919 fgSetDouble("/sim/presets/altitude-ft", alt);
920 fgSetDouble("/sim/presets/heading-deg", heading);
921 fgSetDouble("/position/longitude-deg", lon);
922 fgSetDouble("/position/latitude-deg", lat);
923 fgSetDouble("/position/altitude-ft", alt);
924 fgSetDouble("/orientation/heading-deg", heading);
926 fgSetString("/sim/presets/speed-set", "UVW");
927 fgSetDouble("/velocities/uBody-fps", uvw(0));
928 fgSetDouble("/velocities/vBody-fps", uvw(1));
929 fgSetDouble("/velocities/wBody-fps", uvw(2));
930 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
931 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
932 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
934 fgSetBool("/sim/presets/onground", true);
938 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
944 // Set current_options lon/lat given an airport id and heading (degrees)
945 static bool fgSetPosFromFix( const string& id )
947 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
948 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
950 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
954 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
959 * Initialize vor/ndb/ils/fix list management and query systems (as
960 * well as simple airport db list)
965 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
967 SGPath aptdb( globals->get_fg_root() );
968 aptdb.append( "Airports/apt.dat" );
970 SGPath p_metar( globals->get_fg_root() );
971 p_metar.append( "Airports/metar.dat" );
973 // Initialise the frequency search map BEFORE reading
974 // the airport database:
975 current_commlist = new FGCommList;
976 current_commlist->init( globals->get_fg_root() );
977 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
979 FGNavList *navlist = new FGNavList;
980 FGNavList *loclist = new FGNavList;
981 FGNavList *gslist = new FGNavList;
982 FGNavList *dmelist = new FGNavList;
983 FGNavList *tacanlist = new FGNavList;
984 FGNavList *carrierlist = new FGNavList;
985 FGTACANList *channellist = new FGTACANList;
987 globals->set_navlist( navlist );
988 globals->set_loclist( loclist );
989 globals->set_gslist( gslist );
990 globals->set_dmelist( dmelist );
991 globals->set_tacanlist( tacanlist );
992 globals->set_carrierlist( carrierlist );
993 globals->set_channellist( channellist );
995 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
996 SG_LOG( SG_GENERAL, SG_ALERT,
997 "Problems loading one or more navigational database" );
1000 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1001 SGPath p_fix( globals->get_fg_root() );
1002 p_fix.append( "Navaids/fix.dat" );
1004 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1006 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1007 SGPath p_awy( globals->get_fg_root() );
1008 p_awy.append( "Navaids/awy.dat" );
1009 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1010 //cerr << "Loading Airways" << endl;
1011 awyNet->load (p_awy );
1013 //cerr << "initializing airways" << endl;
1014 globals->set_airwaynet( awyNet );
1020 // Set the initial position based on presets (or defaults)
1021 bool fgInitPosition() {
1022 // cout << "fgInitPosition()" << endl;
1023 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1024 * SG_DEGREES_TO_RADIANS ;
1025 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1026 double alt = fgGetDouble("/sim/presets/altitude-ft");
1028 bool set_pos = false;
1030 // If glideslope is specified, then calculate offset-distance or
1031 // altitude relative to glide slope if either of those was not
1033 if ( fabs( gs ) > 0.01 ) {
1034 fgSetDistOrAltFromGlideSlope();
1038 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1039 // If not, check for an airport-id and use that.
1040 // If not, default to the middle of the KSFO field.
1041 // The default values for lon/lat are deliberately out of range
1042 // so that the airport-id can take effect; valid lon/lat will
1043 // override airport-id, however.
1044 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1045 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1046 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1047 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1052 string apt = fgGetString("/sim/presets/airport-id");
1053 string rwy_no = fgGetString("/sim/presets/runway");
1054 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1055 string vor = fgGetString("/sim/presets/vor-id");
1056 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1057 string ndb = fgGetString("/sim/presets/ndb-id");
1058 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1059 string carrier = fgGetString("/sim/presets/carrier");
1060 string parkpos = fgGetString("/sim/presets/parkpos");
1061 string fix = fgGetString("/sim/presets/fix");
1062 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1063 double hdg = hdg_preset->getDoubleValue();
1065 // save some start parameters, so that we can later say what the
1066 // user really requested. TODO generalize that and move it to options.cxx
1067 static bool start_options_saved = false;
1068 if (!start_options_saved) {
1069 start_options_saved = true;
1070 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1072 opt->setDoubleValue("latitude-deg", lat_deg);
1073 opt->setDoubleValue("longitude-deg", lon_deg);
1074 opt->setDoubleValue("heading-deg", hdg);
1075 opt->setStringValue("airport", apt.c_str());
1076 opt->setStringValue("runway", rwy_no.c_str());
1080 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1082 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1083 // An airport + parking position is requested
1084 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1085 // set tower position
1086 fgSetString("/sim/tower/airport-id", apt.c_str());
1091 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1092 // An airport + runway is requested
1093 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1094 // set tower position (a little off the heading for single
1096 fgSetString("/sim/tower/airport-id", apt.c_str());
1101 if ( !set_pos && !apt.empty() ) {
1102 // An airport is requested (find runway closest to hdg)
1103 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1104 // set tower position (a little off the heading for single
1106 fgSetString("/sim/tower/airport-id", apt.c_str());
1111 if (hdg_preset->getDoubleValue() > 9990.0)
1112 hdg_preset->setDoubleValue(hdg);
1114 if ( !set_pos && !vor.empty() ) {
1115 // a VOR is requested
1116 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1121 if ( !set_pos && !ndb.empty() ) {
1122 // an NDB is requested
1123 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1128 if ( !set_pos && !carrier.empty() ) {
1129 // an aircraft carrier is requested
1130 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1135 if ( !set_pos && !fix.empty() ) {
1136 // a Fix is requested
1137 if ( fgSetPosFromFix( fix ) ) {
1143 // No lon/lat specified, no airport specified, default to
1144 // middle of KSFO field.
1145 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1146 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1149 fgSetDouble( "/position/longitude-deg",
1150 fgGetDouble("/sim/presets/longitude-deg") );
1151 fgSetDouble( "/position/latitude-deg",
1152 fgGetDouble("/sim/presets/latitude-deg") );
1153 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1155 // determine if this should be an on-ground or in-air start
1156 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1157 fgSetBool("/sim/presets/onground", false);
1159 fgSetBool("/sim/presets/onground", true);
1166 // General house keeping initializations
1167 bool fgInitGeneral() {
1170 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1171 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1173 root = globals->get_fg_root();
1174 if ( ! root.length() ) {
1175 // No root path set? Then bail ...
1176 SG_LOG( SG_GENERAL, SG_ALERT,
1177 "Cannot continue without a path to the base package "
1178 << "being defined." );
1181 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1183 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1185 char buf[512], *cwd = getcwd(buf, 511);
1187 SGPropertyNode *curr = fgGetNode("/sim", true);
1188 curr->removeChild("fg-current", 0, false);
1189 curr = curr->getChild("fg-current", 0, true);
1190 curr->setStringValue(cwd ? cwd : "");
1191 curr->setAttribute(SGPropertyNode::WRITE, false);
1193 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1194 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1199 // Initialize the flight model subsystem. This just creates the
1200 // object. The actual fdm initialization is delayed until we get a
1201 // proper scenery elevation hit. This is checked for in main.cxx
1205 if ( cur_fdm_state ) {
1206 delete cur_fdm_state;
1210 double dt = 1.0 / fgGetInt("/sim/model-hz");
1211 string model = fgGetString("/sim/flight-model");
1213 if ( model == "larcsim" ) {
1214 cur_fdm_state = new FGLaRCsim( dt );
1215 } else if ( model == "jsb" ) {
1216 cur_fdm_state = new FGJSBsim( dt );
1218 } else if ( model == "ada" ) {
1219 cur_fdm_state = new FGADA( dt );
1220 } else if ( model == "acms" ) {
1221 cur_fdm_state = new FGACMS( dt );
1222 } else if ( model == "balloon" ) {
1223 cur_fdm_state = new FGBalloonSim( dt );
1224 } else if ( model == "magic" ) {
1225 cur_fdm_state = new FGMagicCarpet( dt );
1227 } else if ( model == "ufo" ) {
1228 cur_fdm_state = new FGUFO( dt );
1229 } else if ( model == "external" ) {
1230 // external is a synonym for "--fdm=null" and is
1231 // maintained here for backwards compatibility
1232 cur_fdm_state = new FGNullFDM( dt );
1233 } else if ( model.find("network") == 0 ) {
1234 string host = "localhost";
1238 string net_options = model.substr(8);
1239 string::size_type begin, end;
1242 end = net_options.find( ",", begin );
1243 if ( end != string::npos ) {
1244 host = net_options.substr(begin, end - begin);
1248 end = net_options.find( ",", begin );
1249 if ( end != string::npos ) {
1250 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1254 end = net_options.find( ",", begin );
1255 if ( end != string::npos ) {
1256 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1260 end = net_options.find( ",", begin );
1261 if ( end != string::npos ) {
1262 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1265 cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1266 } else if ( model.find("pipe") == 0 ) {
1267 // /* old */ string pipe_path = model.substr(5);
1268 // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1269 string pipe_path = "";
1270 string pipe_protocol = "";
1271 string pipe_options = model.substr(5);
1272 string::size_type begin, end;
1275 end = pipe_options.find( ",", begin );
1276 if ( end != string::npos ) {
1277 pipe_path = pipe_options.substr(begin, end - begin);
1280 // protocol (last option)
1281 pipe_protocol = pipe_options.substr(begin);
1282 cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1283 } else if ( model == "null" ) {
1284 cur_fdm_state = new FGNullFDM( dt );
1285 } else if ( model == "yasim" ) {
1286 cur_fdm_state = new YASim( dt );
1288 throw sg_exception(string("Unrecognized flight model '") + model
1289 + "', cannot init flight dynamics model.");
1293 // Initialize view parameters
1295 // force update of model so that viewer can get some data...
1296 globals->get_aircraft_model()->update(0);
1297 // run update for current view so that data is current...
1298 globals->get_viewmgr()->update(0);
1302 SGTime *fgInitTime() {
1304 static const SGPropertyNode *longitude
1305 = fgGetNode("/position/longitude-deg");
1306 static const SGPropertyNode *latitude
1307 = fgGetNode("/position/latitude-deg");
1308 static const SGPropertyNode *cur_time_override
1309 = fgGetNode("/sim/time/cur-time-override", true);
1311 SGPath zone( globals->get_fg_root() );
1312 zone.append( "Timezone" );
1313 SGTime *t = new SGTime( longitude->getDoubleValue()
1314 * SGD_DEGREES_TO_RADIANS,
1315 latitude->getDoubleValue()
1316 * SGD_DEGREES_TO_RADIANS,
1318 cur_time_override->getLongValue() );
1320 globals->set_warp_delta( 0 );
1322 t->update( 0.0, 0.0,
1323 cur_time_override->getLongValue(),
1324 globals->get_warp() );
1330 // set up a time offset (aka warp) if one is specified
1331 void fgInitTimeOffset() {
1332 static const SGPropertyNode *longitude
1333 = fgGetNode("/position/longitude-deg");
1334 static const SGPropertyNode *latitude
1335 = fgGetNode("/position/latitude-deg");
1336 static const SGPropertyNode *cur_time_override
1337 = fgGetNode("/sim/time/cur-time-override", true);
1339 // Handle potential user specified time offsets
1340 int orig_warp = globals->get_warp();
1341 SGTime *t = globals->get_time_params();
1342 time_t cur_time = t->get_cur_time();
1343 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1344 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1345 time_t aircraftLocalTime =
1346 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1348 // Okay, we now have several possible scenarios
1349 int offset = fgGetInt("/sim/startup/time-offset");
1350 string offset_type = fgGetString("/sim/startup/time-offset-type");
1353 if ( offset_type == "real" ) {
1355 } else if ( offset_type == "dawn" ) {
1356 warp = fgTimeSecondsUntilSunAngle( cur_time,
1357 longitude->getDoubleValue()
1358 * SGD_DEGREES_TO_RADIANS,
1359 latitude->getDoubleValue()
1360 * SGD_DEGREES_TO_RADIANS,
1362 } else if ( offset_type == "morning" ) {
1363 warp = fgTimeSecondsUntilSunAngle( cur_time,
1364 longitude->getDoubleValue()
1365 * SGD_DEGREES_TO_RADIANS,
1366 latitude->getDoubleValue()
1367 * SGD_DEGREES_TO_RADIANS,
1369 } else if ( offset_type == "noon" ) {
1370 warp = fgTimeSecondsUntilSunAngle( cur_time,
1371 longitude->getDoubleValue()
1372 * SGD_DEGREES_TO_RADIANS,
1373 latitude->getDoubleValue()
1374 * SGD_DEGREES_TO_RADIANS,
1376 } else if ( offset_type == "afternoon" ) {
1377 warp = fgTimeSecondsUntilSunAngle( cur_time,
1378 longitude->getDoubleValue()
1379 * SGD_DEGREES_TO_RADIANS,
1380 latitude->getDoubleValue()
1381 * SGD_DEGREES_TO_RADIANS,
1383 } else if ( offset_type == "dusk" ) {
1384 warp = fgTimeSecondsUntilSunAngle( cur_time,
1385 longitude->getDoubleValue()
1386 * SGD_DEGREES_TO_RADIANS,
1387 latitude->getDoubleValue()
1388 * SGD_DEGREES_TO_RADIANS,
1390 } else if ( offset_type == "evening" ) {
1391 warp = fgTimeSecondsUntilSunAngle( cur_time,
1392 longitude->getDoubleValue()
1393 * SGD_DEGREES_TO_RADIANS,
1394 latitude->getDoubleValue()
1395 * SGD_DEGREES_TO_RADIANS,
1397 } else if ( offset_type == "midnight" ) {
1398 warp = fgTimeSecondsUntilSunAngle( cur_time,
1399 longitude->getDoubleValue()
1400 * SGD_DEGREES_TO_RADIANS,
1401 latitude->getDoubleValue()
1402 * SGD_DEGREES_TO_RADIANS,
1404 } else if ( offset_type == "system-offset" ) {
1407 } else if ( offset_type == "gmt-offset" ) {
1408 warp = offset - (currGMT - systemLocalTime);
1410 } else if ( offset_type == "latitude-offset" ) {
1411 warp = offset - (aircraftLocalTime - systemLocalTime);
1413 } else if ( offset_type == "system" ) {
1414 warp = offset - (systemLocalTime - currGMT) - cur_time;
1415 } else if ( offset_type == "gmt" ) {
1416 warp = offset - cur_time;
1417 } else if ( offset_type == "latitude" ) {
1418 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1420 SG_LOG( SG_GENERAL, SG_ALERT,
1421 "FG_TIME::Unsupported offset type " << offset_type );
1424 globals->set_warp( orig_warp + warp );
1425 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1426 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1427 cur_time_override->getLongValue(),
1428 globals->get_warp() );
1430 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1431 << globals->get_warp() );
1435 // This is the top level init routine which calls all the other
1436 // initialization routines. If you are adding a subsystem to flight
1437 // gear, its initialization call should located in this routine.
1438 // Returns non-zero if a problem encountered.
1439 bool fgInitSubsystems() {
1440 // static const SGPropertyNode *longitude
1441 // = fgGetNode("/sim/presets/longitude-deg");
1442 // static const SGPropertyNode *latitude
1443 // = fgGetNode("/sim/presets/latitude-deg");
1444 // static const SGPropertyNode *altitude
1445 // = fgGetNode("/sim/presets/altitude-ft");
1446 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1447 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1449 ////////////////////////////////////////////////////////////////////
1450 // Initialize the event manager subsystem.
1451 ////////////////////////////////////////////////////////////////////
1453 globals->get_event_mgr()->init();
1454 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1456 ////////////////////////////////////////////////////////////////////
1457 // Initialize the property interpolator subsystem. Put into the INIT
1458 // group because the "nasal" subsystem may need it at GENERAL take-down.
1459 ////////////////////////////////////////////////////////////////////
1460 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1463 ////////////////////////////////////////////////////////////////////
1464 // Add the FlightGear property utilities.
1465 ////////////////////////////////////////////////////////////////////
1466 globals->add_subsystem("properties", new FGProperties);
1468 ////////////////////////////////////////////////////////////////////
1469 // Initialize the material property subsystem.
1470 ////////////////////////////////////////////////////////////////////
1472 SGPath mpath( globals->get_fg_root() );
1473 mpath.append( "materials.xml" );
1474 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1475 globals->get_props()) ) {
1476 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1481 ////////////////////////////////////////////////////////////////////
1482 // Initialize the scenery management subsystem.
1483 ////////////////////////////////////////////////////////////////////
1485 if ( globals->get_tile_mgr()->init() ) {
1486 // Load the local scenery data
1487 double visibility_meters = fgGetDouble("/environment/visibility-m");
1489 globals->get_tile_mgr()->update( visibility_meters );
1491 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1495 globals->get_scenery()->get_scene_graph()
1496 ->addChild(simgear::Particles::getCommonRoot());
1497 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1499 ////////////////////////////////////////////////////////////////////
1500 // Initialize the flight model subsystem.
1501 ////////////////////////////////////////////////////////////////////
1505 // allocates structures so must happen before any of the flight
1506 // model or control parameters are set
1507 fgAircraftInit(); // In the future this might not be the case.
1510 ////////////////////////////////////////////////////////////////////
1511 // Initialize the weather subsystem.
1512 ////////////////////////////////////////////////////////////////////
1514 // Initialize the weather modeling subsystem
1515 globals->add_subsystem("environment", new FGEnvironmentMgr);
1517 ////////////////////////////////////////////////////////////////////
1518 // Initialize the ridge lift simulation.
1519 ////////////////////////////////////////////////////////////////////
1521 // Initialize the ridgelift subsystem
1522 globals->add_subsystem("ridgelift", new FGRidgeLift);
1524 ////////////////////////////////////////////////////////////////////
1525 // Initialize the aircraft systems and instrumentation (before the
1527 ////////////////////////////////////////////////////////////////////
1529 globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1530 globals->add_subsystem("systems", new FGSystemMgr);
1532 ////////////////////////////////////////////////////////////////////
1533 // Initialize the XML Autopilot subsystem.
1534 ////////////////////////////////////////////////////////////////////
1536 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1537 globals->add_subsystem( "route-manager", new FGRouteMgr );
1539 ////////////////////////////////////////////////////////////////////
1540 // Initialize the view manager subsystem.
1541 ////////////////////////////////////////////////////////////////////
1545 ////////////////////////////////////////////////////////////////////
1546 // Initialize the Input-Output subsystem
1547 ////////////////////////////////////////////////////////////////////
1548 globals->add_subsystem( "io", new FGIO );
1550 ////////////////////////////////////////////////////////////////////
1551 // Create and register the logger.
1552 ////////////////////////////////////////////////////////////////////
1554 globals->add_subsystem("logger", new FGLogger);
1556 ////////////////////////////////////////////////////////////////////
1557 // Create and register the XML GUI.
1558 ////////////////////////////////////////////////////////////////////
1560 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1563 ////////////////////////////////////////////////////////////////////
1564 // Initialize the local time subsystem.
1565 ////////////////////////////////////////////////////////////////////
1567 // update the current timezone each 30 minutes
1568 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1569 &fgUpdateLocalTime, 30*60 );
1570 fgInitTimeOffset(); // the environment subsystem needs this
1573 ////////////////////////////////////////////////////////////////////
1574 // Initialize the lighting subsystem.
1575 ////////////////////////////////////////////////////////////////////
1577 globals->add_subsystem("lighting", new FGLight);
1579 //////////////////////////////////////////////////////////////////////
1580 // Initialize the 2D cloud subsystem.
1581 ////////////////////////////////////////////////////////////////////
1582 fgGetBool("/sim/rendering/bump-mapping", false);
1584 #ifdef ENABLE_AUDIO_SUPPORT
1585 ////////////////////////////////////////////////////////////////////
1586 // Initialize the sound-effects subsystem.
1587 ////////////////////////////////////////////////////////////////////
1588 globals->add_subsystem("voice", new FGVoiceMgr);
1591 ////////////////////////////////////////////////////////////////////
1592 // Initialise the ATC Manager
1593 ////////////////////////////////////////////////////////////////////
1595 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1596 globals->set_ATC_mgr(new FGATCMgr);
1597 globals->get_ATC_mgr()->init();
1599 ////////////////////////////////////////////////////////////////////
1600 // Initialise the AI Manager
1601 ////////////////////////////////////////////////////////////////////
1603 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1604 globals->set_AI_mgr(new FGAIMgr);
1605 globals->get_AI_mgr()->init();
1607 ////////////////////////////////////////////////////////////////////
1608 // Initialise the AI Model Manager
1609 ////////////////////////////////////////////////////////////////////
1610 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1611 globals->add_subsystem("ai_model", new FGAIManager);
1612 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1615 // It's probably a good idea to initialize the top level traffic manager
1616 // After the AI and ATC systems have been initialized properly.
1617 // AI Traffic manager
1618 globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1621 ////////////////////////////////////////////////////////////////////
1622 // Initialize the cockpit subsystem
1623 ////////////////////////////////////////////////////////////////////
1624 if( fgCockpitInit( ¤t_aircraft )) {
1625 // Cockpit initialized ok.
1627 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1632 ////////////////////////////////////////////////////////////////////
1633 // Add a new 2D panel.
1634 ////////////////////////////////////////////////////////////////////
1636 string panel_path = fgGetString("/sim/panel/path",
1637 "Panels/Default/default.xml");
1639 globals->set_current_panel( fgReadPanel(panel_path) );
1640 if (globals->get_current_panel() == 0) {
1641 SG_LOG( SG_INPUT, SG_ALERT,
1642 "Error reading new panel from " << panel_path );
1644 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1645 globals->get_current_panel()->init();
1646 globals->get_current_panel()->bind();
1650 ////////////////////////////////////////////////////////////////////
1651 // Initialize the controls subsystem.
1652 ////////////////////////////////////////////////////////////////////
1654 globals->get_controls()->init();
1655 globals->get_controls()->bind();
1658 ////////////////////////////////////////////////////////////////////
1659 // Initialize the input subsystem.
1660 ////////////////////////////////////////////////////////////////////
1662 globals->add_subsystem("input", new FGInput);
1665 ////////////////////////////////////////////////////////////////////
1666 // Initialize the replay subsystem
1667 ////////////////////////////////////////////////////////////////////
1668 globals->add_subsystem("replay", new FGReplay);
1671 ////////////////////////////////////////////////////////////////////
1672 // Add Sound Manager.
1673 // Put the sound manager last so it can use the CPU while the GPU
1674 // is processing the scenery (doubled the frame-rate for me) -EMH-
1675 ////////////////////////////////////////////////////////////////////
1676 #ifdef ENABLE_AUDIO_SUPPORT
1677 init_volume = fgGetFloat("/sim/sound/volume");
1678 fgSetFloat("/sim/sound/volume", 0.0f);
1680 globals->add_subsystem("soundmgr", new SGSoundMgr);
1683 ////////////////////////////////////////////////////////////////////
1684 // Bind and initialize subsystems.
1685 ////////////////////////////////////////////////////////////////////
1687 globals->get_subsystem_mgr()->bind();
1688 globals->get_subsystem_mgr()->init();
1690 ////////////////////////////////////////////////////////////////////
1691 // Initialize multiplayer subsystem
1692 ////////////////////////////////////////////////////////////////////
1694 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1695 globals->get_multiplayer_mgr()->init();
1697 ////////////////////////////////////////////////////////////////////////
1698 // Initialize the Nasal interpreter.
1699 // Do this last, so that the loaded scripts see initialized state
1700 ////////////////////////////////////////////////////////////////////////
1701 FGNasalSys* nasal = new FGNasalSys();
1702 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1705 // initialize methods that depend on other subsystems.
1706 globals->get_subsystem_mgr()->postinit();
1708 ////////////////////////////////////////////////////////////////////////
1709 // End of subsystem initialization.
1710 ////////////////////////////////////////////////////////////////////
1712 SG_LOG( SG_GENERAL, SG_INFO, endl);
1714 // Save the initial state for future
1716 globals->saveInitialState();
1722 void fgReInitSubsystems()
1724 // static const SGPropertyNode *longitude
1725 // = fgGetNode("/sim/presets/longitude-deg");
1726 // static const SGPropertyNode *latitude
1727 // = fgGetNode("/sim/presets/latitude-deg");
1728 static const SGPropertyNode *altitude
1729 = fgGetNode("/sim/presets/altitude-ft");
1730 static const SGPropertyNode *master_freeze
1731 = fgGetNode("/sim/freeze/master");
1733 SG_LOG( SG_GENERAL, SG_INFO,
1734 "fgReInitSubsystems(): /position/altitude = "
1735 << altitude->getDoubleValue() );
1737 bool freeze = master_freeze->getBoolValue();
1739 fgSetBool("/sim/freeze/master", true);
1741 fgSetBool("/sim/crashed", false);
1743 // Force reupdating the positions of the ai 3d models. They are used for
1744 // initializing ground level for the FDM.
1745 globals->get_subsystem("ai_model")->reinit();
1747 // Initialize the FDM
1750 // allocates structures so must happen before any of the flight
1751 // model or control parameters are set
1752 fgAircraftInit(); // In the future this might not be the case.
1754 // reload offsets from config defaults
1755 globals->get_viewmgr()->reinit();
1759 globals->get_controls()->reset_all();
1761 fgUpdateLocalTime();
1763 // re-init to proper time of day setting
1767 fgSetBool("/sim/freeze/master", false);
1769 fgSetBool("/sim/sceneryloaded",false);
1773 void reInit(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1775 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1777 bool freeze = master_freeze->getBoolValue();
1779 master_freeze->setBoolValue(true);
1781 fgSetBool("/sim/signals/reinit", true);
1782 cur_fdm_state->unbind();
1784 // in case user has changed window size as
1785 // restoreInitialState() overwrites these
1786 int xsize = fgGetInt("/sim/startup/xsize");
1787 int ysize = fgGetInt("/sim/startup/ysize");
1789 // viewports also needs to be saved/restored as
1790 // restoreInitialState() overwrites these
1791 SGPropertyNode *guiNode = new SGPropertyNode;
1792 SGPropertyNode *cameraNode = new SGPropertyNode;
1793 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1794 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1795 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1797 globals->restoreInitialState();
1799 // update our position based on current presets
1802 // We don't know how to resize the window, so keep the last values
1803 // for xsize and ysize, and don't use the one set initially
1804 fgSetInt("/sim/startup/xsize", xsize);
1805 fgSetInt("/sim/startup/ysize", ysize);
1807 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1808 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1813 SGTime *t = globals->get_time_params();
1816 globals->set_time_params(t);
1818 fgReInitSubsystems();
1820 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1821 globals->get_renderer()->resize(xsize, ysize);
1822 fgSetBool("/sim/signals/reinit", false);
1825 master_freeze->setBoolValue(false);