1 // globals.cxx -- Global state that needs to be shared among the sim modules
3 // Written by Curtis Olson, started July 2000.
5 // Copyright (C) 2000 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 Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <boost/foreach.hpp>
30 #include <osgViewer/Viewer>
31 #include <osgDB/Registry>
33 #include <simgear/structure/commands.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/misc/sg_dir.hxx>
36 #include <simgear/timing/sg_time.hxx>
37 #include <simgear/ephemeris/ephemeris.hxx>
38 #include <simgear/scene/material/matlib.hxx>
39 #include <simgear/structure/subsystem_mgr.hxx>
40 #include <simgear/structure/event_mgr.hxx>
41 #include <simgear/sound/soundmgr_openal.hxx>
42 #include <simgear/misc/ResourceManager.hxx>
43 #include <simgear/props/propertyObject.hxx>
44 #include <simgear/props/props_io.hxx>
45 #include <simgear/scene/model/modellib.hxx>
46 #include <simgear/package/Root.hxx>
48 #include <Aircraft/controls.hxx>
49 #include <Airports/runways.hxx>
50 #include <Autopilot/route_mgr.hxx>
51 #include <GUI/FGFontCache.hxx>
53 #include <Scenery/scenery.hxx>
54 #include <Scenery/tilemgr.hxx>
55 #include <Navaids/navlist.hxx>
56 #include <Viewer/renderer.hxx>
57 #include <Viewer/viewmgr.hxx>
58 #include <Sound/sample_queue.hxx>
60 #include "globals.hxx"
63 #include "fg_props.hxx"
66 class AircraftResourceProvider : public simgear::ResourceProvider
69 AircraftResourceProvider() :
70 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
74 virtual SGPath resolve(const std::string& aResource, SGPath&) const
76 string_list pieces(sgPathBranchSplit(aResource));
77 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
78 return SGPath(); // not an Aircraft path
81 // test against the aircraft-dir property
82 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
83 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
84 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
85 // disable this warning for release builds
86 #if defined(ENABLE_DEV_WARNINGS)
88 for (unsigned int i=2; i<pieces.size(); ++i) {
89 betterPath.append(pieces[i]);
91 SG_LOG(SG_AIRCRAFT, SG_WARN, "resolved path:" << aResource << " using /sim/aircraft-dir.\n"
92 "This is legacy behaviour, change to an aircraft relative path:" << betterPath);
95 // current aircraft-dir matches resource aircraft
96 SGPath r(aircraftDir);
97 for (unsigned int i=2; i<pieces.size(); ++i) {
104 // Stop here, otherwise we could end up returning a resource that
105 // belongs to an unrelated version of the same aircraft (from a
106 // different aircraft directory).
111 // try each aircraft dir in turn
112 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
113 const string_list& dirs(globals->get_aircraft_paths());
114 string_list::const_iterator it = dirs.begin();
115 for (; it != dirs.end(); ++it) {
120 } // of aircraft path iteration
122 return SGPath(); // not found
126 class CurrentAircraftDirProvider : public simgear::ResourceProvider
129 CurrentAircraftDirProvider() :
130 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
134 virtual SGPath resolve(const std::string& aResource, SGPath&) const
136 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
137 SGPath p(aircraftDir);
139 return p.exists() ? p : SGPath();
143 ////////////////////////////////////////////////////////////////////////
144 // Implementation of FGGlobals.
145 ////////////////////////////////////////////////////////////////////////
148 FGGlobals *globals = NULL;
152 FGGlobals::FGGlobals() :
153 renderer( new FGRenderer ),
154 subsystem_mgr( new SGSubsystemMgr ),
155 event_mgr( new SGEventMgr ),
161 commands( SGCommandMgr::instance() ),
162 channel_options_list( NULL ),
163 initial_waypoints( NULL ),
164 fontcache ( new FGFontCache ),
166 haveUserSettings(false),
169 SGPropertyNode* root = new SGPropertyNode;
170 props = SGPropertyNode_ptr(root);
171 locale = new FGLocale(props);
173 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
174 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
178 void FGGlobals::initProperties()
180 simgear::PropertyObjectBase::setDefaultRoot(props);
182 positionLon = props->getNode("position/longitude-deg", true);
183 positionLat = props->getNode("position/latitude-deg", true);
184 positionAlt = props->getNode("position/altitude-ft", true);
186 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
187 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
188 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
190 orientPitch = props->getNode("orientation/pitch-deg", true);
191 orientHeading = props->getNode("orientation/heading-deg", true);
192 orientRoll = props->getNode("orientation/roll-deg", true);
197 FGGlobals::~FGGlobals()
199 // save user settings (unless already saved)
202 // stop OSG threading first, to avoid thread races while we tear down
203 // scene-graph pieces
205 osg::ref_ptr<osgViewer::Viewer> vw(renderer->getViewer());
207 // https://code.google.com/p/flightgear-bugs/issues/detail?id=1291
208 // explicitly stop trheading before we delete the renderer or
209 // viewMgr (which ultimately holds refs to the CameraGroup, and
215 // The AIModels manager performs a number of actions upon
216 // Shutdown that implicitly assume that other subsystems
217 // are still operational (Due to the dynamic allocation and
218 // deallocation of AIModel objects. To ensure we can safely
219 // shut down all subsystems, make sure we take down the
220 // AIModels system first.
221 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
223 subsystem_mgr->remove("ai-model");
225 ai.clear(); // ensure AI is deleted now, not at end of this method
229 subsystem_mgr->shutdown();
230 subsystem_mgr->unbind();
232 subsystem_mgr->remove(FGTileMgr::subsystemName());
233 // don't cancel the pager until after shutdown, since AIModels (and
234 // potentially others) can queue delete requests on the pager.
235 if (vw && vw->getDatabasePager()) {
236 vw->getDatabasePager()->cancel();
237 vw->getDatabasePager()->clear();
240 osgDB::Registry::instance()->clearObjectCache();
241 subsystem_mgr->remove(FGScenery::subsystemName());
243 // renderer touches subsystems during its destruction
245 _chatter_queue.clear();
247 delete subsystem_mgr;
248 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
249 vw = 0; // don't delete the viewer until now
254 delete channel_options_list;
255 delete initial_waypoints;
259 simgear::PropertyObjectBase::setDefaultRoot(NULL);
260 simgear::SGModelLib::resetPropertyRoot();
272 // set the fg_root path
273 void FGGlobals::set_fg_root (const std::string &root) {
275 fg_root = tmp.realpath();
277 // append /data to root if it exists
278 tmp.append( "data" );
279 tmp.append( "version" );
280 if ( tmp.exists() ) {
281 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
283 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
284 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
285 << fg_root << "'\n***\n***");
288 // deliberately not a tied property, for fgValidatePath security
289 // write-protect to avoid accidents
290 SGPropertyNode *n = fgGetNode("/sim", true);
291 n->removeChild("fg-root", 0);
292 n = n->getChild("fg-root", 0, true);
293 n->setStringValue(fg_root.c_str());
294 n->setAttribute(SGPropertyNode::WRITE, false);
296 simgear::ResourceManager::instance()->addBasePath(fg_root,
297 simgear::ResourceManager::PRIORITY_DEFAULT);
300 // set the fg_home path
301 void FGGlobals::set_fg_home (const std::string &home) {
303 fg_home = tmp.realpath();
306 PathList FGGlobals::get_data_paths() const
308 PathList r(additional_data_paths);
309 r.push_back(SGPath(fg_root));
313 PathList FGGlobals::get_data_paths(const std::string& suffix) const
316 BOOST_FOREACH(SGPath p, get_data_paths()) {
326 void FGGlobals::append_data_path(const SGPath& path)
328 if (!path.exists()) {
329 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
332 additional_data_paths.push_back(path);
335 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
337 BOOST_FOREACH(SGPath p, additional_data_paths) {
338 p.append(pathSuffix);
344 SGPath rootPath(fg_root);
345 rootPath.append(pathSuffix);
346 if (rootPath.exists()) {
350 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
354 void FGGlobals::append_fg_scenery (const std::string &paths, bool secure)
356 SGPropertyNode* sim = fgGetNode("/sim", true);
358 // find first unused fg-scenery property in /sim
360 while (sim->getChild("fg-scenery", propIndex) != NULL) {
364 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
365 SGPath abspath(path.realpath());
366 if (!abspath.exists()) {
367 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
371 // check for duplicates
372 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
373 if (ex != fg_scenery.end()) {
374 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
378 simgear::Dir dir(abspath);
379 SGPath terrainDir(dir.file("Terrain"));
380 SGPath objectsDir(dir.file("Objects"));
382 // this code used to add *either* the base dir, OR add the
383 // Terrain and Objects subdirs, but the conditional logic was commented
384 // out, such that all three dirs are added. Unfortunately there's
385 // no information as to why the change was made.
386 fg_scenery.push_back(abspath.str());
388 secure_fg_scenery.push_back(abspath.str());
391 if (terrainDir.exists()) {
392 fg_scenery.push_back(terrainDir.str());
395 if (objectsDir.exists()) {
396 fg_scenery.push_back(objectsDir.str());
399 // insert a marker for FGTileEntry::load(), so that
400 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
401 // "B/Terrain", "B/Objects", ""]
402 fg_scenery.push_back("");
404 // make scenery dirs available to Nasal
405 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
406 n->setStringValue(abspath.str());
407 n->setAttribute(SGPropertyNode::WRITE, false);
409 // temporary fix so these values survive reset
410 n->setAttribute(SGPropertyNode::PRESERVE, true);
411 } // of path list iteration
414 void FGGlobals::clear_fg_scenery()
417 secure_fg_scenery.clear();
418 fgGetNode("/sim", true)->removeChildren("fg-scenery");
422 void FGGlobals::set_catalog_aircraft_path(const SGPath& path)
424 catalog_aircraft_dir = path;
427 string_list FGGlobals::get_aircraft_paths() const
430 if (!catalog_aircraft_dir.isNull()) {
431 r.push_back(catalog_aircraft_dir.str());
434 r.insert(r.end(), fg_aircraft_dirs.begin(), fg_aircraft_dirs.end());
438 void FGGlobals::append_aircraft_path(const std::string& path)
440 SGPath dirPath(path);
441 if (!dirPath.exists()) {
442 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft path not found:" << path);
446 SGPath acSubdir(dirPath);
447 acSubdir.append("Aircraft");
448 if (acSubdir.exists()) {
452 "Specified an aircraft-dir with an 'Aircraft' subdirectory:" << dirPath
453 << ", will instead use child directory:" << acSubdir
458 std::string abspath = dirPath.realpath();
459 fg_aircraft_dirs.push_back(abspath);
462 void FGGlobals::append_aircraft_paths(const std::string& path)
464 string_list paths = sgPathSplit(path);
465 for (unsigned int p = 0; p<paths.size(); ++p) {
466 append_aircraft_path(paths[p]);
470 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
472 return simgear::ResourceManager::instance()->findPath(branch);
475 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
477 return simgear::ResourceManager::instance()->findPath(branch);
480 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
482 return simgear::ResourceManager::instance()
483 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
487 FGGlobals::get_renderer () const
492 void FGGlobals::set_renderer(FGRenderer *render)
494 if (render == renderer) {
503 FGGlobals::get_subsystem_mgr () const
505 return subsystem_mgr;
509 FGGlobals::get_subsystem (const char * name) const
511 if (!subsystem_mgr) {
515 return subsystem_mgr->get_subsystem(name);
519 FGGlobals::add_subsystem (const char * name,
520 SGSubsystem * subsystem,
521 SGSubsystemMgr::GroupType type,
524 subsystem_mgr->add(name, subsystem, type, min_time_sec);
528 FGGlobals::get_soundmgr () const
530 return get_subsystem<SGSoundMgr>();
534 FGGlobals::get_event_mgr () const
540 FGGlobals::get_aircraft_position() const
542 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
543 positionLat->getDoubleValue(),
544 positionAlt->getDoubleValue());
548 FGGlobals::get_aircraft_position_cart() const
550 return SGVec3d::fromGeod(get_aircraft_position());
553 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
555 heading = orientHeading->getDoubleValue();
556 pitch = orientPitch->getDoubleValue();
557 roll = orientRoll->getDoubleValue();
561 FGGlobals::get_view_position() const
563 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
564 viewLat->getDoubleValue(),
565 viewAlt->getDoubleValue());
569 FGGlobals::get_view_position_cart() const
571 return SGVec3d::fromGeod(get_view_position());
574 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
576 for (int i=0; i<nd->nChildren(); ++i) {
577 SGPropertyNode* cp = nd->getChild(i);
578 if (SGReferenced::count(cp) > 1) {
579 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
582 treeDumpRefCounts(depth + 1, cp);
586 static void treeClearAliases(SGPropertyNode* nd)
592 for (int i=0; i<nd->nChildren(); ++i) {
593 SGPropertyNode* cp = nd->getChild(i);
594 treeClearAliases(cp);
599 FGGlobals::resetPropertyRoot()
605 // we don't strictly need to clear these (they will be reset when we
606 // initProperties again), but trying to reduce false-positives when dumping
615 orientHeading.clear();
618 // clear aliases so ref-counts are accurate when dumped
619 treeClearAliases(props);
621 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
622 treeDumpRefCounts(0, props);
624 //BaseStackSnapshot::dumpAll(std::cout);
626 props = new SGPropertyNode;
628 locale = new FGLocale(props);
630 // remove /sim/fg-root before writing to prevent hijacking
631 SGPropertyNode *n = props->getNode("/sim", true);
632 n->removeChild("fg-root", 0);
633 n = n->getChild("fg-root", 0, true);
634 n->setStringValue(fg_root.c_str());
635 n->setAttribute(SGPropertyNode::WRITE, false);
638 static std::string autosaveName()
640 std::ostringstream os;
641 string_list versionParts = simgear::strutils::split(VERSION, ".");
642 if (versionParts.size() < 2) {
643 return "autosave.xml";
646 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
650 // Load user settings from autosave.xml
652 FGGlobals::loadUserSettings(const SGPath& dataPath)
654 // remember that we have (tried) to load any existing autsave.xml
655 haveUserSettings = true;
657 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
658 SGPropertyNode autosave;
659 if (autosaveFile.exists()) {
660 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
662 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
663 } catch (sg_exception& e) {
664 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
665 << "(from " << e.getOrigin() << ")");
668 copyProperties(&autosave, globals->get_props());
671 // Save user settings in autosave.xml
673 FGGlobals::saveUserSettings()
675 // only save settings when we have (tried) to load the previous
676 // settings (otherwise user data was lost)
677 if (!haveUserSettings)
680 if (fgGetBool("/sim/startup/save-on-exit")) {
681 // don't save settings more than once on shutdown
682 haveUserSettings = false;
684 SGPath autosaveFile(globals->get_fg_home());
685 autosaveFile.append(autosaveName());
686 autosaveFile.create_dir( 0700 );
687 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
689 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
690 } catch (const sg_exception &e) {
691 guiErrorMessage("Error writing autosave:", e);
693 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
697 long int FGGlobals::get_warp() const
699 return fgGetInt("/sim/time/warp");
702 void FGGlobals::set_warp( long int w )
704 fgSetInt("/sim/time/warp", w);
707 long int FGGlobals::get_warp_delta() const
709 return fgGetInt("/sim/time/warp-delta");
712 void FGGlobals::set_warp_delta( long int d )
714 fgSetInt("/sim/time/warp-delta", d);
717 FGScenery* FGGlobals::get_scenery () const
719 return get_subsystem<FGScenery>();
722 FGTileMgr* FGGlobals::get_tile_mgr () const
724 return get_subsystem<FGTileMgr>();
727 FGViewMgr *FGGlobals::get_viewmgr() const
729 return get_subsystem<FGViewMgr>();
732 FGViewer* FGGlobals::get_current_view () const
734 FGViewMgr* vm = get_viewmgr();
735 return vm ? vm->get_current_view() : 0;
738 void FGGlobals::set_matlib( SGMaterialLib *m )
743 FGControls *FGGlobals::get_controls() const
745 return get_subsystem<FGControls>();
748 FGSampleQueue* FGGlobals::get_chatter_queue() const
750 return _chatter_queue;
753 void FGGlobals::set_chatter_queue(FGSampleQueue* queue)
755 _chatter_queue = queue;
758 void FGGlobals::addListenerToCleanup(SGPropertyChangeListener* l)
760 _listeners_to_cleanup.push_back(l);
763 void FGGlobals::cleanupListeners()
765 SGPropertyChangeListenerVec::iterator i = _listeners_to_cleanup.begin();
766 for (; i != _listeners_to_cleanup.end(); ++i) {
769 _listeners_to_cleanup.clear();
772 simgear::pkg::Root* FGGlobals::packageRoot()
774 return _packageRoot.get();
777 void FGGlobals::setPackageRoot(const SGSharedPtr<simgear::pkg::Root>& p)
782 // end of globals.cxx