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