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>
43 #include <Aircraft/controls.hxx>
44 #include <Airports/runways.hxx>
45 #include <ATCDCL/ATISmgr.hxx>
46 #include <Autopilot/route_mgr.hxx>
47 #include <GUI/FGFontCache.hxx>
49 #include <MultiPlayer/multiplaymgr.hxx>
50 #include <Scenery/scenery.hxx>
51 #include <Scenery/tilemgr.hxx>
52 #include <Navaids/navlist.hxx>
53 #include <Viewer/renderer.hxx>
54 #include <Viewer/viewmgr.hxx>
56 #include "globals.hxx"
59 #include "fg_props.hxx"
62 class AircraftResourceProvider : public simgear::ResourceProvider
65 AircraftResourceProvider() :
66 simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
70 virtual SGPath resolve(const std::string& aResource, SGPath&) const
72 string_list pieces(sgPathBranchSplit(aResource));
73 if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
74 return SGPath(); // not an Aircraft path
77 // test against the aircraft-dir property
78 const char* aircraftDir = fgGetString("/sim/aircraft-dir");
79 string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
80 if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
81 // current aircraft-dir matches resource aircraft
82 SGPath r(aircraftDir);
83 for (unsigned int i=2; i<pieces.size(); ++i) {
88 SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " via /sim/aircraft-dir: " << r.str());
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) {
100 SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " in aircraft dir: " << *it);
103 } // of aircraft path iteration
105 return SGPath(); // not found
109 ////////////////////////////////////////////////////////////////////////
110 // Implementation of FGGlobals.
111 ////////////////////////////////////////////////////////////////////////
118 FGGlobals::FGGlobals() :
119 props( new SGPropertyNode ),
120 initial_state( NULL ),
121 locale( new FGLocale(props) ),
122 renderer( new FGRenderer ),
123 subsystem_mgr( new SGSubsystemMgr ),
124 event_mgr( new SGEventMgr ),
135 commands( SGCommandMgr::instance() ),
136 channel_options_list( NULL ),
137 initial_waypoints( NULL ),
140 fontcache ( new FGFontCache ),
142 haveUserSettings(false)
144 simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider());
145 simgear::PropertyObjectBase::setDefaultRoot(props);
147 positionLon = props->getNode("position/longitude-deg", true);
148 positionLat = props->getNode("position/latitude-deg", true);
149 positionAlt = props->getNode("position/altitude-ft", true);
151 orientPitch = props->getNode("orientation/pitch-deg", true);
152 orientHeading = props->getNode("orientation/heading-deg", true);
153 orientRoll = props->getNode("orientation/roll-deg", true);
157 FGGlobals::~FGGlobals()
159 // save user settings (unless already saved)
162 // The AIModels manager performs a number of actions upon
163 // Shutdown that implicitly assume that other subsystems
164 // are still operational (Due to the dynamic allocation and
165 // deallocation of AIModel objects. To ensure we can safely
166 // shut down all subsystems, make sure we take down the
167 // AIModels system first.
168 SGSubsystem* ai = subsystem_mgr->remove("ai-model");
173 SGSubsystem* sound = subsystem_mgr->remove("sound");
175 subsystem_mgr->shutdown();
176 subsystem_mgr->unbind();
177 delete subsystem_mgr;
194 delete channel_options_list;
195 delete initial_waypoints;
206 // set the fg_root path
207 void FGGlobals::set_fg_root (const string &root) {
209 fg_root = tmp.realpath();
211 // append /data to root if it exists
212 tmp.append( "data" );
213 tmp.append( "version" );
214 if ( tmp.exists() ) {
215 fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
217 fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
218 SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
219 << fg_root << "'\n***\n***");
222 // remove /sim/fg-root before writing to prevent hijacking
223 SGPropertyNode *n = fgGetNode("/sim", true);
224 n->removeChild("fg-root", 0, false);
225 n = n->getChild("fg-root", 0, true);
226 n->setStringValue(fg_root.c_str());
227 n->setAttribute(SGPropertyNode::WRITE, false);
229 simgear::ResourceManager::instance()->addBasePath(fg_root,
230 simgear::ResourceManager::PRIORITY_DEFAULT);
233 // set the fg_home path
234 void FGGlobals::set_fg_home (const string &home) {
236 fg_home = tmp.realpath();
239 void FGGlobals::append_fg_scenery (const string &paths)
241 // fg_scenery.clear();
242 SGPropertyNode* sim = fgGetNode("/sim", true);
244 // find first unused fg-scenery property in /sim
246 while (sim->getChild("fg-scenery", propIndex) != NULL) {
250 BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
251 SGPath abspath(path.realpath());
252 if (!abspath.exists()) {
253 SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
257 // check for duplicates
258 string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
259 if (ex != fg_scenery.end()) {
260 SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
264 simgear::Dir dir(abspath);
265 SGPath terrainDir(dir.file("Terrain"));
266 SGPath objectsDir(dir.file("Objects"));
268 // this code used to add *either* the base dir, OR add the
269 // Terrain and Objects subdirs, but the conditional logic was commented
270 // out, such that all three dirs are added. Unfortunately there's
271 // no information as to why the change was made.
272 fg_scenery.push_back(abspath.str());
274 if (terrainDir.exists()) {
275 fg_scenery.push_back(terrainDir.str());
278 if (objectsDir.exists()) {
279 fg_scenery.push_back(objectsDir.str());
282 // insert a marker for FGTileEntry::load(), so that
283 // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
284 // "B/Terrain", "B/Objects", ""]
285 fg_scenery.push_back("");
287 // make scenery dirs available to Nasal
288 SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
289 n->setStringValue(abspath.str());
290 n->setAttribute(SGPropertyNode::WRITE, false);
291 } // of path list iteration
294 void FGGlobals::append_aircraft_path(const std::string& path)
296 SGPath dirPath(path);
297 if (!dirPath.exists()) {
298 SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
301 std::string abspath = dirPath.realpath();
303 unsigned int index = fg_aircraft_dirs.size();
304 fg_aircraft_dirs.push_back(abspath);
306 // make aircraft dirs available to Nasal
307 SGPropertyNode* sim = fgGetNode("/sim", true);
308 sim->removeChild("fg-aircraft", index, false);
309 SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
310 n->setStringValue(abspath);
311 n->setAttribute(SGPropertyNode::WRITE, false);
314 void FGGlobals::append_aircraft_paths(const std::string& path)
316 string_list paths = sgPathSplit(path);
317 for (unsigned int p = 0; p<paths.size(); ++p) {
318 append_aircraft_path(paths[p]);
322 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
324 return simgear::ResourceManager::instance()->findPath(branch);
327 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
329 return simgear::ResourceManager::instance()->findPath(branch);
332 SGPath FGGlobals::resolve_ressource_path(const std::string& branch) const
334 return simgear::ResourceManager::instance()
335 ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
339 FGGlobals::get_renderer () const
345 FGGlobals::get_subsystem_mgr () const
347 return subsystem_mgr;
351 FGGlobals::get_subsystem (const char * name)
353 return subsystem_mgr->get_subsystem(name);
357 FGGlobals::add_subsystem (const char * name,
358 SGSubsystem * subsystem,
359 SGSubsystemMgr::GroupType type,
362 subsystem_mgr->add(name, subsystem, type, min_time_sec);
366 FGGlobals::get_soundmgr () const
369 return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
375 FGGlobals::get_event_mgr () const
381 FGGlobals::get_aircraft_position() const
383 return SGGeod::fromDegFt(positionLon->getDoubleValue(),
384 positionLat->getDoubleValue(),
385 positionAlt->getDoubleValue());
389 FGGlobals::get_aircraft_positon_cart() const
391 return SGVec3d::fromGeod(get_aircraft_position());
394 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
396 heading = orientHeading->getDoubleValue();
397 pitch = orientPitch->getDoubleValue();
398 roll = orientRoll->getDoubleValue();
402 // Save the current state as the initial state.
404 FGGlobals::saveInitialState ()
406 initial_state = new SGPropertyNode();
408 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
409 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
410 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
411 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
412 if (!copyProperties(props, initial_state, expected, checked))
413 SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
415 // delete various properties from the initial state, since we want to
416 // preserve their values even if doing a restore
417 // => Properties should now use the PRESERVE flag to protect their values
418 // on sim-reset. Remove some specific properties for backward compatibility.
419 SGPropertyNode* sim = initial_state->getChild("sim");
420 SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
421 if (cameraGroupNode) {
422 cameraGroupNode->removeChild("camera");
423 cameraGroupNode->removeChild("gui");
428 // Restore the saved initial state, if any
430 FGGlobals::restoreInitialState ()
432 if ( initial_state == 0 ) {
433 SG_LOG(SG_GENERAL, SG_ALERT,
434 "No initial state available to restore!!!");
437 // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
438 int checked = SGPropertyNode::READ+SGPropertyNode::WRITE+
439 SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
440 int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
441 if ( copyProperties(initial_state, props, expected, checked)) {
442 SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
444 SG_LOG( SG_GENERAL, SG_INFO,
445 "Some errors restoring initial state (read-only props?)" );
450 // Load user settings from autosave.xml
452 FGGlobals::loadUserSettings(const SGPath& dataPath)
454 // remember that we have (tried) to load any existing autsave.xml
455 haveUserSettings = true;
457 SGPath autosaveFile = simgear::Dir(dataPath).file("autosave.xml");
458 SGPropertyNode autosave;
459 if (autosaveFile.exists()) {
460 SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
462 readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
463 } catch (sg_exception& e) {
464 SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
465 << "(from " << e.getOrigin() << ")");
468 copyProperties(&autosave, globals->get_props());
471 // Save user settings in autosave.xml
473 FGGlobals::saveUserSettings()
475 // only save settings when we have (tried) to load the previous
476 // settings (otherwise user data was lost)
477 if (!haveUserSettings)
480 if (fgGetBool("/sim/startup/save-on-exit")) {
481 // don't save settings more than once on shutdown
482 haveUserSettings = false;
484 SGPath autosaveFile(globals->get_fg_home());
485 autosaveFile.append( "autosave.xml" );
486 autosaveFile.create_dir( 0700 );
487 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
489 writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
490 } catch (const sg_exception &e) {
491 guiErrorMessage("Error writing autosave.xml: ", e);
493 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
498 FGGlobals::get_current_view () const
500 return viewmgr->get_current_view();
503 long int FGGlobals::get_warp() const
505 return fgGetInt("/sim/time/warp");
508 void FGGlobals::set_warp( long int w )
510 fgSetInt("/sim/time/warp", w);
513 long int FGGlobals::get_warp_delta() const
515 return fgGetInt("/sim/time/warp-delta");
518 void FGGlobals::set_warp_delta( long int d )
520 fgSetInt("/sim/time/warp-delta", d);
523 // end of globals.cxx