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