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