1 // fg_init.cxx -- Flight Gear top level initialization routines
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <string.h> // strcmp()
32 #if defined( unix ) || defined( __CYGWIN__ )
33 # include <unistd.h> // for gethostname()
36 # include <direct.h> // for getcwd()
37 # define getcwd _getcwd
38 # include <io.h> // isatty()
39 # define isatty _isatty
40 # include "winsock2.h" // for gethostname()
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
46 # define _G_NO_EXTERN_TEMPLATES
49 #include <simgear/compiler.h>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/scene/model/particles.hxx>
64 #include <simgear/sound/soundmgr_openal.hxx>
65 #include <simgear/timing/sg_time.hxx>
66 #include <simgear/timing/lowleveltime.h>
68 #include <Aircraft/controls.hxx>
69 #include <Aircraft/replay.hxx>
70 #include <Airports/apt_loader.hxx>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <Airports/dynamics.hxx>
75 #include <AIModel/AIManager.hxx>
78 # include <ATCDCL/ATCmgr.hxx>
79 # include <ATCDCL/AIMgr.hxx>
80 # include "ATCDCL/commlist.hxx"
82 # include "ATC/atcutils.hxx"
85 #include <Autopilot/route_mgr.hxx>
86 #include <Autopilot/autopilotgroup.hxx>
88 #include <Cockpit/cockpit.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Cockpit/panel_io.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Include/general.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <AIModel/submodel.hxx>
98 #include <AIModel/AIManager.hxx>
99 #include <Navaids/navdb.hxx>
100 #include <Navaids/navlist.hxx>
101 #include <Navaids/fix.hxx>
102 #include <Navaids/fixlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.hxx>
106 #include <Sound/voice.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/sunsolver.hxx>
110 #include <Time/tmp.hxx>
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <FDM/fdm_shell.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Environment/ridge_lift.hxx>
118 #include "fg_init.hxx"
120 #include "fg_commands.hxx"
121 #include "fg_props.hxx"
122 #include "options.hxx"
123 #include "globals.hxx"
124 #include "logger.hxx"
125 #include "renderer.hxx"
126 #include "viewmgr.hxx"
131 # include <CoreFoundation/CoreFoundation.h>
135 using namespace boost::algorithm;
137 extern const char *default_root;
140 // Scan the command line options for the specified option and return
142 static string fgScanForOption( const string& option, int argc, char **argv ) {
145 if (hostname == NULL)
148 gethostname(_hostname, 256);
149 hostname = strdup(_hostname);
150 free_hostname = true;
153 SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
155 int len = option.length();
158 SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
160 string arg = argv[i];
161 if ( arg.find( option ) == 0 ) {
162 return arg.substr( len );
172 // Scan the user config files for the specified option and return
174 static string fgScanForOption( const string& option, const string& path ) {
175 sg_gzifstream in( path );
176 if ( !in.is_open() ) {
180 SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
182 int len = option.length();
185 while ( ! in.eof() ) {
187 getline( in, line, '\n' );
189 // catch extraneous (DOS) line ending character
190 if ( line[line.length() - 1] < 32 ) {
191 line = line.substr( 0, line.length()-1 );
194 if ( line.find( option ) == 0 ) {
195 return line.substr( len );
204 // Scan the user config files for the specified option and return
206 static string fgScanForOption( const string& option ) {
209 #if defined( unix ) || defined( __CYGWIN__ )
210 // Next check home directory for .fgfsrc.hostname file
212 if ( homedir != NULL ) {
213 SGPath config( homedir );
214 config.append( ".fgfsrc" );
215 config.concat( "." );
216 config.concat( hostname );
217 arg = fgScanForOption( option, config.str() );
222 // Next check home directory for .fgfsrc file
224 if ( homedir != NULL ) {
225 SGPath config( homedir );
226 config.append( ".fgfsrc" );
227 arg = fgScanForOption( option, config.str() );
232 // Check for $fg_root/system.fgfsrc
233 SGPath config( globals->get_fg_root() );
234 config.append( "system.fgfsrc" );
235 arg = fgScanForOption( option, config.str() );
242 // Read in configuration (files and command line options) but only set
244 bool fgInitFGRoot ( int argc, char **argv ) {
247 // First parse command line options looking for --fg-root=, this
248 // will override anything specified in a config file
249 root = fgScanForOption( "--fg-root=", argc, argv);
251 // Check in one of the user configuration files.
253 root = fgScanForOption( "--fg-root=" );
255 // Next check if fg-root is set as an env variable
256 if ( root.empty() ) {
257 char *envp = ::getenv( "FG_ROOT" );
258 if ( envp != NULL ) {
263 // Otherwise, default to a random compiled-in location if we can't
264 // find fg-root any other way.
265 if ( root.empty() ) {
266 #if defined( __CYGWIN__ )
268 #elif defined( _WIN32 )
270 #elif defined(__APPLE__)
272 The following code looks for the base package inside the application
273 bundle, in the standard Contents/Resources location.
275 CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
277 // look for a 'data' subdir
278 CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
280 // now convert down to a path, and the a c-string
281 CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
282 root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
284 CFRelease(resourcesUrl);
292 SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
293 globals->set_fg_root(root);
299 // Read in configuration (files and command line options) but only set
301 bool fgInitFGAircraft ( int argc, char **argv ) {
304 // First parse command line options looking for --aircraft=, this
305 // will override anything specified in a config file
306 aircraft = fgScanForOption( "--aircraft=", argc, argv );
307 if ( aircraft.empty() ) {
308 // check synonym option
309 aircraft = fgScanForOption( "--vehicle=", argc, argv );
312 // Check in one of the user configuration files.
313 if ( aircraft.empty() ) {
314 aircraft = fgScanForOption( "--aircraft=" );
316 if ( aircraft.empty() ) {
317 aircraft = fgScanForOption( "--vehicle=" );
320 // if an aircraft was specified, set the property name
321 if ( !aircraft.empty() ) {
322 SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
323 fgSetString("/sim/aircraft", aircraft.c_str() );
325 SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
332 // Return the current base package version
333 string fgBasePackageVersion() {
334 SGPath base_path( globals->get_fg_root() );
335 base_path.append("version");
337 sg_gzifstream in( base_path.str() );
338 if ( !in.is_open() ) {
339 SGPath old_path( globals->get_fg_root() );
340 old_path.append( "Thanks" );
341 sg_gzifstream old( old_path.str() );
342 if ( !old.is_open() ) {
345 return "[old version]";
356 // Initialize the localization
357 SGPropertyNode *fgInitLocale(const char *language) {
358 SGPropertyNode *c_node = NULL, *d_node = NULL;
359 SGPropertyNode *intl = fgGetNode("/sim/intl");
361 SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
363 // localization not defined
368 // Select the proper language from the list
370 vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
371 for (unsigned int i = 0; i < locale.size(); i++) {
373 vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
374 for (unsigned int j = 0; j < lang.size(); j++) {
376 if (!strcmp(lang[j]->getStringValue(), language)) {
385 d_node = intl->getChild("locale");
389 // Check for localized font
390 SGPropertyNode *font_n = c_node->getNode("font", true);
391 if ( !strcmp(font_n->getStringValue(), "") )
392 font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
396 // Load the default strings
398 SGPath d_path( globals->get_fg_root() );
400 const char *d_path_str = d_node->getStringValue("strings");
402 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
406 d_path.append(d_path_str);
407 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
409 SGPropertyNode *strings = c_node->getNode("strings");
411 readProperties(d_path.str(), strings);
412 } catch (const sg_exception &) {
413 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
418 // Load the language specific strings
420 if (c_node != d_node) {
421 SGPath c_path( globals->get_fg_root() );
423 const char *c_path_str = c_node->getStringValue("strings");
425 SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
429 c_path.append(c_path_str);
430 SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
433 readProperties(c_path.str(), strings);
434 } catch (const sg_exception &) {
435 SG_LOG(SG_GENERAL, SG_ALERT,
436 "Unable to read the localized strings from " << c_path.str());
446 // Initialize the localization routines
447 bool fgDetectLanguage() {
448 const char *language = ::getenv("LANG");
450 if (language == NULL) {
451 SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
455 SGPropertyNode *locale = fgInitLocale(language);
457 SG_LOG(SG_GENERAL, SG_ALERT,
458 "No internationalization settings specified in preferences.xml" );
463 globals->set_locale( locale );
468 // Attempt to locate and parse the various non-XML config files in order
469 // from least precidence to greatest precidence
471 do_options (int argc, char ** argv)
473 // Check for $fg_root/system.fgfsrc
474 SGPath config( globals->get_fg_root() );
475 config.append( "system.fgfsrc" );
476 fgParseOptions(config.str());
478 #if defined( unix ) || defined( __CYGWIN__ )
479 config.concat( "." );
480 config.concat( hostname );
481 fgParseOptions(config.str());
484 // Check for ~/.fgfsrc
485 if ( homedir != NULL ) {
486 config.set( homedir );
487 config.append( ".fgfsrc" );
488 fgParseOptions(config.str());
491 #if defined( unix ) || defined( __CYGWIN__ )
492 // Check for ~/.fgfsrc.hostname
493 config.concat( "." );
494 config.concat( hostname );
495 fgParseOptions(config.str());
498 // Parse remaining command line options
499 // These will override anything specified in a config file
500 fgParseArgs(argc, argv);
504 void fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
506 if (!dirPath.exists()) {
507 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
512 simgear::Dir dir(dirPath);
513 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
514 simgear::PathList::iterator p;
515 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
516 // check file name ends with -set.xml
518 // if we found a -set.xml at this level, don't recurse any deeper
521 bool done = (obj->*pred)(*p);
525 } // of -set.xml iteration
528 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
529 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
530 if (p->file() == "CVS") {
534 fgFindAircraftInDir(*p, obj, pred);
536 } // of recursive case
539 class FindAndCacheAircraft
542 FindAndCacheAircraft(SGPropertyNode* autoSave)
544 _cache = autoSave->getNode("sim/startup/path-cache", true);
549 std::string aircraft = fgGetString( "/sim/aircraft", "");
550 if (aircraft.empty()) {
551 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
555 _searchAircraft = aircraft + "-set.xml";
557 // prepare cache for re-scan
558 SGPropertyNode *n = _cache->getNode("fg-root", true);
559 n->setStringValue(globals->get_fg_root().c_str());
560 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
561 _cache->removeChildren("aircraft");
563 SGPath aircraftDir(globals->get_fg_root());
564 aircraftDir.append("Aircraft");
566 fgFindAircraftInDir(aircraftDir, this, &FindAndCacheAircraft::checkAircraft);
569 if (_foundPath.str().empty()) {
570 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
574 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
575 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
576 if (!_foundPath.exists()) {
577 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
582 readProperties(_foundPath.str(), globals->get_props());
583 } catch ( const sg_exception &e ) {
584 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
594 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
595 return false; // cache mismatch
598 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
599 for (unsigned int i = 0; i < cache.size(); i++) {
600 const char *name = cache[i]->getStringValue("file", "");
601 if (!boost::equals(_searchAircraft, name, is_iequal())) {
605 SGPath xml(cache[i]->getStringValue("path", ""));
613 } // of aircraft in cache iteration
618 bool checkAircraft(const SGPath& p)
623 if (!_cache->getChild("aircraft", i++, false))
627 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
629 std::string fileName(p.file());
630 n = entry->getNode("file", true);
631 n->setStringValue(fileName);
632 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
634 n = entry->getNode("path", true);
635 n->setStringValue(p.dir());
636 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
638 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
646 std::string _searchAircraft;
648 SGPropertyNode* _cache;
651 // Read in configuration (file and command line)
652 bool fgInitConfig ( int argc, char **argv ) {
654 // First, set some sane default values
657 // Read global preferences from $FG_ROOT/preferences.xml
658 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
659 fgLoadProps("preferences.xml", globals->get_props());
660 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
662 // Detect the required language as early as possible
663 if ( !fgDetectLanguage() ) {
667 SGPropertyNode autosave;
669 char *envp = ::getenv( "APPDATA" );
671 SGPath config( envp );
672 config.append( "flightgear.org" );
674 if ( homedir != NULL ) {
675 SGPath config( homedir );
676 config.append( ".fgfs" );
678 const char *fg_home = getenv("FG_HOME");
682 SGPath home_export(config.str());
683 home_export.append("Export/dummy");
684 home_export.create_dir(0777);
686 // Set /sim/fg-home and don't allow malign code to override it until
687 // Nasal security is set up. Use FG_HOME if necessary.
688 SGPropertyNode *home = fgGetNode("/sim", true);
689 home->removeChild("fg-home", 0, false);
690 home = home->getChild("fg-home", 0, true);
691 home->setStringValue(config.c_str());
692 home->setAttribute(SGPropertyNode::WRITE, false);
694 config.append( "autosave.xml" );
695 if (config.exists()) {
696 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
698 readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
699 } catch (sg_exception& e) {
700 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
701 << "(from " << e.getOrigin() << ")");
706 // Scan user config files and command line for a specified aircraft.
707 fgInitFGAircraft(argc, argv);
708 FindAndCacheAircraft f(&autosave);
709 if (!f.loadAircraft()) {
713 copyProperties(&autosave, globals->get_props());
715 // parse options after loading aircraft to ensure any user
716 // overrides of defaults are honored.
717 do_options(argc, argv);
722 // Set current tower position lon/lat given an airport id
723 static bool fgSetTowerPosFromAirportID( const string& id) {
724 const FGAirport *a = fgFindAirportID( id);
726 SGGeod tower = a->getTowerLocation();
727 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
728 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
729 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
737 struct FGTowerLocationListener : SGPropertyChangeListener {
738 void valueChanged(SGPropertyNode* node) {
739 const string id(node->getStringValue());
740 fgSetTowerPosFromAirportID(id);
744 void fgInitTowerLocationListener() {
745 fgGetNode("/sim/tower/airport-id", true)
746 ->addChangeListener( new FGTowerLocationListener(), true );
749 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
751 SGGeod startPos(aStartPos);
752 if (aTargetHeading == HUGE_VAL) {
753 aTargetHeading = aHeading;
756 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
757 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
758 offsetDistance *= SG_NM_TO_METER;
759 double offsetAzimuth = aHeading;
760 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
761 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
762 aHeading = aTargetHeading;
767 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
772 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
773 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
774 fgSetDouble("/sim/presets/heading-deg", aHeading );
776 // other code depends on the actual values being set ...
777 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
778 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
779 fgSetDouble("/orientation/heading-deg", aHeading );
782 // Set current_options lon/lat given an airport id and heading (degrees)
783 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
787 // set initial position from runway and heading
788 SG_LOG( SG_GENERAL, SG_INFO,
789 "Attempting to set starting position from airport code "
790 << id << " heading " << tgt_hdg );
792 const FGAirport* apt = fgFindAirportID(id);
793 if (!apt) return false;
794 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
795 fgSetString("/sim/atc/runway", r->ident().c_str());
797 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
798 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
802 // Set current_options lon/lat given an airport id and parkig position name
803 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
807 // can't see an easy way around this const_cast at the moment
808 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
810 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
813 FGAirportDynamics* dcs = apt->getDynamics();
815 SG_LOG( SG_GENERAL, SG_ALERT,
816 "Failed to find parking position " << parkpos <<
817 " at airport " << id );
821 int park_index = dcs->getNrOfParkings() - 1;
822 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
823 if (park_index < 0) {
824 SG_LOG( SG_GENERAL, SG_ALERT,
825 "Failed to find parking position " << parkpos <<
826 " at airport " << id );
829 FGParking* parking = dcs->getParking(park_index);
830 parking->setAvailable(false);
832 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
833 parking->getHeading());
838 // Set current_options lon/lat given an airport id and runway number
839 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
843 // set initial position from airport and runway number
844 SG_LOG( SG_GENERAL, SG_INFO,
845 "Attempting to set starting position for "
846 << id << ":" << rwy );
848 const FGAirport* apt = fgFindAirportID(id);
850 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
854 if (!apt->hasRunwayWithIdent(rwy)) {
855 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
856 "Failed to find runway " << rwy <<
857 " at airport " << id << ". Using default runway." );
861 FGRunway* r(apt->getRunwayByIdent(rwy));
862 fgSetString("/sim/atc/runway", r->ident().c_str());
863 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
864 fgApplyStartOffset(startPos, r->headingDeg());
869 static void fgSetDistOrAltFromGlideSlope() {
870 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
871 string apt_id = fgGetString("/sim/presets/airport-id");
872 double gs = fgGetDouble("/sim/presets/glideslope-deg")
873 * SG_DEGREES_TO_RADIANS ;
874 double od = fgGetDouble("/sim/presets/offset-distance-nm");
875 double alt = fgGetDouble("/sim/presets/altitude-ft");
877 double apt_elev = 0.0;
878 if ( ! apt_id.empty() ) {
879 apt_elev = fgGetAirportElev( apt_id );
880 if ( apt_elev < -9990.0 ) {
887 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
888 // set altitude from glideslope and offset-distance
889 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
890 alt = fabs(od*tan(gs)) + apt_elev;
891 fgSetDouble("/sim/presets/altitude-ft", alt);
892 fgSetBool("/sim/presets/onground", false);
893 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
895 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
896 // set offset-distance from glideslope and altitude
897 od = (alt - apt_elev) / tan(gs);
898 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
899 fgSetDouble("/sim/presets/offset-distance-nm", od);
900 fgSetBool("/sim/presets/onground", false);
901 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
903 } else if( fabs(gs) > 0.01 ) {
904 SG_LOG( SG_GENERAL, SG_ALERT,
905 "Glideslope given but not altitude or offset-distance." );
906 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
907 fgSetDouble("/sim/presets/glideslope-deg", 0);
908 fgSetBool("/sim/presets/onground", true);
913 // Set current_options lon/lat given an airport id and heading (degrees)
914 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
916 = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
919 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
920 << id << ":" << freq );
924 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
928 // Set current_options lon/lat given an aircraft carrier id
929 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
931 // set initial position from runway and heading
935 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
936 double lon = geodPos.getLongitudeDeg();
937 double lat = geodPos.getLatitudeDeg();
938 double alt = geodPos.getElevationFt();
940 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
941 << carrier << " at lat = " << lat << ", lon = " << lon
942 << ", alt = " << alt << ", heading = " << heading);
944 fgSetDouble("/sim/presets/longitude-deg", lon);
945 fgSetDouble("/sim/presets/latitude-deg", lat);
946 fgSetDouble("/sim/presets/altitude-ft", alt);
947 fgSetDouble("/sim/presets/heading-deg", heading);
948 fgSetDouble("/position/longitude-deg", lon);
949 fgSetDouble("/position/latitude-deg", lat);
950 fgSetDouble("/position/altitude-ft", alt);
951 fgSetDouble("/orientation/heading-deg", heading);
953 fgSetString("/sim/presets/speed-set", "UVW");
954 fgSetDouble("/velocities/uBody-fps", uvw(0));
955 fgSetDouble("/velocities/vBody-fps", uvw(1));
956 fgSetDouble("/velocities/wBody-fps", uvw(2));
957 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
958 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
959 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
961 fgSetBool("/sim/presets/onground", true);
965 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
971 // Set current_options lon/lat given an airport id and heading (degrees)
972 static bool fgSetPosFromFix( const string& id )
974 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
975 FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
977 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
981 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
986 * Initialize vor/ndb/ils/fix list management and query systems (as
987 * well as simple airport db list)
992 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
994 SGPath aptdb( globals->get_fg_root() );
995 aptdb.append( "Airports/apt.dat" );
997 SGPath p_metar( globals->get_fg_root() );
998 p_metar.append( "Airports/metar.dat" );
1000 // Initialise the frequency search map BEFORE reading
1001 // the airport database:
1005 current_commlist = new FGCommList;
1006 current_commlist->init( globals->get_fg_root() );
1007 fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1009 FGNavList *navlist = new FGNavList;
1010 FGNavList *loclist = new FGNavList;
1011 FGNavList *gslist = new FGNavList;
1012 FGNavList *dmelist = new FGNavList;
1013 FGNavList *tacanlist = new FGNavList;
1014 FGNavList *carrierlist = new FGNavList;
1015 FGTACANList *channellist = new FGTACANList;
1017 globals->set_navlist( navlist );
1018 globals->set_loclist( loclist );
1019 globals->set_gslist( gslist );
1020 globals->set_dmelist( dmelist );
1021 globals->set_tacanlist( tacanlist );
1022 globals->set_carrierlist( carrierlist );
1023 globals->set_channellist( channellist );
1025 if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1026 SG_LOG( SG_GENERAL, SG_ALERT,
1027 "Problems loading one or more navigational database" );
1030 SG_LOG(SG_GENERAL, SG_INFO, " Fixes");
1031 SGPath p_fix( globals->get_fg_root() );
1032 p_fix.append( "Navaids/fix.dat" );
1034 fixlist.init( p_fix ); // adds fixes to the DB in positioned.cxx
1036 SG_LOG(SG_GENERAL, SG_INFO, " Airways");
1037 SGPath p_awy( globals->get_fg_root() );
1038 p_awy.append( "Navaids/awy.dat" );
1039 FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1040 //cerr << "Loading Airways" << endl;
1041 awyNet->load (p_awy );
1043 //cerr << "initializing airways" << endl;
1044 globals->set_airwaynet( awyNet );
1050 // Set the initial position based on presets (or defaults)
1051 bool fgInitPosition() {
1052 // cout << "fgInitPosition()" << endl;
1053 double gs = fgGetDouble("/sim/presets/glideslope-deg")
1054 * SG_DEGREES_TO_RADIANS ;
1055 double od = fgGetDouble("/sim/presets/offset-distance-nm");
1056 double alt = fgGetDouble("/sim/presets/altitude-ft");
1058 bool set_pos = false;
1060 // If glideslope is specified, then calculate offset-distance or
1061 // altitude relative to glide slope if either of those was not
1063 if ( fabs( gs ) > 0.01 ) {
1064 fgSetDistOrAltFromGlideSlope();
1068 // If we have an explicit, in-range lon/lat, don't change it, just use it.
1069 // If not, check for an airport-id and use that.
1070 // If not, default to the middle of the KSFO field.
1071 // The default values for lon/lat are deliberately out of range
1072 // so that the airport-id can take effect; valid lon/lat will
1073 // override airport-id, however.
1074 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1075 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1076 if ( lon_deg >= -180.0 && lon_deg <= 180.0
1077 && lat_deg >= -90.0 && lat_deg <= 90.0 )
1082 string apt = fgGetString("/sim/presets/airport-id");
1083 string rwy_no = fgGetString("/sim/presets/runway");
1084 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1085 string vor = fgGetString("/sim/presets/vor-id");
1086 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1087 string ndb = fgGetString("/sim/presets/ndb-id");
1088 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1089 string carrier = fgGetString("/sim/presets/carrier");
1090 string parkpos = fgGetString("/sim/presets/parkpos");
1091 string fix = fgGetString("/sim/presets/fix");
1092 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1093 double hdg = hdg_preset->getDoubleValue();
1095 // save some start parameters, so that we can later say what the
1096 // user really requested. TODO generalize that and move it to options.cxx
1097 static bool start_options_saved = false;
1098 if (!start_options_saved) {
1099 start_options_saved = true;
1100 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1102 opt->setDoubleValue("latitude-deg", lat_deg);
1103 opt->setDoubleValue("longitude-deg", lon_deg);
1104 opt->setDoubleValue("heading-deg", hdg);
1105 opt->setStringValue("airport", apt.c_str());
1106 opt->setStringValue("runway", rwy_no.c_str());
1110 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1112 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1113 // An airport + parking position is requested
1114 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1115 // set tower position
1116 fgSetString("/sim/tower/airport-id", apt.c_str());
1121 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1122 // An airport + runway is requested
1123 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1124 // set tower position (a little off the heading for single
1126 fgSetString("/sim/tower/airport-id", apt.c_str());
1131 if ( !set_pos && !apt.empty() ) {
1132 // An airport is requested (find runway closest to hdg)
1133 if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1134 // set tower position (a little off the heading for single
1136 fgSetString("/sim/tower/airport-id", apt.c_str());
1141 if (hdg_preset->getDoubleValue() > 9990.0)
1142 hdg_preset->setDoubleValue(hdg);
1144 if ( !set_pos && !vor.empty() ) {
1145 // a VOR is requested
1146 if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1151 if ( !set_pos && !ndb.empty() ) {
1152 // an NDB is requested
1153 if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1158 if ( !set_pos && !carrier.empty() ) {
1159 // an aircraft carrier is requested
1160 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1165 if ( !set_pos && !fix.empty() ) {
1166 // a Fix is requested
1167 if ( fgSetPosFromFix( fix ) ) {
1173 // No lon/lat specified, no airport specified, default to
1174 // middle of KSFO field.
1175 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1176 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1179 fgSetDouble( "/position/longitude-deg",
1180 fgGetDouble("/sim/presets/longitude-deg") );
1181 fgSetDouble( "/position/latitude-deg",
1182 fgGetDouble("/sim/presets/latitude-deg") );
1183 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1185 // determine if this should be an on-ground or in-air start
1186 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1187 fgSetBool("/sim/presets/onground", false);
1189 fgSetBool("/sim/presets/onground", true);
1196 // General house keeping initializations
1197 bool fgInitGeneral() {
1200 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1201 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1203 root = globals->get_fg_root();
1204 if ( ! root.length() ) {
1205 // No root path set? Then bail ...
1206 SG_LOG( SG_GENERAL, SG_ALERT,
1207 "Cannot continue without a path to the base package "
1208 << "being defined." );
1211 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1213 globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1215 char buf[512], *cwd = getcwd(buf, 511);
1217 SGPropertyNode *curr = fgGetNode("/sim", true);
1218 curr->removeChild("fg-current", 0, false);
1219 curr = curr->getChild("fg-current", 0, true);
1220 curr->setStringValue(cwd ? cwd : "");
1221 curr->setAttribute(SGPropertyNode::WRITE, false);
1223 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1224 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1228 // Initialize view parameters
1230 // force update of model so that viewer can get some data...
1231 globals->get_aircraft_model()->update(0);
1232 // run update for current view so that data is current...
1233 globals->get_viewmgr()->update(0);
1237 SGTime *fgInitTime() {
1239 static const SGPropertyNode *longitude
1240 = fgGetNode("/position/longitude-deg");
1241 static const SGPropertyNode *latitude
1242 = fgGetNode("/position/latitude-deg");
1243 static const SGPropertyNode *cur_time_override
1244 = fgGetNode("/sim/time/cur-time-override", true);
1246 SGPath zone( globals->get_fg_root() );
1247 zone.append( "Timezone" );
1248 SGTime *t = new SGTime( longitude->getDoubleValue()
1249 * SGD_DEGREES_TO_RADIANS,
1250 latitude->getDoubleValue()
1251 * SGD_DEGREES_TO_RADIANS,
1253 cur_time_override->getLongValue() );
1255 globals->set_warp_delta( 0 );
1257 t->update( 0.0, 0.0,
1258 cur_time_override->getLongValue(),
1259 globals->get_warp() );
1265 // set up a time offset (aka warp) if one is specified
1266 void fgInitTimeOffset() {
1267 static const SGPropertyNode *longitude
1268 = fgGetNode("/position/longitude-deg");
1269 static const SGPropertyNode *latitude
1270 = fgGetNode("/position/latitude-deg");
1271 static const SGPropertyNode *cur_time_override
1272 = fgGetNode("/sim/time/cur-time-override", true);
1274 // Handle potential user specified time offsets
1275 int orig_warp = globals->get_warp();
1276 SGTime *t = globals->get_time_params();
1277 time_t cur_time = t->get_cur_time();
1278 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1279 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1280 time_t aircraftLocalTime =
1281 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1283 // Okay, we now have several possible scenarios
1284 int offset = fgGetInt("/sim/startup/time-offset");
1285 string offset_type = fgGetString("/sim/startup/time-offset-type");
1288 if ( offset_type == "real" ) {
1290 } else if ( offset_type == "dawn" ) {
1291 warp = fgTimeSecondsUntilSunAngle( cur_time,
1292 longitude->getDoubleValue()
1293 * SGD_DEGREES_TO_RADIANS,
1294 latitude->getDoubleValue()
1295 * SGD_DEGREES_TO_RADIANS,
1297 } else if ( offset_type == "morning" ) {
1298 warp = fgTimeSecondsUntilSunAngle( cur_time,
1299 longitude->getDoubleValue()
1300 * SGD_DEGREES_TO_RADIANS,
1301 latitude->getDoubleValue()
1302 * SGD_DEGREES_TO_RADIANS,
1304 } else if ( offset_type == "noon" ) {
1305 warp = fgTimeSecondsUntilSunAngle( cur_time,
1306 longitude->getDoubleValue()
1307 * SGD_DEGREES_TO_RADIANS,
1308 latitude->getDoubleValue()
1309 * SGD_DEGREES_TO_RADIANS,
1311 } else if ( offset_type == "afternoon" ) {
1312 warp = fgTimeSecondsUntilSunAngle( cur_time,
1313 longitude->getDoubleValue()
1314 * SGD_DEGREES_TO_RADIANS,
1315 latitude->getDoubleValue()
1316 * SGD_DEGREES_TO_RADIANS,
1318 } else if ( offset_type == "dusk" ) {
1319 warp = fgTimeSecondsUntilSunAngle( cur_time,
1320 longitude->getDoubleValue()
1321 * SGD_DEGREES_TO_RADIANS,
1322 latitude->getDoubleValue()
1323 * SGD_DEGREES_TO_RADIANS,
1325 } else if ( offset_type == "evening" ) {
1326 warp = fgTimeSecondsUntilSunAngle( cur_time,
1327 longitude->getDoubleValue()
1328 * SGD_DEGREES_TO_RADIANS,
1329 latitude->getDoubleValue()
1330 * SGD_DEGREES_TO_RADIANS,
1332 } else if ( offset_type == "midnight" ) {
1333 warp = fgTimeSecondsUntilSunAngle( cur_time,
1334 longitude->getDoubleValue()
1335 * SGD_DEGREES_TO_RADIANS,
1336 latitude->getDoubleValue()
1337 * SGD_DEGREES_TO_RADIANS,
1339 } else if ( offset_type == "system-offset" ) {
1342 } else if ( offset_type == "gmt-offset" ) {
1343 warp = offset - (currGMT - systemLocalTime);
1345 } else if ( offset_type == "latitude-offset" ) {
1346 warp = offset - (aircraftLocalTime - systemLocalTime);
1348 } else if ( offset_type == "system" ) {
1349 warp = offset - (systemLocalTime - currGMT) - cur_time;
1350 } else if ( offset_type == "gmt" ) {
1351 warp = offset - cur_time;
1352 } else if ( offset_type == "latitude" ) {
1353 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
1355 SG_LOG( SG_GENERAL, SG_ALERT,
1356 "FG_TIME::Unsupported offset type " << offset_type );
1359 globals->set_warp( orig_warp + warp );
1360 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1361 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1362 cur_time_override->getLongValue(),
1363 globals->get_warp() );
1365 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
1366 << globals->get_warp() );
1370 // This is the top level init routine which calls all the other
1371 // initialization routines. If you are adding a subsystem to flight
1372 // gear, its initialization call should located in this routine.
1373 // Returns non-zero if a problem encountered.
1374 bool fgInitSubsystems() {
1375 // static const SGPropertyNode *longitude
1376 // = fgGetNode("/sim/presets/longitude-deg");
1377 // static const SGPropertyNode *latitude
1378 // = fgGetNode("/sim/presets/latitude-deg");
1379 // static const SGPropertyNode *altitude
1380 // = fgGetNode("/sim/presets/altitude-ft");
1382 SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1383 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1385 ////////////////////////////////////////////////////////////////////
1386 // Initialize the event manager subsystem.
1387 ////////////////////////////////////////////////////////////////////
1389 globals->get_event_mgr()->init();
1390 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1392 ////////////////////////////////////////////////////////////////////
1393 // Initialize the property interpolator subsystem. Put into the INIT
1394 // group because the "nasal" subsystem may need it at GENERAL take-down.
1395 ////////////////////////////////////////////////////////////////////
1396 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1399 ////////////////////////////////////////////////////////////////////
1400 // Add the FlightGear property utilities.
1401 ////////////////////////////////////////////////////////////////////
1402 globals->add_subsystem("properties", new FGProperties);
1404 ////////////////////////////////////////////////////////////////////
1405 // Initialize the material property subsystem.
1406 ////////////////////////////////////////////////////////////////////
1408 SGPath mpath( globals->get_fg_root() );
1409 mpath.append( "materials.xml" );
1410 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1411 globals->get_props()) ) {
1412 SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1417 ////////////////////////////////////////////////////////////////////
1418 // Initialize the scenery management subsystem.
1419 ////////////////////////////////////////////////////////////////////
1421 if ( globals->get_tile_mgr()->init() ) {
1422 // Load the local scenery data
1423 double visibility_meters = fgGetDouble("/environment/visibility-m");
1424 globals->get_tile_mgr()->update( visibility_meters );
1426 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1430 globals->get_scenery()->get_scene_graph()
1431 ->addChild(simgear::Particles::getCommonRoot());
1432 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1434 ////////////////////////////////////////////////////////////////////
1435 // Initialize the flight model subsystem.
1436 ////////////////////////////////////////////////////////////////////
1438 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1440 ////////////////////////////////////////////////////////////////////
1441 // Initialize the weather subsystem.
1442 ////////////////////////////////////////////////////////////////////
1444 // Initialize the weather modeling subsystem
1445 globals->add_subsystem("environment", new FGEnvironmentMgr);
1447 ////////////////////////////////////////////////////////////////////
1448 // Initialize the ridge lift simulation.
1449 ////////////////////////////////////////////////////////////////////
1451 // Initialize the ridgelift subsystem
1452 globals->add_subsystem("ridgelift", new FGRidgeLift);
1454 ////////////////////////////////////////////////////////////////////
1455 // Initialize the aircraft systems and instrumentation (before the
1457 ////////////////////////////////////////////////////////////////////
1459 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1460 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1462 ////////////////////////////////////////////////////////////////////
1463 // Initialize the XML Autopilot subsystem.
1464 ////////////////////////////////////////////////////////////////////
1466 globals->add_subsystem( "xml-autopilot", new FGXMLAutopilotGroup, SGSubsystemMgr::FDM );
1467 globals->add_subsystem( "route-manager", new FGRouteMgr );
1469 ////////////////////////////////////////////////////////////////////
1470 // Initialize the view manager subsystem.
1471 ////////////////////////////////////////////////////////////////////
1475 ////////////////////////////////////////////////////////////////////
1476 // Initialize the Input-Output subsystem
1477 ////////////////////////////////////////////////////////////////////
1478 globals->add_subsystem( "io", new FGIO );
1480 ////////////////////////////////////////////////////////////////////
1481 // Create and register the logger.
1482 ////////////////////////////////////////////////////////////////////
1484 globals->add_subsystem("logger", new FGLogger);
1486 ////////////////////////////////////////////////////////////////////
1487 // Create and register the XML GUI.
1488 ////////////////////////////////////////////////////////////////////
1490 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1493 ////////////////////////////////////////////////////////////////////
1494 // Initialize the local time subsystem.
1495 ////////////////////////////////////////////////////////////////////
1497 // update the current timezone each 30 minutes
1498 globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1499 &fgUpdateLocalTime, 30*60 );
1500 fgInitTimeOffset(); // the environment subsystem needs this
1503 ////////////////////////////////////////////////////////////////////
1504 // Initialize the lighting subsystem.
1505 ////////////////////////////////////////////////////////////////////
1507 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1509 //////////////////////////////////////////////////////////////////////
1510 // Initialize the 2D cloud subsystem.
1511 ////////////////////////////////////////////////////////////////////
1512 fgGetBool("/sim/rendering/bump-mapping", false);
1514 #ifdef ENABLE_AUDIO_SUPPORT
1515 ////////////////////////////////////////////////////////////////////
1516 // Initialize the sound-effects subsystem.
1517 ////////////////////////////////////////////////////////////////////
1518 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1521 ////////////////////////////////////////////////////////////////////
1522 // Initialise the ATC Manager
1523 ////////////////////////////////////////////////////////////////////
1526 SG_LOG(SG_GENERAL, SG_INFO, " ATC Manager");
1527 globals->set_ATC_mgr(new FGATCMgr);
1528 globals->get_ATC_mgr()->init();
1530 ////////////////////////////////////////////////////////////////////
1531 // Initialise the AI Manager
1532 ////////////////////////////////////////////////////////////////////
1534 SG_LOG(SG_GENERAL, SG_INFO, " AI Manager");
1535 globals->set_AI_mgr(new FGAIMgr);
1536 globals->get_AI_mgr()->init();
1538 ////////////////////////////////////////////////////////////////////
1539 // Initialise the AI Model Manager
1540 ////////////////////////////////////////////////////////////////////
1541 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1542 globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1543 globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1546 // It's probably a good idea to initialize the top level traffic manager
1547 // After the AI and ATC systems have been initialized properly.
1548 // AI Traffic manager
1549 globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1552 if( fgCockpitInit()) {
1553 // Cockpit initialized ok.
1555 SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1560 ////////////////////////////////////////////////////////////////////
1561 // Add a new 2D panel.
1562 ////////////////////////////////////////////////////////////////////
1564 string panel_path = fgGetString("/sim/panel/path",
1565 "Panels/Default/default.xml");
1567 globals->set_current_panel( fgReadPanel(panel_path) );
1568 if (globals->get_current_panel() == 0) {
1569 SG_LOG( SG_INPUT, SG_ALERT,
1570 "Error reading new panel from " << panel_path );
1572 SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1573 globals->get_current_panel()->init();
1574 globals->get_current_panel()->bind();
1578 ////////////////////////////////////////////////////////////////////
1579 // Initialize the controls subsystem.
1580 ////////////////////////////////////////////////////////////////////
1582 globals->get_controls()->init();
1583 globals->get_controls()->bind();
1586 ////////////////////////////////////////////////////////////////////
1587 // Initialize the input subsystem.
1588 ////////////////////////////////////////////////////////////////////
1590 globals->add_subsystem("input", new FGInput);
1593 ////////////////////////////////////////////////////////////////////
1594 // Initialize the replay subsystem
1595 ////////////////////////////////////////////////////////////////////
1596 globals->add_subsystem("replay", new FGReplay);
1599 ////////////////////////////////////////////////////////////////////
1600 // Bind and initialize subsystems.
1601 ////////////////////////////////////////////////////////////////////
1603 globals->get_subsystem_mgr()->bind();
1604 globals->get_subsystem_mgr()->init();
1606 ////////////////////////////////////////////////////////////////////
1607 // Initialize multiplayer subsystem
1608 ////////////////////////////////////////////////////////////////////
1610 globals->set_multiplayer_mgr(new FGMultiplayMgr);
1611 globals->get_multiplayer_mgr()->init();
1613 ////////////////////////////////////////////////////////////////////////
1614 // Initialize the Nasal interpreter.
1615 // Do this last, so that the loaded scripts see initialized state
1616 ////////////////////////////////////////////////////////////////////////
1617 FGNasalSys* nasal = new FGNasalSys();
1618 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1621 // initialize methods that depend on other subsystems.
1622 globals->get_subsystem_mgr()->postinit();
1624 ////////////////////////////////////////////////////////////////////////
1625 // End of subsystem initialization.
1626 ////////////////////////////////////////////////////////////////////
1628 SG_LOG( SG_GENERAL, SG_INFO, endl);
1630 // Save the initial state for future
1632 globals->saveInitialState();
1638 void fgReInitSubsystems()
1640 // static const SGPropertyNode *longitude
1641 // = fgGetNode("/sim/presets/longitude-deg");
1642 // static const SGPropertyNode *latitude
1643 // = fgGetNode("/sim/presets/latitude-deg");
1644 static const SGPropertyNode *altitude
1645 = fgGetNode("/sim/presets/altitude-ft");
1646 static const SGPropertyNode *master_freeze
1647 = fgGetNode("/sim/freeze/master");
1649 SG_LOG( SG_GENERAL, SG_INFO,
1650 "fgReInitSubsystems(): /position/altitude = "
1651 << altitude->getDoubleValue() );
1653 bool freeze = master_freeze->getBoolValue();
1655 fgSetBool("/sim/freeze/master", true);
1657 fgSetBool("/sim/crashed", false);
1659 // Force reupdating the positions of the ai 3d models. They are used for
1660 // initializing ground level for the FDM.
1661 globals->get_subsystem("ai_model")->reinit();
1663 // Initialize the FDM
1664 globals->get_subsystem("flight")->reinit();
1666 // reload offsets from config defaults
1667 globals->get_viewmgr()->reinit();
1671 globals->get_controls()->reset_all();
1673 fgUpdateLocalTime();
1675 // re-init to proper time of day setting
1679 fgSetBool("/sim/freeze/master", false);
1681 fgSetBool("/sim/sceneryloaded",false);
1685 void doSimulatorReset(void) // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1687 static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1689 bool freeze = master_freeze->getBoolValue();
1691 master_freeze->setBoolValue(true);
1693 fgSetBool("/sim/signals/reinit", true);
1695 globals->get_subsystem("flight")->unbind();
1697 // in case user has changed window size as
1698 // restoreInitialState() overwrites these
1699 int xsize = fgGetInt("/sim/startup/xsize");
1700 int ysize = fgGetInt("/sim/startup/ysize");
1702 // viewports also needs to be saved/restored as
1703 // restoreInitialState() overwrites these
1704 SGPropertyNode *guiNode = new SGPropertyNode;
1705 SGPropertyNode *cameraNode = new SGPropertyNode;
1706 SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1707 copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1708 copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1710 globals->restoreInitialState();
1712 // update our position based on current presets
1715 // We don't know how to resize the window, so keep the last values
1716 // for xsize and ysize, and don't use the one set initially
1717 fgSetInt("/sim/startup/xsize", xsize);
1718 fgSetInt("/sim/startup/ysize", ysize);
1720 copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1721 copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1726 SGTime *t = globals->get_time_params();
1729 globals->set_time_params(t);
1731 fgReInitSubsystems();
1733 globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1734 globals->get_renderer()->resize(xsize, ysize);
1735 fgSetBool("/sim/signals/reinit", false);
1738 master_freeze->setBoolValue(false);
1741 ///////////////////////////////////////////////////////////////////////////////
1742 // helper object to implement the --show-aircraft command.
1743 // resides here so we can share the fgFindAircraftInDir template above,
1744 // and hence ensure this command lists exectly the same aircraft as the normal
1751 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1755 void show(const SGPath& path)
1757 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1759 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1760 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1761 cout << "Available aircraft:" << endl;
1762 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1763 cout << _aircraft[i] << endl;
1768 bool processAircraft(const SGPath& path)
1770 SGPropertyNode root;
1772 readProperties(path.str(), &root);
1773 } catch (sg_exception& e) {
1778 string descStr(" ");
1779 descStr += path.file();
1781 SGPropertyNode *node = root.getNode("sim");
1783 SGPropertyNode* desc = node->getNode("description");
1784 // if a status tag is found, read it in
1785 if (node->hasValue("status")) {
1786 maturity = getNumMaturity(node->getStringValue("status"));
1790 if (descStr.size() <= 27+3) {
1791 descStr.append(29+3-descStr.size(), ' ');
1794 descStr.append( 32, ' ');
1796 descStr += desc->getStringValue();
1798 } // of have 'sim' node
1800 if (maturity < _minStatus) {
1804 _aircraft.push_back(descStr);
1809 int getNumMaturity(const char * str)
1811 // changes should also be reflected in $FG_ROOT/data/options.xml &
1812 // $FG_ROOT/data/Translations/string-default.xml
1813 const char* levels[] = {"alpha","beta","early-production","production"};
1815 if (!strcmp(str, "all")) {
1819 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1820 if (strcmp(str,levels[i])==0)
1826 // recommended in Meyers, Effective STL when internationalization and embedded
1827 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1828 struct ciLessLibC : public std::binary_function<string, string, bool>
1830 bool operator()(const std::string &lhs, const std::string &rhs) const
1832 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1837 string_list _aircraft;
1840 void fgShowAircraft(const SGPath &path)
1846 cout << "Hit a key to continue..." << endl;