]> git.mxchange.org Git - flightgear.git/blob - src/Main/globals.cxx
Globals: delete/shutdown tweaks.
[flightgear.git] / src / Main / globals.cxx
1 // globals.cxx -- Global state that needs to be shared among the sim modules
2 //
3 // Written by Curtis Olson, started July 2000.
4 //
5 // Copyright (C) 2000  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <boost/foreach.hpp>
28 #include <algorithm>
29
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>
43
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>
49 #include <GUI/gui.h>
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>
56
57 #include "globals.hxx"
58 #include "locale.hxx"
59
60 #include "fg_props.hxx"
61 #include "fg_io.hxx"
62
63 class AircraftResourceProvider : public simgear::ResourceProvider
64 {
65 public:
66   AircraftResourceProvider() :
67     simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
68   {
69   }
70   
71   virtual SGPath resolve(const std::string& aResource, SGPath&) const
72   {
73     string_list pieces(sgPathBranchSplit(aResource));
74     if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
75       return SGPath(); // not an Aircraft path
76     }
77     
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) {
85           r.append(pieces[i]);
86         }
87         
88         if (r.exists()) {
89           return r;
90         }
91     }
92   
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) {
98       SGPath p(*it, res);
99       if (p.exists()) {
100         return p;
101       }
102     } // of aircraft path iteration
103     
104     return SGPath(); // not found
105   }
106 };
107
108 class CurrentAircraftDirProvider : public simgear::ResourceProvider
109 {
110 public:
111   CurrentAircraftDirProvider() :
112     simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
113   {
114   }
115   
116   virtual SGPath resolve(const std::string& aResource, SGPath&) const
117   {
118     const char* aircraftDir = fgGetString("/sim/aircraft-dir");
119     SGPath p(aircraftDir);
120     p.append(aResource);
121     return p.exists() ? p : SGPath();
122   }
123 };
124
125 ////////////////////////////////////////////////////////////////////////
126 // Implementation of FGGlobals.
127 ////////////////////////////////////////////////////////////////////////
128
129 // global global :-)
130 FGGlobals *globals;
131
132
133 // Constructor
134 FGGlobals::FGGlobals() :
135     props( new SGPropertyNode ),
136     initial_state( NULL ),
137     locale( new FGLocale(props) ),
138     renderer( new FGRenderer ),
139     subsystem_mgr( new SGSubsystemMgr ),
140     event_mgr( new SGEventMgr ),
141     sim_time_sec( 0.0 ),
142     fg_root( "" ),
143     fg_home( "" ),
144     time_params( NULL ),
145     ephem( NULL ),
146     matlib( NULL ),
147     route_mgr( NULL ),
148     ATIS_mgr( NULL ),
149     controls( NULL ),
150     viewmgr( NULL ),
151     commands( SGCommandMgr::instance() ),
152     channel_options_list( NULL ),
153     initial_waypoints( NULL ),
154     scenery( NULL ),
155     tile_mgr( NULL ),
156     fontcache ( new FGFontCache ),
157     channellist( NULL ),
158     haveUserSettings(false)
159 {
160   simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
161   simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
162   simgear::PropertyObjectBase::setDefaultRoot(props);
163   
164   positionLon = props->getNode("position/longitude-deg", true);
165   positionLat = props->getNode("position/latitude-deg", true);
166   positionAlt = props->getNode("position/altitude-ft", true);
167   
168   viewLon = props->getNode("sim/current-view/viewer-lon-deg", true);
169   viewLat = props->getNode("sim/current-view/viewer-lat-deg", true);
170   viewAlt = props->getNode("sim/current-view/viewer-elev-ft", true);
171   
172   orientPitch = props->getNode("orientation/pitch-deg", true);
173   orientHeading = props->getNode("orientation/heading-deg", true);
174   orientRoll = props->getNode("orientation/roll-deg", true);
175 }
176
177 // Destructor
178 FGGlobals::~FGGlobals() 
179 {
180     // save user settings (unless already saved)
181     saveUserSettings();
182
183     // The AIModels manager performs a number of actions upon
184     // Shutdown that implicitly assume that other subsystems
185     // are still operational (Due to the dynamic allocation and
186     // deallocation of AIModel objects. To ensure we can safely
187     // shut down all subsystems, make sure we take down the 
188     // AIModels system first.
189     SGSubsystem* ai = globals->get_subsystem("ai-model");
190     if (ai) {
191         ai->unbind();
192         subsystem_mgr->remove("ai-model");
193     }
194
195     subsystem_mgr->remove("aircraft-model");
196     subsystem_mgr->remove("tile-manager");
197     subsystem_mgr->remove("model-manager");
198     
199     subsystem_mgr->shutdown();
200     subsystem_mgr->unbind();
201     delete subsystem_mgr;
202     subsystem_mgr = NULL; // important so ::get_subsystem returns NULL 
203     
204     delete renderer;
205     renderer = NULL;
206     
207     delete time_params;
208     delete matlib;
209     delete route_mgr;
210
211     delete ATIS_mgr;
212
213     delete channel_options_list;
214     delete initial_waypoints;
215     delete scenery;
216     delete fontcache;
217
218     delete channellist;
219
220     simgear::PropertyObjectBase::setDefaultRoot(NULL);
221     simgear::SGModelLib::resetPropertyRoot();
222     
223     delete locale;
224     locale = NULL;
225     
226     delete props;
227 }
228
229 // set the fg_root path
230 void FGGlobals::set_fg_root (const std::string &root) {
231     SGPath tmp(root);
232     fg_root = tmp.realpath();
233
234     // append /data to root if it exists
235     tmp.append( "data" );
236     tmp.append( "version" );
237     if ( tmp.exists() ) {
238         fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
239         fg_root += "/data";
240         fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
241         SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
242                 << fg_root << "'\n***\n***");
243     }
244
245     // remove /sim/fg-root before writing to prevent hijacking
246     SGPropertyNode *n = fgGetNode("/sim", true);
247     n->removeChild("fg-root", 0, false);
248     n = n->getChild("fg-root", 0, true);
249     n->setStringValue(fg_root.c_str());
250     n->setAttribute(SGPropertyNode::WRITE, false);
251     
252     simgear::ResourceManager::instance()->addBasePath(fg_root, 
253       simgear::ResourceManager::PRIORITY_DEFAULT);
254 }
255
256 // set the fg_home path
257 void FGGlobals::set_fg_home (const std::string &home) {
258     SGPath tmp(home);
259     fg_home = tmp.realpath();
260 }
261
262 PathList FGGlobals::get_data_paths() const
263 {
264     PathList r(additional_data_paths);
265     r.push_back(SGPath(fg_root));
266     return r;
267 }
268
269 PathList FGGlobals::get_data_paths(const std::string& suffix) const
270 {
271     PathList r;
272     BOOST_FOREACH(SGPath p, get_data_paths()) {
273         p.append(suffix);
274         if (p.exists()) {
275             r.push_back(p);
276         }
277     }
278
279     return r;
280 }
281
282 void FGGlobals::append_data_path(const SGPath& path)
283 {
284     if (!path.exists()) {
285         SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
286     }
287     
288     additional_data_paths.push_back(path);
289 }
290
291 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
292 {
293     BOOST_FOREACH(SGPath p, additional_data_paths) {
294         p.append(pathSuffix);
295         if (p.exists()) {
296             return p;
297         }
298     }
299     
300     SGPath rootPath(fg_root);
301     rootPath.append(pathSuffix);
302     if (rootPath.exists()) {
303         return rootPath;
304     }
305     
306     SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
307     return SGPath();
308 }
309
310 void FGGlobals::append_fg_scenery (const std::string &paths)
311 {
312 //    fg_scenery.clear();
313     SGPropertyNode* sim = fgGetNode("/sim", true);
314
315   // find first unused fg-scenery property in /sim
316     int propIndex = 0;
317     while (sim->getChild("fg-scenery", propIndex) != NULL) {
318       ++propIndex; 
319     }
320   
321     BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
322         SGPath abspath(path.realpath());
323         if (!abspath.exists()) {
324           SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
325           continue;
326         }
327
328       // check for duplicates
329       string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
330       if (ex != fg_scenery.end()) {
331         SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
332         continue;
333       }
334       
335         simgear::Dir dir(abspath);
336         SGPath terrainDir(dir.file("Terrain"));
337         SGPath objectsDir(dir.file("Objects"));
338         
339       // this code used to add *either* the base dir, OR add the 
340       // Terrain and Objects subdirs, but the conditional logic was commented
341       // out, such that all three dirs are added. Unfortunately there's
342       // no information as to why the change was made.
343         fg_scenery.push_back(abspath.str());
344         
345         if (terrainDir.exists()) {
346           fg_scenery.push_back(terrainDir.str());
347         }
348         
349         if (objectsDir.exists()) {
350           fg_scenery.push_back(objectsDir.str());
351         }
352         
353         // insert a marker for FGTileEntry::load(), so that
354         // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
355         // "B/Terrain", "B/Objects", ""]
356         fg_scenery.push_back("");
357         
358       // make scenery dirs available to Nasal
359         SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
360         n->setStringValue(abspath.str());
361         n->setAttribute(SGPropertyNode::WRITE, false);
362     } // of path list iteration
363 }
364
365 void FGGlobals::append_aircraft_path(const std::string& path)
366 {
367   SGPath dirPath(path);
368   if (!dirPath.exists()) {
369     SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
370     return;
371   }
372   std::string abspath = dirPath.realpath();
373   
374   unsigned int index = fg_aircraft_dirs.size();  
375   fg_aircraft_dirs.push_back(abspath);
376   
377 // make aircraft dirs available to Nasal
378   SGPropertyNode* sim = fgGetNode("/sim", true);
379   sim->removeChild("fg-aircraft", index, false);
380   SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
381   n->setStringValue(abspath);
382   n->setAttribute(SGPropertyNode::WRITE, false);
383 }
384
385 void FGGlobals::append_aircraft_paths(const std::string& path)
386 {
387   string_list paths = sgPathSplit(path);
388   for (unsigned int p = 0; p<paths.size(); ++p) {
389     append_aircraft_path(paths[p]);
390   }
391 }
392
393 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
394 {
395   return simgear::ResourceManager::instance()->findPath(branch);
396 }
397
398 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
399 {
400   return simgear::ResourceManager::instance()->findPath(branch);
401 }
402
403 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
404 {
405   return simgear::ResourceManager::instance()
406     ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
407 }
408
409 FGRenderer *
410 FGGlobals::get_renderer () const
411 {
412    return renderer;
413 }
414
415 SGSubsystemMgr *
416 FGGlobals::get_subsystem_mgr () const
417 {
418     return subsystem_mgr;
419 }
420
421 SGSubsystem *
422 FGGlobals::get_subsystem (const char * name)
423 {
424     if (!subsystem_mgr) {
425         return NULL;
426     }
427     
428     return subsystem_mgr->get_subsystem(name);
429 }
430
431 void
432 FGGlobals::add_subsystem (const char * name,
433                           SGSubsystem * subsystem,
434                           SGSubsystemMgr::GroupType type,
435                           double min_time_sec)
436 {
437     subsystem_mgr->add(name, subsystem, type, min_time_sec);
438 }
439
440 SGSoundMgr *
441 FGGlobals::get_soundmgr () const
442 {
443     if (subsystem_mgr)
444         return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
445
446     return NULL;
447 }
448
449 SGEventMgr *
450 FGGlobals::get_event_mgr () const
451 {
452     return event_mgr;
453 }
454
455 SGGeod
456 FGGlobals::get_aircraft_position() const
457 {
458   return SGGeod::fromDegFt(positionLon->getDoubleValue(),
459                            positionLat->getDoubleValue(),
460                            positionAlt->getDoubleValue());
461 }
462
463 SGVec3d
464 FGGlobals::get_aircraft_position_cart() const
465 {
466     return SGVec3d::fromGeod(get_aircraft_position());
467 }
468
469 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
470 {
471   heading = orientHeading->getDoubleValue();
472   pitch = orientPitch->getDoubleValue();
473   roll = orientRoll->getDoubleValue();
474 }
475
476 SGGeod
477 FGGlobals::get_view_position() const
478 {
479   return SGGeod::fromDegFt(viewLon->getDoubleValue(),
480                            viewLat->getDoubleValue(),
481                            viewAlt->getDoubleValue());
482 }
483
484 SGVec3d
485 FGGlobals::get_view_position_cart() const
486 {
487   return SGVec3d::fromGeod(get_view_position());
488 }
489
490 // Save the current state as the initial state.
491 void
492 FGGlobals::saveInitialState ()
493 {
494   initial_state = new SGPropertyNode();
495
496   // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
497   int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
498                  SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
499   int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
500   if (!copyProperties(props, initial_state, expected, checked))
501     SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
502     
503   // delete various properties from the initial state, since we want to
504   // preserve their values even if doing a restore
505   // => Properties should now use the PRESERVE flag to protect their values
506   // on sim-reset. Remove some specific properties for backward compatibility.
507   SGPropertyNode* sim = initial_state->getChild("sim");
508   SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
509   if (cameraGroupNode) {
510     cameraGroupNode->removeChild("camera");
511     cameraGroupNode->removeChild("gui");
512   }
513 }
514
515 static std::string autosaveName()
516 {
517     std::ostringstream os;
518     string_list versionParts = simgear::strutils::split(VERSION, ".");
519     if (versionParts.size() < 2) {
520         return "autosave.xml";
521     }
522     
523     os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
524     return os.str();
525 }
526
527 // Restore the saved initial state, if any
528 void
529 FGGlobals::restoreInitialState ()
530 {
531     if ( initial_state == 0 ) {
532         SG_LOG(SG_GENERAL, SG_ALERT,
533                "No initial state available to restore!!!");
534         return;
535     }
536     // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
537     int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
538                    SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
539     int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
540     if ( copyProperties(initial_state, props, expected, checked)) {
541         SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
542     } else {
543         SG_LOG( SG_GENERAL, SG_INFO,
544                 "Some errors restoring initial state (read-only props?)" );
545     }
546
547 }
548
549 // Load user settings from autosave.xml
550 void
551 FGGlobals::loadUserSettings(const SGPath& dataPath)
552 {
553     // remember that we have (tried) to load any existing autsave.xml
554     haveUserSettings = true;
555
556     SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
557     SGPropertyNode autosave;
558     if (autosaveFile.exists()) {
559       SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
560       try {
561           readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
562       } catch (sg_exception& e) {
563           SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
564             << "(from " << e.getOrigin() << ")");
565       }
566     }
567     copyProperties(&autosave, globals->get_props());
568 }
569
570 // Save user settings in autosave.xml
571 void
572 FGGlobals::saveUserSettings()
573 {
574     // only save settings when we have (tried) to load the previous
575     // settings (otherwise user data was lost)
576     if (!haveUserSettings)
577         return;
578
579     if (fgGetBool("/sim/startup/save-on-exit")) {
580       // don't save settings more than once on shutdown
581       haveUserSettings = false;
582
583       SGPath autosaveFile(globals->get_fg_home());
584       autosaveFile.append(autosaveName());
585       autosaveFile.create_dir( 0700 );
586       SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
587       try {
588         writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
589       } catch (const sg_exception &e) {
590         guiErrorMessage("Error writing autosave:", e);
591       }
592       SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
593     }
594 }
595
596 FGViewer *
597 FGGlobals::get_current_view () const
598 {
599   return viewmgr->get_current_view();
600 }
601
602 long int FGGlobals::get_warp() const
603 {
604   return fgGetInt("/sim/time/warp");
605 }
606
607 void FGGlobals::set_warp( long int w )
608 {
609   fgSetInt("/sim/time/warp", w);
610 }
611
612 long int FGGlobals::get_warp_delta() const
613 {
614   return fgGetInt("/sim/time/warp-delta");
615 }
616
617 void FGGlobals::set_warp_delta( long int d )
618 {
619   fgSetInt("/sim/time/warp-delta", d);
620 }
621
622 // end of globals.cxx