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 <ATCDCL/ATISmgr.hxx>
50 #include <Autopilot/route_mgr.hxx>
51 #include <GUI/FGFontCache.hxx>
53 #include <MultiPlayer/multiplaymgr.hxx>
54 #include <Scenery/scenery.hxx>
55 #include <Scenery/tilemgr.hxx>
56 #include <Navaids/navlist.hxx>
57 #include <Viewer/renderer.hxx>
58 #include <Viewer/viewmgr.hxx>
59 #include <Sound/sample_queue.hxx>
61 #include "globals.hxx"
64 #include "fg_props.hxx"
67 class AircraftResourceProvider : public simgear::ResourceProvider
70 AircraftResourceProvider() :
71 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
75 virtual SGPath resolve(const std::string& aResource, SGPath&) const
77 string_list pieces(sgPathBranchSplit(aResource));
78 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
79 return SGPath(); // not an Aircraft path
82 // test against the aircraft-dir property
83 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
84 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
85 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
86 // current aircraft-dir matches resource aircraft
87 SGPath r(aircraftDir);
88 for (unsigned int i=2; i<pieces.size(); ++i) {
97 // try each aircraft dir in turn
98 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
99 const string_list& dirs(globals->get_aircraft_paths());
100 string_list::const_iterator it = dirs.begin();
101 for (; it != dirs.end(); ++it) {
106 } // of aircraft path iteration
108 return SGPath(); // not found
112 class CurrentAircraftDirProvider : public simgear::ResourceProvider
115 CurrentAircraftDirProvider() :
116 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
120 virtual SGPath resolve(const std::string& aResource, SGPath&) const
122 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
123 SGPath p(aircraftDir);
125 return p.exists() ? p : SGPath();
129 ////////////////////////////////////////////////////////////////////////
130 // Implementation of FGGlobals.
131 ////////////////////////////////////////////////////////////////////////
134 FGGlobals *globals = NULL;
138 FGGlobals::FGGlobals() :
139 initial_state( NULL ),
140 renderer( new FGRenderer ),
141 subsystem_mgr( new SGSubsystemMgr ),
142 event_mgr( new SGEventMgr ),
153 commands( SGCommandMgr::instance() ),
154 channel_options_list( NULL ),
155 initial_waypoints( NULL ),
156 fontcache ( new FGFontCache ),
158 haveUserSettings(false),
161 SGPropertyNode* root = new SGPropertyNode;
162 props = SGPropertyNode_ptr(root);
163 locale = new FGLocale(props);
165 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
166 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
170 void FGGlobals::initProperties()
172 simgear::PropertyObjectBase::setDefaultRoot(props);
174 positionLon = props->getNode("position/longitude-deg", true);
175 positionLat = props->getNode("position/latitude-deg", true);
176 positionAlt = props->getNode("position/altitude-ft", true);
178 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
179 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
180 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
182 orientPitch = props->getNode("orientation/pitch-deg", true);
183 orientHeading = props->getNode("orientation/heading-deg", true);
184 orientRoll = props->getNode("orientation/roll-deg", true);
189 FGGlobals::~FGGlobals()
191 // save user settings (unless already saved)
194 // The AIModels manager performs a number of actions upon
195 // Shutdown that implicitly assume that other subsystems
196 // are still operational (Due to the dynamic allocation and
197 // deallocation of AIModel objects. To ensure we can safely
198 // shut down all subsystems, make sure we take down the
199 // AIModels system first.
200 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
202 subsystem_mgr->remove("ai-model");
204 ai.clear(); // ensure AI is deleted now, not at end of this method
207 subsystem_mgr->shutdown();
208 subsystem_mgr->unbind();
210 subsystem_mgr->remove("aircraft-model");
211 subsystem_mgr->remove("tile-manager");
212 subsystem_mgr->remove("model-manager");
215 // don't cancel the pager until after shutdown, since AIModels (and
216 // potentially others) can queue delete requests on the pager.
217 if (renderer->getViewer() && renderer->getViewer()->getDatabasePager()) {
218 renderer->getViewer()->getDatabasePager()->cancel();
219 renderer->getViewer()->getDatabasePager()->clear();
221 osgDB::Registry::instance()->clearObjectCache();
223 // renderer touches subsystems during its destruction
226 _chatter_queue.clear();
228 delete subsystem_mgr;
229 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
235 delete channel_options_list;
236 delete initial_waypoints;
240 simgear::PropertyObjectBase::setDefaultRoot(NULL);
241 simgear::SGModelLib::resetPropertyRoot();
253 // set the fg_root path
254 void FGGlobals::set_fg_root (const std::string &root) {
256 fg_root = tmp.realpath();
258 // append /data to root if it exists
259 tmp.append( "data" );
260 tmp.append( "version" );
261 if ( tmp.exists() ) {
262 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
264 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
265 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
266 << fg_root << "'\n***\n***");
269 // remove /sim/fg-root before writing to prevent hijacking
270 SGPropertyNode *n = fgGetNode("/sim", true);
271 n->removeChild("fg-root", 0, false);
272 n = n->getChild("fg-root", 0, true);
273 n->setStringValue(fg_root.c_str());
274 n->setAttribute(SGPropertyNode::WRITE, false);
276 simgear::ResourceManager::instance()->addBasePath(fg_root,
277 simgear::ResourceManager::PRIORITY_DEFAULT);
280 // set the fg_home path
281 void FGGlobals::set_fg_home (const std::string &home) {
283 fg_home = tmp.realpath();
286 PathList FGGlobals::get_data_paths() const
288 PathList r(additional_data_paths);
289 r.push_back(SGPath(fg_root));
293 PathList FGGlobals::get_data_paths(const std::string& suffix) const
296 BOOST_FOREACH(SGPath p, get_data_paths()) {
306 void FGGlobals::append_data_path(const SGPath& path)
308 if (!path.exists()) {
309 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
312 additional_data_paths.push_back(path);
315 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
317 BOOST_FOREACH(SGPath p, additional_data_paths) {
318 p.append(pathSuffix);
324 SGPath rootPath(fg_root);
325 rootPath.append(pathSuffix);
326 if (rootPath.exists()) {
330 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
334 void FGGlobals::append_fg_scenery (const std::string &paths)
336 // fg_scenery.clear();
337 SGPropertyNode* sim = fgGetNode("/sim", true);
339 // find first unused fg-scenery property in /sim
341 while (sim->getChild("fg-scenery", propIndex) != NULL) {
345 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
346 SGPath abspath(path.realpath());
347 if (!abspath.exists()) {
348 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
352 // check for duplicates
353 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
354 if (ex != fg_scenery.end()) {
355 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
359 simgear::Dir dir(abspath);
360 SGPath terrainDir(dir.file("Terrain"));
361 SGPath objectsDir(dir.file("Objects"));
363 // this code used to add *either* the base dir, OR add the
364 // Terrain and Objects subdirs, but the conditional logic was commented
365 // out, such that all three dirs are added. Unfortunately there's
366 // no information as to why the change was made.
367 fg_scenery.push_back(abspath.str());
369 if (terrainDir.exists()) {
370 fg_scenery.push_back(terrainDir.str());
373 if (objectsDir.exists()) {
374 fg_scenery.push_back(objectsDir.str());
377 // insert a marker for FGTileEntry::load(), so that
378 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
379 // "B/Terrain", "B/Objects", ""]
380 fg_scenery.push_back("");
382 // make scenery dirs available to Nasal
383 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
384 n->setStringValue(abspath.str());
385 n->setAttribute(SGPropertyNode::WRITE, false);
386 } // of path list iteration
389 void FGGlobals::append_aircraft_path(const std::string& path)
391 SGPath dirPath(path);
392 if (!dirPath.exists()) {
393 SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
396 std::string abspath = dirPath.realpath();
398 unsigned int index = fg_aircraft_dirs.size();
399 fg_aircraft_dirs.push_back(abspath);
401 // make aircraft dirs available to Nasal
402 SGPropertyNode* sim = fgGetNode("/sim", true);
403 sim->removeChild("fg-aircraft", index, false);
404 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
405 n->setStringValue(abspath);
406 n->setAttribute(SGPropertyNode::WRITE, false);
409 void FGGlobals::append_aircraft_paths(const std::string& path)
411 string_list paths = sgPathSplit(path);
412 for (unsigned int p = 0; p<paths.size(); ++p) {
413 append_aircraft_path(paths[p]);
417 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
419 return simgear::ResourceManager::instance()->findPath(branch);
422 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
424 return simgear::ResourceManager::instance()->findPath(branch);
427 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
429 return simgear::ResourceManager::instance()
430 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
434 FGGlobals::get_renderer () const
439 void FGGlobals::set_renderer(FGRenderer *render)
441 if (render == renderer) {
450 FGGlobals::get_subsystem_mgr () const
452 return subsystem_mgr;
456 FGGlobals::get_subsystem (const char * name)
458 if (!subsystem_mgr) {
462 return subsystem_mgr->get_subsystem(name);
466 FGGlobals::add_subsystem (const char * name,
467 SGSubsystem * subsystem,
468 SGSubsystemMgr::GroupType type,
471 subsystem_mgr->add(name, subsystem, type, min_time_sec);
475 FGGlobals::get_soundmgr () const
478 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
484 FGGlobals::get_event_mgr () const
490 FGGlobals::get_aircraft_position() const
492 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
493 positionLat->getDoubleValue(),
494 positionAlt->getDoubleValue());
498 FGGlobals::get_aircraft_position_cart() const
500 return SGVec3d::fromGeod(get_aircraft_position());
503 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
505 heading = orientHeading->getDoubleValue();
506 pitch = orientPitch->getDoubleValue();
507 roll = orientRoll->getDoubleValue();
511 FGGlobals::get_view_position() const
513 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
514 viewLat->getDoubleValue(),
515 viewAlt->getDoubleValue());
519 FGGlobals::get_view_position_cart() const
521 return SGVec3d::fromGeod(get_view_position());
524 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
526 for (int i=0; i<nd->nChildren(); ++i) {
527 SGPropertyNode* cp = nd->getChild(i);
528 if (SGReferenced::count(cp) > 1) {
529 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
532 treeDumpRefCounts(depth + 1, cp);
537 FGGlobals::resetPropertyRoot()
543 // we don't strictly need to clear these (they will be reset when we
544 // initProperties again), but trying to reduce false-positives when dumping
553 orientHeading.clear();
556 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
557 treeDumpRefCounts(0, props);
559 //BaseStackSnapshot::dumpAll(std::cout);
561 props = new SGPropertyNode;
563 locale = new FGLocale(props);
565 // remove /sim/fg-root before writing to prevent hijacking
566 SGPropertyNode *n = props->getNode("/sim", true);
567 n->removeChild("fg-root", 0, false);
568 n = n->getChild("fg-root", 0, true);
569 n->setStringValue(fg_root.c_str());
570 n->setAttribute(SGPropertyNode::WRITE, false);
573 // Save the current state as the initial state.
575 FGGlobals::saveInitialState ()
577 initial_state = new SGPropertyNode();
579 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
580 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
581 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
582 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
583 if (!copyProperties(props, initial_state, expected, checked))
584 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
586 // delete various properties from the initial state, since we want to
587 // preserve their values even if doing a restore
588 // => Properties should now use the PRESERVE flag to protect their values
589 // on sim-reset. Remove some specific properties for backward compatibility.
590 SGPropertyNode* sim = initial_state->getChild("sim");
591 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
592 if (cameraGroupNode) {
593 cameraGroupNode->removeChild("camera");
594 cameraGroupNode->removeChild("gui");
598 static std::string autosaveName()
600 std::ostringstream os;
601 string_list versionParts = simgear::strutils::split(VERSION, ".");
602 if (versionParts.size() < 2) {
603 return "autosave.xml";
606 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
610 // Restore the saved initial state, if any
612 FGGlobals::restoreInitialState ()
614 if ( initial_state == 0 ) {
615 SG_LOG(SG_GENERAL, SG_ALERT,
616 "No initial state available to restore!!!");
619 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
620 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
621 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
622 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
623 if ( copyProperties(initial_state, props, expected, checked)) {
624 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
626 SG_LOG( SG_GENERAL, SG_INFO,
627 "Some errors restoring initial state (read-only props?)" );
632 // Load user settings from autosave.xml
634 FGGlobals::loadUserSettings(const SGPath& dataPath)
636 // remember that we have (tried) to load any existing autsave.xml
637 haveUserSettings = true;
639 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
640 SGPropertyNode autosave;
641 if (autosaveFile.exists()) {
642 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
644 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
645 } catch (sg_exception& e) {
646 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
647 << "(from " << e.getOrigin() << ")");
650 copyProperties(&autosave, globals->get_props());
653 // Save user settings in autosave.xml
655 FGGlobals::saveUserSettings()
657 // only save settings when we have (tried) to load the previous
658 // settings (otherwise user data was lost)
659 if (!haveUserSettings)
662 if (fgGetBool("/sim/startup/save-on-exit")) {
663 // don't save settings more than once on shutdown
664 haveUserSettings = false;
666 SGPath autosaveFile(globals->get_fg_home());
667 autosaveFile.append(autosaveName());
668 autosaveFile.create_dir( 0700 );
669 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
671 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
672 } catch (const sg_exception &e) {
673 guiErrorMessage("Error writing autosave:", e);
675 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
680 FGGlobals::get_current_view () const
682 return viewmgr->get_current_view();
685 long int FGGlobals::get_warp() const
687 return fgGetInt("/sim/time/warp");
690 void FGGlobals::set_warp( long int w )
692 fgSetInt("/sim/time/warp", w);
695 long int FGGlobals::get_warp_delta() const
697 return fgGetInt("/sim/time/warp-delta");
700 void FGGlobals::set_warp_delta( long int d )
702 fgSetInt("/sim/time/warp-delta", d);
705 FGScenery* FGGlobals::get_scenery () const
707 return _scenery.get();
710 void FGGlobals::set_scenery ( FGScenery *s )
715 FGTileMgr* FGGlobals::get_tile_mgr () const
717 return _tile_mgr.get();
720 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
725 void FGGlobals::set_matlib( SGMaterialLib *m )
732 FGSampleQueue* FGGlobals::get_chatter_queue() const
734 return _chatter_queue;
737 void FGGlobals::set_chatter_queue(FGSampleQueue* queue)
739 _chatter_queue = queue;
742 void FGGlobals::addListenerToCleanup(SGPropertyChangeListener* l)
744 _listeners_to_cleanup.push_back(l);
747 void FGGlobals::cleanupListeners()
749 SGPropertyChangeListenerVec::iterator i = _listeners_to_cleanup.begin();
750 for (; i != _listeners_to_cleanup.end(); ++i) {
753 _listeners_to_cleanup.clear();
756 // end of globals.cxx