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