]> git.mxchange.org Git - flightgear.git/blob - src/Main/globals.cxx
Break config init / aircraft loading apart.
[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 = NULL;
131
132
133 // Constructor
134 FGGlobals::FGGlobals() :
135     initial_state( NULL ),
136     renderer( new FGRenderer ),
137     subsystem_mgr( new SGSubsystemMgr ),
138     event_mgr( new SGEventMgr ),
139     sim_time_sec( 0.0 ),
140     fg_root( "" ),
141     fg_home( "" ),
142     time_params( NULL ),
143     ephem( NULL ),
144     matlib( NULL ),
145     route_mgr( NULL ),
146     ATIS_mgr( NULL ),
147     controls( NULL ),
148     viewmgr( NULL ),
149     commands( new SGCommandMgr ),
150     channel_options_list( NULL ),
151     initial_waypoints( NULL ),
152     fontcache ( new FGFontCache ),
153     channellist( NULL ),
154     haveUserSettings(false)
155 {
156     SGPropertyNode* root = new SGPropertyNode;
157     props = SGPropertyNode_ptr(root);
158     locale = new FGLocale(props);
159     
160     simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider);
161     simgear::ResourceManager::instance()->addProvider(new CurrentAircraftDirProvider);
162     initProperties();
163 }
164
165 void FGGlobals::initProperties()
166 {
167     simgear::PropertyObjectBase::setDefaultRoot(props);
168     
169     positionLon = props->getNode("position/longitude-deg", true);
170     positionLat = props->getNode("position/latitude-deg", true);
171     positionAlt = props->getNode("position/altitude-ft", true);
172     
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);
176     
177     orientPitch = props->getNode("orientation/pitch-deg", true);
178     orientHeading = props->getNode("orientation/heading-deg", true);
179     orientRoll = props->getNode("orientation/roll-deg", true);
180
181 }
182
183 // Destructor
184 FGGlobals::~FGGlobals() 
185 {
186     // save user settings (unless already saved)
187     saveUserSettings();
188
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");
196     if (ai) {
197         subsystem_mgr->remove("ai-model");
198         ai->unbind();
199         ai.clear(); // ensure AI is deleted now, not at end of this method
200     }
201     
202     subsystem_mgr->shutdown();
203     subsystem_mgr->unbind();    
204
205     subsystem_mgr->remove("aircraft-model");
206     subsystem_mgr->remove("tile-manager");
207     subsystem_mgr->remove("model-manager");
208     _tile_mgr.clear();
209
210     // renderer touches subsystems during its destruction
211     set_renderer(NULL);
212     _scenery.clear();
213
214     delete subsystem_mgr;
215     subsystem_mgr = NULL; // important so ::get_subsystem returns NULL 
216
217     delete time_params;
218     set_matlib(NULL);
219     delete route_mgr;
220     delete ATIS_mgr;
221     delete channel_options_list;
222     delete initial_waypoints;
223     delete fontcache;
224     delete channellist;
225
226     simgear::PropertyObjectBase::setDefaultRoot(NULL);
227     simgear::SGModelLib::resetPropertyRoot();
228     
229     delete locale;
230     locale = NULL;
231     
232     props.clear();
233     
234     delete commands;
235 }
236
237 // set the fg_root path
238 void FGGlobals::set_fg_root (const std::string &root) {
239     SGPath tmp(root);
240     fg_root = tmp.realpath();
241
242     // append /data to root if it exists
243     tmp.append( "data" );
244     tmp.append( "version" );
245     if ( tmp.exists() ) {
246         fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
247         fg_root += "/data";
248         fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
249         SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
250                 << fg_root << "'\n***\n***");
251     }
252
253     // remove /sim/fg-root before writing to prevent hijacking
254     SGPropertyNode *n = fgGetNode("/sim", true);
255     n->removeChild("fg-root", 0, false);
256     n = n->getChild("fg-root", 0, true);
257     n->setStringValue(fg_root.c_str());
258     n->setAttribute(SGPropertyNode::WRITE, false);
259     
260     simgear::ResourceManager::instance()->addBasePath(fg_root, 
261       simgear::ResourceManager::PRIORITY_DEFAULT);
262 }
263
264 // set the fg_home path
265 void FGGlobals::set_fg_home (const std::string &home) {
266     SGPath tmp(home);
267     fg_home = tmp.realpath();
268 }
269
270 PathList FGGlobals::get_data_paths() const
271 {
272     PathList r(additional_data_paths);
273     r.push_back(SGPath(fg_root));
274     return r;
275 }
276
277 PathList FGGlobals::get_data_paths(const std::string& suffix) const
278 {
279     PathList r;
280     BOOST_FOREACH(SGPath p, get_data_paths()) {
281         p.append(suffix);
282         if (p.exists()) {
283             r.push_back(p);
284         }
285     }
286
287     return r;
288 }
289
290 void FGGlobals::append_data_path(const SGPath& path)
291 {
292     if (!path.exists()) {
293         SG_LOG(SG_GENERAL, SG_WARN, "adding non-existant data path:" << path);
294     }
295     
296     additional_data_paths.push_back(path);
297 }
298
299 SGPath FGGlobals::find_data_dir(const std::string& pathSuffix) const
300 {
301     BOOST_FOREACH(SGPath p, additional_data_paths) {
302         p.append(pathSuffix);
303         if (p.exists()) {
304             return p;
305         }
306     }
307     
308     SGPath rootPath(fg_root);
309     rootPath.append(pathSuffix);
310     if (rootPath.exists()) {
311         return rootPath;
312     }
313     
314     SG_LOG(SG_GENERAL, SG_WARN, "dir not found in any data path:" << pathSuffix);
315     return SGPath();
316 }
317
318 void FGGlobals::append_fg_scenery (const std::string &paths)
319 {
320 //    fg_scenery.clear();
321     SGPropertyNode* sim = fgGetNode("/sim", true);
322
323   // find first unused fg-scenery property in /sim
324     int propIndex = 0;
325     while (sim->getChild("fg-scenery", propIndex) != NULL) {
326       ++propIndex; 
327     }
328   
329     BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
330         SGPath abspath(path.realpath());
331         if (!abspath.exists()) {
332           SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << abspath.str());
333           continue;
334         }
335
336       // check for duplicates
337       string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), abspath.str());
338       if (ex != fg_scenery.end()) {
339         SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << abspath.str());
340         continue;
341       }
342       
343         simgear::Dir dir(abspath);
344         SGPath terrainDir(dir.file("Terrain"));
345         SGPath objectsDir(dir.file("Objects"));
346         
347       // this code used to add *either* the base dir, OR add the 
348       // Terrain and Objects subdirs, but the conditional logic was commented
349       // out, such that all three dirs are added. Unfortunately there's
350       // no information as to why the change was made.
351         fg_scenery.push_back(abspath.str());
352         
353         if (terrainDir.exists()) {
354           fg_scenery.push_back(terrainDir.str());
355         }
356         
357         if (objectsDir.exists()) {
358           fg_scenery.push_back(objectsDir.str());
359         }
360         
361         // insert a marker for FGTileEntry::load(), so that
362         // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
363         // "B/Terrain", "B/Objects", ""]
364         fg_scenery.push_back("");
365         
366       // make scenery dirs available to Nasal
367         SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
368         n->setStringValue(abspath.str());
369         n->setAttribute(SGPropertyNode::WRITE, false);
370     } // of path list iteration
371 }
372
373 void FGGlobals::append_aircraft_path(const std::string& path)
374 {
375   SGPath dirPath(path);
376   if (!dirPath.exists()) {
377     SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
378     return;
379   }
380   std::string abspath = dirPath.realpath();
381   
382   unsigned int index = fg_aircraft_dirs.size();  
383   fg_aircraft_dirs.push_back(abspath);
384   
385 // make aircraft dirs available to Nasal
386   SGPropertyNode* sim = fgGetNode("/sim", true);
387   sim->removeChild("fg-aircraft", index, false);
388   SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
389   n->setStringValue(abspath);
390   n->setAttribute(SGPropertyNode::WRITE, false);
391 }
392
393 void FGGlobals::append_aircraft_paths(const std::string& path)
394 {
395   string_list paths = sgPathSplit(path);
396   for (unsigned int p = 0; p<paths.size(); ++p) {
397     append_aircraft_path(paths[p]);
398   }
399 }
400
401 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
402 {
403   return simgear::ResourceManager::instance()->findPath(branch);
404 }
405
406 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
407 {
408   return simgear::ResourceManager::instance()->findPath(branch);
409 }
410
411 SGPath FGGlobals::resolve_resource_path(const std::string& branch) const
412 {
413   return simgear::ResourceManager::instance()
414     ->findPath(branch, SGPath(fgGetString("/sim/aircraft-dir")));
415 }
416
417 FGRenderer *
418 FGGlobals::get_renderer () const
419 {
420    return renderer;
421 }
422
423 void FGGlobals::set_renderer(FGRenderer *render)
424 {
425     if (render == renderer) {
426         return;
427     }
428     
429     delete renderer;
430     renderer = render;
431 }
432
433 SGSubsystemMgr *
434 FGGlobals::get_subsystem_mgr () const
435 {
436     return subsystem_mgr;
437 }
438
439 SGSubsystem *
440 FGGlobals::get_subsystem (const char * name)
441 {
442     if (!subsystem_mgr) {
443         return NULL;
444     }
445     
446     return subsystem_mgr->get_subsystem(name);
447 }
448
449 void
450 FGGlobals::add_subsystem (const char * name,
451                           SGSubsystem * subsystem,
452                           SGSubsystemMgr::GroupType type,
453                           double min_time_sec)
454 {
455     subsystem_mgr->add(name, subsystem, type, min_time_sec);
456 }
457
458 SGSoundMgr *
459 FGGlobals::get_soundmgr () const
460 {
461     if (subsystem_mgr)
462         return (SGSoundMgr*) subsystem_mgr->get_subsystem("sound");
463
464     return NULL;
465 }
466
467 SGEventMgr *
468 FGGlobals::get_event_mgr () const
469 {
470     return event_mgr;
471 }
472
473 SGGeod
474 FGGlobals::get_aircraft_position() const
475 {
476   return SGGeod::fromDegFt(positionLon->getDoubleValue(),
477                            positionLat->getDoubleValue(),
478                            positionAlt->getDoubleValue());
479 }
480
481 SGVec3d
482 FGGlobals::get_aircraft_position_cart() const
483 {
484     return SGVec3d::fromGeod(get_aircraft_position());
485 }
486
487 void FGGlobals::get_aircraft_orientation(double& heading, double& pitch, double& roll)
488 {
489   heading = orientHeading->getDoubleValue();
490   pitch = orientPitch->getDoubleValue();
491   roll = orientRoll->getDoubleValue();
492 }
493
494 SGGeod
495 FGGlobals::get_view_position() const
496 {
497   return SGGeod::fromDegFt(viewLon->getDoubleValue(),
498                            viewLat->getDoubleValue(),
499                            viewAlt->getDoubleValue());
500 }
501
502 SGVec3d
503 FGGlobals::get_view_position_cart() const
504 {
505   return SGVec3d::fromGeod(get_view_position());
506 }
507
508 static void treeDumpRefCounts(int depth, SGPropertyNode* nd)
509 {
510     for (int i=0; i<nd->nChildren(); ++i) {
511         SGPropertyNode* cp = nd->getChild(i);
512         if (SGReferenced::count(cp) > 1) {
513             SG_LOG(SG_GENERAL, SG_INFO, "\t" << cp->getPath() << " refcount:" << SGReferenced::count(cp));
514         }
515         
516         treeDumpRefCounts(depth + 1, cp);
517     }
518 }
519
520 void
521 FGGlobals::resetPropertyRoot()
522 {
523     delete locale;
524     
525     SG_LOG(SG_GENERAL, SG_INFO, "root props refcount:" << props.getNumRefs());
526     treeDumpRefCounts(0, props);
527
528     props = new SGPropertyNode;
529     initProperties();
530     locale = new FGLocale(props);
531     
532     // remove /sim/fg-root before writing to prevent hijacking
533     SGPropertyNode *n = props->getNode("/sim", true);
534     n->removeChild("fg-root", 0, false);
535     n = n->getChild("fg-root", 0, true);
536     n->setStringValue(fg_root.c_str());
537     n->setAttribute(SGPropertyNode::WRITE, false);
538 }
539
540 // Save the current state as the initial state.
541 void
542 FGGlobals::saveInitialState ()
543 {
544   initial_state = new SGPropertyNode();
545
546   // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
547   int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
548                  SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
549   int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
550   if (!copyProperties(props, initial_state, expected, checked))
551     SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
552     
553   // delete various properties from the initial state, since we want to
554   // preserve their values even if doing a restore
555   // => Properties should now use the PRESERVE flag to protect their values
556   // on sim-reset. Remove some specific properties for backward compatibility.
557   SGPropertyNode* sim = initial_state->getChild("sim");
558   SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
559   if (cameraGroupNode) {
560     cameraGroupNode->removeChild("camera");
561     cameraGroupNode->removeChild("gui");
562   }
563 }
564
565 static std::string autosaveName()
566 {
567     std::ostringstream os;
568     string_list versionParts = simgear::strutils::split(VERSION, ".");
569     if (versionParts.size() < 2) {
570         return "autosave.xml";
571     }
572     
573     os << "autosave_" << versionParts[0] << "_" << versionParts[1] << ".xml";
574     return os.str();
575 }
576
577 // Restore the saved initial state, if any
578 void
579 FGGlobals::restoreInitialState ()
580 {
581     if ( initial_state == 0 ) {
582         SG_LOG(SG_GENERAL, SG_ALERT,
583                "No initial state available to restore!!!");
584         return;
585     }
586     // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
587     int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
588                    SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
589     int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
590     if ( copyProperties(initial_state, props, expected, checked)) {
591         SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
592     } else {
593         SG_LOG( SG_GENERAL, SG_INFO,
594                 "Some errors restoring initial state (read-only props?)" );
595     }
596
597 }
598
599 // Load user settings from autosave.xml
600 void
601 FGGlobals::loadUserSettings(const SGPath& dataPath)
602 {
603     // remember that we have (tried) to load any existing autsave.xml
604     haveUserSettings = true;
605
606     SGPath autosaveFile = simgear::Dir(dataPath).file(autosaveName());
607     SGPropertyNode autosave;
608     if (autosaveFile.exists()) {
609       SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << autosaveFile.str());
610       try {
611           readProperties(autosaveFile.str(), &autosave, SGPropertyNode::USERARCHIVE);
612       } catch (sg_exception& e) {
613           SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
614             << "(from " << e.getOrigin() << ")");
615       }
616     }
617     copyProperties(&autosave, globals->get_props());
618 }
619
620 // Save user settings in autosave.xml
621 void
622 FGGlobals::saveUserSettings()
623 {
624     // only save settings when we have (tried) to load the previous
625     // settings (otherwise user data was lost)
626     if (!haveUserSettings)
627         return;
628
629     if (fgGetBool("/sim/startup/save-on-exit")) {
630       // don't save settings more than once on shutdown
631       haveUserSettings = false;
632
633       SGPath autosaveFile(globals->get_fg_home());
634       autosaveFile.append(autosaveName());
635       autosaveFile.create_dir( 0700 );
636       SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << autosaveFile.str());
637       try {
638         writeProperties(autosaveFile.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
639       } catch (const sg_exception &e) {
640         guiErrorMessage("Error writing autosave:", e);
641       }
642       SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
643     }
644 }
645
646 FGViewer *
647 FGGlobals::get_current_view () const
648 {
649   return viewmgr->get_current_view();
650 }
651
652 long int FGGlobals::get_warp() const
653 {
654   return fgGetInt("/sim/time/warp");
655 }
656
657 void FGGlobals::set_warp( long int w )
658 {
659   fgSetInt("/sim/time/warp", w);
660 }
661
662 long int FGGlobals::get_warp_delta() const
663 {
664   return fgGetInt("/sim/time/warp-delta");
665 }
666
667 void FGGlobals::set_warp_delta( long int d )
668 {
669   fgSetInt("/sim/time/warp-delta", d);
670 }
671
672 FGScenery* FGGlobals::get_scenery () const
673 {
674     return _scenery.get();
675 }
676
677 void FGGlobals::set_scenery ( FGScenery *s )
678 {
679     _scenery = s;
680 }
681
682 FGTileMgr* FGGlobals::get_tile_mgr () const
683 {
684     return _tile_mgr.get();
685 }
686
687 void FGGlobals::set_tile_mgr ( FGTileMgr *t )
688 {
689     _tile_mgr = t;
690 }
691
692 void FGGlobals::set_matlib( SGMaterialLib *m )
693 {
694     if (matlib)
695         delete matlib;
696     matlib = m;
697 }
698
699 // end of globals.cxx