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 <simgear/structure/commands.hxx>
31 #include <simgear/misc/sg_path.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/ephemeris/ephemeris.hxx>
35 #include <simgear/scene/material/matlib.hxx>
36 #include <simgear/structure/subsystem_mgr.hxx>
37 #include <simgear/structure/event_mgr.hxx>
38 #include <simgear/sound/soundmgr_openal.hxx>
39 #include <simgear/misc/ResourceManager.hxx>
40 #include <simgear/props/propertyObject.hxx>
41 #include <simgear/props/props_io.hxx>
42 #include <simgear/scene/model/modellib.hxx>
44 #include <Aircraft/controls.hxx>
45 #include <Airports/runways.hxx>
46 #include <ATCDCL/ATISmgr.hxx>
47 #include <Autopilot/route_mgr.hxx>
48 #include <GUI/FGFontCache.hxx>
50 #include <MultiPlayer/multiplaymgr.hxx>
51 #include <Scenery/scenery.hxx>
52 #include <Scenery/tilemgr.hxx>
53 #include <Navaids/navlist.hxx>
54 #include <Viewer/renderer.hxx>
55 #include <Viewer/viewmgr.hxx>
57 #include "globals.hxx"
60 #include "fg_props.hxx"
63 class AircraftResourceProvider : public simgear::ResourceProvider
66 AircraftResourceProvider() :
67 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
71 virtual SGPath resolve(const std::string& aResource, SGPath&) const
73 string_list pieces(sgPathBranchSplit(aResource));
74 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
75 return SGPath(); // not an Aircraft path
78 // test against the aircraft-dir property
79 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
80 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
81 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
82 // current aircraft-dir matches resource aircraft
83 SGPath r(aircraftDir);
84 for (unsigned int i=2; i<pieces.size(); ++i) {
93 // try each aircraft dir in turn
94 std::string res(aResource, 9); // resource path with 'Aircraft/' removed
95 const string_list& dirs(globals->get_aircraft_paths());
96 string_list::const_iterator it = dirs.begin();
97 for (; it != dirs.end(); ++it) {
102 } // of aircraft path iteration
104 return SGPath(); // not found
108 class CurrentAircraftDirProvider : public simgear::ResourceProvider
111 CurrentAircraftDirProvider() :
112 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
116 virtual SGPath resolve(const std::string& aResource, SGPath&) const
118 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
119 SGPath p(aircraftDir);
121 return p.exists() ? p : SGPath();
125 ////////////////////////////////////////////////////////////////////////
126 // Implementation of FGGlobals.
127 ////////////////////////////////////////////////////////////////////////
130 FGGlobals *globals = NULL;
134 FGGlobals::FGGlobals() :
135 initial_state( NULL ),
136 renderer( new FGRenderer ),
137 subsystem_mgr( new SGSubsystemMgr ),
138 event_mgr( new SGEventMgr ),
149 commands( SGCommandMgr::instance() ),
150 channel_options_list( NULL ),
151 initial_waypoints( NULL ),
152 fontcache ( new FGFontCache ),
154 haveUserSettings(false)
156 SGPropertyNode* root = new SGPropertyNode;
157 props = SGPropertyNode_ptr(root);
158 locale = new FGLocale(props);
160 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
161 simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
165 void FGGlobals::initProperties()
167 simgear::PropertyObjectBase::setDefaultRoot(props);
169 positionLon = props->getNode("position/longitude-deg", true);
170 positionLat = props->getNode("position/latitude-deg", true);
171 positionAlt = props->getNode("position/altitude-ft", true);
173 viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
174 viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
175 viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
177 orientPitch = props->getNode("orientation/pitch-deg", true);
178 orientHeading = props->getNode("orientation/heading-deg", true);
179 orientRoll = props->getNode("orientation/roll-deg", true);
184 FGGlobals::~FGGlobals()
186 // save user settings (unless already saved)
189 // The AIModels manager performs a number of actions upon
190 // Shutdown that implicitly assume that other subsystems
191 // are still operational (Due to the dynamic allocation and
192 // deallocation of AIModel objects. To ensure we can safely
193 // shut down all subsystems, make sure we take down the
194 // AIModels system first.
195 SGSubsystemRef ai = subsystem_mgr->get_subsystem("ai-model");
197 subsystem_mgr->remove("ai-model");
199 ai.clear(); // ensure AI is deleted now, not at end of this method
202 subsystem_mgr->shutdown();
203 subsystem_mgr->unbind();
205 subsystem_mgr->remove("aircraft-model");
206 subsystem_mgr->remove("tile-manager");
207 subsystem_mgr->remove("model-manager");
210 // renderer touches subsystems during its destruction
214 delete subsystem_mgr;
215 subsystem_mgr = NULL; // important so ::get_subsystem returns NULL
221 delete channel_options_list;
222 delete initial_waypoints;
226 simgear::PropertyObjectBase::setDefaultRoot(NULL);
227 simgear::SGModelLib::resetPropertyRoot();
235 // set the fg_root path
236 void FGGlobals::set_fg_root (const std::string &root) {
238 fg_root = tmp.realpath();
240 // append /data to root if it exists
241 tmp.append( "data" );
242 tmp.append( "version" );
243 if ( tmp.exists() ) {
244 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
246 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
247 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
248 << fg_root << "'\n***\n***");
251 // remove /sim/fg-root before writing to prevent hijacking
252 SGPropertyNode *n = fgGetNode("/sim", true);
253 n->removeChild("fg-root", 0, false);
254 n = n->getChild("fg-root", 0, true);
255 n->setStringValue(fg_root.c_str());
256 n->setAttribute(SGPropertyNode::WRITE, false);
258 simgear::ResourceManager::instance()->addBasePath(fg_root,
259 simgear::ResourceManager::PRIORITY_DEFAULT);
262 // set the fg_home path
263 void FGGlobals::set_fg_home (const std::string &home) {
265 fg_home = tmp.realpath();
268 PathList FGGlobals::get_data_paths() const
270 PathList r(additional_data_paths);
271 r.push_back(SGPath(fg_root));
275 PathList FGGlobals::get_data_paths(const std::string& suffix) const
278 BOOST_FOREACH(SGPath p, get_data_paths()) {
288 void FGGlobals::append_data_path(const SGPath& path)
290 if (!path.exists()) {
291 SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
294 additional_data_paths.push_back(path);
297 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
299 BOOST_FOREACH(SGPath p, additional_data_paths) {
300 p.append(pathSuffix);
306 SGPath rootPath(fg_root);
307 rootPath.append(pathSuffix);
308 if (rootPath.exists()) {
312 SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
316 void FGGlobals::append_fg_scenery (const std::string &paths)
318 // fg_scenery.clear();
319 SGPropertyNode* sim = fgGetNode("/sim", true);
321 // find first unused fg-scenery property in /sim
323 while (sim->getChild("fg-scenery", propIndex) != NULL) {
327 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
328 SGPath abspath(path.realpath());
329 if (!abspath.exists()) {
330 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
334 // check for duplicates
335 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
336 if (ex != fg_scenery.end()) {
337 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
341 simgear::Dir dir(abspath);
342 SGPath terrainDir(dir.file("Terrain"));
343 SGPath objectsDir(dir.file("Objects"));
345 // this code used to add *either* the base dir, OR add the
346 // Terrain and Objects subdirs, but the conditional logic was commented
347 // out, such that all three dirs are added. Unfortunately there's
348 // no information as to why the change was made.
349 fg_scenery.push_back(abspath.str());
351 if (terrainDir.exists()) {
352 fg_scenery.push_back(terrainDir.str());
355 if (objectsDir.exists()) {
356 fg_scenery.push_back(objectsDir.str());
359 // insert a marker for FGTileEntry::load(), so that
360 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
361 // "B/Terrain", "B/Objects", ""]
362 fg_scenery.push_back("");
364 // make scenery dirs available to Nasal
365 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
366 n->setStringValue(abspath.str());
367 n->setAttribute(SGPropertyNode::WRITE, false);
368 } // of path list iteration
371 void FGGlobals::append_aircraft_path(const std::string& path)
373 SGPath dirPath(path);
374 if (!dirPath.exists()) {
375 SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
378 std::string abspath = dirPath.realpath();
380 unsigned int index = fg_aircraft_dirs.size();
381 fg_aircraft_dirs.push_back(abspath);
383 // make aircraft dirs available to Nasal
384 SGPropertyNode* sim = fgGetNode("/sim", true);
385 sim->removeChild("fg-aircraft", index, false);
386 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
387 n->setStringValue(abspath);
388 n->setAttribute(SGPropertyNode::WRITE, false);
391 void FGGlobals::append_aircraft_paths(const std::string& path)
393 string_list paths = sgPathSplit(path);
394 for (unsigned int p = 0; p<paths.size(); ++p) {
395 append_aircraft_path(paths[p]);
399 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
401 return simgear::ResourceManager::instance()->findPath(branch);
404 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
406 return simgear::ResourceManager::instance()->findPath(branch);
409 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
411 return simgear::ResourceManager::instance()
412 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
416 FGGlobals::get_renderer () const
421 void FGGlobals::set_renderer(FGRenderer *render)
423 if (render == renderer) {
432 FGGlobals::get_subsystem_mgr () const
434 return subsystem_mgr;
438 FGGlobals::get_subsystem (const char * name)
440 if (!subsystem_mgr) {
444 return subsystem_mgr->get_subsystem(name);
448 FGGlobals::add_subsystem (const char * name,
449 SGSubsystem * subsystem,
450 SGSubsystemMgr::GroupType type,
453 subsystem_mgr->add(name, subsystem, type, min_time_sec);
457 FGGlobals::get_soundmgr () const
460 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
466 FGGlobals::get_event_mgr () const
472 FGGlobals::get_aircraft_position() const
474 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
475 positionLat->getDoubleValue(),
476 positionAlt->getDoubleValue());
480 FGGlobals::get_aircraft_position_cart() const
482 return SGVec3d::fromGeod(get_aircraft_position());
485 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
487 heading = orientHeading->getDoubleValue();
488 pitch = orientPitch->getDoubleValue();
489 roll = orientRoll->getDoubleValue();
493 FGGlobals::get_view_position() const
495 return SGGeod::fromDegFt(viewLon->getDoubleValue(),
496 viewLat->getDoubleValue(),
497 viewAlt->getDoubleValue());
501 FGGlobals::get_view_position_cart() const
503 return SGVec3d::fromGeod(get_view_position());
506 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
508 for (int i=0; i<nd->nChildren(); ++i) {
509 SGPropertyNode* cp = nd->getChild(i);
510 if (SGReferenced::count(cp) > 1) {
511 SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
514 treeDumpRefCounts(depth + 1, cp);
519 FGGlobals::resetPropertyRoot()
523 SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
524 treeDumpRefCounts(0, props);
526 props = new SGPropertyNode;
528 locale = new FGLocale(props);
530 // remove /sim/fg-root before writing to prevent hijacking
531 SGPropertyNode *n = props->getNode("/sim", true);
532 n->removeChild("fg-root", 0, false);
533 n = n->getChild("fg-root", 0, true);
534 n->setStringValue(fg_root.c_str());
535 n->setAttribute(SGPropertyNode::WRITE, false);
538 // Save the current state as the initial state.
540 FGGlobals::saveInitialState ()
542 initial_state = new SGPropertyNode();
544 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
545 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
546 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
547 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
548 if (!copyProperties(props, initial_state, expected, checked))
549 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
551 // delete various properties from the initial state, since we want to
552 // preserve their values even if doing a restore
553 // => Properties should now use the PRESERVE flag to protect their values
554 // on sim-reset. Remove some specific properties for backward compatibility.
555 SGPropertyNode* sim = initial_state->getChild("sim");
556 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
557 if (cameraGroupNode) {
558 cameraGroupNode->removeChild("camera");
559 cameraGroupNode->removeChild("gui");
563 static std::string autosaveName()
565 std::ostringstream os;
566 string_list versionParts = simgear::strutils::split(VERSION, ".");
567 if (versionParts.size() < 2) {
568 return "autosave.xml";
571 os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
575 // Restore the saved initial state, if any
577 FGGlobals::restoreInitialState ()
579 if ( initial_state == 0 ) {
580 SG_LOG(SG_GENERAL, SG_ALERT,
581 "No initial state available to restore!!!");
584 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
585 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
586 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
587 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
588 if ( copyProperties(initial_state, props, expected, checked)) {
589 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
591 SG_LOG( SG_GENERAL, SG_INFO,
592 "Some errors restoring initial state (read-only props?)" );
597 // Load user settings from autosave.xml
599 FGGlobals::loadUserSettings(const SGPath& dataPath)
601 // remember that we have (tried) to load any existing autsave.xml
602 haveUserSettings = true;
604 SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
605 SGPropertyNode autosave;
606 if (autosaveFile.exists()) {
607 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
609 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
610 } catch (sg_exception& e) {
611 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
612 << "(from " << e.getOrigin() << ")");
615 copyProperties(&autosave, globals->get_props());
618 // Save user settings in autosave.xml
620 FGGlobals::saveUserSettings()
622 // only save settings when we have (tried) to load the previous
623 // settings (otherwise user data was lost)
624 if (!haveUserSettings)
627 if (fgGetBool("/sim/startup/save-on-exit")) {
628 // don't save settings more than once on shutdown
629 haveUserSettings = false;
631 SGPath autosaveFile(globals->get_fg_home());
632 autosaveFile.append(autosaveName());
633 autosaveFile.create_dir( 0700 );
634 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
636 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
637 } catch (const sg_exception &e) {
638 guiErrorMessage("Error writing autosave:", e);
640 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
645 FGGlobals::get_current_view () const
647 return viewmgr->get_current_view();
650 long int FGGlobals::get_warp() const
652 return fgGetInt("/sim/time/warp");
655 void FGGlobals::set_warp( long int w )
657 fgSetInt("/sim/time/warp", w);
660 long int FGGlobals::get_warp_delta() const
662 return fgGetInt("/sim/time/warp-delta");
665 void FGGlobals::set_warp_delta( long int d )
667 fgSetInt("/sim/time/warp-delta", d);
670 FGScenery* FGGlobals::get_scenery () const
672 return _scenery.get();
675 void FGGlobals::set_scenery ( FGScenery *s )
680 FGTileMgr* FGGlobals::get_tile_mgr () const
682 return _tile_mgr.get();
685 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
690 void FGGlobals::set_matlib( SGMaterialLib *m )
697 // end of globals.cxx