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()
33 # include <io.h> // isatty()
34 # define isatty _isatty
37 // work around a stdc++ lib bug in some versions of linux, but doesn't
38 // seem to hurt to have this here for all versions of Linux.
40 # define _G_NO_EXTERN_TEMPLATES
43 #include <simgear/compiler.h>
46 #include <boost/algorithm/string/compare.hpp>
47 #include <boost/algorithm/string/predicate.hpp>
49 #include <simgear/constants.h>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/structure/exception.hxx>
52 #include <simgear/structure/event_mgr.hxx>
53 #include <simgear/structure/SGPerfMon.hxx>
54 #include <simgear/misc/sg_path.hxx>
55 #include <simgear/misc/sg_dir.hxx>
56 #include <simgear/misc/sgstream.hxx>
57 #include <simgear/misc/strutils.hxx>
58 #include <simgear/props/props_io.hxx>
60 #include <simgear/misc/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/scene/model/particles.hxx>
64 #include <Aircraft/controls.hxx>
65 #include <Aircraft/replay.hxx>
66 #include <Airports/runways.hxx>
67 #include <Airports/simple.hxx>
68 #include <Airports/dynamics.hxx>
70 #include <AIModel/AIManager.hxx>
72 #include <ATCDCL/ATISmgr.hxx>
73 #include <ATC/atc_mgr.hxx>
75 #include <Autopilot/route_mgr.hxx>
76 #include <Autopilot/autopilotgroup.hxx>
78 #include <Cockpit/panel.hxx>
79 #include <Cockpit/panel_io.hxx>
81 #include <Canvas/canvas_mgr.hxx>
82 #include <Canvas/gui_mgr.hxx>
83 #include <GUI/new_gui.hxx>
84 #include <Input/input.hxx>
85 #include <Instrumentation/instrument_mgr.hxx>
86 #include <Model/acmodel.hxx>
87 #include <Model/modelmgr.hxx>
88 #include <AIModel/submodel.hxx>
89 #include <AIModel/AIManager.hxx>
90 #include <Navaids/navdb.hxx>
91 #include <Navaids/navlist.hxx>
92 #include <Scenery/scenery.hxx>
93 #include <Scenery/tilemgr.hxx>
94 #include <Scripting/NasalSys.hxx>
95 #include <Sound/voice.hxx>
96 #include <Sound/soundmanager.hxx>
97 #include <Systems/system_mgr.hxx>
98 #include <Time/light.hxx>
99 #include <Traffic/TrafficMgr.hxx>
100 #include <MultiPlayer/multiplaymgr.hxx>
101 #include <FDM/fdm_shell.hxx>
102 #include <Environment/ephemeris.hxx>
103 #include <Environment/environment_mgr.hxx>
104 #include <Viewer/renderer.hxx>
105 #include <Viewer/viewmgr.hxx>
106 #include <Navaids/NavDataCache.hxx>
108 #include "fg_init.hxx"
110 #include "fg_commands.hxx"
111 #include "fg_props.hxx"
112 #include "options.hxx"
113 #include "globals.hxx"
114 #include "logger.hxx"
116 #include "positioninit.hxx"
119 using namespace boost::algorithm;
122 // Return the current base package version
123 string fgBasePackageVersion() {
124 SGPath base_path( globals->get_fg_root() );
125 base_path.append("version");
127 sg_gzifstream in( base_path.str() );
128 if ( !in.is_open() ) {
129 SGPath old_path( globals->get_fg_root() );
130 old_path.append( "Thanks" );
131 sg_gzifstream old( old_path.str() );
132 if ( !old.is_open() ) {
135 return "[old version]";
147 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
149 if (!dirPath.exists()) {
150 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
155 simgear::Dir dir(dirPath);
156 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
157 simgear::PathList::iterator p;
158 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
159 // check file name ends with -set.xml
161 // if we found a -set.xml at this level, don't recurse any deeper
164 bool done = (obj->*pred)(*p);
168 } // of -set.xml iteration
174 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
175 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
176 if (p->file() == "CVS") {
180 if (fgFindAircraftInDir(*p, obj, pred)) {
183 } // of subdirs iteration
189 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
191 const string_list& paths(globals->get_aircraft_paths());
192 string_list::const_iterator it = paths.begin();
193 for (; it != paths.end(); ++it) {
194 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
198 } // of aircraft paths iteration
200 // if we reach this point, search the default location (always last)
201 SGPath rootAircraft(globals->get_fg_root());
202 rootAircraft.append("Aircraft");
203 fgFindAircraftInDir(rootAircraft, obj, pred);
206 class FindAndCacheAircraft
209 FindAndCacheAircraft(SGPropertyNode* autoSave)
211 _cache = autoSave->getNode("sim/startup/path-cache", true);
216 std::string aircraft = fgGetString( "/sim/aircraft", "");
217 if (aircraft.empty()) {
218 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
222 _searchAircraft = aircraft + "-set.xml";
223 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
224 if (!aircraftDir.empty()) {
225 // aircraft-dir was set, skip any searching at all, if it's valid
226 simgear::Dir acPath(aircraftDir);
227 SGPath setFile = acPath.file(_searchAircraft);
228 if (setFile.exists()) {
229 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
232 readProperties(setFile.str(), globals->get_props());
233 } catch ( const sg_exception &e ) {
234 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
240 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
241 "' not found in specified dir:" << aircraftDir);
247 // prepare cache for re-scan
248 SGPropertyNode *n = _cache->getNode("fg-root", true);
249 n->setStringValue(globals->get_fg_root().c_str());
250 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
251 n = _cache->getNode("fg-aircraft", true);
252 n->setStringValue(getAircraftPaths().c_str());
253 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
254 _cache->removeChildren("aircraft");
256 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
259 if (_foundPath.str().empty()) {
260 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
264 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
265 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
266 if (!_foundPath.exists()) {
267 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
272 readProperties(_foundPath.str(), globals->get_props());
273 } catch ( const sg_exception &e ) {
274 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
282 SGPath getAircraftPaths() {
283 string_list pathList = globals->get_aircraft_paths();
284 SGPath aircraftPaths;
285 string_list::const_iterator it = pathList.begin();
286 if (it != pathList.end()) {
287 aircraftPaths.set(*it);
290 for (; it != pathList.end(); ++it) {
291 aircraftPaths.add(*it);
293 return aircraftPaths;
298 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
299 return false; // cache mismatch
302 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
303 return false; // cache mismatch
306 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
307 for (unsigned int i = 0; i < cache.size(); i++) {
308 const char *name = cache[i]->getStringValue("file", "");
309 if (!boost::equals(_searchAircraft, name, is_iequal())) {
313 SGPath xml(cache[i]->getStringValue("path", ""));
321 } // of aircraft in cache iteration
326 bool checkAircraft(const SGPath& p)
331 if (!_cache->getChild("aircraft", i++, false))
335 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
337 std::string fileName(p.file());
338 n = entry->getNode("file", true);
339 n->setStringValue(fileName);
340 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
342 n = entry->getNode("path", true);
343 n->setStringValue(p.dir());
344 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
346 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
354 std::string _searchAircraft;
356 SGPropertyNode* _cache;
360 static SGPath platformDefaultDataPath()
362 char *envp = ::getenv( "APPDATA" );
363 SGPath config( envp );
364 config.append( "flightgear.org" );
369 #include <CoreServices/CoreServices.h>
371 static SGPath platformDefaultDataPath()
374 OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
379 unsigned char path[1024];
380 if (FSRefMakePath(&ref, path, 1024) != noErr) {
385 appData.set((const char*) path);
386 appData.append("FlightGear");
390 static SGPath platformDefaultDataPath()
392 SGPath config( homedir );
393 config.append( ".fgfs" );
398 // Read in configuration (file and command line)
399 bool fgInitConfig ( int argc, char **argv )
401 SGPath dataPath = platformDefaultDataPath();
403 const char *fg_home = getenv("FG_HOME");
407 globals->set_fg_home(dataPath.c_str());
409 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
410 if (!exportDir.exists()) {
411 exportDir.create(0777);
414 // Set /sim/fg-home and don't allow malign code to override it until
415 // Nasal security is set up. Use FG_HOME if necessary.
416 SGPropertyNode *home = fgGetNode("/sim", true);
417 home->removeChild("fg-home", 0, false);
418 home = home->getChild("fg-home", 0, true);
419 home->setStringValue(dataPath.c_str());
420 home->setAttribute(SGPropertyNode::WRITE, false);
422 flightgear::Options::sharedInstance()->init(argc, argv, dataPath);
424 // Read global preferences from $FG_ROOT/preferences.xml
425 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
426 fgLoadProps("preferences.xml", globals->get_props());
427 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
429 // do not load user settings when reset to default is requested
430 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults"))
432 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
436 globals->loadUserSettings(dataPath);
439 // Scan user config files and command line for a specified aircraft.
440 flightgear::Options::sharedInstance()->initAircraft();
442 FindAndCacheAircraft f(globals->get_props());
443 if (!f.loadAircraft()) {
447 // parse options after loading aircraft to ensure any user
448 // overrides of defaults are honored.
449 flightgear::Options::sharedInstance()->processOptions();
454 // Set current tower position lon/lat given an airport id
455 static bool fgSetTowerPosFromAirportID( const string& id) {
456 const FGAirport *a = fgFindAirportID( id);
458 SGGeod tower = a->getTowerLocation();
459 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
460 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
461 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
469 struct FGTowerLocationListener : SGPropertyChangeListener {
470 void valueChanged(SGPropertyNode* node) {
471 string id(node->getStringValue());
472 if (fgGetBool("/sim/tower/auto-position",true))
474 // enforce using closest airport when auto-positioning is enabled
475 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
476 if (closest_airport && (id != closest_airport))
478 id = closest_airport;
479 node->setStringValue(id);
482 fgSetTowerPosFromAirportID(id);
486 struct FGClosestTowerLocationListener : SGPropertyChangeListener
488 void valueChanged(SGPropertyNode* )
490 // closest airport has changed
491 if (fgGetBool("/sim/tower/auto-position",true))
493 // update tower position
494 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
496 fgSetString("/sim/tower/airport-id", id);
501 void fgInitTowerLocationListener() {
502 fgGetNode("/sim/tower/airport-id", true)
503 ->addChangeListener( new FGTowerLocationListener(), true );
504 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
505 fgGetNode("/sim/airport/closest-airport-id", true)
506 ->addChangeListener(ntcl , true );
507 fgGetNode("/sim/tower/auto-position", true)
508 ->addChangeListener(ntcl, true );
511 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
513 SGGeod startPos(aStartPos);
514 if (aTargetHeading == HUGE_VAL) {
515 aTargetHeading = aHeading;
518 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
519 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
520 offsetDistance *= SG_NM_TO_METER;
521 double offsetAzimuth = aHeading;
522 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
523 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
524 aHeading = aTargetHeading;
529 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
534 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
535 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
536 fgSetDouble("/sim/presets/heading-deg", aHeading );
538 // other code depends on the actual values being set ...
539 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
540 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
541 fgSetDouble("/orientation/heading-deg", aHeading );
544 // Set current_options lon/lat given an airport id and heading (degrees)
545 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
549 // set initial position from runway and heading
550 SG_LOG( SG_GENERAL, SG_INFO,
551 "Attempting to set starting position from airport code "
552 << id << " heading " << tgt_hdg );
554 const FGAirport* apt = fgFindAirportID(id);
555 if (!apt) return false;
556 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
557 fgSetString("/sim/atc/runway", r->ident().c_str());
559 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
560 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
564 // Set current_options lon/lat given an airport id and parkig position name
565 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
569 // can't see an easy way around this const_cast at the moment
570 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
572 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
575 FGAirportDynamics* dcs = apt->getDynamics();
577 SG_LOG( SG_GENERAL, SG_ALERT,
578 "Airport " << id << "does not appear to have parking information available");
582 int park_index = dcs->getNrOfParkings() - 1;
584 double radius = fgGetDouble("/sim/dimensions/radius-m");
585 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
586 double lat, lon, heading;
591 acData = globals->get_fg_home();
592 acData.append("aircraft-data");
593 string acfile = fgGetString("/sim/aircraft") + string(".xml");
594 acData.append(acfile);
596 readProperties(acData.str(), &root);
597 SGPropertyNode * node = root.getNode("sim");
598 fltType = node->getStringValue("aircraft-class", "NONE" );
599 acOperator = node->getStringValue("aircraft-operator", "NONE" );
600 } catch (const sg_exception &) {
601 SG_LOG(SG_GENERAL, SG_INFO,
602 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
604 // cout << path.str() << endl;
606 if (fltType.empty() || fltType == "NONE") {
607 SG_LOG(SG_GENERAL, SG_INFO,
608 "Aircraft type information not found in: " << acData.str() << ". Using default value");
609 fltType = fgGetString("/sim/aircraft-class" );
611 if (acOperator.empty() || fltType == "NONE") {
612 SG_LOG(SG_GENERAL, SG_INFO,
613 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
614 acOperator = fgGetString("/sim/aircraft-operator" );
617 cerr << "Running aircraft " << fltType << " of livery " << acOperator << endl;
618 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
619 succes = dcs->getAvailableParking(&lat, &lon, &heading, &park_index, radius, fltType, acType, acOperator);
621 fgGetString("/sim/presets/parkpos");
622 fgSetString("/sim/presets/parkpos", dcs->getParking(park_index)->getName());
624 SG_LOG( SG_GENERAL, SG_ALERT,
625 "Failed to find a suitable parking at airport " << id );
629 //cerr << "We shouldn't get here when AVAILABLE" << endl;
630 while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
631 if (park_index < 0) {
632 SG_LOG( SG_GENERAL, SG_ALERT,
633 "Failed to find parking position " << parkpos <<
634 " at airport " << id );
638 FGParking* parking = dcs->getParking(park_index);
639 parking->setAvailable(false);
641 SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
642 parking->getHeading());
647 // Set current_options lon/lat given an airport id and runway number
648 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
652 // set initial position from airport and runway number
653 SG_LOG( SG_GENERAL, SG_INFO,
654 "Attempting to set starting position for "
655 << id << ":" << rwy );
657 const FGAirport* apt = fgFindAirportID(id);
659 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
663 if (!apt->hasRunwayWithIdent(rwy)) {
664 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
665 "Failed to find runway " << rwy <<
666 " at airport " << id << ". Using default runway." );
670 FGRunway* r(apt->getRunwayByIdent(rwy));
671 fgSetString("/sim/atc/runway", r->ident().c_str());
672 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
673 fgApplyStartOffset(startPos, r->headingDeg());
678 static void fgSetDistOrAltFromGlideSlope() {
679 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
680 string apt_id = fgGetString("/sim/presets/airport-id");
681 double gs = fgGetDouble("/sim/presets/glideslope-deg")
682 * SG_DEGREES_TO_RADIANS ;
683 double od = fgGetDouble("/sim/presets/offset-distance-nm");
684 double alt = fgGetDouble("/sim/presets/altitude-ft");
686 double apt_elev = 0.0;
687 if ( ! apt_id.empty() ) {
688 apt_elev = fgGetAirportElev( apt_id );
689 if ( apt_elev < -9990.0 ) {
696 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
697 // set altitude from glideslope and offset-distance
698 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
699 alt = fabs(od*tan(gs)) + apt_elev;
700 fgSetDouble("/sim/presets/altitude-ft", alt);
701 fgSetBool("/sim/presets/onground", false);
702 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
704 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
705 // set offset-distance from glideslope and altitude
706 od = (alt - apt_elev) / tan(gs);
707 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
708 fgSetDouble("/sim/presets/offset-distance-nm", od);
709 fgSetBool("/sim/presets/onground", false);
710 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
712 } else if( fabs(gs) > 0.01 ) {
713 SG_LOG( SG_GENERAL, SG_ALERT,
714 "Glideslope given but not altitude or offset-distance." );
715 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
716 fgSetDouble("/sim/presets/glideslope-deg", 0);
717 fgSetBool("/sim/presets/onground", true);
722 // Set current_options lon/lat given an airport id and heading (degrees)
723 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
725 FGNavList::TypeFilter filter(type);
726 const nav_list_type navlist
727 = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
729 if (navlist.size() == 0 ) {
730 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
731 << id << ":" << freq );
735 if( navlist.size() > 1 ) {
737 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
738 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
739 // NDB stored in kHz, VOR stored in MHz * 100 :-P
740 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
741 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
742 buf << (*it)->ident() << " "
743 << setprecision(5) << (double)((*it)->get_freq() * factor) << " "
744 << (*it)->get_lat() << "/" << (*it)->get_lon()
748 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
752 FGNavRecord *nav = navlist[0];
753 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
757 // Set current_options lon/lat given an aircraft carrier id
758 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
760 // set initial position from runway and heading
764 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
765 double lon = geodPos.getLongitudeDeg();
766 double lat = geodPos.getLatitudeDeg();
767 double alt = geodPos.getElevationFt();
769 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
770 << carrier << " at lat = " << lat << ", lon = " << lon
771 << ", alt = " << alt << ", heading = " << heading);
773 fgSetDouble("/sim/presets/longitude-deg", lon);
774 fgSetDouble("/sim/presets/latitude-deg", lat);
775 fgSetDouble("/sim/presets/altitude-ft", alt);
776 fgSetDouble("/sim/presets/heading-deg", heading);
777 fgSetDouble("/position/longitude-deg", lon);
778 fgSetDouble("/position/latitude-deg", lat);
779 fgSetDouble("/position/altitude-ft", alt);
780 fgSetDouble("/orientation/heading-deg", heading);
782 fgSetString("/sim/presets/speed-set", "UVW");
783 fgSetDouble("/velocities/uBody-fps", uvw(0));
784 fgSetDouble("/velocities/vBody-fps", uvw(1));
785 fgSetDouble("/velocities/wBody-fps", uvw(2));
786 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
787 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
788 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
790 fgSetBool("/sim/presets/onground", true);
794 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
800 // Set current_options lon/lat given an airport id and heading (degrees)
801 static bool fgSetPosFromFix( const string& id )
803 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
804 FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
806 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
810 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
815 * Initialize vor/ndb/ils/fix list management and query systems (as
816 * well as simple airport db list)
821 SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
823 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
824 if (cache->isRebuildRequired()) {
829 SG_LOG(SG_GENERAL, SG_INFO, "rebuilding NavDataCache took:" << st.elapsedMSec());
832 FGTACANList *channellist = new FGTACANList;
833 globals->set_channellist( channellist );
835 SGPath path(globals->get_fg_root());
836 path.append( "Navaids/TACAN_freq.dat" );
837 flightgear::loadTacan(path, channellist);
842 // General house keeping initializations
843 bool fgInitGeneral() {
846 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
847 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
849 root = globals->get_fg_root();
850 if ( ! root.length() ) {
851 // No root path set? Then bail ...
852 SG_LOG( SG_GENERAL, SG_ALERT,
853 "Cannot continue without a path to the base package "
854 << "being defined." );
857 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
859 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
860 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
861 fgSetString("/sim/startup/browser-app", globals->get_browser());
863 simgear::Dir cwd(simgear::Dir::current());
864 SGPropertyNode *curr = fgGetNode("/sim", true);
865 curr->removeChild("fg-current", 0, false);
866 curr = curr->getChild("fg-current", 0, true);
867 curr->setStringValue(cwd.path().str());
868 curr->setAttribute(SGPropertyNode::WRITE, false);
870 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
871 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
875 // This is the top level init routine which calls all the other
876 // initialization routines. If you are adding a subsystem to flight
877 // gear, its initialization call should located in this routine.
878 // Returns non-zero if a problem encountered.
879 void fgCreateSubsystems() {
881 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
882 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
884 ////////////////////////////////////////////////////////////////////
885 // Initialize the sound subsystem.
886 ////////////////////////////////////////////////////////////////////
887 // Sound manager uses an own subsystem group "SOUND" which is the last
888 // to be updated in every loop.
889 // Sound manager is updated last so it can use the CPU while the GPU
890 // is processing the scenery (doubled the frame-rate for me) -EMH-
891 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
893 ////////////////////////////////////////////////////////////////////
894 // Initialize the event manager subsystem.
895 ////////////////////////////////////////////////////////////////////
897 globals->get_event_mgr()->init();
898 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
900 ////////////////////////////////////////////////////////////////////
901 // Initialize the property interpolator subsystem. Put into the INIT
902 // group because the "nasal" subsystem may need it at GENERAL take-down.
903 ////////////////////////////////////////////////////////////////////
904 globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
907 ////////////////////////////////////////////////////////////////////
908 // Add the FlightGear property utilities.
909 ////////////////////////////////////////////////////////////////////
910 globals->add_subsystem("properties", new FGProperties);
913 ////////////////////////////////////////////////////////////////////
914 // Add the performance monitoring system.
915 ////////////////////////////////////////////////////////////////////
916 globals->add_subsystem("performance-mon",
917 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
918 fgGetNode("/sim/performance-monitor", true)));
920 ////////////////////////////////////////////////////////////////////
921 // Initialize the material property subsystem.
922 ////////////////////////////////////////////////////////////////////
924 SGPath mpath( globals->get_fg_root() );
925 mpath.append( fgGetString("/sim/rendering/materials-file") );
926 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
927 globals->get_props()) ) {
928 SG_LOG( SG_GENERAL, SG_ALERT,
929 "Error loading materials file " << mpath.str() );
934 ////////////////////////////////////////////////////////////////////
935 // Initialize the scenery management subsystem.
936 ////////////////////////////////////////////////////////////////////
938 globals->get_scenery()->get_scene_graph()
939 ->addChild(simgear::Particles::getCommonRoot());
940 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
942 ////////////////////////////////////////////////////////////////////
943 // Initialize the flight model subsystem.
944 ////////////////////////////////////////////////////////////////////
946 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
948 ////////////////////////////////////////////////////////////////////
949 // Initialize the weather subsystem.
950 ////////////////////////////////////////////////////////////////////
952 // Initialize the weather modeling subsystem
953 globals->add_subsystem("environment", new FGEnvironmentMgr);
954 globals->add_subsystem("ephemeris", new Ephemeris);
956 ////////////////////////////////////////////////////////////////////
957 // Initialize the aircraft systems and instrumentation (before the
959 ////////////////////////////////////////////////////////////////////
961 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
962 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
964 ////////////////////////////////////////////////////////////////////
965 // Initialize the XML Autopilot subsystem.
966 ////////////////////////////////////////////////////////////////////
968 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
969 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
970 globals->add_subsystem( "route-manager", new FGRouteMgr );
972 ////////////////////////////////////////////////////////////////////
973 // Initialize the Input-Output subsystem
974 ////////////////////////////////////////////////////////////////////
975 globals->add_subsystem( "io", new FGIO );
977 ////////////////////////////////////////////////////////////////////
978 // Create and register the logger.
979 ////////////////////////////////////////////////////////////////////
981 globals->add_subsystem("logger", new FGLogger);
983 ////////////////////////////////////////////////////////////////////
984 // Create and register the XML GUI.
985 ////////////////////////////////////////////////////////////////////
987 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
989 //////////////////////////////////////////////////////////////////////
990 // Initialize the 2D cloud subsystem.
991 ////////////////////////////////////////////////////////////////////
992 fgGetBool("/sim/rendering/bump-mapping", false);
994 ////////////////////////////////////////////////////////////////////
995 // Initialize the canvas 2d drawing subsystem.
996 ////////////////////////////////////////////////////////////////////
997 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
998 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
1000 ////////////////////////////////////////////////////////////////////
1001 // Initialise the ATIS Manager
1002 // Note that this is old stuff, but is necessary for the
1003 // current ATIS implementation. Therefore, leave it in here
1004 // until the ATIS system is ported over to make use of the ATIS
1005 // sub system infrastructure.
1006 ////////////////////////////////////////////////////////////////////
1008 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
1010 ////////////////////////////////////////////////////////////////////
1011 // Initialize the ATC subsystem
1012 ////////////////////////////////////////////////////////////////////
1013 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
1015 ////////////////////////////////////////////////////////////////////
1016 // Initialize multiplayer subsystem
1017 ////////////////////////////////////////////////////////////////////
1019 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1021 ////////////////////////////////////////////////////////////////////
1022 // Initialise the AI Model Manager
1023 ////////////////////////////////////////////////////////////////////
1024 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
1025 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1026 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1029 // It's probably a good idea to initialize the top level traffic manager
1030 // After the AI and ATC systems have been initialized properly.
1031 // AI Traffic manager
1032 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1034 ////////////////////////////////////////////////////////////////////
1035 // Add a new 2D panel.
1036 ////////////////////////////////////////////////////////////////////
1038 fgSetArchivable("/sim/panel/visibility");
1039 fgSetArchivable("/sim/panel/x-offset");
1040 fgSetArchivable("/sim/panel/y-offset");
1041 fgSetArchivable("/sim/panel/jitter");
1043 ////////////////////////////////////////////////////////////////////
1044 // Initialize the controls subsystem.
1045 ////////////////////////////////////////////////////////////////////
1047 globals->get_controls()->init();
1048 globals->get_controls()->bind();
1051 ////////////////////////////////////////////////////////////////////
1052 // Initialize the input subsystem.
1053 ////////////////////////////////////////////////////////////////////
1055 globals->add_subsystem("input", new FGInput);
1058 ////////////////////////////////////////////////////////////////////
1059 // Initialize the replay subsystem
1060 ////////////////////////////////////////////////////////////////////
1061 globals->add_subsystem("replay", new FGReplay);
1063 #ifdef ENABLE_AUDIO_SUPPORT
1064 ////////////////////////////////////////////////////////////////////
1065 // Initialize the sound-effects subsystem.
1066 ////////////////////////////////////////////////////////////////////
1067 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1070 ////////////////////////////////////////////////////////////////////
1071 // Initialize the lighting subsystem.
1072 ////////////////////////////////////////////////////////////////////
1074 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1076 // ordering here is important : Nasal (via events), then models, then views
1077 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1079 FGAircraftModel* acm = new FGAircraftModel;
1080 globals->set_aircraft_model(acm);
1081 globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1083 FGModelMgr* mm = new FGModelMgr;
1084 globals->set_model_mgr(mm);
1085 globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1087 FGViewMgr *viewmgr = new FGViewMgr;
1088 globals->set_viewmgr( viewmgr );
1089 globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1091 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
1092 SGSubsystemMgr::DISPLAY);
1095 void fgPostInitSubsystems()
1100 ////////////////////////////////////////////////////////////////////////
1101 // Initialize the Nasal interpreter.
1102 // Do this last, so that the loaded scripts see initialized state
1103 ////////////////////////////////////////////////////////////////////////
1104 FGNasalSys* nasal = new FGNasalSys();
1105 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1107 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
1109 // initialize methods that depend on other subsystems.
1111 globals->get_subsystem_mgr()->postinit();
1112 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
1114 ////////////////////////////////////////////////////////////////////
1115 // TODO FIXME! UGLY KLUDGE!
1116 ////////////////////////////////////////////////////////////////////
1118 /* Scenarios require Nasal, so FGAIManager loads the scenarios,
1119 * including its models such as a/c carriers, in its 'postinit',
1120 * which is the very last thing we do.
1121 * fgInitPosition is called very early in main.cxx/fgIdleFunction,
1122 * one of the first things we do, long before scenarios/carriers are
1123 * loaded. => When requested "initial preset position" relates to a
1124 * carrier, recalculate the 'initial' position here (how have things
1125 * ever worked before this hack - this init sequence has always been
1127 std::string carrier = fgGetString("/sim/presets/carrier","");
1130 // clear preset location and re-trigger position setup
1131 fgSetDouble("/sim/presets/longitude-deg", 9999);
1132 fgSetDouble("/sim/presets/latitude-deg", 9999);
1133 flightgear::initPosition();
1137 ////////////////////////////////////////////////////////////////////////
1138 // End of subsystem initialization.
1139 ////////////////////////////////////////////////////////////////////
1141 fgSetBool("/sim/crashed", false);
1142 fgSetBool("/sim/initialized", true);
1144 SG_LOG( SG_GENERAL, SG_INFO, endl);
1146 // Save the initial state for future
1148 globals->saveInitialState();
1151 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1152 void fgReInitSubsystems()
1154 static const SGPropertyNode *master_freeze
1155 = fgGetNode("/sim/freeze/master");
1157 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1159 // setup state to begin re-init
1160 bool freeze = master_freeze->getBoolValue();
1162 fgSetBool("/sim/freeze/master", true);
1165 fgSetBool("/sim/signals/reinit", true);
1166 fgSetBool("/sim/crashed", false);
1168 // do actual re-init steps
1169 globals->get_subsystem("flight")->unbind();
1171 // reset control state, before restoring initial state; -set or config files
1172 // may specify values for flaps, trim tabs, magnetos, etc
1173 globals->get_controls()->reset_all();
1175 globals->restoreInitialState();
1177 // update our position based on current presets
1178 flightgear::initPosition();
1180 // Force reupdating the positions of the ai 3d models. They are used for
1181 // initializing ground level for the FDM.
1182 globals->get_subsystem("ai-model")->reinit();
1184 // Initialize the FDM
1185 globals->get_subsystem("flight")->reinit();
1187 // reset replay buffers
1188 globals->get_subsystem("replay")->reinit();
1190 // reload offsets from config defaults
1191 globals->get_viewmgr()->reinit();
1193 globals->get_subsystem("time")->reinit();
1195 // need to bind FDMshell again, since we manually unbound it above...
1196 globals->get_subsystem("flight")->bind();
1198 // setup state to end re-init
1199 fgSetBool("/sim/signals/reinit", false);
1201 fgSetBool("/sim/freeze/master", false);
1203 fgSetBool("/sim/sceneryloaded",false);
1207 ///////////////////////////////////////////////////////////////////////////////
1208 // helper object to implement the --show-aircraft command.
1209 // resides here so we can share the fgFindAircraftInDir template above,
1210 // and hence ensure this command lists exectly the same aircraft as the normal
1217 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1221 void show(const SGPath& path)
1223 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1225 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1226 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1227 cout << "Available aircraft:" << endl;
1228 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1229 cout << _aircraft[i] << endl;
1234 bool processAircraft(const SGPath& path)
1236 SGPropertyNode root;
1238 readProperties(path.str(), &root);
1239 } catch (sg_exception& ) {
1244 string descStr(" ");
1245 descStr += path.file();
1246 // trim common suffix from file names
1247 int nPos = descStr.rfind("-set.xml");
1248 if (nPos == (int)(descStr.size() - 8)) {
1249 descStr.resize(nPos);
1252 SGPropertyNode *node = root.getNode("sim");
1254 SGPropertyNode* desc = node->getNode("description");
1255 // if a status tag is found, read it in
1256 if (node->hasValue("status")) {
1257 maturity = getNumMaturity(node->getStringValue("status"));
1261 if (descStr.size() <= 27+3) {
1262 descStr.append(29+3-descStr.size(), ' ');
1265 descStr.append( 32, ' ');
1267 descStr += desc->getStringValue();
1269 } // of have 'sim' node
1271 if (maturity < _minStatus) {
1275 _aircraft.push_back(descStr);
1280 int getNumMaturity(const char * str)
1282 // changes should also be reflected in $FG_ROOT/data/options.xml &
1283 // $FG_ROOT/data/Translations/string-default.xml
1284 const char* levels[] = {"alpha","beta","early-production","production"};
1286 if (!strcmp(str, "all")) {
1290 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1291 if (strcmp(str,levels[i])==0)
1297 // recommended in Meyers, Effective STL when internationalization and embedded
1298 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1299 struct ciLessLibC : public std::binary_function<string, string, bool>
1301 bool operator()(const std::string &lhs, const std::string &rhs) const
1303 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1308 string_list _aircraft;
1311 void fgShowAircraft(const SGPath &path)
1317 cout << "Hit a key to continue..." << endl;