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.
28 #include <simgear/compiler.h>
32 #include <string.h> // strcmp()
34 #if defined(SG_WINDOWS)
35 # include <io.h> // isatty()
36 # include <process.h> // _getpid()
38 # define isatty _isatty
42 #include <boost/algorithm/string/compare.hpp>
43 #include <boost/algorithm/string/predicate.hpp>
45 #include <simgear/constants.h>
46 #include <simgear/debug/logstream.hxx>
47 #include <simgear/structure/exception.hxx>
48 #include <simgear/structure/event_mgr.hxx>
49 #include <simgear/structure/SGPerfMon.hxx>
50 #include <simgear/misc/sg_path.hxx>
51 #include <simgear/misc/sg_dir.hxx>
52 #include <simgear/misc/sgstream.hxx>
53 #include <simgear/misc/strutils.hxx>
54 #include <simgear/props/props_io.hxx>
56 #include <simgear/scene/material/matlib.hxx>
57 #include <simgear/scene/model/particles.hxx>
58 #include <simgear/scene/tsync/terrasync.hxx>
60 #include <Aircraft/controls.hxx>
61 #include <Aircraft/replay.hxx>
62 #include <Aircraft/FlightHistory.hxx>
63 #include <Airports/runways.hxx>
64 #include <Airports/airport.hxx>
65 #include <Airports/dynamics.hxx>
67 #include <AIModel/AIManager.hxx>
69 #include <ATCDCL/ATISmgr.hxx>
70 #include <ATC/atc_mgr.hxx>
72 #include <Autopilot/route_mgr.hxx>
73 #include <Autopilot/autopilotgroup.hxx>
75 #include <Cockpit/panel.hxx>
76 #include <Cockpit/panel_io.hxx>
78 #include <Canvas/canvas_mgr.hxx>
79 #include <Canvas/gui_mgr.hxx>
80 #include <GUI/new_gui.hxx>
81 #include <GUI/MessageBox.hxx>
82 #include <Input/input.hxx>
83 #include <Instrumentation/instrument_mgr.hxx>
84 #include <Model/acmodel.hxx>
85 #include <Model/modelmgr.hxx>
86 #include <AIModel/submodel.hxx>
87 #include <AIModel/AIManager.hxx>
88 #include <Navaids/navdb.hxx>
89 #include <Navaids/navlist.hxx>
90 #include <Scenery/scenery.hxx>
91 #include <Scenery/tilemgr.hxx>
92 #include <Scripting/NasalSys.hxx>
93 #include <Sound/voice.hxx>
94 #include <Sound/soundmanager.hxx>
95 #include <Systems/system_mgr.hxx>
96 #include <Time/light.hxx>
97 #include <Traffic/TrafficMgr.hxx>
98 #include <MultiPlayer/multiplaymgr.hxx>
99 #include <FDM/fdm_shell.hxx>
100 #include <Environment/ephemeris.hxx>
101 #include <Environment/environment_mgr.hxx>
102 #include <Viewer/renderer.hxx>
103 #include <Viewer/viewmgr.hxx>
104 #include <Navaids/NavDataCache.hxx>
105 #include <Instrumentation/HUD/HUD.hxx>
106 #include <Cockpit/cockpitDisplayManager.hxx>
107 #include <Network/HTTPClient.hxx>
108 #include <Network/fgcom.hxx>
110 #include "fg_init.hxx"
112 #include "fg_commands.hxx"
113 #include "fg_props.hxx"
114 #include "FGInterpolator.hxx"
115 #include "options.hxx"
116 #include "globals.hxx"
117 #include "logger.hxx"
119 #include "positioninit.hxx"
126 using namespace boost::algorithm;
129 // Return the current base package version
130 string fgBasePackageVersion() {
131 SGPath base_path( globals->get_fg_root() );
132 base_path.append("version");
133 if (!base_path.exists()) {
137 sg_gzifstream in( base_path.str() );
150 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
152 if (!dirPath.exists()) {
153 SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
158 simgear::Dir dir(dirPath);
159 simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
160 simgear::PathList::iterator p;
161 for (p = setFiles.begin(); p != setFiles.end(); ++p) {
162 // check file name ends with -set.xml
164 // if we found a -set.xml at this level, don't recurse any deeper
167 bool done = (obj->*pred)(*p);
171 } // of -set.xml iteration
177 simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
178 for (p = subdirs.begin(); p != subdirs.end(); ++p) {
179 if (p->file() == "CVS") {
183 if (fgFindAircraftInDir(*p, obj, pred)) {
186 } // of subdirs iteration
192 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
194 const string_list& paths(globals->get_aircraft_paths());
195 string_list::const_iterator it = paths.begin();
196 for (; it != paths.end(); ++it) {
197 bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
201 } // of aircraft paths iteration
203 // if we reach this point, search the default location (always last)
204 SGPath rootAircraft(globals->get_fg_root());
205 rootAircraft.append("Aircraft");
206 fgFindAircraftInDir(rootAircraft, obj, pred);
209 class FindAndCacheAircraft
212 FindAndCacheAircraft(SGPropertyNode* autoSave)
214 _cache = autoSave->getNode("sim/startup/path-cache", true);
219 std::string aircraft = fgGetString( "/sim/aircraft", "");
220 if (aircraft.empty()) {
221 flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
222 SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
226 _searchAircraft = aircraft + "-set.xml";
227 std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
228 if (!aircraftDir.empty()) {
229 // aircraft-dir was set, skip any searching at all, if it's valid
230 simgear::Dir acPath(aircraftDir);
231 SGPath setFile = acPath.file(_searchAircraft);
232 if (setFile.exists()) {
233 SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
236 readProperties(setFile.str(), globals->get_props());
237 } catch ( const sg_exception &e ) {
238 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
239 flightgear::fatalMessageBox("Error reading aircraft",
240 "An error occured reading the requested aircraft (" + aircraft + ")",
241 e.getFormattedMessage());
247 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft <<
248 "' not found in specified dir:" << aircraftDir);
249 flightgear::fatalMessageBox("Aircraft not found",
250 "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
257 // prepare cache for re-scan
258 SGPropertyNode *n = _cache->getNode("fg-root", true);
259 n->setStringValue(globals->get_fg_root().c_str());
260 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
261 n = _cache->getNode("fg-aircraft", true);
262 n->setStringValue(getAircraftPaths().c_str());
263 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
264 _cache->removeChildren("aircraft");
266 fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
269 if (_foundPath.str().empty()) {
270 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
271 flightgear::fatalMessageBox("Aircraft not found",
272 "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
277 SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
278 fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
279 if (!_foundPath.exists()) {
280 SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
285 readProperties(_foundPath.str(), globals->get_props());
286 } catch ( const sg_exception &e ) {
287 SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
288 flightgear::fatalMessageBox("Error reading aircraft",
289 "An error occured reading the requested aircraft (" + aircraft + ")",
290 e.getFormattedMessage());
298 SGPath getAircraftPaths() {
299 string_list pathList = globals->get_aircraft_paths();
300 SGPath aircraftPaths;
301 string_list::const_iterator it = pathList.begin();
302 if (it != pathList.end()) {
303 aircraftPaths.set(*it);
306 for (; it != pathList.end(); ++it) {
307 aircraftPaths.add(*it);
309 return aircraftPaths;
314 if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
315 return false; // cache mismatch
318 if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
319 return false; // cache mismatch
322 vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
323 for (unsigned int i = 0; i < cache.size(); i++) {
324 const char *name = cache[i]->getStringValue("file", "");
325 if (!boost::equals(_searchAircraft, name, is_iequal())) {
329 SGPath xml(cache[i]->getStringValue("path", ""));
337 } // of aircraft in cache iteration
342 bool checkAircraft(const SGPath& p)
347 if (!_cache->getChild("aircraft", i++, false))
351 SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
353 std::string fileName(p.file());
354 n = entry->getNode("file", true);
355 n->setStringValue(fileName);
356 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
358 n = entry->getNode("path", true);
359 n->setStringValue(p.dir());
360 n->setAttribute(SGPropertyNode::USERARCHIVE, true);
362 if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
370 std::string _searchAircraft;
372 SGPropertyNode* _cache;
376 static SGPath platformDefaultDataPath()
378 char *envp = ::getenv( "APPDATA" );
379 SGPath config( envp );
380 config.append( "flightgear.org" );
385 #include <CoreServices/CoreServices.h>
387 static SGPath platformDefaultDataPath()
390 OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
395 unsigned char path[1024];
396 if (FSRefMakePath(&ref, path, 1024) != noErr) {
401 appData.set((const char*) path);
402 appData.append("FlightGear");
406 static SGPath platformDefaultDataPath()
408 return SGPath::home() / ".fgfs";
414 SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
415 globals->set_fg_home(dataPath.c_str());
417 simgear::Dir fgHome(dataPath);
418 if (!fgHome.exists()) {
422 if (!fgHome.exists()) {
423 flightgear::fatalMessageBox("Problem setting up user data",
424 "Unable to create the user-data storage folder at: '"
425 + dataPath.str() + "'");
429 if (fgGetBool("/sim/fghome-readonly", false)) {
430 // user / config forced us into readonly mode, fine
431 SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
435 // write our PID, and check writeability
436 SGPath pidPath(dataPath, "fgfs.pid");
437 if (pidPath.exists()) {
438 SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
439 // set a marker property so terrasync/navcache don't try to write
440 // from secondary instances
441 fgSetBool("/sim/fghome-readonly", true);
447 #if defined(SG_WINDOWS)
448 size_t len = snprintf(buf, 16, "%d", _getpid());
450 HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE,
451 FILE_SHARE_READ, /* sharing */
452 NULL, /* security attributes */
453 CREATE_NEW, /* error if already exists */
454 FILE_FLAG_DELETE_ON_CLOSE,
455 NULL /* template */);
457 result = (f != INVALID_HANDLE_VALUE);
460 WriteFile(f, buf, len, &written, NULL /* overlapped */);
463 // POSIX, do open+unlink trick to the file is deleted on exit, even if we
465 size_t len = snprintf(buf, 16, "%d", getpid());
466 int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
468 ::write(fd, buf, len);
469 ::unlink(pidPath.c_str()); // delete file when app quits
473 fgSetBool("/sim/fghome-readonly", false);
476 flightgear::fatalMessageBox("File permissions problem",
477 "Can't write to user-data storage folder, check file permissions and FG_HOME.",
478 "User-data at:" + dataPath.str());
483 // Read in configuration (file and command line)
484 int fgInitConfig ( int argc, char **argv )
486 SGPath dataPath = globals->get_fg_home();
488 simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
489 if (!exportDir.exists()) {
490 exportDir.create(0777);
493 // Set /sim/fg-home and don't allow malign code to override it until
494 // Nasal security is set up. Use FG_HOME if necessary.
495 SGPropertyNode *home = fgGetNode("/sim", true);
496 home->removeChild("fg-home", 0, false);
497 home = home->getChild("fg-home", 0, true);
498 home->setStringValue(dataPath.c_str());
499 home->setAttribute(SGPropertyNode::WRITE, false);
501 flightgear::Options* options = flightgear::Options::sharedInstance();
502 options->init(argc, argv, dataPath);
503 bool loadDefaults = flightgear::Options::sharedInstance()->shouldLoadDefaultConfig();
505 // Read global preferences from $FG_ROOT/preferences.xml
506 SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
507 fgLoadProps("preferences.xml", globals->get_props());
508 SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
510 // do not load user settings when reset to default is requested, or if
511 // told to explicitly ignore
512 if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
514 SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
518 globals->loadUserSettings(dataPath);
521 SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
522 }// of no-default-config selected
524 // Scan user config files and command line for a specified aircraft.
525 options->initAircraft();
527 FindAndCacheAircraft f(globals->get_props());
528 if (!f.loadAircraft()) {
529 return flightgear::FG_OPTIONS_ERROR;
532 // parse options after loading aircraft to ensure any user
533 // overrides of defaults are honored.
534 return options->processOptions();
540 * Initialize vor/ndb/ils/fix list management and query systems (as
541 * well as simple airport db list)
542 * This is called multiple times in the case of a cache rebuild,
543 * to allow lengthy caching to take place in the background, without
544 * blocking the main/UI thread.
549 flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
550 static bool doingRebuild = false;
551 if (doingRebuild || cache->isRebuildRequired()) {
553 bool finished = cache->rebuild();
555 // sleep to give the rebuild thread more time
556 SGTimeStamp::sleepForMSec(50);
561 FGTACANList *channellist = new FGTACANList;
562 globals->set_channellist( channellist );
564 SGPath path(globals->get_fg_root());
565 path.append( "Navaids/TACAN_freq.dat" );
566 flightgear::loadTacan(path, channellist);
571 // General house keeping initializations
572 bool fgInitGeneral() {
575 SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
576 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
578 root = globals->get_fg_root();
579 if ( ! root.length() ) {
580 // No root path set? Then bail ...
581 SG_LOG( SG_GENERAL, SG_ALERT,
582 "Cannot continue without a path to the base package "
583 << "being defined." );
586 SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
588 // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
589 globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
590 fgSetString("/sim/startup/browser-app", globals->get_browser());
592 simgear::Dir cwd(simgear::Dir::current());
593 SGPropertyNode *curr = fgGetNode("/sim", true);
594 curr->removeChild("fg-current", 0, false);
595 curr = curr->getChild("fg-current", 0, true);
596 curr->setStringValue(cwd.path().str());
597 curr->setAttribute(SGPropertyNode::WRITE, false);
599 fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
600 fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
604 // Write various configuraton values out to the logs
605 void fgOutputSettings()
607 SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
608 SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
610 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
611 SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
612 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
614 SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
615 SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
618 // This is the top level init routine which calls all the other
619 // initialization routines. If you are adding a subsystem to flight
620 // gear, its initialization call should located in this routine.
621 // Returns non-zero if a problem encountered.
622 void fgCreateSubsystems() {
624 SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
625 SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
627 ////////////////////////////////////////////////////////////////////
628 // Initialize the sound subsystem.
629 ////////////////////////////////////////////////////////////////////
630 // Sound manager uses an own subsystem group "SOUND" which is the last
631 // to be updated in every loop.
632 // Sound manager is updated last so it can use the CPU while the GPU
633 // is processing the scenery (doubled the frame-rate for me) -EMH-
634 globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
636 ////////////////////////////////////////////////////////////////////
637 // Initialize the event manager subsystem.
638 ////////////////////////////////////////////////////////////////////
640 globals->get_event_mgr()->init();
641 globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
643 ////////////////////////////////////////////////////////////////////
644 // Initialize the property interpolator subsystem. Put into the INIT
645 // group because the "nasal" subsystem may need it at GENERAL take-down.
646 ////////////////////////////////////////////////////////////////////
647 FGInterpolator* interp = new FGInterpolator;
648 interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
649 globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
650 SGPropertyNode::setInterpolationMgr(interp);
652 ////////////////////////////////////////////////////////////////////
653 // Add the FlightGear property utilities.
654 ////////////////////////////////////////////////////////////////////
655 globals->add_subsystem("properties", new FGProperties);
658 ////////////////////////////////////////////////////////////////////
659 // Add the performance monitoring system.
660 ////////////////////////////////////////////////////////////////////
661 globals->add_subsystem("performance-mon",
662 new SGPerformanceMonitor(globals->get_subsystem_mgr(),
663 fgGetNode("/sim/performance-monitor", true)));
665 ////////////////////////////////////////////////////////////////////
666 // Initialize the material property subsystem.
667 ////////////////////////////////////////////////////////////////////
669 SGPath mpath( globals->get_fg_root() );
670 mpath.append( fgGetString("/sim/rendering/materials-file") );
671 if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
672 globals->get_props()) ) {
673 throw sg_io_exception("Error loading materials file", mpath);
676 globals->add_subsystem( "http", new FGHTTPClient );
678 ////////////////////////////////////////////////////////////////////
679 // Initialize the scenery management subsystem.
680 ////////////////////////////////////////////////////////////////////
682 globals->get_scenery()->get_scene_graph()
683 ->addChild(simgear::Particles::getCommonRoot());
684 simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
686 ////////////////////////////////////////////////////////////////////
687 // Initialize the flight model subsystem.
688 ////////////////////////////////////////////////////////////////////
690 globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
692 ////////////////////////////////////////////////////////////////////
693 // Initialize the weather subsystem.
694 ////////////////////////////////////////////////////////////////////
696 // Initialize the weather modeling subsystem
697 globals->add_subsystem("environment", new FGEnvironmentMgr);
698 globals->add_subsystem("ephemeris", new Ephemeris);
700 ////////////////////////////////////////////////////////////////////
701 // Initialize the aircraft systems and instrumentation (before the
703 ////////////////////////////////////////////////////////////////////
705 globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
706 globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
707 globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
708 globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
710 ////////////////////////////////////////////////////////////////////
711 // Initialize the XML Autopilot subsystem.
712 ////////////////////////////////////////////////////////////////////
714 globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
715 globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
716 globals->add_subsystem( "route-manager", new FGRouteMgr );
718 ////////////////////////////////////////////////////////////////////
719 // Initialize the Input-Output subsystem
720 ////////////////////////////////////////////////////////////////////
721 globals->add_subsystem( "io", new FGIO );
723 ////////////////////////////////////////////////////////////////////
724 // Create and register the logger.
725 ////////////////////////////////////////////////////////////////////
727 globals->add_subsystem("logger", new FGLogger);
729 ////////////////////////////////////////////////////////////////////
730 // Create and register the XML GUI.
731 ////////////////////////////////////////////////////////////////////
733 globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
735 //////////////////////////////////////////////////////////////////////
736 // Initialize the 2D cloud subsystem.
737 ////////////////////////////////////////////////////////////////////
738 fgGetBool("/sim/rendering/bump-mapping", false);
740 ////////////////////////////////////////////////////////////////////
741 // Initialize the canvas 2d drawing subsystem.
742 ////////////////////////////////////////////////////////////////////
743 globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
744 globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
746 ////////////////////////////////////////////////////////////////////
747 // Initialise the ATIS Manager
748 // Note that this is old stuff, but is necessary for the
749 // current ATIS implementation. Therefore, leave it in here
750 // until the ATIS system is ported over to make use of the ATIS
751 // sub system infrastructure.
752 ////////////////////////////////////////////////////////////////////
754 globals->add_subsystem("ATIS", new FGATISMgr, SGSubsystemMgr::INIT, 0.4);
756 ////////////////////////////////////////////////////////////////////
757 // Initialize the ATC subsystem
758 ////////////////////////////////////////////////////////////////////
759 globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
761 ////////////////////////////////////////////////////////////////////
762 // Initialize multiplayer subsystem
763 ////////////////////////////////////////////////////////////////////
765 globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
767 ////////////////////////////////////////////////////////////////////
768 // Initialise the AI Model Manager
769 ////////////////////////////////////////////////////////////////////
770 SG_LOG(SG_GENERAL, SG_INFO, " AI Model Manager");
771 globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
772 globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
775 // It's probably a good idea to initialize the top level traffic manager
776 // After the AI and ATC systems have been initialized properly.
777 // AI Traffic manager
778 globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
780 ////////////////////////////////////////////////////////////////////
781 // Add a new 2D panel.
782 ////////////////////////////////////////////////////////////////////
784 fgSetArchivable("/sim/panel/visibility");
785 fgSetArchivable("/sim/panel/x-offset");
786 fgSetArchivable("/sim/panel/y-offset");
787 fgSetArchivable("/sim/panel/jitter");
789 ////////////////////////////////////////////////////////////////////
790 // Initialize the controls subsystem.
791 ////////////////////////////////////////////////////////////////////
793 globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
795 ////////////////////////////////////////////////////////////////////
796 // Initialize the input subsystem.
797 ////////////////////////////////////////////////////////////////////
799 globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
802 ////////////////////////////////////////////////////////////////////
803 // Initialize the replay subsystem
804 ////////////////////////////////////////////////////////////////////
805 globals->add_subsystem("replay", new FGReplay);
806 globals->add_subsystem("history", new FGFlightHistory);
808 #ifdef ENABLE_AUDIO_SUPPORT
809 ////////////////////////////////////////////////////////////////////
810 // Initialize the sound-effects subsystem.
811 ////////////////////////////////////////////////////////////////////
812 globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
816 ////////////////////////////////////////////////////////////////////
817 // Initialize the FGCom subsystem.
818 ////////////////////////////////////////////////////////////////////
819 globals->add_subsystem("fgcom", new FGCom);
822 ////////////////////////////////////////////////////////////////////
823 // Initialize the lighting subsystem.
824 ////////////////////////////////////////////////////////////////////
826 globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
828 // ordering here is important : Nasal (via events), then models, then views
829 globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
831 globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
832 globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
834 globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
836 globals->add_subsystem("tile-manager", globals->get_tile_mgr(),
837 SGSubsystemMgr::DISPLAY);
840 void fgPostInitSubsystems()
845 ////////////////////////////////////////////////////////////////////////
846 // Initialize the Nasal interpreter.
847 // Do this last, so that the loaded scripts see initialized state
848 ////////////////////////////////////////////////////////////////////////
849 FGNasalSys* nasal = new FGNasalSys();
850 globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
852 SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
854 // Ensure IOrules and path validation are working properly by trying to
855 // access a folder/file which should never be accessible.
856 const char* no_access_path =
862 if( fgValidatePath(no_access_path, true) )
867 "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
869 if( fgValidatePath(no_access_path, false) )
874 "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
877 // initialize methods that depend on other subsystems.
879 globals->get_subsystem_mgr()->postinit();
880 SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
882 ////////////////////////////////////////////////////////////////////////
883 // End of subsystem initialization.
884 ////////////////////////////////////////////////////////////////////
886 fgSetBool("/sim/crashed", false);
887 fgSetBool("/sim/initialized", true);
889 SG_LOG( SG_GENERAL, SG_INFO, endl);
891 // Save the initial state for future
893 globals->saveInitialState();
896 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
897 void fgReInitSubsystems()
899 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
901 SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
903 // setup state to begin re-init
904 bool freeze = master_freeze->getBoolValue();
906 master_freeze->setBoolValue(true);
909 fgSetBool("/sim/signals/reinit", true);
910 fgSetBool("/sim/crashed", false);
912 // do actual re-init steps
913 globals->get_subsystem("flight")->unbind();
915 // reset control state, before restoring initial state; -set or config files
916 // may specify values for flaps, trim tabs, magnetos, etc
917 globals->get_controls()->reset_all();
919 globals->restoreInitialState();
921 // update our position based on current presets
922 // this will mark position as needed finalized which we'll do in the
924 flightgear::initPosition();
926 simgear::SGTerraSync* terraSync =
927 static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
929 terraSync->reposition();
932 // Force reupdating the positions of the ai 3d models. They are used for
933 // initializing ground level for the FDM.
934 globals->get_subsystem("ai-model")->reinit();
936 // Initialize the FDM
937 globals->get_subsystem("flight")->reinit();
939 // reset replay buffers
940 globals->get_subsystem("replay")->reinit();
942 // reload offsets from config defaults
943 globals->get_viewmgr()->reinit();
945 // ugly: finalizePosition waits for METAR to arrive for the new airport.
946 // we don't re-init the environment manager here, since historically we did
947 // not, and doing so seems to have other issues. All that's needed is to
948 // schedule METAR fetch immediately, so it's available for finalizePosition.
949 // So we manually extract the METAR-fetching component inside the environment
950 // manager, and re-init that.
951 SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
953 envMgr->get_subsystem("realwx")->reinit();
956 globals->get_subsystem("time")->reinit();
958 // need to bind FDMshell again, since we manually unbound it above...
959 globals->get_subsystem("flight")->bind();
961 // need to reset aircraft (systems/instruments) so they can adapt to current environment
962 globals->get_subsystem("systems")->reinit();
963 globals->get_subsystem("instrumentation")->reinit();
965 globals->get_subsystem("ATIS")->reinit();
967 // setup state to end re-init
968 fgSetBool("/sim/signals/reinit", false);
970 master_freeze->setBoolValue(false);
972 fgSetBool("/sim/sceneryloaded",false);
976 ///////////////////////////////////////////////////////////////////////////////
977 // helper object to implement the --show-aircraft command.
978 // resides here so we can share the fgFindAircraftInDir template above,
979 // and hence ensure this command lists exectly the same aircraft as the normal
986 _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
990 void show(const SGPath& path)
992 fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
994 simgear::requestConsole(); // ensure console is shown on Windows
996 std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
997 cout << "Available aircraft:" << endl;
998 for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
999 cout << _aircraft[i] << endl;
1004 bool processAircraft(const SGPath& path)
1006 SGPropertyNode root;
1008 readProperties(path.str(), &root);
1009 } catch (sg_exception& ) {
1014 string descStr(" ");
1015 descStr += path.file();
1016 // trim common suffix from file names
1017 int nPos = descStr.rfind("-set.xml");
1018 if (nPos == (int)(descStr.size() - 8)) {
1019 descStr.resize(nPos);
1022 SGPropertyNode *node = root.getNode("sim");
1024 SGPropertyNode* desc = node->getNode("description");
1025 // if a status tag is found, read it in
1026 if (node->hasValue("status")) {
1027 maturity = getNumMaturity(node->getStringValue("status"));
1031 if (descStr.size() <= 27+3) {
1032 descStr.append(29+3-descStr.size(), ' ');
1035 descStr.append( 32, ' ');
1037 descStr += desc->getStringValue();
1039 } // of have 'sim' node
1041 if (maturity < _minStatus) {
1045 _aircraft.push_back(descStr);
1050 int getNumMaturity(const char * str)
1052 // changes should also be reflected in $FG_ROOT/data/options.xml &
1053 // $FG_ROOT/data/Translations/string-default.xml
1054 const char* levels[] = {"alpha","beta","early-production","production"};
1056 if (!strcmp(str, "all")) {
1060 for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
1061 if (strcmp(str,levels[i])==0)
1067 // recommended in Meyers, Effective STL when internationalization and embedded
1068 // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
1069 struct ciLessLibC : public std::binary_function<string, string, bool>
1071 bool operator()(const std::string &lhs, const std::string &rhs) const
1073 return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1078 string_list _aircraft;
1081 void fgShowAircraft(const SGPath &path)
1087 cout << "Hit a key to continue..." << endl;