]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Pull Ephemeris out of FGGlobals
[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 #include <Airports/airportdynamicsmanager.hxx>
84
85 #include <AIModel/AIManager.hxx>
86
87 #include <ATC/atc_mgr.hxx>
88
89 #include <Autopilot/route_mgr.hxx>
90 #include <Autopilot/autopilotgroup.hxx>
91
92 #include <Cockpit/panel.hxx>
93 #include <Cockpit/panel_io.hxx>
94
95 #include <Canvas/canvas_mgr.hxx>
96 #include <Canvas/gui_mgr.hxx>
97 #include <Canvas/FGCanvasSystemAdapter.hxx>
98 #include <GUI/new_gui.hxx>
99 #include <GUI/MessageBox.hxx>
100 #include <Input/input.hxx>
101 #include <Instrumentation/instrument_mgr.hxx>
102 #include <Model/acmodel.hxx>
103 #include <Model/modelmgr.hxx>
104 #include <AIModel/submodel.hxx>
105 #include <AIModel/AIManager.hxx>
106 #include <AIModel/performancedb.hxx>
107 #include <Navaids/navdb.hxx>
108 #include <Navaids/navlist.hxx>
109 #include <Scenery/scenery.hxx>
110 #include <Scenery/SceneryPager.hxx>
111 #include <Scenery/tilemgr.hxx>
112 #include <Scripting/NasalSys.hxx>
113 #include <Sound/voice.hxx>
114 #include <Sound/soundmanager.hxx>
115 #include <Systems/system_mgr.hxx>
116 #include <Time/light.hxx>
117 #include <Time/TimeManager.hxx>
118
119 #include <Traffic/TrafficMgr.hxx>
120 #include <MultiPlayer/multiplaymgr.hxx>
121 #include <FDM/fdm_shell.hxx>
122 #include <Environment/ephemeris.hxx>
123 #include <Environment/environment_mgr.hxx>
124 #include <Viewer/renderer.hxx>
125 #include <Viewer/viewmgr.hxx>
126 #include <Viewer/FGEventHandler.hxx>
127 #include <Navaids/NavDataCache.hxx>
128 #include <Instrumentation/HUD/HUD.hxx>
129 #include <Cockpit/cockpitDisplayManager.hxx>
130 #include <Network/HTTPClient.hxx>
131 #include <Network/fgcom.hxx>
132 #include <Network/http/httpd.hxx>
133 #include <Include/version.h>
134 #include <Viewer/splash.hxx>
135 #include <Viewer/CameraGroup.hxx>
136
137 #include "fg_init.hxx"
138 #include "fg_io.hxx"
139 #include "fg_commands.hxx"
140 #include "fg_props.hxx"
141 #include "FGInterpolator.hxx"
142 #include "options.hxx"
143 #include "globals.hxx"
144 #include "logger.hxx"
145 #include "main.hxx"
146 #include "positioninit.hxx"
147 #include "util.hxx"
148 #include "AircraftDirVisitorBase.hxx"
149
150 #if defined(SG_MAC)
151 #include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
152 #endif
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(const SGPath& base_path) {
166     SGPath p(base_path);
167     p.append("version");
168     if (!p.exists()) {
169         return string();
170     }
171     
172     sg_gzifstream in( p.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.  Use FG_HOME if necessary.
452     // deliberately not a tied property, for fgValidatePath security
453     // write-protect to avoid accidents
454     SGPropertyNode *home = fgGetNode("/sim", true);
455     home->removeChild("fg-home", 0);
456     home = home->getChild("fg-home", 0, true);
457     home->setStringValue(dataPath.c_str());
458     home->setAttribute(SGPropertyNode::WRITE, false);
459   
460     fgSetDefaults();
461     flightgear::Options* options = flightgear::Options::sharedInstance();
462     if (!reinit) {
463         options->init(argc, argv, dataPath);
464     }
465     
466     bool loadDefaults = options->shouldLoadDefaultConfig();
467     if (loadDefaults) {
468       // Read global preferences from $FG_ROOT/preferences.xml
469       SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
470       fgLoadProps("preferences.xml", globals->get_props());
471       SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
472         
473       // do not load user settings when reset to default is requested, or if
474       // told to explicitly ignore
475       if (options->isOptionSet("restore-defaults") || options->isOptionSet("ignore-autosave"))
476       {
477           SG_LOG(SG_GENERAL, SG_ALERT, "Ignoring user settings. Restoring defaults.");
478       }
479       else
480       {
481           globals->loadUserSettings(dataPath);
482       }
483     } else {
484       SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
485     }// of no-default-config selected
486     
487     return flightgear::FG_OPTIONS_OK;
488 }
489
490 static void initAircraftDirsNasalSecurity()
491 {
492     // deliberately not a tied property, for fgValidatePath security
493     // write-protect to avoid accidents
494     SGPropertyNode* sim = fgGetNode("/sim", true);
495     sim->removeChildren("fg-aircraft");
496
497     int index = 0;
498     string_list const aircraft_paths = globals->get_aircraft_paths();
499     for( string_list::const_iterator it = aircraft_paths.begin();
500                                      it != aircraft_paths.end();
501                                    ++it, ++index )
502     {
503         SGPropertyNode* n = sim->getChild("fg-aircraft", index, true);
504         n->setStringValue(*it);
505         n->setAttribute(SGPropertyNode::WRITE, false);
506     }
507 }
508
509 void fgInitAircraftPaths(bool reinit)
510 {
511   if (!globals->packageRoot()) {
512       fgInitPackageRoot();
513   }
514
515   SGSharedPtr<Root> pkgRoot(globals->packageRoot());
516   SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
517   aircraftProp->setAttribute(SGPropertyNode::PRESERVE, true);
518
519   if (!reinit) {
520       flightgear::Options::sharedInstance()->initPaths();
521   }
522 }
523
524 int fgInitAircraft(bool reinit)
525 {
526     if (!reinit) {
527         flightgear::Options::sharedInstance()->initAircraft();
528     }
529     
530     SGSharedPtr<Root> pkgRoot(globals->packageRoot());
531     SGPropertyNode* aircraftProp = fgGetNode("/sim/aircraft", true);
532
533     string aircraftId(aircraftProp->getStringValue());
534     PackageRef acftPackage = pkgRoot->getPackageById(aircraftId);
535     if (acftPackage) {
536         if (acftPackage->isInstalled()) {
537             SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft from package:" << acftPackage->qualifiedId());
538
539             // set catalog path so intra-package dependencies within the catalog
540             // are resolved correctly.
541             globals->set_catalog_aircraft_path(acftPackage->catalog()->installRoot());
542
543             // set aircraft-dir to short circuit the search process
544             InstallRef acftInstall = acftPackage->install();
545             fgSetString("/sim/aircraft-dir", acftInstall->path().c_str());
546
547             // overwrite the fully qualified ID with the aircraft one, so the
548             // code in FindAndCacheAircraft works as normal
549             // note since we may be using a variant, we can't use the package ID
550             size_t lastDot = aircraftId.rfind('.');
551             if (lastDot != std::string::npos) {
552                 aircraftId = aircraftId.substr(lastDot + 1);
553             }
554             aircraftProp->setStringValue(aircraftId);
555
556             // run the traditional-code path below
557         } else {
558 #if 0
559             // naturally the better option would be to on-demand install it!
560             flightgear::fatalMessageBox("Aircraft not installed",
561                                         "Requested aircraft is not currently installed.",
562                                         aircraftId);
563
564             return flightgear::FG_OPTIONS_ERROR;
565 #endif
566             // fall back the default aircraft instead
567         }
568     }
569
570     initAircraftDirsNasalSecurity();
571
572     FindAndCacheAircraft f(globals->get_props());
573     if (!f.loadAircraft()) {
574         return flightgear::FG_OPTIONS_ERROR;
575     }
576     
577     return flightgear::FG_OPTIONS_OK;
578 }
579
580 /**
581  * Initialize vor/ndb/ils/fix list management and query systems (as
582  * well as simple airport db list)
583  * This is called multiple times in the case of a cache rebuild,
584  * to allow lengthy caching to take place in the background, without
585  * blocking the main/UI thread.
586  */
587 bool
588 fgInitNav ()
589 {
590     flightgear::NavDataCache* cache = flightgear::NavDataCache::instance();
591     static bool doingRebuild = false;
592
593     if (!cache) {
594         cache = flightgear::NavDataCache::createInstance();
595         doingRebuild = cache->isRebuildRequired();
596     }
597
598     static const char* splashIdentsByRebuildPhase[] = {
599         "loading-nav-dat",
600         "navdata-airports",
601         "navdata-navaids",
602         "navdata-fixes",
603         "navdata-pois"
604     };
605
606     if (doingRebuild) {
607         flightgear::NavDataCache::RebuildPhase phase;
608         phase = cache->rebuild();
609         if (phase != flightgear::NavDataCache::REBUILD_DONE) {
610             // update the splash text based on percentage, phase
611
612             fgSplashProgress(splashIdentsByRebuildPhase[phase],
613                              cache->rebuildPhaseCompletionPercentage());
614
615             // sleep to give the rebuild thread more time
616             SGTimeStamp::sleepForMSec(50);
617             return false;
618         }
619     }
620
621   FGTACANList *channellist = new FGTACANList;
622   globals->set_channellist( channellist );
623   
624   SGPath path(globals->get_fg_root());
625   path.append( "Navaids/TACAN_freq.dat" );
626   flightgear::loadTacan(path, channellist);
627   
628   return true;
629 }
630
631 // General house keeping initializations
632 bool fgInitGeneral() {
633     string root;
634
635     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
636     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
637
638     root = globals->get_fg_root();
639     if ( ! root.length() ) {
640         // No root path set? Then bail ...
641         SG_LOG( SG_GENERAL, SG_ALERT,
642                 "Cannot continue without a path to the base package "
643                 << "being defined." );
644         return false;
645     }
646     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
647
648     // Note: browser command is hard-coded for Mac/Windows, so this only affects other platforms
649     globals->set_browser(fgGetString("/sim/startup/browser-app", WEB_BROWSER));
650     fgSetString("/sim/startup/browser-app", globals->get_browser());
651
652     simgear::Dir cwd(simgear::Dir::current());
653     SGPropertyNode *curr = fgGetNode("/sim", true);
654     curr->removeChild("fg-current", 0);
655     curr = curr->getChild("fg-current", 0, true);
656     curr->setStringValue(cwd.path().str());
657     curr->setAttribute(SGPropertyNode::WRITE, false);
658
659     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
660     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
661     return true;
662 }
663
664 // Write various configuraton values out to the logs
665 void fgOutputSettings()
666 {    
667     SG_LOG( SG_GENERAL, SG_INFO, "Configuration State" );
668     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
669     
670     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-dir = " << '"' << fgGetString("/sim/aircraft-dir") << '"' );
671     SG_LOG( SG_GENERAL, SG_INFO, "fghome-dir = " << '"' << globals->get_fg_home() << '"');
672     SG_LOG( SG_GENERAL, SG_INFO, "download-dir = " << '"' << fgGetString("/sim/paths/download-dir") << '"' );
673     SG_LOG( SG_GENERAL, SG_INFO, "terrasync-dir = " << '"' << fgGetString("/sim/terrasync/scenery-dir") << '"' );
674
675     SG_LOG( SG_GENERAL, SG_INFO, "aircraft-search-paths = \n\t" << simgear::strutils::join(globals->get_aircraft_paths(), "\n\t") );
676     SG_LOG( SG_GENERAL, SG_INFO, "scenery-search-paths = \n\t" << simgear::strutils::join(globals->get_fg_scenery(), "\n\t") );
677 }
678
679 // This is the top level init routine which calls all the other
680 // initialization routines.  If you are adding a subsystem to flight
681 // gear, its initialization call should located in this routine.
682 // Returns non-zero if a problem encountered.
683 void fgCreateSubsystems(bool duringReset) {
684
685     SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
686     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
687
688     ////////////////////////////////////////////////////////////////////
689     // Initialize the sound subsystem.
690     ////////////////////////////////////////////////////////////////////
691     // Sound manager uses an own subsystem group "SOUND" which is the last
692     // to be updated in every loop.
693     // Sound manager is updated last so it can use the CPU while the GPU
694     // is processing the scenery (doubled the frame-rate for me) -EMH-
695     globals->add_new_subsystem<FGSoundManager>(SGSubsystemMgr::SOUND);
696
697     ////////////////////////////////////////////////////////////////////
698     // Initialize the event manager subsystem.
699     ////////////////////////////////////////////////////////////////////
700
701     globals->get_event_mgr()->init();
702     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
703
704     ////////////////////////////////////////////////////////////////////
705     // Initialize the property interpolator subsystem. Put into the INIT
706     // group because the "nasal" subsystem may need it at GENERAL take-down.
707     ////////////////////////////////////////////////////////////////////
708     globals->add_subsystem("prop-interpolator", new FGInterpolator, SGSubsystemMgr::INIT);
709
710
711     ////////////////////////////////////////////////////////////////////
712     // Add the FlightGear property utilities.
713     ////////////////////////////////////////////////////////////////////
714     globals->add_subsystem("properties", new FGProperties);
715
716
717     ////////////////////////////////////////////////////////////////////
718     // Add the FlightGear property utilities.
719     ////////////////////////////////////////////////////////////////////
720     globals->add_new_subsystem<flightgear::AirportDynamicsManager>();
721
722     ////////////////////////////////////////////////////////////////////
723     // Add the performance monitoring system.
724     ////////////////////////////////////////////////////////////////////
725     globals->add_subsystem("performance-mon",
726             new SGPerformanceMonitor(globals->get_subsystem_mgr(),
727                                      fgGetNode("/sim/performance-monitor", true)));
728
729     ////////////////////////////////////////////////////////////////////
730     // Initialize the material property subsystem.
731     ////////////////////////////////////////////////////////////////////
732
733     SGPath mpath( globals->get_fg_root() );
734     mpath.append( fgGetString("/sim/rendering/materials-file") );
735     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
736             globals->get_props()) ) {
737        throw sg_io_exception("Error loading materials file", mpath);
738     }
739
740     // may exist already due to GUI startup
741     if (!globals->get_subsystem("http")) {
742         globals->add_subsystem( "http", new FGHTTPClient );
743     }
744
745     ////////////////////////////////////////////////////////////////////
746     // Initialize the scenery management subsystem.
747     ////////////////////////////////////////////////////////////////////
748
749     globals->get_scenery()->get_scene_graph()
750         ->addChild(simgear::Particles::getCommonRoot());
751     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
752
753     ////////////////////////////////////////////////////////////////////
754     // Initialize the flight model subsystem.
755     ////////////////////////////////////////////////////////////////////
756
757     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
758
759     ////////////////////////////////////////////////////////////////////
760     // Initialize the weather subsystem.
761     ////////////////////////////////////////////////////////////////////
762
763     // Initialize the weather modeling subsystem
764     globals->add_subsystem("environment", new FGEnvironmentMgr);
765     globals->add_new_subsystem<Ephemeris>();
766     
767     ////////////////////////////////////////////////////////////////////
768     // Initialize the aircraft systems and instrumentation (before the
769     // autopilot.)
770     ////////////////////////////////////////////////////////////////////
771
772     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
773     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
774     globals->add_subsystem("hud", new HUD, SGSubsystemMgr::DISPLAY);
775     globals->add_subsystem("cockpit-displays", new flightgear::CockpitDisplayManager, SGSubsystemMgr::DISPLAY);
776   
777     ////////////////////////////////////////////////////////////////////
778     // Initialize the XML Autopilot subsystem.
779     ////////////////////////////////////////////////////////////////////
780
781     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance("autopilot"), SGSubsystemMgr::FDM );
782     globals->add_subsystem( "xml-proprules", FGXMLAutopilotGroup::createInstance("property-rule"), SGSubsystemMgr::GENERAL );
783     globals->add_new_subsystem<FGRouteMgr>();
784
785     ////////////////////////////////////////////////////////////////////
786     // Initialize the Input-Output subsystem
787     ////////////////////////////////////////////////////////////////////
788     globals->add_subsystem( "io", new FGIO );
789   
790     ////////////////////////////////////////////////////////////////////
791     // Create and register the logger.
792     ////////////////////////////////////////////////////////////////////
793     
794     globals->add_subsystem("logger", new FGLogger);
795
796     ////////////////////////////////////////////////////////////////////
797     // Create and register the XML GUI.
798     ////////////////////////////////////////////////////////////////////
799
800     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
801
802     //////////////////////////////////////////////////////////////////////
803     // Initialize the 2D cloud subsystem.
804     ////////////////////////////////////////////////////////////////////
805     fgGetBool("/sim/rendering/bump-mapping", false);
806
807     ////////////////////////////////////////////////////////////////////
808     // Initialize the canvas 2d drawing subsystem.
809     ////////////////////////////////////////////////////////////////////
810     simgear::canvas::Canvas::setSystemAdapter(
811       simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
812     );
813     globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
814     globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
815
816     ////////////////////////////////////////////////////////////////////
817    // Initialize the ATC subsystem
818     ////////////////////////////////////////////////////////////////////
819
820     globals->add_new_subsystem<PerformanceDB>(SGSubsystemMgr::POST_FDM);
821     globals->add_subsystem("ATC", new FGATCManager, SGSubsystemMgr::POST_FDM);
822
823     ////////////////////////////////////////////////////////////////////
824     // Initialize multiplayer subsystem
825     ////////////////////////////////////////////////////////////////////
826
827     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
828
829     ////////////////////////////////////////////////////////////////////
830     // Initialise the AI Model Manager
831     ////////////////////////////////////////////////////////////////////
832
833     globals->add_subsystem("ai-model", new FGAIManager, SGSubsystemMgr::POST_FDM);
834     globals->add_subsystem("submodel-mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
835
836
837     // It's probably a good idea to initialize the top level traffic manager
838     // After the AI and ATC systems have been initialized properly.
839     // AI Traffic manager
840     globals->add_subsystem("traffic-manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
841
842     ////////////////////////////////////////////////////////////////////
843     // Add a new 2D panel.
844     ////////////////////////////////////////////////////////////////////
845
846     fgSetArchivable("/sim/panel/visibility");
847     fgSetArchivable("/sim/panel/x-offset");
848     fgSetArchivable("/sim/panel/y-offset");
849     fgSetArchivable("/sim/panel/jitter");
850   
851     ////////////////////////////////////////////////////////////////////
852     // Initialize the controls subsystem.
853     ////////////////////////////////////////////////////////////////////
854     
855     globals->add_new_subsystem<FGControls>(SGSubsystemMgr::GENERAL);
856
857     ////////////////////////////////////////////////////////////////////
858     // Initialize the input subsystem.
859     ////////////////////////////////////////////////////////////////////
860
861     globals->add_subsystem("input", new FGInput, SGSubsystemMgr::GENERAL);
862
863
864     ////////////////////////////////////////////////////////////////////
865     // Initialize the replay subsystem
866     ////////////////////////////////////////////////////////////////////
867     globals->add_subsystem("replay", new FGReplay);
868     globals->add_subsystem("history", new FGFlightHistory);
869     
870 #ifdef ENABLE_AUDIO_SUPPORT
871     ////////////////////////////////////////////////////////////////////
872     // Initialize the sound-effects subsystem.
873     ////////////////////////////////////////////////////////////////////
874     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
875 #endif
876
877 #ifdef ENABLE_IAX
878     ////////////////////////////////////////////////////////////////////
879     // Initialize the FGCom subsystem.
880     ////////////////////////////////////////////////////////////////////
881     globals->add_subsystem("fgcom", new FGCom);
882 #endif
883
884     {
885       SGSubsystem * httpd = flightgear::http::FGHttpd::createInstance( fgGetNode(flightgear::http::PROPERTY_ROOT) );
886       if( NULL != httpd ) 
887         globals->add_subsystem("httpd", httpd  );
888     }
889
890     ////////////////////////////////////////////////////////////////////
891     // Initialize the lighting subsystem.
892     ////////////////////////////////////////////////////////////////////
893
894     // ordering here is important : Nasal (via events), then models, then views
895     if (!duringReset) {
896         globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
897         globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
898     }
899
900     globals->add_new_subsystem<FGAircraftModel>(SGSubsystemMgr::DISPLAY);
901     globals->add_new_subsystem<FGModelMgr>(SGSubsystemMgr::DISPLAY);
902
903     globals->add_new_subsystem<FGViewMgr>(SGSubsystemMgr::DISPLAY);
904 }
905
906 void fgPostInitSubsystems()
907 {
908     SGTimeStamp st;
909     st.stamp();
910   
911     ////////////////////////////////////////////////////////////////////////
912     // Initialize the Nasal interpreter.
913     // Do this last, so that the loaded scripts see initialized state
914     ////////////////////////////////////////////////////////////////////////
915     FGNasalSys* nasal = new FGNasalSys();
916     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
917     nasal->init();
918     SG_LOG(SG_GENERAL, SG_INFO, "Nasal init took:" << st.elapsedMSec());
919
920     // initialize methods that depend on other subsystems.
921     st.stamp();
922     globals->get_subsystem_mgr()->postinit();
923     SG_LOG(SG_GENERAL, SG_INFO, "Subsystems postinit took:" << st.elapsedMSec());
924   
925     ////////////////////////////////////////////////////////////////////////
926     // End of subsystem initialization.
927     ////////////////////////////////////////////////////////////////////
928
929     fgSetBool("/sim/crashed", false);
930     fgSetBool("/sim/initialized", true);
931
932     SG_LOG( SG_GENERAL, SG_INFO, endl);
933 }
934
935 // re-position is a simplified version of the traditional (legacy)
936 // reset procedure. We only need to poke systems which will be upset by
937 // a sudden change in aircraft position. Since this potentially includes
938 // Nasal, we trigger the 'reinit' signal.
939 void fgStartReposition()
940 {
941   SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
942   SG_LOG( SG_GENERAL, SG_INFO, "fgStartReposition()");
943   
944   // ensure we are frozen
945   bool freeze = master_freeze->getBoolValue();
946   if ( !freeze ) {
947     master_freeze->setBoolValue(true);
948   }
949   
950   // set this signal so Nasal scripts can take action.
951   fgSetBool("/sim/signals/reinit", true);
952   fgSetBool("/sim/crashed", false);
953   
954   FDMShell* fdm = static_cast<FDMShell*>(globals->get_subsystem("flight"));
955   fdm->unbind();
956   
957   // update our position based on current presets
958   // this will mark position as needed finalized which we'll do in the
959   // main-loop
960   flightgear::initPosition();
961   
962   simgear::SGTerraSync* terraSync =
963   static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
964   if (terraSync) {
965     terraSync->reposition();
966   }
967   
968   // Initialize the FDM
969   globals->get_subsystem("flight")->reinit();
970   
971   // reset replay buffers
972   globals->get_subsystem("replay")->reinit();
973   
974   // ugly: finalizePosition waits for METAR to arrive for the new airport.
975   // we don't re-init the environment manager here, since historically we did
976   // not, and doing so seems to have other issues. All that's needed is to
977   // schedule METAR fetch immediately, so it's available for finalizePosition.
978   // So we manually extract the METAR-fetching component inside the environment
979   // manager, and re-init that.
980   SGSubsystemGroup* envMgr = static_cast<SGSubsystemGroup*>(globals->get_subsystem("environment"));
981   if (envMgr) {
982     envMgr->get_subsystem("realwx")->reinit();
983   }
984   
985   // need to bind FDMshell again, since we manually unbound it above...
986   fdm->bind();
987   
988   // need to reset aircraft (systems/instruments/autopilot)
989   // so they can adapt to current environment
990   globals->get_subsystem("systems")->reinit();
991   globals->get_subsystem("instrumentation")->reinit();
992   globals->get_subsystem("xml-autopilot")->reinit();
993     
994   // setup state to end re-init
995   fgSetBool("/sim/signals/reinit", false);
996   if ( !freeze ) {
997     master_freeze->setBoolValue(false);
998   }
999   fgSetBool("/sim/sceneryloaded",false);
1000 }
1001
1002 void fgStartNewReset()
1003 {
1004     SGPropertyNode_ptr preserved(new SGPropertyNode);
1005   
1006     if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
1007         SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
1008     
1009     fgSetBool("/sim/signals/reinit", true);
1010     fgSetBool("/sim/freeze/master", true);
1011     
1012     SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
1013     // Nasal is manually inited in fgPostInit, ensure it's already shutdown
1014     // before other subsystems, so Nasal listeners don't fire during shutdown
1015     SGSubsystem* nasal = subsystemManger->get_subsystem("nasal");
1016     nasal->shutdown();
1017     nasal->unbind();
1018     subsystemManger->remove("nasal");
1019     
1020     subsystemManger->shutdown();
1021     subsystemManger->unbind();
1022     
1023     // remove most subsystems, with a few exceptions.
1024     for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
1025         SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
1026         const string_list& names(grp->member_names());
1027         string_list::const_iterator it;
1028         for (it = names.begin(); it != names.end(); ++it) {
1029             if ((*it == "time") || (*it == "terrasync") || (*it == "events")
1030                 || (*it == "lighting") || (*it == FGTileMgr::subsystemName()) || (*it == FGScenery::subsystemName()))
1031             {
1032                 continue;
1033             }
1034             
1035             try {
1036                 subsystemManger->remove(it->c_str());
1037             } catch (std::exception& e) {
1038                 SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
1039             } catch (...) {
1040                 SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
1041             }
1042             
1043             // don't delete here, dropping the ref should be sufficient
1044         }
1045     } // of top-level groups iteration
1046     
1047     FGRenderer* render = globals->get_renderer();
1048     // needed or we crash in multi-threaded OSG mode
1049     render->getViewer()->stopThreading();
1050     
1051     // order is important here since tile-manager shutdown needs to
1052     // access the scenery object
1053     subsystemManger->remove(FGTileMgr::subsystemName());
1054     subsystemManger->remove(FGScenery::subsystemName());
1055
1056     FGScenery::getPagerSingleton()->clearRequests();
1057     flightgear::CameraGroup::setDefault(NULL);
1058     
1059     // don't cancel the pager until after shutdown, since AIModels (and
1060     // potentially others) can queue delete requests on the pager.
1061     render->getViewer()->getDatabasePager()->cancel();
1062     render->getViewer()->getDatabasePager()->clear();
1063     
1064     osgDB::Registry::instance()->clearObjectCache();
1065     
1066     // preserve the event handler; re-creating it would entail fixing the
1067     // idle handler
1068     osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
1069     
1070     globals->set_renderer(NULL);
1071     globals->set_matlib(NULL);
1072     globals->set_chatter_queue(NULL);
1073     
1074     simgear::clearEffectCache();
1075     simgear::SGModelLib::resetPropertyRoot();
1076         
1077     simgear::GlobalParticleCallback::setSwitch(NULL);
1078     
1079     globals->resetPropertyRoot();
1080     // otherwise channels are duplicated
1081     globals->get_channel_options_list()->clear();
1082   
1083     fgInitConfig(0, NULL, true);
1084     fgInitGeneral(); // all of this?
1085     
1086     flightgear::Options::sharedInstance()->processOptions();
1087     
1088     // PRESERVED properties over-write state from options, intentionally
1089     if ( copyProperties(preserved, globals->get_props()) ) {
1090         SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
1091     } else {
1092         SG_LOG( SG_GENERAL, SG_INFO,
1093                "Some errors restoring preserved state (read-only props?)" );
1094     }
1095
1096     fgGetNode("/sim")->removeChild("aircraft-dir");
1097     fgInitAircraftPaths(true);
1098     fgInitAircraft(true);
1099     
1100     render = new FGRenderer;
1101     render->setEventHandler(eventHandler);
1102     eventHandler->reset();
1103     globals->set_renderer(render);
1104     render->init();
1105     render->setViewer(viewer.get());
1106
1107     viewer->getDatabasePager()->setUpThreads(1, 1);
1108     
1109     // must do this before splashinit for Rembrandt
1110     flightgear::CameraGroup::buildDefaultGroup(viewer.get());
1111     render->splashinit();
1112     viewer->startThreading();
1113     
1114     fgOSResetProperties();
1115
1116 // init some things manually
1117 // which do not follow the regular init pattern
1118     
1119     globals->get_event_mgr()->init();
1120     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1121     
1122     globals->set_matlib( new SGMaterialLib );
1123     
1124 // terra-sync needs the property tree root, pass it back in
1125     simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
1126     terra_sync->setRoot(globals->get_props());
1127
1128     fgSetBool("/sim/signals/reinit", false);
1129     fgSetBool("/sim/freeze/master", false);
1130     fgSetBool("/sim/sceneryloaded",false);
1131 }
1132
1133 void fgInitPackageRoot()
1134 {
1135     if (globals->packageRoot()) {
1136         return;
1137     }
1138     
1139     SGPath packageAircraftDir = flightgear::defaultDownloadDir();
1140     packageAircraftDir.append("Aircraft");
1141
1142     SGSharedPtr<Root> pkgRoot(new Root(packageAircraftDir, FLIGHTGEAR_VERSION));
1143     // set the http client later (too early in startup right now)
1144     globals->setPackageRoot(pkgRoot);
1145
1146 }