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>
47 #include <Aircraft/controls.hxx>
48 #include <Airports/runways.hxx>
49 #include <Autopilot/route_mgr.hxx>
50 #include <GUI/FGFontCache.hxx>
52 #include <MultiPlayer/multiplaymgr.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 // current aircraft-dir matches resource aircraft
86 SGPath r(aircraftDir);
87 for (unsigned int i=2; i<pieces.size(); ++i) {
96 // try each aircraft dir in turn
97 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
98 const string_list& dirs(globals->get_aircraft_paths());
99 string_list::const_iterator it = dirs.begin();
100 for (; it != dirs.end(); ++it) {
105 } // of aircraft path iteration
107 return SGPath(); // not found
111 class CurrentAircraftDirProvider : public simgear::ResourceProvider
114 CurrentAircraftDirProvider() :
115 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
119 virtual SGPath resolve(const std::string& aResource, SGPath&) const
121 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
122 SGPath p(aircraftDir);
124 return p.exists() ? p : SGPath();
128 ////////////////////////////////////////////////////////////////////////
129 // Implementation of FGGlobals.
130 ////////////////////////////////////////////////////////////////////////
133 FGGlobals *globals = NULL;
137 FGGlobals::FGGlobals() :
138 renderer( new FGRenderer ),
139 subsystem_mgr( new SGSubsystemMgr ),
140 event_mgr( new SGEventMgr ),
149 commands( SGCommandMgr::instance() ),
150 channel_options_list( NULL ),
151 initial_waypoints( NULL ),
152 fontcache ( new FGFontCache ),
154 haveUserSettings(false),
157 SGPropertyNode* root = new SGPropertyNode;
158 props = SGPropertyNode_ptr(root);
159 locale = new FGLocale(props);
161 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
162 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
166 void FGGlobals::initProperties()
168 simgear::PropertyObjectBase::setDefaultRoot(props);
170 positionLon = props->getNode("position/longitude-deg", true);
171 positionLat = props->getNode("position/latitude-deg", true);
172 positionAlt = props->getNode("position/altitude-ft", true);
174 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
175 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
176 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
178 orientPitch = props->getNode("orientation/pitch-deg", true);
179 orientHeading = props->getNode("orientation/heading-deg", true);
180 orientRoll = props->getNode("orientation/roll-deg", true);
185 FGGlobals::~FGGlobals()
187 // save user settings (unless already saved)
190 // The AIModels manager performs a number of actions upon
191 // Shutdown that implicitly assume that other subsystems
192 // are still operational (Due to the dynamic allocation and
193 // deallocation of AIModel objects. To ensure we can safely
194 // shut down all subsystems, make sure we take down the
195 // AIModels system first.
196 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
198 subsystem_mgr->remove("ai-model");
200 ai.clear(); // ensure AI is deleted now, not at end of this method
203 subsystem_mgr->shutdown();
204 subsystem_mgr->unbind();
206 subsystem_mgr->remove("aircraft-model");
207 subsystem_mgr->remove("tile-manager");
208 subsystem_mgr->remove("model-manager");
211 osg::ref_ptr<osgViewer::Viewer> vw(renderer->getViewer());
213 // https://code.google.com/p/flightgear-bugs/issues/detail?id=1291
214 // explicitly stop trheading before we delete the renderer or
215 // viewMgr (which ultimately holds refs to the CameraGroup, and
220 // don't cancel the pager until after shutdown, since AIModels (and
221 // potentially others) can queue delete requests on the pager.
222 if (vw && vw->getDatabasePager()) {
223 vw->getDatabasePager()->cancel();
224 vw->getDatabasePager()->clear();
227 osgDB::Registry::instance()->clearObjectCache();
229 // renderer touches subsystems during its destruction
232 _chatter_queue.clear();
234 delete subsystem_mgr;
235 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
236 vw = 0; // don't delete the viewer until now
241 delete channel_options_list;
242 delete initial_waypoints;
246 simgear::PropertyObjectBase::setDefaultRoot(NULL);
247 simgear::SGModelLib::resetPropertyRoot();
259 // set the fg_root path
260 void FGGlobals::set_fg_root (const std::string &root) {
262 fg_root = tmp.realpath();
264 // append /data to root if it exists
265 tmp.append( "data" );
266 tmp.append( "version" );
267 if ( tmp.exists() ) {
268 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
270 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
271 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
272 << fg_root << "'\n***\n***");
275 // remove /sim/fg-root before writing to prevent hijacking
276 SGPropertyNode *n = fgGetNode("/sim", true);
277 n->removeChild("fg-root", 0);
278 n = n->getChild("fg-root", 0, true);
279 n->setStringValue(fg_root.c_str());
280 n->setAttribute(SGPropertyNode::WRITE, false);
282 simgear::ResourceManager::instance()->addBasePath(fg_root,
283 simgear::ResourceManager::PRIORITY_DEFAULT);
286 // set the fg_home path
287 void FGGlobals::set_fg_home (const std::string &home) {
289 fg_home = tmp.realpath();
292 PathList FGGlobals::get_data_paths() const
294 PathList r(additional_data_paths);
295 r.push_back(SGPath(fg_root));
299 PathList FGGlobals::get_data_paths(const std::string& suffix) const
302 BOOST_FOREACH(SGPath p, get_data_paths()) {
312 void FGGlobals::append_data_path(const SGPath& path)
314 if (!path.exists()) {
315 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
318 additional_data_paths.push_back(path);
321 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
323 BOOST_FOREACH(SGPath p, additional_data_paths) {
324 p.append(pathSuffix);
330 SGPath rootPath(fg_root);
331 rootPath.append(pathSuffix);
332 if (rootPath.exists()) {
336 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
340 void FGGlobals::append_fg_scenery (const std::string &paths)
342 SGPropertyNode* sim = fgGetNode("/sim", true);
344 // find first unused fg-scenery property in /sim
346 while (sim->getChild("fg-scenery", propIndex) != NULL) {
350 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
351 SGPath abspath(path.realpath());
352 if (!abspath.exists()) {
353 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
357 // check for duplicates
358 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
359 if (ex != fg_scenery.end()) {
360 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
364 simgear::Dir dir(abspath);
365 SGPath terrainDir(dir.file("Terrain"));
366 SGPath objectsDir(dir.file("Objects"));
368 // this code used to add *either* the base dir, OR add the
369 // Terrain and Objects subdirs, but the conditional logic was commented
370 // out, such that all three dirs are added. Unfortunately there's
371 // no information as to why the change was made.
372 fg_scenery.push_back(abspath.str());
374 if (terrainDir.exists()) {
375 fg_scenery.push_back(terrainDir.str());
378 if (objectsDir.exists()) {
379 fg_scenery.push_back(objectsDir.str());
382 // insert a marker for FGTileEntry::load(), so that
383 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
384 // "B/Terrain", "B/Objects", ""]
385 fg_scenery.push_back("");
387 // make scenery dirs available to Nasal
388 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
389 n->setStringValue(abspath.str());
390 n->setAttribute(SGPropertyNode::WRITE, false);
392 // temporary fix so these values survive reset
393 n->setAttribute(SGPropertyNode::PRESERVE, true);
394 } // of path list iteration
397 void FGGlobals::clear_fg_scenery()
402 void FGGlobals::append_aircraft_path(const std::string& path)
404 SGPath dirPath(path);
405 if (!dirPath.exists()) {
406 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft path not found:" << path);
410 SGPath acSubdir(dirPath);
411 acSubdir.append("Aircraft");
412 if (acSubdir.exists()) {
413 SG_LOG(SG_GENERAL, SG_WARN, "Specified an aircraft-dir with an 'Aircraft' subdirectory:" << dirPath
414 << ", will instead use child directory:" << acSubdir);
418 std::string abspath = dirPath.realpath();
419 unsigned int index = fg_aircraft_dirs.size();
420 fg_aircraft_dirs.push_back(abspath);
422 // make aircraft dirs available to Nasal
423 SGPropertyNode* sim = fgGetNode("/sim", true);
424 sim->removeChild("fg-aircraft", index);
425 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
426 n->setStringValue(abspath);
427 n->setAttribute(SGPropertyNode::WRITE, false);
430 void FGGlobals::append_aircraft_paths(const std::string& path)
432 string_list paths = sgPathSplit(path);
433 for (unsigned int p = 0; p<paths.size(); ++p) {
434 append_aircraft_path(paths[p]);
438 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
440 return simgear::ResourceManager::instance()->findPath(branch);
443 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
445 return simgear::ResourceManager::instance()->findPath(branch);
448 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
450 return simgear::ResourceManager::instance()
451 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
455 FGGlobals::get_renderer () const
460 void FGGlobals::set_renderer(FGRenderer *render)
462 if (render == renderer) {
471 FGGlobals::get_subsystem_mgr () const
473 return subsystem_mgr;
477 FGGlobals::get_subsystem (const char * name)
479 if (!subsystem_mgr) {
483 return subsystem_mgr->get_subsystem(name);
487 FGGlobals::add_subsystem (const char * name,
488 SGSubsystem * subsystem,
489 SGSubsystemMgr::GroupType type,
492 subsystem_mgr->add(name, subsystem, type, min_time_sec);
496 FGGlobals::get_soundmgr () const
499 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
505 FGGlobals::get_event_mgr () const
511 FGGlobals::get_aircraft_position() const
513 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
514 positionLat->getDoubleValue(),
515 positionAlt->getDoubleValue());
519 FGGlobals::get_aircraft_position_cart() const
521 return SGVec3d::fromGeod(get_aircraft_position());
524 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
526 heading = orientHeading->getDoubleValue();
527 pitch = orientPitch->getDoubleValue();
528 roll = orientRoll->getDoubleValue();
532 FGGlobals::get_view_position() const
534 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
535 viewLat->getDoubleValue(),
536 viewAlt->getDoubleValue());
540 FGGlobals::get_view_position_cart() const
542 return SGVec3d::fromGeod(get_view_position());
545 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
547 for (int i=0; i<nd->nChildren(); ++i) {
548 SGPropertyNode* cp = nd->getChild(i);
549 if (SGReferenced::count(cp) > 1) {
550 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
553 treeDumpRefCounts(depth + 1, cp);
557 static void treeClearAliases(SGPropertyNode* nd)
563 for (int i=0; i<nd->nChildren(); ++i) {
564 SGPropertyNode* cp = nd->getChild(i);
565 treeClearAliases(cp);
570 FGGlobals::resetPropertyRoot()
576 // we don't strictly need to clear these (they will be reset when we
577 // initProperties again), but trying to reduce false-positives when dumping
586 orientHeading.clear();
589 // clear aliases so ref-counts are accurate when dumped
590 treeClearAliases(props);
592 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
593 treeDumpRefCounts(0, props);
595 //BaseStackSnapshot::dumpAll(std::cout);
597 props = new SGPropertyNode;
599 locale = new FGLocale(props);
601 // remove /sim/fg-root before writing to prevent hijacking
602 SGPropertyNode *n = props->getNode("/sim", true);
603 n->removeChild("fg-root", 0);
604 n = n->getChild("fg-root", 0, true);
605 n->setStringValue(fg_root.c_str());
606 n->setAttribute(SGPropertyNode::WRITE, false);
609 static std::string autosaveName()
611 std::ostringstream os;
612 string_list versionParts = simgear::strutils::split(VERSION, ".");
613 if (versionParts.size() < 2) {
614 return "autosave.xml";
617 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
621 // Load user settings from autosave.xml
623 FGGlobals::loadUserSettings(const SGPath& dataPath)
625 // remember that we have (tried) to load any existing autsave.xml
626 haveUserSettings = true;
628 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
629 SGPropertyNode autosave;
630 if (autosaveFile.exists()) {
631 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
633 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
634 } catch (sg_exception& e) {
635 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
636 << "(from " << e.getOrigin() << ")");
639 copyProperties(&autosave, globals->get_props());
642 // Save user settings in autosave.xml
644 FGGlobals::saveUserSettings()
646 // only save settings when we have (tried) to load the previous
647 // settings (otherwise user data was lost)
648 if (!haveUserSettings)
651 if (fgGetBool("/sim/startup/save-on-exit")) {
652 // don't save settings more than once on shutdown
653 haveUserSettings = false;
655 SGPath autosaveFile(globals->get_fg_home());
656 autosaveFile.append(autosaveName());
657 autosaveFile.create_dir( 0700 );
658 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
660 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
661 } catch (const sg_exception &e) {
662 guiErrorMessage("Error writing autosave:", e);
664 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
669 FGGlobals::get_current_view () const
671 return viewmgr->get_current_view();
674 long int FGGlobals::get_warp() const
676 return fgGetInt("/sim/time/warp");
679 void FGGlobals::set_warp( long int w )
681 fgSetInt("/sim/time/warp", w);
684 long int FGGlobals::get_warp_delta() const
686 return fgGetInt("/sim/time/warp-delta");
689 void FGGlobals::set_warp_delta( long int d )
691 fgSetInt("/sim/time/warp-delta", d);
694 FGScenery* FGGlobals::get_scenery () const
696 return _scenery.get();
699 void FGGlobals::set_scenery ( FGScenery *s )
704 FGTileMgr* FGGlobals::get_tile_mgr () const
706 return _tile_mgr.get();
709 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
714 void FGGlobals::set_matlib( SGMaterialLib *m )
719 FGSampleQueue* FGGlobals::get_chatter_queue() const
721 return _chatter_queue;
724 void FGGlobals::set_chatter_queue(FGSampleQueue* queue)
726 _chatter_queue = queue;
729 void FGGlobals::addListenerToCleanup(SGPropertyChangeListener* l)
731 _listeners_to_cleanup.push_back(l);
734 void FGGlobals::cleanupListeners()
736 SGPropertyChangeListenerVec::iterator i = _listeners_to_cleanup.begin();
737 for (; i != _listeners_to_cleanup.end(); ++i) {
740 _listeners_to_cleanup.clear();
743 // end of globals.cxx