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