]> git.mxchange.org Git - flightgear.git/blob - src/Main/globals.cxx
dc48bd8467ed543dd5d94cd14ec484f5728b6b72
[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/magvar/magvar.hxx>
36 #include <simgear/scene/material/matlib.hxx>
37 #include <simgear/structure/subsystem_mgr.hxx>
38 #include <simgear/structure/event_mgr.hxx>
39 #include <simgear/sound/soundmgr_openal.hxx>
40 #include <simgear/misc/ResourceManager.hxx>
41 #include <simgear/props/propertyObject.hxx>
42 #include <simgear/props/props_io.hxx>
43 #include <simgear/scene/model/placement.hxx>
44
45 #include <Aircraft/controls.hxx>
46 #include <Airports/runways.hxx>
47 #include <ATCDCL/ATCmgr.hxx>
48 #include <Autopilot/route_mgr.hxx>
49 #include <Cockpit/panel.hxx>
50 #include <GUI/new_gui.hxx>
51 #include <Model/acmodel.hxx>
52 #include <Model/modelmgr.hxx>
53 #include <MultiPlayer/multiplaymgr.hxx>
54 #include <Scenery/scenery.hxx>
55 #include <Scenery/tilemgr.hxx>
56 #include <Navaids/navlist.hxx>
57
58 #include "globals.hxx"
59 #include "renderer.hxx"
60 #include "viewmgr.hxx"
61
62 #include "fg_props.hxx"
63 #include "fg_io.hxx"
64
65 class AircraftResourceProvider : public simgear::ResourceProvider
66 {
67 public:
68   AircraftResourceProvider() :
69     simgear::ResourceProvider(simgear::ResourceManager::PRIORITY_HIGH)
70   {
71   }
72   
73   virtual SGPath resolve(const std::string& aResource, SGPath&) const
74   {
75     string_list pieces(sgPathBranchSplit(aResource));
76     if ((pieces.size() < 3) || (pieces.front() != "Aircraft")) {
77       return SGPath(); // not an Aircraft path
78     }
79     
80   // test against the aircraft-dir property
81     const char* aircraftDir = fgGetString("/sim/aircraft-dir");
82     string_list aircraftDirPieces(sgPathBranchSplit(aircraftDir));
83     if (!aircraftDirPieces.empty() && (aircraftDirPieces.back() == pieces[1])) {
84         // current aircraft-dir matches resource aircraft
85         SGPath r(aircraftDir);
86         for (unsigned int i=2; i<pieces.size(); ++i) {
87           r.append(pieces[i]);
88         }
89         
90         if (r.exists()) {
91           SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " via /sim/aircraft-dir: " << r.str());
92           return r;
93         }
94     }
95   
96   // try each aircraft dir in turn
97     std::string res(aResource, 9); // resource path with 'Aircraft/' removed
98     const string_list& dirs(globals->get_aircraft_paths());
99     string_list::const_iterator it = dirs.begin();
100     for (; it != dirs.end(); ++it) {
101       SGPath p(*it, res);
102       if (p.exists()) {
103         SG_LOG(SG_IO, SG_DEBUG, "found path:" << aResource << " in aircraft dir: " << *it);
104         return p;
105       }
106     } // of aircraft path iteration
107     
108     return SGPath(); // not found
109   }
110 };
111
112 ////////////////////////////////////////////////////////////////////////
113 // Implementation of FGGlobals.
114 ////////////////////////////////////////////////////////////////////////
115
116 // global global :-)
117 FGGlobals *globals;
118
119
120 // Constructor
121 FGGlobals::FGGlobals() :
122     props( new SGPropertyNode ),
123     initial_state( NULL ),
124     locale( NULL ),
125     renderer( new FGRenderer ),
126     subsystem_mgr( new SGSubsystemMgr ),
127     event_mgr( new SGEventMgr ),
128     soundmgr( new SGSoundMgr ),
129     sim_time_sec( 0.0 ),
130     fg_root( "" ),
131     time_params( NULL ),
132     ephem( NULL ),
133     mag( NULL ),
134     matlib( NULL ),
135     route_mgr( NULL ),
136     current_panel( NULL ),
137     ATC_mgr( NULL ),
138     controls( NULL ),
139     viewmgr( NULL ),
140     commands( SGCommandMgr::instance() ),
141     acmodel( NULL ),
142     model_mgr( NULL ),
143     channel_options_list( NULL ),
144     initial_waypoints( NULL ),
145     scenery( NULL ),
146     tile_mgr( NULL ),
147     fontcache ( new FGFontCache ),
148     navlist( NULL ),
149     loclist( NULL ),
150     gslist( NULL ),
151     dmelist( NULL ),
152     tacanlist( NULL ),
153     carrierlist( NULL ),
154     channellist( NULL )    
155 {
156   simgear::ResourceManager::instance()->addProvider(new AircraftResourceProvider());
157   simgear::PropertyObjectBase::setDefaultRoot(props);
158 }
159
160
161 // Destructor
162 FGGlobals::~FGGlobals() 
163 {    
164 // The AIModels manager performs a number of actions upon
165     // Shutdown that implicitly assume that other subsystems
166     // are still operational (Due to the dynamic allocation and
167     // deallocation of AIModel objects. To ensure we can safely
168     // shut down all subsystems, make sure we take down the 
169     // AIModels system first.
170     SGSubsystem* ai = subsystem_mgr->remove("ai-model");
171     if (ai) {
172         ai->unbind();
173         delete ai;
174     }
175     
176     subsystem_mgr->shutdown();
177     subsystem_mgr->unbind();
178     delete subsystem_mgr;
179     
180     delete renderer;
181     renderer = NULL;
182     
183     delete time_params;
184     delete mag;
185     delete matlib;
186     delete route_mgr;
187     delete current_panel;
188
189     delete ATC_mgr;
190
191     if (controls)
192     {
193         controls->unbind();
194         delete controls;
195     }
196
197     delete channel_options_list;
198     delete initial_waypoints;
199     delete scenery;
200     delete fontcache;
201
202     delete navlist;
203     delete loclist;
204     delete gslist;
205     delete dmelist;
206     delete tacanlist;
207     delete carrierlist;
208     delete channellist;
209
210     soundmgr->unbind();
211     delete soundmgr;
212 }
213
214
215 // set the fg_root path
216 void FGGlobals::set_fg_root (const string &root) {
217     fg_root = root;
218
219     // append /data to root if it exists
220     SGPath tmp( fg_root );
221     tmp.append( "data" );
222     tmp.append( "version" );
223     if ( ulFileExists( tmp.c_str() ) ) {
224         fgGetNode("BAD_FG_ROOT", true)->setStringValue(fg_root);
225         fg_root += "/data";
226         fgGetNode("GOOD_FG_ROOT", true)->setStringValue(fg_root);
227         SG_LOG(SG_GENERAL, SG_ALERT, "***\n***\n*** Warning: changing bad FG_ROOT/--fg-root to '"
228                 << fg_root << "'\n***\n***");
229     }
230
231     // remove /sim/fg-root before writing to prevent hijacking
232     SGPropertyNode *n = fgGetNode("/sim", true);
233     n->removeChild("fg-root", 0, false);
234     n = n->getChild("fg-root", 0, true);
235     n->setStringValue(fg_root.c_str());
236     n->setAttribute(SGPropertyNode::WRITE, false);
237     
238     simgear::ResourceManager::instance()->addBasePath(fg_root, 
239       simgear::ResourceManager::PRIORITY_DEFAULT);
240 }
241
242 void FGGlobals::append_fg_scenery (const string &paths)
243 {
244 //    fg_scenery.clear();
245     SGPropertyNode* sim = fgGetNode("/sim", true);
246
247   // find first unused fg-scenery property in /sim
248     int propIndex = 0;
249     while (sim->getChild("fg-scenery", propIndex) != NULL) {
250       ++propIndex; 
251     }
252   
253     BOOST_FOREACH(const SGPath& path, sgPathSplit( paths )) {
254         if (!path.exists()) {
255           SG_LOG(SG_GENERAL, SG_WARN, "scenery path not found:" << path.str());
256           continue;
257         }
258
259       // check for duplicates
260       string_list::const_iterator ex = std::find(fg_scenery.begin(), fg_scenery.end(), path.str());
261       if (ex != fg_scenery.end()) {
262         SG_LOG(SG_GENERAL, SG_INFO, "skipping duplicate add of scenery path:" << path.str());
263         continue;
264       }
265       
266         simgear::Dir dir(path);
267         SGPath terrainDir(dir.file("Terrain"));
268         SGPath objectsDir(dir.file("Objects"));
269         
270       // this code used to add *either* the base dir, OR add the 
271       // Terrain and Objects subdirs, but the conditional logic was commented
272       // out, such that all three dirs are added. Unfortunately there's
273       // no information as to why the change was made.
274         fg_scenery.push_back(path.str());
275         
276         if (terrainDir.exists()) {
277           fg_scenery.push_back(terrainDir.str());
278         }
279         
280         if (objectsDir.exists()) {
281           fg_scenery.push_back(objectsDir.str());
282         }
283         
284         // insert a marker for FGTileEntry::load(), so that
285         // FG_SCENERY=A:B becomes list ["A/Terrain", "A/Objects", "",
286         // "B/Terrain", "B/Objects", ""]
287         fg_scenery.push_back("");
288         
289       // make scenery dirs available to Nasal
290         SGPropertyNode* n = sim->getChild("fg-scenery", propIndex++, true);
291         n->setStringValue(path.str());
292         n->setAttribute(SGPropertyNode::WRITE, false);
293     } // of path list iteration
294 }
295
296 void FGGlobals::append_aircraft_path(const std::string& path)
297 {
298   SGPath dirPath(path);
299   if (!dirPath.exists()) {
300     SG_LOG(SG_GENERAL, SG_WARN, "aircraft path not found:" << path);
301     return;
302   }
303   
304   unsigned int index = fg_aircraft_dirs.size();  
305   fg_aircraft_dirs.push_back(path);
306   
307 // make aircraft dirs available to Nasal
308   SGPropertyNode* sim = fgGetNode("/sim", true);
309   sim->removeChild("fg-aircraft", index, false);
310   SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
311   n->setStringValue(path);
312   n->setAttribute(SGPropertyNode::WRITE, false);
313 }
314
315 void FGGlobals::append_aircraft_paths(const std::string& path)
316 {
317   string_list paths = sgPathSplit(path);
318   for (unsigned int p = 0; p<paths.size(); ++p) {
319     append_aircraft_path(paths[p]);
320   }
321 }
322
323 SGPath FGGlobals::resolve_aircraft_path(const std::string& branch) const
324 {
325   return simgear::ResourceManager::instance()->findPath(branch);
326 }
327
328 SGPath FGGlobals::resolve_maybe_aircraft_path(const std::string& branch) const
329 {
330   return simgear::ResourceManager::instance()->findPath(branch);
331 }
332
333 FGRenderer *
334 FGGlobals::get_renderer () const
335 {
336    return renderer;
337 }
338
339 SGSubsystemMgr *
340 FGGlobals::get_subsystem_mgr () const
341 {
342     return subsystem_mgr;
343 }
344
345 SGSubsystem *
346 FGGlobals::get_subsystem (const char * name)
347 {
348     return subsystem_mgr->get_subsystem(name);
349 }
350
351 void
352 FGGlobals::add_subsystem (const char * name,
353                           SGSubsystem * subsystem,
354                           SGSubsystemMgr::GroupType type,
355                           double min_time_sec)
356 {
357     subsystem_mgr->add(name, subsystem, type, min_time_sec);
358 }
359
360 SGSoundMgr *
361 FGGlobals::get_soundmgr () const
362 {
363     return soundmgr;
364 }
365
366 SGEventMgr *
367 FGGlobals::get_event_mgr () const
368 {
369     return event_mgr;
370 }
371
372 const SGGeod &
373 FGGlobals::get_aircraft_position() const
374 {
375     if( acmodel != NULL ) {
376         SGModelPlacement * mp = acmodel->get3DModel();
377         if( mp != NULL )
378             return mp->getPosition();
379     }
380     throw sg_exception("Can't get aircraft position", "FGGlobals::get_aircraft_position()" );
381 }
382
383 SGVec3d
384 FGGlobals::get_aircraft_positon_cart() const
385 {
386     return SGVec3d::fromGeod(get_aircraft_position());
387 }
388
389
390 // Save the current state as the initial state.
391 void
392 FGGlobals::saveInitialState ()
393 {
394   initial_state = new SGPropertyNode();
395
396   // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
397   int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
398                  SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
399   int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
400   if (!copyProperties(props, initial_state, expected, checked))
401     SG_LOG(SG_GENERAL, SG_ALERT, "Error saving initial state");
402     
403   // delete various properties from the initial state, since we want to
404   // preserve their values even if doing a restore
405   // => Properties should now use the PRESERVE flag to protect their values
406   // on sim-reset. Remove some specific properties for backward compatibility.
407   SGPropertyNode* sim = initial_state->getChild("sim");
408   SGPropertyNode* cameraGroupNode = sim->getNode("rendering/camera-group");
409   if (cameraGroupNode) {
410     cameraGroupNode->removeChild("camera");
411     cameraGroupNode->removeChild("gui");
412   }
413 }
414
415
416 // Restore the saved initial state, if any
417 void
418 FGGlobals::restoreInitialState ()
419 {
420     if ( initial_state == 0 ) {
421         SG_LOG(SG_GENERAL, SG_ALERT,
422                "No initial state available to restore!!!");
423         return;
424     }
425     // copy properties which are READ/WRITEable - but not USERARCHIVEd or PRESERVEd
426     int checked  = SGPropertyNode::READ+SGPropertyNode::WRITE+
427                    SGPropertyNode::USERARCHIVE+SGPropertyNode::PRESERVE;
428     int expected = SGPropertyNode::READ+SGPropertyNode::WRITE;
429     if ( copyProperties(initial_state, props, expected, checked)) {
430         SG_LOG( SG_GENERAL, SG_INFO, "Initial state restored successfully" );
431     } else {
432         SG_LOG( SG_GENERAL, SG_INFO,
433                 "Some errors restoring initial state (read-only props?)" );
434     }
435
436 }
437
438 FGViewer *
439 FGGlobals::get_current_view () const
440 {
441   return viewmgr->get_current_view();
442 }
443
444 long int FGGlobals::get_warp() const
445 {
446   return fgGetInt("/sim/time/warp");
447 }
448
449 void FGGlobals::set_warp( long int w )
450 {
451   fgSetInt("/sim/time/warp", w);
452 }
453
454 long int FGGlobals::get_warp_delta() const
455 {
456   return fgGetInt("/sim/time/warp-delta");
457 }
458
459 void FGGlobals::set_warp_delta( long int d )
460 {
461   fgSetInt("/sim/time/warp-delta", d);
462 }
463     
464 // end of globals.cxx