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