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 initial_state( NULL ),
139 renderer( new FGRenderer ),
140 subsystem_mgr( new SGSubsystemMgr ),
141 event_mgr( new SGEventMgr ),
150 commands( SGCommandMgr::instance() ),
151 channel_options_list( NULL ),
152 initial_waypoints( NULL ),
153 fontcache ( new FGFontCache ),
155 haveUserSettings(false),
158 SGPropertyNode* root = new SGPropertyNode;
159 props = SGPropertyNode_ptr(root);
160 locale = new FGLocale(props);
162 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
163 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
167 void FGGlobals::initProperties()
169 simgear::PropertyObjectBase::setDefaultRoot(props);
171 positionLon = props->getNode("position/longitude-deg", true);
172 positionLat = props->getNode("position/latitude-deg", true);
173 positionAlt = props->getNode("position/altitude-ft", true);
175 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
176 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
177 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
179 orientPitch = props->getNode("orientation/pitch-deg", true);
180 orientHeading = props->getNode("orientation/heading-deg", true);
181 orientRoll = props->getNode("orientation/roll-deg", true);
186 FGGlobals::~FGGlobals()
188 // save user settings (unless already saved)
191 // The AIModels manager performs a number of actions upon
192 // Shutdown that implicitly assume that other subsystems
193 // are still operational (Due to the dynamic allocation and
194 // deallocation of AIModel objects. To ensure we can safely
195 // shut down all subsystems, make sure we take down the
196 // AIModels system first.
197 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
199 subsystem_mgr->remove("ai-model");
201 ai.clear(); // ensure AI is deleted now, not at end of this method
204 subsystem_mgr->shutdown();
205 subsystem_mgr->unbind();
207 subsystem_mgr->remove("aircraft-model");
208 subsystem_mgr->remove("tile-manager");
209 subsystem_mgr->remove("model-manager");
212 osg::ref_ptr<osgViewer::Viewer> vw(renderer->getViewer());
214 // https://code.google.com/p/flightgear-bugs/issues/detail?id=1291
215 // explicitly stop trheading before we delete the renderer or
216 // viewMgr (which ultimately holds refs to the CameraGroup, and
221 // don't cancel the pager until after shutdown, since AIModels (and
222 // potentially others) can queue delete requests on the pager.
223 if (vw && vw->getDatabasePager()) {
224 vw->getDatabasePager()->cancel();
225 vw->getDatabasePager()->clear();
228 osgDB::Registry::instance()->clearObjectCache();
230 // renderer touches subsystems during its destruction
233 _chatter_queue.clear();
235 delete subsystem_mgr;
236 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
237 vw = 0; // don't delete the viewer until now
242 delete channel_options_list;
243 delete initial_waypoints;
247 simgear::PropertyObjectBase::setDefaultRoot(NULL);
248 simgear::SGModelLib::resetPropertyRoot();
260 // set the fg_root path
261 void FGGlobals::set_fg_root (const std::string &root) {
263 fg_root = tmp.realpath();
265 // append /data to root if it exists
266 tmp.append( "data" );
267 tmp.append( "version" );
268 if ( tmp.exists() ) {
269 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
271 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
272 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
273 << fg_root << "'\n***\n***");
276 // remove /sim/fg-root before writing to prevent hijacking
277 SGPropertyNode *n = fgGetNode("/sim", true);
278 n->removeChild("fg-root", 0);
279 n = n->getChild("fg-root", 0, true);
280 n->setStringValue(fg_root.c_str());
281 n->setAttribute(SGPropertyNode::WRITE, false);
283 simgear::ResourceManager::instance()->addBasePath(fg_root,
284 simgear::ResourceManager::PRIORITY_DEFAULT);
287 // set the fg_home path
288 void FGGlobals::set_fg_home (const std::string &home) {
290 fg_home = tmp.realpath();
293 PathList FGGlobals::get_data_paths() const
295 PathList r(additional_data_paths);
296 r.push_back(SGPath(fg_root));
300 PathList FGGlobals::get_data_paths(const std::string& suffix) const
303 BOOST_FOREACH(SGPath p, get_data_paths()) {
313 void FGGlobals::append_data_path(const SGPath& path)
315 if (!path.exists()) {
316 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
319 additional_data_paths.push_back(path);
322 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
324 BOOST_FOREACH(SGPath p, additional_data_paths) {
325 p.append(pathSuffix);
331 SGPath rootPath(fg_root);
332 rootPath.append(pathSuffix);
333 if (rootPath.exists()) {
337 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
341 void FGGlobals::append_fg_scenery (const std::string &paths)
343 // fg_scenery.clear();
344 SGPropertyNode* sim = fgGetNode("/sim", true);
346 // find first unused fg-scenery property in /sim
348 while (sim->getChild("fg-scenery", propIndex) != NULL) {
352 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
353 SGPath abspath(path.realpath());
354 if (!abspath.exists()) {
355 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
359 // check for duplicates
360 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
361 if (ex != fg_scenery.end()) {
362 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
366 simgear::Dir dir(abspath);
367 SGPath terrainDir(dir.file("Terrain"));
368 SGPath objectsDir(dir.file("Objects"));
370 // this code used to add *either* the base dir, OR add the
371 // Terrain and Objects subdirs, but the conditional logic was commented
372 // out, such that all three dirs are added. Unfortunately there's
373 // no information as to why the change was made.
374 fg_scenery.push_back(abspath.str());
376 if (terrainDir.exists()) {
377 fg_scenery.push_back(terrainDir.str());
380 if (objectsDir.exists()) {
381 fg_scenery.push_back(objectsDir.str());
384 // insert a marker for FGTileEntry::load(), so that
385 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
386 // "B/Terrain", "B/Objects", ""]
387 fg_scenery.push_back("");
389 // make scenery dirs available to Nasal
390 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
391 n->setStringValue(abspath.str());
392 n->setAttribute(SGPropertyNode::WRITE, false);
393 } // of path list iteration
396 void FGGlobals::append_aircraft_path(const std::string& path)
398 SGPath dirPath(path);
399 if (!dirPath.exists()) {
400 SG_LOG(SG_GENERAL, SG_ALERT, "aircraft path not found:" << path);
404 SGPath acSubdir(dirPath);
405 acSubdir.append("Aircraft");
406 if (acSubdir.exists()) {
407 SG_LOG(SG_GENERAL, SG_WARN, "Specified an aircraft-dir with an 'Aircraft' subdirectory:" << dirPath
408 << ", will instead use child directory:" << acSubdir);
412 std::string abspath = dirPath.realpath();
413 unsigned int index = fg_aircraft_dirs.size();
414 fg_aircraft_dirs.push_back(abspath);
416 // make aircraft dirs available to Nasal
417 SGPropertyNode* sim = fgGetNode("/sim", true);
418 sim->removeChild("fg-aircraft", index);
419 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
420 n->setStringValue(abspath);
421 n->setAttribute(SGPropertyNode::WRITE, false);
424 void FGGlobals::append_aircraft_paths(const std::string& path)
426 string_list paths = sgPathSplit(path);
427 for (unsigned int p = 0; p<paths.size(); ++p) {
428 append_aircraft_path(paths[p]);
432 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
434 return simgear::ResourceManager::instance()->findPath(branch);
437 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
439 return simgear::ResourceManager::instance()->findPath(branch);
442 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
444 return simgear::ResourceManager::instance()
445 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
449 FGGlobals::get_renderer () const
454 void FGGlobals::set_renderer(FGRenderer *render)
456 if (render == renderer) {
465 FGGlobals::get_subsystem_mgr () const
467 return subsystem_mgr;
471 FGGlobals::get_subsystem (const char * name)
473 if (!subsystem_mgr) {
477 return subsystem_mgr->get_subsystem(name);
481 FGGlobals::add_subsystem (const char * name,
482 SGSubsystem * subsystem,
483 SGSubsystemMgr::GroupType type,
486 subsystem_mgr->add(name, subsystem, type, min_time_sec);
490 FGGlobals::get_soundmgr () const
493 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
499 FGGlobals::get_event_mgr () const
505 FGGlobals::get_aircraft_position() const
507 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
508 positionLat->getDoubleValue(),
509 positionAlt->getDoubleValue());
513 FGGlobals::get_aircraft_position_cart() const
515 return SGVec3d::fromGeod(get_aircraft_position());
518 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
520 heading = orientHeading->getDoubleValue();
521 pitch = orientPitch->getDoubleValue();
522 roll = orientRoll->getDoubleValue();
526 FGGlobals::get_view_position() const
528 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
529 viewLat->getDoubleValue(),
530 viewAlt->getDoubleValue());
534 FGGlobals::get_view_position_cart() const
536 return SGVec3d::fromGeod(get_view_position());
539 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
541 for (int i=0; i<nd->nChildren(); ++i) {
542 SGPropertyNode* cp = nd->getChild(i);
543 if (SGReferenced::count(cp) > 1) {
544 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
547 treeDumpRefCounts(depth + 1, cp);
551 static void treeClearAliases(SGPropertyNode* nd)
557 for (int i=0; i<nd->nChildren(); ++i) {
558 SGPropertyNode* cp = nd->getChild(i);
559 treeClearAliases(cp);
564 FGGlobals::resetPropertyRoot()
570 // we don't strictly need to clear these (they will be reset when we
571 // initProperties again), but trying to reduce false-positives when dumping
580 orientHeading.clear();
583 // clear aliases so ref-counts are accurate when dumped
584 treeClearAliases(props);
586 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
587 treeDumpRefCounts(0, props);
589 //BaseStackSnapshot::dumpAll(std::cout);
591 props = new SGPropertyNode;
593 locale = new FGLocale(props);
595 // remove /sim/fg-root before writing to prevent hijacking
596 SGPropertyNode *n = props->getNode("/sim", true);
597 n->removeChild("fg-root", 0);
598 n = n->getChild("fg-root", 0, true);
599 n->setStringValue(fg_root.c_str());
600 n->setAttribute(SGPropertyNode::WRITE, false);
603 // Save the current state as the initial state.
605 FGGlobals::saveInitialState ()
607 initial_state = new SGPropertyNode();
609 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
610 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
611 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
612 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
613 if (!copyProperties(props, initial_state, expected, checked))
614 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
616 // delete various properties from the initial state, since we want to
617 // preserve their values even if doing a restore
618 // => Properties should now use the PRESERVE flag to protect their values
619 // on sim-reset. Remove some specific properties for backward compatibility.
620 SGPropertyNode* sim = initial_state->getChild("sim");
621 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
622 if (cameraGroupNode) {
623 cameraGroupNode->removeChild("camera");
624 cameraGroupNode->removeChild("gui");
628 static std::string autosaveName()
630 std::ostringstream os;
631 string_list versionParts = simgear::strutils::split(VERSION, ".");
632 if (versionParts.size() < 2) {
633 return "autosave.xml";
636 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
640 // Restore the saved initial state, if any
642 FGGlobals::restoreInitialState ()
644 if ( initial_state == 0 ) {
645 SG_LOG(SG_GENERAL, SG_ALERT,
646 "No initial state available to restore!!!");
649 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
650 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
651 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
652 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
653 if ( copyProperties(initial_state, props, expected, checked)) {
654 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
656 SG_LOG( SG_GENERAL, SG_INFO,
657 "Some errors restoring initial state (read-only props?)" );
662 // Load user settings from autosave.xml
664 FGGlobals::loadUserSettings(const SGPath& dataPath)
666 // remember that we have (tried) to load any existing autsave.xml
667 haveUserSettings = true;
669 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
670 SGPropertyNode autosave;
671 if (autosaveFile.exists()) {
672 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
674 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
675 } catch (sg_exception& e) {
676 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
677 << "(from " << e.getOrigin() << ")");
680 copyProperties(&autosave, globals->get_props());
683 // Save user settings in autosave.xml
685 FGGlobals::saveUserSettings()
687 // only save settings when we have (tried) to load the previous
688 // settings (otherwise user data was lost)
689 if (!haveUserSettings)
692 if (fgGetBool("/sim/startup/save-on-exit")) {
693 // don't save settings more than once on shutdown
694 haveUserSettings = false;
696 SGPath autosaveFile(globals->get_fg_home());
697 autosaveFile.append(autosaveName());
698 autosaveFile.create_dir( 0700 );
699 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
701 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
702 } catch (const sg_exception &e) {
703 guiErrorMessage("Error writing autosave:", e);
705 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
710 FGGlobals::get_current_view () const
712 return viewmgr->get_current_view();
715 long int FGGlobals::get_warp() const
717 return fgGetInt("/sim/time/warp");
720 void FGGlobals::set_warp( long int w )
722 fgSetInt("/sim/time/warp", w);
725 long int FGGlobals::get_warp_delta() const
727 return fgGetInt("/sim/time/warp-delta");
730 void FGGlobals::set_warp_delta( long int d )
732 fgSetInt("/sim/time/warp-delta", d);
735 FGScenery* FGGlobals::get_scenery () const
737 return _scenery.get();
740 void FGGlobals::set_scenery ( FGScenery *s )
745 FGTileMgr* FGGlobals::get_tile_mgr () const
747 return _tile_mgr.get();
750 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
755 void FGGlobals::set_matlib( SGMaterialLib *m )
760 FGSampleQueue* FGGlobals::get_chatter_queue() const
762 return _chatter_queue;
765 void FGGlobals::set_chatter_queue(FGSampleQueue* queue)
767 _chatter_queue = queue;
770 void FGGlobals::addListenerToCleanup(SGPropertyChangeListener* l)
772 _listeners_to_cleanup.push_back(l);
775 void FGGlobals::cleanupListeners()
777 SGPropertyChangeListenerVec::iterator i = _listeners_to_cleanup.begin();
778 for (; i != _listeners_to_cleanup.end(); ++i) {
781 _listeners_to_cleanup.clear();
784 // end of globals.cxx