]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
A new comm radio and atis implementation
[flightgear.git] / src / Main / fg_init.cxx
1 // fg_init.cxx -- Flight Gear top level initialization routines
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  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
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>             // strcmp()
33
34 #if defined(SG_WINDOWS)
35 #  include <io.h>               // isatty()
36 #  include <process.h>          // _getpid()
37 #  include <Windows.h>
38 #  define isatty _isatty
39 #else
40 // for open() and options
41 #  include <sys/types.h>        
42 #  include <sys/stat.h>
43 #  include <fcntl.h>
44 #endif
45
46 #include <string>
47
48 #include <boost/algorithm/string/compare.hpp>
49 #include <boost/algorithm/string/predicate.hpp>
50
51 #include <osgViewer/Viewer>
52
53 #include <simgear/canvas/Canvas.hxx>
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/structure/exception.hxx>
57 #include <simgear/structure/event_mgr.hxx>
58 #include <simgear/structure/SGPerfMon.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/sgstream.hxx>
62 #include <simgear/misc/strutils.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/scene/tsync/terrasync.hxx>
65
66 #include <simgear/scene/model/modellib.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/material/Effect.hxx>
69 #include <simgear/scene/model/particles.hxx>
70 #include <simgear/scene/tsync/terrasync.hxx>
71
72 #include <Aircraft/controls.hxx>
73 #include <Aircraft/replay.hxx>
74 #include <Aircraft/FlightHistory.hxx>
75 #include <Airports/runways.hxx>
76 #include <Airports/airport.hxx>
77 #include <Airports/dynamics.hxx>
78
79 #include <AIModel/AIManager.hxx>
80
81 #include <ATC/atc_mgr.hxx>
82
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
85
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/panel_io.hxx>
88
89 #include <Canvas/canvas_mgr.hxx>
90 #include <Canvas/gui_mgr.hxx>
91 #include <Canvas/FGCanvasSystemAdapter.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <GUI/MessageBox.hxx>
94 #include <Input/input.hxx>
95 #include <Instrumentation/instrument_mgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Model/modelmgr.hxx>
98 #include <AIModel/submodel.hxx>
99 #include <AIModel/AIManager.hxx>
100 #include <Navaids/navdb.hxx>
101 #include <Navaids/navlist.hxx>
102 #include <Scenery/scenery.hxx>
103 #include <Scenery/tilemgr.hxx>
104 #include <Scripting/NasalSys.hxx>
105 #include <Sound/voice.hxx>
106 #include <Sound/soundmanager.hxx>
107 #include <Systems/system_mgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/TimeManager.hxx>
110
111 #include <Traffic/TrafficMgr.hxx>
112 #include <MultiPlayer/multiplaymgr.hxx>
113 #include <FDM/fdm_shell.hxx>
114 #include <Environment/ephemeris.hxx>
115 #include <Environment/environment_mgr.hxx>
116 #include <Viewer/renderer.hxx>
117 #include <Viewer/viewmgr.hxx>
118 #include <Viewer/FGEventHandler.hxx>
119 #include <Navaids/NavDataCache.hxx>
120 #include <Instrumentation/HUD/HUD.hxx>
121 #include <Cockpit/cockpitDisplayManager.hxx>
122 #include <Network/HTTPClient.hxx>
123 #include <Network/fgcom.hxx>
124
125 #include <Viewer/CameraGroup.hxx>
126
127 #include "fg_init.hxx"
128 #include "fg_io.hxx"
129 #include "fg_commands.hxx"
130 #include "fg_props.hxx"
131 #include "FGInterpolator.hxx"
132 #include "options.hxx"
133 #include "globals.hxx"
134 #include "logger.hxx"
135 #include "main.hxx"
136 #include "positioninit.hxx"
137 #include "util.hxx"
138 #include "AircraftDirVisitorBase.hxx"
139
140 #if defined(SG_MAC)
141 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
142 #endif
143
144 //#define NEW_RESET 1
145
146 using std::string;
147 using std::endl;
148 using std::cerr;
149 using std::cout;
150 using namespace boost::algorithm;
151
152 extern osg::ref_ptr<osgViewer::Viewer> viewer;
153
154 // Return the current base package version
155 string fgBasePackageVersion() {
156     SGPath base_path( globals->get_fg_root() );
157     base_path.append("version");
158     if (!base_path.exists()) {
159         return string();
160     }
161     
162     sg_gzifstream in( base_path.str() );
163     if (!in.is_open()) {
164         return string();
165     }
166
167     string version;
168     in >> version;
169
170     return version;
171 }
172
173 class FindAndCacheAircraft : public AircraftDirVistorBase
174 {
175 public:
176   FindAndCacheAircraft(SGPropertyNode* autoSave)
177   {
178     _cache = autoSave->getNode("sim/startup/path-cache", true);
179   }
180   
181   bool loadAircraft()
182   {
183     std::string aircraft = fgGetString( "/sim/aircraft", "");
184     if (aircraft.empty()) {
185         flightgear::fatalMessageBox("No aircraft", "No aircraft was specified");
186       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
187       return false;
188     }
189     
190     _searchAircraft = aircraft + "-set.xml";
191     std::string aircraftDir = fgGetString("/sim/aircraft-dir", "");
192     if (!aircraftDir.empty()) {
193       // aircraft-dir was set, skip any searching at all, if it's valid
194       simgear::Dir acPath(aircraftDir);
195       SGPath setFile = acPath.file(_searchAircraft);
196       if (setFile.exists()) {
197         SG_LOG(SG_GENERAL, SG_INFO, "found aircraft in dir: " << aircraftDir );
198         
199         try {
200           readProperties(setFile.str(), globals->get_props());
201         } catch ( const sg_exception &e ) {
202           SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
203             flightgear::fatalMessageBox("Error reading aircraft",
204                                         "An error occured reading the requested aircraft (" + aircraft + ")",
205                                         e.getFormattedMessage());
206           return false;
207         }
208         
209         return true;
210       } else {
211         SG_LOG(SG_GENERAL, SG_ALERT, "aircraft '" << _searchAircraft << 
212                "' not found in specified dir:" << aircraftDir);
213           flightgear::fatalMessageBox("Aircraft not found",
214                                       "The requested aircraft '" + aircraft + "' could not be found in the specified location.",
215                                       aircraftDir);
216         return false;
217       }
218     }
219     
220     if (!checkCache()) {
221       // prepare cache for re-scan
222       SGPropertyNode *n = _cache->getNode("fg-root", true);
223       n->setStringValue(globals->get_fg_root().c_str());
224       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
225       n = _cache->getNode("fg-aircraft", true);
226       n->setStringValue(getAircraftPaths().c_str());
227       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
228       _cache->removeChildren("aircraft");
229   
230         visitAircraftPaths();
231     }
232     
233     if (_foundPath.str().empty()) {
234       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
235         flightgear::fatalMessageBox("Aircraft not found",
236                                     "The requested aircraft '" + aircraft + "' could not be found in any of the search paths");
237
238       return false;
239     }
240     
241     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
242     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
243     if (!_foundPath.exists()) {
244       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
245       return false;
246     }
247     
248     try {
249       readProperties(_foundPath.str(), globals->get_props());
250     } catch ( const sg_exception &e ) {
251       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
252         flightgear::fatalMessageBox("Error reading aircraft",
253                                     "An error occured reading the requested aircraft (" + aircraft + ")",
254                                     e.getFormattedMessage());
255       return false;
256     }
257     
258     return true;
259   }
260   
261 private:
262   SGPath getAircraftPaths() {
263     string_list pathList = globals->get_aircraft_paths();
264     SGPath aircraftPaths;
265     string_list::const_iterator it = pathList.begin();
266     if (it != pathList.end()) {
267         aircraftPaths.set(*it);
268         it++;
269     }
270     for (; it != pathList.end(); ++it) {
271         aircraftPaths.add(*it);
272     }
273     return aircraftPaths;
274   }
275   
276   bool checkCache()
277   {
278     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
279       return false; // cache mismatch
280     }
281
282     if (getAircraftPaths().str() != _cache->getStringValue("fg-aircraft", "")) {
283       return false; // cache mismatch
284     }
285     
286     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
287     for (unsigned int i = 0; i < cache.size(); i++) {
288       const char *name = cache[i]->getStringValue("file", "");
289       if (!boost::equals(_searchAircraft, name, is_iequal())) {
290         continue;
291       }
292       
293       SGPath xml(cache[i]->getStringValue("path", ""));
294       xml.append(name);
295       if (xml.exists()) {
296         _foundPath = xml;
297         return true;
298       } 
299       
300       return false;
301     } // of aircraft in cache iteration
302     
303     return false;
304   }
305   
306   virtual VisitResult visit(const SGPath& p)
307   {
308     // create cache node
309     int i = 0;
310     while (1) {
311         if (!_cache->getChild("aircraft", i++, false))
312             break;
313     }
314     
315     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
316
317     std::string fileName(p.file());
318     n = entry->getNode("file", true);
319     n->setStringValue(fileName);
320     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
321
322     n = entry->getNode("path", true);
323     n->setStringValue(p.dir());
324     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
325
326     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
327         _foundPath = p;
328         return VISIT_DONE;
329     }
330
331     return VISIT_CONTINUE;
332   }
333   
334   std::string _searchAircraft;
335   SGPath _foundPath;
336   SGPropertyNode* _cache;
337 };
338
339 #ifdef _WIN32
340 static SGPath platformDefaultDataPath()
341 {
342   char *envp = ::getenv( "APPDATA" );
343   SGPath config( envp );
344   config.append( "flightgear.org" );
345   return config;
346 }
347
348 #elif defined(SG_MAC)
349
350 // platformDefaultDataPath defined in GUI/CocoaHelpers.h
351
352 #else
353 static SGPath platformDefaultDataPath()
354 {
355   return SGPath::home() / ".fgfs";
356 }
357 #endif
358
359 bool fgInitHome()
360 {
361   SGPath dataPath = SGPath::fromEnv("FG_HOME", platformDefaultDataPath());
362   globals->set_fg_home(dataPath.c_str());
363     
364     simgear::Dir fgHome(dataPath);
365     if (!fgHome.exists()) {
366         fgHome.create(0755);
367     }
368     
369     if (!fgHome.exists()) {
370         flightgear::fatalMessageBox("Problem setting up user data",
371                                     "Unable to create the user-data storage folder at: '"
372                                     + dataPath.str() + "'");
373         return false;
374     }
375     
376     if (fgGetBool("/sim/fghome-readonly", false)) {
377         // user / config forced us into readonly mode, fine
378         SG_LOG(SG_GENERAL, SG_INFO, "Running with FG_HOME readonly");
379         return true;
380     }
381     
382 // write our PID, and check writeability
383     SGPath pidPath(dataPath, "fgfs.pid");
384     if (pidPath.exists()) {
385         SG_LOG(SG_GENERAL, SG_INFO, "flightgear instance already running, switching to FG_HOME read-only.");
386         // set a marker property so terrasync/navcache don't try to write
387         // from secondary instances
388         fgSetBool("/sim/fghome-readonly", true);
389         return true;
390     }
391     
392     char buf[16];
393     bool result = false;
394 #if defined(SG_WINDOWS)
395     size_t len = snprintf(buf, 16, "%d", _getpid());
396
397     HANDLE f = CreateFileA(pidPath.c_str(), GENERIC_READ | GENERIC_WRITE, 
398                                                    FILE_SHARE_READ, /* sharing */
399                            NULL, /* security attributes */
400                            CREATE_NEW, /* error if already exists */
401                            FILE_FLAG_DELETE_ON_CLOSE,
402                                                    NULL /* template */);
403     
404     result = (f != INVALID_HANDLE_VALUE);
405     if (result) {
406                 DWORD written;
407         WriteFile(f, buf, len, &written, NULL /* overlapped */);
408     }
409 #else
410     // POSIX, do open+unlink trick to the file is deleted on exit, even if we
411     // crash or exit(-1)
412     ssize_t len = snprintf(buf, 16, "%d", getpid());
413     int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
414     if (fd >= 0) {
415         result = ::write(fd, buf, len) == len;
416         if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
417           result = false;
418     }
419 #endif
420
421     fgSetBool("/sim/fghome-readonly", false);
422
423     if (!result) {
424         flightgear::fatalMessageBox("File permissions problem",
425                                     "Can't write to user-data storage folder, check file permissions and FG_HOME.",
426                                     "User-data at:" + dataPath.str());
427     }
428     return result;
429 }
430
431 // Read in configuration (file and command line)
432 int fgInitConfig ( int argc, char **argv, bool reinit )
433 {
434     SGPath dataPath = globals->get_fg_home();
435     
436     simgear::Dir exportDir(simgear::Dir(dataPath).file("Export"));
437     if (!exportDir.exists()) {
438       exportDir.create(0755);
439     }
440     
441     // Set /sim/fg-home and don't allow malign code to override it until
442     // Nasal security is set up.  Use FG_HOME if necessary.
443     SGPropertyNode *home = fgGetNode("/sim", true);
444     home->removeChild("fg-home", 0, false);
445     home = home->getChild("fg-home", 0, true);
446     home->setStringValue(dataPath.c_str());
447     home->setAttribute(SGPropertyNode::WRITE, false);
448   
449     fgSetDefaults();
450     flightgear::Options* options = flightgear::Options::sharedInstance();
451     if (!reinit) {
452         options->init(argc, argv, dataPath);
453     }
454     
455     bool loadDefaults = options->shouldLoadDefaultConfig();
456     if (loadDefaults) {
457       // Read global preferences from $FG_ROOT/preferences.xml
458       SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
459       fgLoadProps("preferences.xml", globals->get_props());
460       SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
461         
462       // do not load user settings when reset to default is requested, or if
463       // told to explicitly ignore
464       if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
465       {
466           SG_LOG(SG_ALL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
467       }
468       else
469       {
470           globals->loadUserSettings(dataPath);
471       }
472     } else {
473       SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
474     }// of no-default-config selected
475     
476     return flightgear::FG_OPTIONS_OK;
477 }
478
479 int fgInitAircraft(bool reinit)
480 {
481     // Scan user config files and command line for a specified aircraft.
482     if (!reinit) {
483         flightgear::Options::sharedInstance()->initAircraft();
484     }
485     
486     FindAndCacheAircraft f(globals->get_props());
487     if (!f.loadAircraft()) {
488         return flightgear::FG_OPTIONS_ERROR;
489     }
490     
491     return flightgear::FG_OPTIONS_OK;
492 }
493
494 /**
495  * Initialize vor/ndb/ils/fix list management and query systems (as
496  * well as simple airport db list)
497  * This is called multiple times in the case of a cache rebuild,
498  * to allow lengthy caching to take place in the background, without
499  * blocking the main/UI thread.
500  */
501 bool
502 fgInitNav ()
503 {
504   flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
505   static bool doingRebuild = false;
506   if (doingRebuild || cache->isRebuildRequired()) {
507     doingRebuild = true;
508     bool finished = cache->rebuild();
509     if (!finished) {
510       // sleep to give the rebuild thread more time
511       SGTimeStamp::sleepForMSec(50);
512       return false;
513     }
514   }
515   
516   FGTACANList *channellist = new FGTACANList;
517   globals->set_channellist( channellist );
518   
519   SGPath path(globals->get_fg_root());
520   path.append( "Navaids/TACAN_freq.dat" );
521   flightgear::loadTacan(path, channellist);
522   
523   return true;
524 }
525
526 // General house keeping initializations
527 bool fgInitGeneral() {
528     string root;
529
530     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
531     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
532
533     root = globals->get_fg_root();
534     if ( ! root.length() ) {
535         // No root path set? Then bail ...
536         SG_LOG( SG_GENERAL, SG_ALERT,
537                 "Cannot continue without a path to the base package "
538                 << "being defined." );
539         return false;
540     }
541     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
542
543     // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
544     globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
545     fgSetString("/sim/startup/browser-app", globals->get_browser());
546
547     simgear::Dir cwd(simgear::Dir::current());
548     SGPropertyNode *curr = fgGetNode("/sim", true);
549     curr->removeChild("fg-current", 0, false);
550     curr = curr->getChild("fg-current", 0, true);
551     curr->setStringValue(cwd.path().str());
552     curr->setAttribute(SGPropertyNode::WRITE, false);
553
554     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
555     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
556     return true;
557 }
558
559 // Write various configuraton values out to the logs
560 void fgOutputSettings()
561 {    
562     SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
563     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
564     
565     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
566     SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
567     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"');
568     
569     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
570     SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
571 }
572
573 // This is the top level init routine which calls all the other
574 // initialization routines.  If you are adding a subsystem to flight
575 // gear, its initialization call should located in this routine.
576 // Returns non-zero if a problem encountered.
577 void fgCreateSubsystems(bool duringReset) {
578
579     SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
580     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
581
582     ////////////////////////////////////////////////////////////////////
583     // Initialize the sound subsystem.
584     ////////////////////////////////////////////////////////////////////
585     // Sound manager uses an own subsystem group "SOUND" which is the last
586     // to be updated in every loop.
587     // Sound manager is updated last so it can use the CPU while the GPU
588     // is processing the scenery (doubled the frame-rate for me) -EMH-
589     globals->add_subsystem("sound", new FGSoundManager, SGSubsystemMgr::SOUND);
590
591     ////////////////////////////////////////////////////////////////////
592     // Initialize the event manager subsystem.
593     ////////////////////////////////////////////////////////////////////
594
595     globals->get_event_mgr()->init();
596     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
597
598     ////////////////////////////////////////////////////////////////////
599     // Initialize the property interpolator subsystem. Put into the INIT
600     // group because the "nasal" subsystem may need it at GENERAL take-down.
601     ////////////////////////////////////////////////////////////////////
602     FGInterpolator* interp = new FGInterpolator;
603     interp->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
604     globals->add_subsystem("prop-interpolator", interp, SGSubsystemMgr::INIT);
605     SGPropertyNode::setInterpolationMgr(interp);
606
607     ////////////////////////////////////////////////////////////////////
608     // Add the FlightGear property utilities.
609     ////////////////////////////////////////////////////////////////////
610     globals->add_subsystem("properties", new FGProperties);
611
612
613     ////////////////////////////////////////////////////////////////////
614     // Add the performance monitoring system.
615     ////////////////////////////////////////////////////////////////////
616     globals->add_subsystem("performance-mon",
617             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
618                                      fgGetNode("/sim/performance-monitor", true)));
619
620     ////////////////////////////////////////////////////////////////////
621     // Initialize the material property subsystem.
622     ////////////////////////////////////////////////////////////////////
623
624     SGPath mpath( globals->get_fg_root() );
625     mpath.append( fgGetString("/sim/rendering/materials-file") );
626     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
627             globals->get_props()) ) {
628        throw sg_io_exception("Error loading materials file", mpath);
629     }
630     
631     globals->add_subsystem( "http", new FGHTTPClient );
632     
633     ////////////////////////////////////////////////////////////////////
634     // Initialize the scenery management subsystem.
635     ////////////////////////////////////////////////////////////////////
636
637     globals->get_scenery()->get_scene_graph()
638         ->addChild(simgear::Particles::getCommonRoot());
639     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
640
641     ////////////////////////////////////////////////////////////////////
642     // Initialize the flight model subsystem.
643     ////////////////////////////////////////////////////////////////////
644
645     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
646
647     ////////////////////////////////////////////////////////////////////
648     // Initialize the weather subsystem.
649     ////////////////////////////////////////////////////////////////////
650
651     // Initialize the weather modeling subsystem
652     globals->add_subsystem("environment", new FGEnvironmentMgr);
653     globals->add_subsystem("ephemeris", new Ephemeris);
654     
655     ////////////////////////////////////////////////////////////////////
656     // Initialize the aircraft systems and instrumentation (before the
657     // autopilot.)
658     ////////////////////////////////////////////////////////////////////
659
660     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
661     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
662     globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
663     globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
664   
665     ////////////////////////////////////////////////////////////////////
666     // Initialize the XML Autopilot subsystem.
667     ////////////////////////////////////////////////////////////////////
668
669     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
670     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
671     globals->add_subsystem( "route-manager", new FGRouteMgr );
672
673     ////////////////////////////////////////////////////////////////////
674     // Initialize the Input-Output subsystem
675     ////////////////////////////////////////////////////////////////////
676     globals->add_subsystem( "io", new FGIO );
677   
678     ////////////////////////////////////////////////////////////////////
679     // Create and register the logger.
680     ////////////////////////////////////////////////////////////////////
681     
682     globals->add_subsystem("logger", new FGLogger);
683
684     ////////////////////////////////////////////////////////////////////
685     // Create and register the XML GUI.
686     ////////////////////////////////////////////////////////////////////
687
688     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
689
690     //////////////////////////////////////////////////////////////////////
691     // Initialize the 2D cloud subsystem.
692     ////////////////////////////////////////////////////////////////////
693     fgGetBool("/sim/rendering/bump-mapping", false);
694
695     ////////////////////////////////////////////////////////////////////
696     // Initialize the canvas 2d drawing subsystem.
697     ////////////////////////////////////////////////////////////////////
698     simgear::canvas::Canvas::setSystemAdapter(
699       simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
700     );
701     globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
702     globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
703
704     ////////////////////////////////////////////////////////////////////
705    // Initialize the ATC subsystem
706     ////////////////////////////////////////////////////////////////////
707     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
708
709     ////////////////////////////////////////////////////////////////////
710     // Initialize multiplayer subsystem
711     ////////////////////////////////////////////////////////////////////
712
713     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
714
715     ////////////////////////////////////////////////////////////////////
716     // Initialise the AI Model Manager
717     ////////////////////////////////////////////////////////////////////
718     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
719     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
720     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
721
722
723     // It's probably a good idea to initialize the top level traffic manager
724     // After the AI and ATC systems have been initialized properly.
725     // AI Traffic manager
726     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
727
728     ////////////////////////////////////////////////////////////////////
729     // Add a new 2D panel.
730     ////////////////////////////////////////////////////////////////////
731
732     fgSetArchivable("/sim/panel/visibility");
733     fgSetArchivable("/sim/panel/x-offset");
734     fgSetArchivable("/sim/panel/y-offset");
735     fgSetArchivable("/sim/panel/jitter");
736   
737     ////////////////////////////////////////////////////////////////////
738     // Initialize the controls subsystem.
739     ////////////////////////////////////////////////////////////////////
740     
741     globals->add_subsystem("controls", new FGControls, SGSubsystemMgr::GENERAL);
742
743     ////////////////////////////////////////////////////////////////////
744     // Initialize the input subsystem.
745     ////////////////////////////////////////////////////////////////////
746
747     globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
748
749
750     ////////////////////////////////////////////////////////////////////
751     // Initialize the replay subsystem
752     ////////////////////////////////////////////////////////////////////
753     globals->add_subsystem("replay", new FGReplay);
754     globals->add_subsystem("history", new FGFlightHistory);
755     
756 #ifdef ENABLE_AUDIO_SUPPORT
757     ////////////////////////////////////////////////////////////////////
758     // Initialize the sound-effects subsystem.
759     ////////////////////////////////////////////////////////////////////
760     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
761 #endif
762
763 #ifdef ENABLE_IAX
764     ////////////////////////////////////////////////////////////////////
765     // Initialize the FGCom subsystem.
766     ////////////////////////////////////////////////////////////////////
767     globals->add_subsystem("fgcom", new FGCom);
768 #endif
769
770     ////////////////////////////////////////////////////////////////////
771     // Initialize the lighting subsystem.
772     ////////////////////////////////////////////////////////////////////
773
774     // ordering here is important : Nasal (via events), then models, then views
775     if (!duringReset) {
776         globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
777         globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
778     }
779
780     globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
781     globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
782
783     globals->add_subsystem("view-manager", new FGViewMgr, SGSubsystemMgr::DISPLAY);
784
785     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
786       SGSubsystemMgr::DISPLAY);
787 }
788
789 void fgPostInitSubsystems()
790 {
791     SGTimeStamp st;
792     st.stamp();
793   
794     ////////////////////////////////////////////////////////////////////////
795     // Initialize the Nasal interpreter.
796     // Do this last, so that the loaded scripts see initialized state
797     ////////////////////////////////////////////////////////////////////////
798     FGNasalSys* nasal = new FGNasalSys();
799     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
800     nasal->init();
801     SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
802
803     // Ensure IOrules and path validation are working properly by trying to
804     // access a folder/file which should never be accessible.
805     const char* no_access_path =
806 #ifdef _WIN32
807       "Z:"
808 #endif
809       "/do-not-access";
810
811     if( fgValidatePath(no_access_path, true) )
812       SG_LOG
813       (
814         SG_GENERAL,
815         SG_ALERT,
816         "Check your IOrules! (write to '" << no_access_path << "' is allowed)"
817       );
818     if( fgValidatePath(no_access_path, false) )
819       SG_LOG
820       (
821         SG_GENERAL,
822         SG_ALERT,
823         "Check your IOrules! (read from '" << no_access_path << "' is allowed)"
824       );
825   
826     // initialize methods that depend on other subsystems.
827     st.stamp();
828     globals->get_subsystem_mgr()->postinit();
829     SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
830   
831     ////////////////////////////////////////////////////////////////////////
832     // End of subsystem initialization.
833     ////////////////////////////////////////////////////////////////////
834
835     fgSetBool("/sim/crashed", false);
836     fgSetBool("/sim/initialized", true);
837
838     SG_LOG( SG_GENERAL, SG_INFO, endl);
839
840                                 // Save the initial state for future
841                                 // reference.
842     globals->saveInitialState();
843 }
844
845 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
846 void fgReInitSubsystems()
847 {
848 #ifdef NEW_RESET
849     fgResetIdleState();
850     return;
851 #endif
852     
853     SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
854
855     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
856
857 // setup state to begin re-init
858     bool freeze = master_freeze->getBoolValue();
859     if ( !freeze ) {
860         master_freeze->setBoolValue(true);
861     }
862     
863     fgSetBool("/sim/signals/reinit", true);
864     fgSetBool("/sim/crashed", false);
865
866 // do actual re-init steps
867     globals->get_subsystem("flight")->unbind();
868     
869   // reset control state, before restoring initial state; -set or config files
870   // may specify values for flaps, trim tabs, magnetos, etc
871     globals->get_controls()->reset_all();
872         
873     globals->restoreInitialState();
874
875     // update our position based on current presets
876     // this will mark position as needed finalized which we'll do in the
877     // main-loop
878     flightgear::initPosition();
879     
880     simgear::SGTerraSync* terraSync =
881         static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
882     if (terraSync) {
883         terraSync->reposition();
884     }
885     
886     // Force reupdating the positions of the ai 3d models. They are used for
887     // initializing ground level for the FDM.
888     globals->get_subsystem("ai-model")->reinit();
889
890     // Initialize the FDM
891     globals->get_subsystem("flight")->reinit();
892
893     // reset replay buffers
894     globals->get_subsystem("replay")->reinit();
895     
896     // reload offsets from config defaults
897     globals->get_viewmgr()->reinit();
898
899     // ugly: finalizePosition waits for METAR to arrive for the new airport.
900     // we don't re-init the environment manager here, since historically we did
901     // not, and doing so seems to have other issues. All that's needed is to
902     // schedule METAR fetch immediately, so it's available for finalizePosition.
903     // So we manually extract the METAR-fetching component inside the environment
904     // manager, and re-init that.
905     SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
906     if (envMgr) {
907       envMgr->get_subsystem("realwx")->reinit();
908     }
909   
910     globals->get_subsystem("time")->reinit();
911
912     // need to bind FDMshell again, since we manually unbound it above...
913     globals->get_subsystem("flight")->bind();
914
915     // need to reset aircraft (systems/instruments) so they can adapt to current environment
916     globals->get_subsystem("systems")->reinit();
917     globals->get_subsystem("instrumentation")->reinit();
918
919 // setup state to end re-init
920     fgSetBool("/sim/signals/reinit", false);
921     if ( !freeze ) {
922         master_freeze->setBoolValue(false);
923     }
924     fgSetBool("/sim/sceneryloaded",false);
925 }
926
927
928 // re-position is a simplified version of the traditional (legacy)
929 // reset procedure. We only need to poke systems which will be upset by
930 // a sudden change in aircraft position. Since this potentially includes
931 // Nasal, we trigger the 'reinit' signal.
932 void fgStartReposition()
933 {
934   SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
935   SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
936   
937   // ensure we are frozen
938   bool freeze = master_freeze->getBoolValue();
939   if ( !freeze ) {
940     master_freeze->setBoolValue(true);
941   }
942   
943   // set this signal so Nasal scripts can take action.
944   fgSetBool("/sim/signals/reinit", true);
945   fgSetBool("/sim/crashed", false);
946   
947   globals->get_subsystem("flight")->unbind();
948   
949   // update our position based on current presets
950   // this will mark position as needed finalized which we'll do in the
951   // main-loop
952   flightgear::initPosition();
953   
954   simgear::SGTerraSync* terraSync =
955   static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
956   if (terraSync) {
957     terraSync->reposition();
958   }
959   
960   // Force reupdating the positions of the ai 3d models. They are used for
961   // initializing ground level for the FDM.
962   //globals->get_subsystem("ai-model")->reinit();
963   
964   // Initialize the FDM
965   globals->get_subsystem("flight")->reinit();
966   
967   // reset replay buffers
968   globals->get_subsystem("replay")->reinit();
969   
970   // ugly: finalizePosition waits for METAR to arrive for the new airport.
971   // we don't re-init the environment manager here, since historically we did
972   // not, and doing so seems to have other issues. All that's needed is to
973   // schedule METAR fetch immediately, so it's available for finalizePosition.
974   // So we manually extract the METAR-fetching component inside the environment
975   // manager, and re-init that.
976   SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
977   if (envMgr) {
978     envMgr->get_subsystem("realwx")->reinit();
979   }
980   
981   // need to bind FDMshell again, since we manually unbound it above...
982   globals->get_subsystem("flight")->bind();
983   
984   // need to reset aircraft (systems/instruments) so they can adapt to current environment
985   globals->get_subsystem("systems")->reinit();
986   globals->get_subsystem("instrumentation")->reinit();
987   
988   globals->get_subsystem("ATIS")->reinit();
989   
990   // setup state to end re-init
991   fgSetBool("/sim/signals/reinit", false);
992   if ( !freeze ) {
993     master_freeze->setBoolValue(false);
994   }
995   fgSetBool("/sim/sceneryloaded",false);
996 }
997
998 void fgStartNewReset()
999 {
1000     SGPropertyNode_ptr preserved(new SGPropertyNode);
1001   
1002     if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1003         SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1004     
1005     fgSetBool("/sim/signals/reinit", true);
1006     fgSetBool("/sim/freeze/master", true);
1007     
1008     SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1009     // Nasal is manually inited in fgPostInit, ensure it's already shutdown
1010     // before other subsystems, so Nasal listeners don't fire during shutdonw
1011     SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
1012     nasal->shutdown();
1013     nasal->unbind();
1014     subsystemManger->remove("nasal");
1015     
1016     subsystemManger->shutdown();
1017     subsystemManger->unbind();
1018     
1019     // remove most subsystems, with a few exceptions.
1020     for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1021         SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1022         const string_list& names(grp->member_names());
1023         string_list::const_iterator it;
1024         for (it = names.begin(); it != names.end(); ++it) {
1025             if ((*it == "time") || (*it == "terrasync") || (*it == "events")
1026                 || (*it == "lighting"))
1027             {
1028                 continue;
1029             }
1030             
1031             try {
1032                 subsystemManger->remove(it->c_str());
1033             } catch (std::exception& e) {
1034                 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1035             } catch (...) {
1036                 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1037             }
1038             
1039             // don't delete here, dropping the ref should be sufficient
1040         }
1041     } // of top-level groups iteration
1042     
1043     // order is important here since tile-manager shutdown needs to
1044     // access the scenery object
1045     globals->set_tile_mgr(NULL);
1046     globals->set_scenery(NULL);
1047     flightgear::CameraGroup::setDefault(NULL);
1048     
1049     FGRenderer* render = globals->get_renderer();
1050     // don't cancel the pager until after shutdown, since AIModels (and
1051     // potentially others) can queue delete requests on the pager.
1052     render->getViewer()->getDatabasePager()->cancel();
1053     render->getViewer()->getDatabasePager()->clear();
1054     
1055     osgDB::Registry::instance()->clearObjectCache();
1056     
1057     // preserve the event handler; re-creating it would entail fixing the
1058     // idle handler
1059     osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1060     
1061     globals->set_renderer(NULL);
1062     globals->set_matlib(NULL);
1063     globals->set_chatter_queue(NULL);
1064     
1065     simgear::clearEffectCache();
1066     simgear::SGModelLib::resetPropertyRoot();
1067         
1068     simgear::GlobalParticleCallback::setSwitch(NULL);
1069     
1070     globals->resetPropertyRoot();
1071     fgInitConfig(0, NULL, true);
1072     fgInitGeneral(); // all of this?
1073     
1074     if ( copyProperties(preserved, globals->get_props()) ) {
1075         SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1076     } else {
1077         SG_LOG( SG_GENERAL, SG_INFO,
1078                "Some errors restoring preserved state (read-only props?)" );
1079     }
1080
1081     fgGetNode("/sim")->removeChild("aircraft-dir");
1082     fgInitAircraft(true);
1083     flightgear::Options::sharedInstance()->processOptions();
1084     
1085     render = new FGRenderer;
1086     render->setEventHandler(eventHandler);
1087     globals->set_renderer(render);
1088     render->init();
1089     render->setViewer(viewer.get());
1090
1091     viewer->getDatabasePager()->setUpThreads(1, 1);
1092     
1093     // must do this before splashinit for Rembrandt
1094     flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1095     render->splashinit();
1096     
1097     fgOSResetProperties();
1098
1099 // init some things manually
1100 // which do not follow the regular init pattern
1101     
1102     globals->get_event_mgr()->init();
1103     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1104     
1105     globals->set_matlib( new SGMaterialLib );
1106     
1107 // terra-sync needs the property tree root, pass it back in
1108     simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1109     terra_sync->setRoot(globals->get_props());
1110
1111     fgSetBool("/sim/signals/reinit", false);
1112     fgSetBool("/sim/freeze/master", false);
1113     fgSetBool("/sim/sceneryloaded",false);
1114 }
1115