]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Merge commit 'refs/merge-requests/1552' of git@gitorious.org:fg/flightgear into next
[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 <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>             // strcmp()
31
32 #if defined( unix ) || defined( __CYGWIN__ )
33 #  include <unistd.h>           // for gethostname()
34 #endif
35 #ifdef _WIN32
36 #  include <direct.h>           // for getcwd()
37 #  define getcwd _getcwd
38 #  include <io.h>               // isatty()
39 #  define isatty _isatty
40 #  include "winsock2.h"         // for gethostname()
41 #endif
42
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
45 #ifdef linux
46 #  define _G_NO_EXTERN_TEMPLATES
47 #endif
48
49 #include <simgear/compiler.h>
50
51 #include <string>
52 #include <boost/algorithm/string/compare.hpp>
53 #include <boost/algorithm/string/predicate.hpp>
54
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/structure/exception.hxx>
58 #include <simgear/structure/event_mgr.hxx>
59 #include <simgear/misc/sg_path.hxx>
60 #include <simgear/misc/sg_dir.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/scene/model/particles.hxx>
64 #include <simgear/sound/soundmgr_openal.hxx>
65
66 #include <Aircraft/controls.hxx>
67 #include <Aircraft/replay.hxx>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <Airports/dynamics.hxx>
72
73 #include <AIModel/AIManager.hxx>
74
75 #if ENABLE_ATCDCL
76 #   include <ATCDCL/ATCmgr.hxx>
77 #   include "ATCDCL/commlist.hxx"
78 #else
79 #   include "ATC/atis.hxx"
80 #   include "ATC/atcutils.hxx"
81 #endif
82
83 #include <Autopilot/route_mgr.hxx>
84 #include <Autopilot/autopilotgroup.hxx>
85
86 #include <Cockpit/cockpit.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Cockpit/panel_io.hxx>
89
90 #include <GUI/new_gui.hxx>
91 #include <Include/general.hxx>
92 #include <Input/input.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <AIModel/submodel.hxx>
96 #include <AIModel/AIManager.hxx>
97 #include <Navaids/navdb.hxx>
98 #include <Navaids/navlist.hxx>
99 #include <Navaids/fix.hxx>
100 #include <Navaids/fixlist.hxx>
101 #include <Scenery/scenery.hxx>
102 #include <Scenery/tilemgr.hxx>
103 #include <Scripting/NasalSys.hxx>
104 #include <Sound/voice.hxx>
105 #include <Systems/system_mgr.hxx>
106 #include <Time/light.hxx>
107 #include <Traffic/TrafficMgr.hxx>
108 #include <MultiPlayer/multiplaymgr.hxx>
109 #include <FDM/fdm_shell.hxx>
110
111 #include <Environment/environment_mgr.hxx>
112
113 #include "fg_init.hxx"
114 #include "fg_io.hxx"
115 #include "fg_commands.hxx"
116 #include "fg_props.hxx"
117 #include "options.hxx"
118 #include "globals.hxx"
119 #include "logger.hxx"
120 #include "renderer.hxx"
121 #include "viewmgr.hxx"
122 #include "main.hxx"
123
124
125 #ifdef __APPLE__
126 #  include <CoreFoundation/CoreFoundation.h>
127 #endif
128
129 using std::string;
130 using namespace boost::algorithm;
131
132 extern const char *default_root;
133
134
135 // Scan the command line options for the specified option and return
136 // the value.
137 static string fgScanForOption( const string& option, int argc, char **argv ) {
138     int i = 1;
139
140     if (hostname == NULL)
141     {
142         char _hostname[256];
143         if( gethostname(_hostname, 256) >= 0 ) {
144             hostname = strdup(_hostname);
145             free_hostname = true;
146         }
147     }
148
149     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
150
151     int len = option.length();
152
153     while ( i < argc ) {
154         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
155
156         string arg = argv[i];
157         if ( arg.find( option ) == 0 ) {
158             return arg.substr( len );
159         }
160
161         i++;
162     }
163
164     return "";
165 }
166
167
168 // Scan the user config files for the specified option and return
169 // the value.
170 static string fgScanForOption( const string& option, const string& path ) {
171     sg_gzifstream in( path );
172     if ( !in.is_open() ) {
173         return "";
174     }
175
176     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
177
178     int len = option.length();
179
180     in >> skipcomment;
181     while ( ! in.eof() ) {
182         string line;
183         getline( in, line, '\n' );
184
185         // catch extraneous (DOS) line ending character
186         if ( line[line.length() - 1] < 32 ) {
187             line = line.substr( 0, line.length()-1 );
188         }
189
190         if ( line.find( option ) == 0 ) {
191             return line.substr( len );
192         }
193
194         in >> skipcomment;
195     }
196
197     return "";
198 }
199
200 // Scan the user config files for the specified option and return
201 // the value.
202 static string fgScanForOption( const string& option ) {
203     string arg("");
204
205 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
206     // Next check home directory for .fgfsrc.hostname file
207     if ( arg.empty() ) {
208         if ( homedir != NULL && hostname != NULL && strlen(hostname) > 0) {
209             SGPath config( homedir );
210             config.append( ".fgfsrc" );
211             config.concat( "." );
212             config.concat( hostname );
213             arg = fgScanForOption( option, config.str() );
214         }
215     }
216 #endif
217
218     // Next check home directory for .fgfsrc file
219     if ( arg.empty() ) {
220         if ( homedir != NULL ) {
221             SGPath config( homedir );
222             config.append( ".fgfsrc" );
223             arg = fgScanForOption( option, config.str() );
224         }
225     }
226
227     if ( arg.empty() ) {
228         // Check for $fg_root/system.fgfsrc
229         SGPath config( globals->get_fg_root() );
230         config.append( "system.fgfsrc" );
231         arg = fgScanForOption( option, config.str() );
232     }
233
234     return arg;
235 }
236
237
238 // Read in configuration (files and command line options) but only set
239 // fg_root and aircraft_paths, which are needed *before* do_options() is called
240 // in fgInitConfig
241
242 bool fgInitFGRoot ( int argc, char **argv ) {
243     string root;
244
245     // First parse command line options looking for --fg-root=, this
246     // will override anything specified in a config file
247     root = fgScanForOption( "--fg-root=", argc, argv);
248
249     // Check in one of the user configuration files.
250     if (root.empty() )
251         root = fgScanForOption( "--fg-root=" );
252     
253     // Next check if fg-root is set as an env variable
254     if ( root.empty() ) {
255         char *envp = ::getenv( "FG_ROOT" );
256         if ( envp != NULL ) {
257             root = envp;
258         }
259     }
260
261     // Otherwise, default to a random compiled-in location if we can't
262     // find fg-root any other way.
263     if ( root.empty() ) {
264 #if defined( __CYGWIN__ )
265         root = "../data";
266 #elif defined( _WIN32 )
267         root = "..\\data";
268 #elif defined(__APPLE__) 
269         /*
270         The following code looks for the base package inside the application 
271         bundle, in the standard Contents/Resources location. 
272         */
273         CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
274
275         // look for a 'data' subdir
276         CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
277
278         // now convert down to a path, and the a c-string
279         CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
280         root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
281
282         CFRelease(resourcesUrl);
283         CFRelease(dataDir);
284         CFRelease(path);
285 #else
286         root = PKGLIBDIR;
287 #endif
288     }
289
290     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
291     globals->set_fg_root(root);
292     
293     return true;
294 }
295
296
297 // Read in configuration (files and command line options) but only set
298 // aircraft
299 bool fgInitFGAircraft ( int argc, char **argv ) {
300     
301     string aircraftDir = fgScanForOption("--fg-aircraft=", argc, argv);
302     if (aircraftDir.empty()) {
303       aircraftDir =  fgScanForOption("--fg-aircraft="); 
304     }
305
306     const char* envp = ::getenv("FG_AIRCRAFT");
307     if (aircraftDir.empty() && envp) {
308       globals->append_aircraft_paths(envp);
309     }
310     
311     if (!aircraftDir.empty()) {
312       globals->append_aircraft_paths(aircraftDir);
313     }
314     
315     string aircraft;
316
317     // First parse command line options looking for --aircraft=, this
318     // will override anything specified in a config file
319     aircraft = fgScanForOption( "--aircraft=", argc, argv );
320     if ( aircraft.empty() ) {
321         // check synonym option
322         aircraft = fgScanForOption( "--vehicle=", argc, argv );
323     }
324
325     // Check in one of the user configuration files.
326     if ( aircraft.empty() ) {
327         aircraft = fgScanForOption( "--aircraft=" );
328     }
329     if ( aircraft.empty() ) {
330         aircraft = fgScanForOption( "--vehicle=" );
331     }
332
333     // if an aircraft was specified, set the property name
334     if ( !aircraft.empty() ) {
335         SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
336         fgSetString("/sim/aircraft", aircraft.c_str() );
337     } else {
338         SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
339     }
340
341     return true;
342 }
343
344
345 // Return the current base package version
346 string fgBasePackageVersion() {
347     SGPath base_path( globals->get_fg_root() );
348     base_path.append("version");
349
350     sg_gzifstream in( base_path.str() );
351     if ( !in.is_open() ) {
352         SGPath old_path( globals->get_fg_root() );
353         old_path.append( "Thanks" );
354         sg_gzifstream old( old_path.str() );
355         if ( !old.is_open() ) {
356             return "[none]";
357         } else {
358             return "[old version]";
359         }
360     }
361
362     string version;
363     in >> version;
364
365     return version;
366 }
367
368
369 // Initialize the localization
370 SGPropertyNode *fgInitLocale(const char *language) {
371    SGPropertyNode *c_node = NULL, *d_node = NULL;
372    SGPropertyNode *intl = fgGetNode("/sim/intl");
373
374    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
375
376    // localization not defined
377    if (!intl)
378       return NULL;
379
380    //
381    // Select the proper language from the list
382    //
383    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
384    for (unsigned int i = 0; i < locale.size(); i++) {
385
386       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
387       for (unsigned int j = 0; j < lang.size(); j++) {
388
389          if (!strcmp(lang[j]->getStringValue(), language)) {
390             c_node = locale[i];
391             break;
392          }
393       }
394    }
395
396
397    // Get the defaults
398    d_node = intl->getChild("locale");
399    if (!c_node)
400       c_node = d_node;
401
402    // Check for localized font
403    SGPropertyNode *font_n = c_node->getNode("font", true);
404    if ( !strcmp(font_n->getStringValue(), "") )
405       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
406
407
408    //
409    // Load the default strings
410    //
411    SGPath d_path( globals->get_fg_root() );
412
413    const char *d_path_str = d_node->getStringValue("strings");
414    if (!d_path_str) {
415       SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << d_node->getPath() << "/strings.");
416       return NULL;
417    }
418
419    d_path.append(d_path_str);
420    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << d_path.str());
421
422    SGPropertyNode *strings = c_node->getNode("strings");
423    try {
424       readProperties(d_path.str(), strings);
425    } catch (const sg_exception &) {
426       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
427       return NULL;
428    }
429
430    //
431    // Load the language specific strings
432    //
433    if (c_node != d_node) {
434       SGPath c_path( globals->get_fg_root() );
435
436       const char *c_path_str = c_node->getStringValue("strings");
437       if (!c_path_str) {
438          SG_LOG(SG_GENERAL, SG_ALERT, "No path in " << c_node->getPath() << "/strings");
439          return NULL;
440       }
441
442       c_path.append(c_path_str);
443       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from " << c_path.str());
444
445       try {
446          readProperties(c_path.str(), strings);
447       } catch (const sg_exception &) {
448          SG_LOG(SG_GENERAL, SG_ALERT,
449                  "Unable to read the localized strings from " << c_path.str());
450          return NULL;
451       }
452    }
453
454    return c_node;
455 }
456
457
458
459 // Initialize the localization routines
460 bool fgDetectLanguage() {
461     const char *language = ::getenv("LANG");
462
463     if (language == NULL) {
464         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
465         language = "C";
466     }
467
468     SGPropertyNode *locale = fgInitLocale(language);
469     if (!locale) {
470        SG_LOG(SG_GENERAL, SG_ALERT,
471               "No internationalization settings specified in preferences.xml" );
472
473        return false;
474     }
475
476     globals->set_locale( locale );
477
478     return true;
479 }
480
481 // Attempt to locate and parse the various non-XML config files in order
482 // from least precidence to greatest precidence
483 static void
484 do_options (int argc, char ** argv)
485 {
486     // Check for $fg_root/system.fgfsrc
487     SGPath config( globals->get_fg_root() );
488     config.append( "system.fgfsrc" );
489     fgParseOptions(config.str());
490
491 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
492     if( hostname != NULL && strlen(hostname) > 0 ) {
493         config.concat( "." );
494         config.concat( hostname );
495         fgParseOptions(config.str());
496     }
497 #endif
498
499     // Check for ~/.fgfsrc
500     if ( homedir != NULL ) {
501         config.set( homedir );
502         config.append( ".fgfsrc" );
503         fgParseOptions(config.str());
504     }
505
506 #if defined( unix ) || defined( __CYGWIN__ ) || defined(_MSC_VER)
507     if( hostname != NULL && strlen(hostname) > 0 ) {
508         // Check for ~/.fgfsrc.hostname
509         config.concat( "." );
510         config.concat( hostname );
511         fgParseOptions(config.str());
512     }
513 #endif
514
515     // Parse remaining command line options
516     // These will override anything specified in a config file
517     fgParseArgs(argc, argv);
518 }
519
520 template <class T>
521 bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
522 {
523   if (!dirPath.exists()) {
524     SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
525     return false;
526   }
527     
528   bool recurse = true;
529   simgear::Dir dir(dirPath);
530   simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
531   simgear::PathList::iterator p;
532   for (p = setFiles.begin(); p != setFiles.end(); ++p) {
533     // check file name ends with -set.xml
534     
535     // if we found a -set.xml at this level, don't recurse any deeper
536     recurse = false;
537     
538     bool done = (obj->*pred)(*p);
539     if (done) {
540       return true;
541     }
542   } // of -set.xml iteration
543   
544   if (!recurse) {
545     return false;
546   }
547   
548   simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
549   for (p = subdirs.begin(); p != subdirs.end(); ++p) {
550     if (p->file() == "CVS") {
551       continue;
552     }
553     
554     if (fgFindAircraftInDir(*p, obj, pred)) {
555       return true;
556     }
557   } // of subdirs iteration
558   
559   return false;
560 }
561
562 template <class T>
563 void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
564 {
565   const string_list& paths(globals->get_aircraft_paths());
566   string_list::const_iterator it = paths.begin();
567   for (; it != paths.end(); ++it) {
568     bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
569     if (done) {
570       return;
571     }
572   } // of aircraft paths iteration
573   
574   // if we reach this point, search the default location (always last)
575   SGPath rootAircraft(globals->get_fg_root());
576   rootAircraft.append("Aircraft");
577   fgFindAircraftInDir(rootAircraft, obj, pred);
578 }
579
580 class FindAndCacheAircraft
581 {
582 public:
583   FindAndCacheAircraft(SGPropertyNode* autoSave)
584   {
585     _cache = autoSave->getNode("sim/startup/path-cache", true);
586   }
587   
588   bool loadAircraft()
589   {
590     std::string aircraft = fgGetString( "/sim/aircraft", "");    
591     if (aircraft.empty()) {
592       SG_LOG(SG_GENERAL, SG_ALERT, "no aircraft specified");
593       return false;
594     }
595     
596     _searchAircraft = aircraft + "-set.xml";
597     if (!checkCache()) {
598       // prepare cache for re-scan
599       SGPropertyNode *n = _cache->getNode("fg-root", true);
600       n->setStringValue(globals->get_fg_root().c_str());
601       n->setAttribute(SGPropertyNode::USERARCHIVE, true);
602       _cache->removeChildren("aircraft");
603   
604       fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
605     }
606     
607     if (_foundPath.str().empty()) {
608       SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find specified aircraft: " << aircraft );
609       return false;
610     }
611     
612     SG_LOG(SG_GENERAL, SG_INFO, "Loading aircraft -set file from:" << _foundPath.str());
613     fgSetString( "/sim/aircraft-dir", _foundPath.dir().c_str());
614     if (!_foundPath.exists()) {
615       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to find -set file:" << _foundPath.str());
616       return false;
617     }
618     
619     try {
620       readProperties(_foundPath.str(), globals->get_props());
621     } catch ( const sg_exception &e ) {
622       SG_LOG(SG_INPUT, SG_ALERT, "Error reading aircraft: " << e.getFormattedMessage());
623       return false;
624     }
625     
626     return true;
627   }
628   
629 private:
630   bool checkCache()
631   {
632     if (globals->get_fg_root() != _cache->getStringValue("fg-root", "")) {
633       return false; // cache mismatch
634     }
635     
636     vector<SGPropertyNode_ptr> cache = _cache->getChildren("aircraft");
637     for (unsigned int i = 0; i < cache.size(); i++) {
638       const char *name = cache[i]->getStringValue("file", "");
639       if (!boost::equals(_searchAircraft, name, is_iequal())) {
640         continue;
641       }
642       
643       SGPath xml(cache[i]->getStringValue("path", ""));
644       xml.append(name);
645       if (xml.exists()) {
646         _foundPath = xml;
647         return true;
648       } 
649       
650       return false;
651     } // of aircraft in cache iteration
652     
653     return false;
654   }
655   
656   bool checkAircraft(const SGPath& p)
657   {
658     // create cache node
659     int i = 0;
660     while (1) {
661         if (!_cache->getChild("aircraft", i++, false))
662             break;
663     }
664     
665     SGPropertyNode *n, *entry = _cache->getChild("aircraft", --i, true);
666
667     std::string fileName(p.file());
668     n = entry->getNode("file", true);
669     n->setStringValue(fileName);
670     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
671
672     n = entry->getNode("path", true);
673     n->setStringValue(p.dir());
674     n->setAttribute(SGPropertyNode::USERARCHIVE, true);
675
676     if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
677         _foundPath = p;
678         return true;
679     }
680
681     return false;
682   }
683   
684   std::string _searchAircraft;
685   SGPath _foundPath;
686   SGPropertyNode* _cache;
687 };
688
689 // Read in configuration (file and command line)
690 bool fgInitConfig ( int argc, char **argv ) {
691
692     // First, set some sane default values
693     fgSetDefaults();
694
695     // Read global preferences from $FG_ROOT/preferences.xml
696     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
697     fgLoadProps("preferences.xml", globals->get_props());
698     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
699
700     // Detect the required language as early as possible
701     if ( !fgDetectLanguage() ) {
702         return false;
703     }
704
705     SGPropertyNode autosave;
706 #ifdef _WIN32
707     char *envp = ::getenv( "APPDATA" );
708     if (envp != NULL ) {
709         SGPath config( envp );
710         config.append( "flightgear.org" );
711 #else
712     if ( homedir != NULL ) {
713         SGPath config( homedir );
714         config.append( ".fgfs" );
715 #endif
716         const char *fg_home = getenv("FG_HOME");
717         if (fg_home)
718             config = fg_home;
719
720         SGPath home_export(config.str());
721         home_export.append("Export/dummy");
722         home_export.create_dir(0777);
723
724         // Set /sim/fg-home and don't allow malign code to override it until
725         // Nasal security is set up.  Use FG_HOME if necessary.
726         SGPropertyNode *home = fgGetNode("/sim", true);
727         home->removeChild("fg-home", 0, false);
728         home = home->getChild("fg-home", 0, true);
729         home->setStringValue(config.c_str());
730         home->setAttribute(SGPropertyNode::WRITE, false);
731
732         config.append( "autosave.xml" );
733         if (config.exists()) {
734           SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
735           try {
736               readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
737           } catch (sg_exception& e) {
738               SG_LOG(SG_INPUT, SG_WARN, "failed to read user settings:" << e.getMessage()
739                 << "(from " << e.getOrigin() << ")");
740           }
741         }
742     }
743     
744     // Scan user config files and command line for a specified aircraft.
745     fgInitFGAircraft(argc, argv);
746     FindAndCacheAircraft f(&autosave);
747     if (!f.loadAircraft()) {
748       return false;
749     }
750
751     copyProperties(&autosave, globals->get_props());
752
753     // parse options after loading aircraft to ensure any user
754     // overrides of defaults are honored.
755     do_options(argc, argv);
756
757     return true;
758 }
759
760 // Set current tower position lon/lat given an airport id
761 static bool fgSetTowerPosFromAirportID( const string& id) {
762     const FGAirport *a = fgFindAirportID( id);
763     if (a) {
764         SGGeod tower = a->getTowerLocation();
765         fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
766         fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
767         fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
768         return true;
769     } else {
770         return false;
771     }
772
773 }
774
775 struct FGTowerLocationListener : SGPropertyChangeListener {
776     void valueChanged(SGPropertyNode* node) {
777         const string id(node->getStringValue());
778         fgSetTowerPosFromAirportID(id);
779     }
780 };
781
782 void fgInitTowerLocationListener() {
783     fgGetNode("/sim/tower/airport-id",  true)
784         ->addChangeListener( new FGTowerLocationListener(), true );
785 }
786
787 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
788 {
789   SGGeod startPos(aStartPos);
790   if (aTargetHeading == HUGE_VAL) {
791     aTargetHeading = aHeading;
792   }
793   
794   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
795     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
796     offsetDistance *= SG_NM_TO_METER;
797     double offsetAzimuth = aHeading;
798     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
799       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
800       aHeading = aTargetHeading;
801     }
802
803     SGGeod offset;
804     double az2; // dummy
805     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
806     startPos = offset;
807   }
808
809   // presets
810   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
811   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
812   fgSetDouble("/sim/presets/heading-deg", aHeading );
813
814   // other code depends on the actual values being set ...
815   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
816   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
817   fgSetDouble("/orientation/heading-deg", aHeading );
818 }
819
820 // Set current_options lon/lat given an airport id and heading (degrees)
821 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
822     if ( id.empty() )
823         return false;
824
825     // set initial position from runway and heading
826     SG_LOG( SG_GENERAL, SG_INFO,
827             "Attempting to set starting position from airport code "
828             << id << " heading " << tgt_hdg );
829
830     const FGAirport* apt = fgFindAirportID(id);
831     if (!apt) return false;
832     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
833     fgSetString("/sim/atc/runway", r->ident().c_str());
834
835     SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
836           fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
837     return true;
838 }
839
840 // Set current_options lon/lat given an airport id and parkig position name
841 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
842     if ( id.empty() )
843         return false;
844
845     // can't see an easy way around this const_cast at the moment
846     FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
847     if (!apt) {
848         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
849         return false;
850     }
851     FGAirportDynamics* dcs = apt->getDynamics();
852     if (!dcs) {
853         SG_LOG( SG_GENERAL, SG_ALERT,
854                 "Failed to find parking position " << parkpos <<
855                 " at airport " << id );
856         return false;
857     }
858     
859     int park_index = dcs->getNrOfParkings() - 1;
860     while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
861     if (park_index < 0) {
862         SG_LOG( SG_GENERAL, SG_ALERT,
863                 "Failed to find parking position " << parkpos <<
864                 " at airport " << id );
865         return false;
866     }
867     FGParking* parking = dcs->getParking(park_index);
868     parking->setAvailable(false);
869     fgApplyStartOffset(
870       SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
871       parking->getHeading());
872     return true;
873 }
874
875
876 // Set current_options lon/lat given an airport id and runway number
877 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
878     if ( id.empty() )
879         return false;
880
881     // set initial position from airport and runway number
882     SG_LOG( SG_GENERAL, SG_INFO,
883             "Attempting to set starting position for "
884             << id << ":" << rwy );
885
886     const FGAirport* apt = fgFindAirportID(id);
887     if (!apt) {
888       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
889       return false;
890     }
891     
892     if (!apt->hasRunwayWithIdent(rwy)) {
893       SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
894                 "Failed to find runway " << rwy <<
895                 " at airport " << id << ". Using default runway." );
896       return false;
897     }
898     
899     FGRunway* r(apt->getRunwayByIdent(rwy));
900     fgSetString("/sim/atc/runway", r->ident().c_str());
901     SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
902           fgApplyStartOffset(startPos, r->headingDeg());
903     return true;
904 }
905
906
907 static void fgSetDistOrAltFromGlideSlope() {
908     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
909     string apt_id = fgGetString("/sim/presets/airport-id");
910     double gs = fgGetDouble("/sim/presets/glideslope-deg")
911         * SG_DEGREES_TO_RADIANS ;
912     double od = fgGetDouble("/sim/presets/offset-distance-nm");
913     double alt = fgGetDouble("/sim/presets/altitude-ft");
914
915     double apt_elev = 0.0;
916     if ( ! apt_id.empty() ) {
917         apt_elev = fgGetAirportElev( apt_id );
918         if ( apt_elev < -9990.0 ) {
919             apt_elev = 0.0;
920         }
921     } else {
922         apt_elev = 0.0;
923     }
924
925     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
926         // set altitude from glideslope and offset-distance
927         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
928         alt = fabs(od*tan(gs)) + apt_elev;
929         fgSetDouble("/sim/presets/altitude-ft", alt);
930         fgSetBool("/sim/presets/onground", false);
931         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
932                 << alt  << " ft" );
933     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
934         // set offset-distance from glideslope and altitude
935         od  = (alt - apt_elev) / tan(gs);
936         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
937         fgSetDouble("/sim/presets/offset-distance-nm", od);
938         fgSetBool("/sim/presets/onground", false);
939         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
940                 << od  << " nm" );
941     } else if( fabs(gs) > 0.01 ) {
942         SG_LOG( SG_GENERAL, SG_ALERT,
943                 "Glideslope given but not altitude or offset-distance." );
944         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
945         fgSetDouble("/sim/presets/glideslope-deg", 0);
946         fgSetBool("/sim/presets/onground", true);
947     }
948 }
949
950
951 // Set current_options lon/lat given an airport id and heading (degrees)
952 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
953     FGNavRecord *nav
954         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
955
956   if (!nav) {
957     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
958                 << id << ":" << freq );
959     return false;
960   }
961   
962   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
963   return true;
964 }
965
966 // Set current_options lon/lat given an aircraft carrier id
967 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
968
969     // set initial position from runway and heading
970     SGGeod geodPos;
971     double heading;
972     SGVec3d uvw;
973     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
974         double lon = geodPos.getLongitudeDeg();
975         double lat = geodPos.getLatitudeDeg();
976         double alt = geodPos.getElevationFt();
977
978         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
979                 << carrier << " at lat = " << lat << ", lon = " << lon
980                 << ", alt = " << alt << ", heading = " << heading);
981
982         fgSetDouble("/sim/presets/longitude-deg",  lon);
983         fgSetDouble("/sim/presets/latitude-deg",  lat);
984         fgSetDouble("/sim/presets/altitude-ft", alt);
985         fgSetDouble("/sim/presets/heading-deg", heading);
986         fgSetDouble("/position/longitude-deg",  lon);
987         fgSetDouble("/position/latitude-deg",  lat);
988         fgSetDouble("/position/altitude-ft", alt);
989         fgSetDouble("/orientation/heading-deg", heading);
990
991         fgSetString("/sim/presets/speed-set", "UVW");
992         fgSetDouble("/velocities/uBody-fps", uvw(0));
993         fgSetDouble("/velocities/vBody-fps", uvw(1));
994         fgSetDouble("/velocities/wBody-fps", uvw(2));
995         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
996         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
997         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
998
999         fgSetBool("/sim/presets/onground", true);
1000
1001         return true;
1002     } else {
1003         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1004                 << carrier );
1005         return false;
1006     }
1007 }
1008  
1009 // Set current_options lon/lat given an airport id and heading (degrees)
1010 static bool fgSetPosFromFix( const string& id )
1011 {
1012   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1013   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1014   if (!fix) {
1015     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1016     return false;
1017   }
1018   
1019   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1020   return true;
1021 }
1022
1023 /**
1024  * Initialize vor/ndb/ils/fix list management and query systems (as
1025  * well as simple airport db list)
1026  */
1027 bool
1028 fgInitNav ()
1029 {
1030     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1031
1032     SGPath aptdb( globals->get_fg_root() );
1033     aptdb.append( "Airports/apt.dat" );
1034
1035     SGPath p_metar( globals->get_fg_root() );
1036     p_metar.append( "Airports/metar.dat" );
1037
1038 // Initialise the frequency search map BEFORE reading
1039 // the airport database:
1040
1041
1042
1043     current_commlist = new FGCommList;
1044     current_commlist->init( globals->get_fg_root() );
1045     fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1046
1047     FGNavList *navlist = new FGNavList;
1048     FGNavList *loclist = new FGNavList;
1049     FGNavList *gslist = new FGNavList;
1050     FGNavList *dmelist = new FGNavList;
1051     FGNavList *tacanlist = new FGNavList;
1052     FGNavList *carrierlist = new FGNavList;
1053     FGTACANList *channellist = new FGTACANList;
1054
1055     globals->set_navlist( navlist );
1056     globals->set_loclist( loclist );
1057     globals->set_gslist( gslist );
1058     globals->set_dmelist( dmelist );
1059     globals->set_tacanlist( tacanlist );
1060     globals->set_carrierlist( carrierlist );
1061     globals->set_channellist( channellist );
1062
1063     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1064         SG_LOG( SG_GENERAL, SG_ALERT,
1065                 "Problems loading one or more navigational database" );
1066     }
1067     
1068     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1069     SGPath p_fix( globals->get_fg_root() );
1070     p_fix.append( "Navaids/fix.dat" );
1071     FGFixList fixlist;
1072     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
1073
1074     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
1075     SGPath p_awy( globals->get_fg_root() );
1076     p_awy.append( "Navaids/awy.dat" );
1077     FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1078     //cerr << "Loading Airways" << endl;
1079     awyNet->load (p_awy );
1080     awyNet->init();
1081     //cerr << "initializing airways" << endl;
1082     globals->set_airwaynet( awyNet );
1083
1084     return true;
1085 }
1086
1087
1088 // Set the initial position based on presets (or defaults)
1089 bool fgInitPosition() {
1090     // cout << "fgInitPosition()" << endl;
1091     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1092         * SG_DEGREES_TO_RADIANS ;
1093     double od = fgGetDouble("/sim/presets/offset-distance-nm");
1094     double alt = fgGetDouble("/sim/presets/altitude-ft");
1095
1096     bool set_pos = false;
1097
1098     // If glideslope is specified, then calculate offset-distance or
1099     // altitude relative to glide slope if either of those was not
1100     // specified.
1101     if ( fabs( gs ) > 0.01 ) {
1102         fgSetDistOrAltFromGlideSlope();
1103     }
1104
1105
1106     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1107     // If not, check for an airport-id and use that.
1108     // If not, default to the middle of the KSFO field.
1109     // The default values for lon/lat are deliberately out of range
1110     // so that the airport-id can take effect; valid lon/lat will
1111     // override airport-id, however.
1112     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1113     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1114     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1115          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1116     {
1117         set_pos = true;
1118     }
1119
1120     string apt = fgGetString("/sim/presets/airport-id");
1121     string rwy_no = fgGetString("/sim/presets/runway");
1122     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1123     string vor = fgGetString("/sim/presets/vor-id");
1124     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1125     string ndb = fgGetString("/sim/presets/ndb-id");
1126     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1127     string carrier = fgGetString("/sim/presets/carrier");
1128     string parkpos = fgGetString("/sim/presets/parkpos");
1129     string fix = fgGetString("/sim/presets/fix");
1130     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1131     double hdg = hdg_preset->getDoubleValue();
1132
1133     // save some start parameters, so that we can later say what the
1134     // user really requested. TODO generalize that and move it to options.cxx
1135     static bool start_options_saved = false;
1136     if (!start_options_saved) {
1137         start_options_saved = true;
1138         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1139
1140         opt->setDoubleValue("latitude-deg", lat_deg);
1141         opt->setDoubleValue("longitude-deg", lon_deg);
1142         opt->setDoubleValue("heading-deg", hdg);
1143         opt->setStringValue("airport", apt.c_str());
1144         opt->setStringValue("runway", rwy_no.c_str());
1145     }
1146
1147     if (hdg > 9990.0)
1148         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1149
1150     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1151         // An airport + parking position is requested
1152         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1153             // set tower position
1154             fgSetString("/sim/tower/airport-id",  apt.c_str());
1155             set_pos = true;
1156         }
1157     }
1158
1159     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1160         // An airport + runway is requested
1161         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1162             // set tower position (a little off the heading for single
1163             // runway airports)
1164             fgSetString("/sim/tower/airport-id",  apt.c_str());
1165             set_pos = true;
1166         }
1167     }
1168
1169     if ( !set_pos && !apt.empty() ) {
1170         // An airport is requested (find runway closest to hdg)
1171         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1172             // set tower position (a little off the heading for single
1173             // runway airports)
1174             fgSetString("/sim/tower/airport-id",  apt.c_str());
1175             set_pos = true;
1176         }
1177     }
1178
1179     if (hdg_preset->getDoubleValue() > 9990.0)
1180         hdg_preset->setDoubleValue(hdg);
1181
1182     if ( !set_pos && !vor.empty() ) {
1183         // a VOR is requested
1184         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1185             set_pos = true;
1186         }
1187     }
1188
1189     if ( !set_pos && !ndb.empty() ) {
1190         // an NDB is requested
1191         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1192             set_pos = true;
1193         }
1194     }
1195
1196     if ( !set_pos && !carrier.empty() ) {
1197         // an aircraft carrier is requested
1198         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1199             set_pos = true;
1200         }
1201     }
1202
1203     if ( !set_pos && !fix.empty() ) {
1204         // a Fix is requested
1205         if ( fgSetPosFromFix( fix ) ) {
1206             set_pos = true;
1207         }
1208     }
1209
1210     if ( !set_pos ) {
1211         // No lon/lat specified, no airport specified, default to
1212         // middle of KSFO field.
1213         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1214         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1215     }
1216
1217     fgSetDouble( "/position/longitude-deg",
1218                  fgGetDouble("/sim/presets/longitude-deg") );
1219     fgSetDouble( "/position/latitude-deg",
1220                  fgGetDouble("/sim/presets/latitude-deg") );
1221     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1222
1223     // determine if this should be an on-ground or in-air start
1224     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1225         fgSetBool("/sim/presets/onground", false);
1226     } else {
1227         fgSetBool("/sim/presets/onground", true);
1228     }
1229
1230     return true;
1231 }
1232
1233
1234 // General house keeping initializations
1235 bool fgInitGeneral() {
1236     string root;
1237
1238     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1239     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1240
1241     root = globals->get_fg_root();
1242     if ( ! root.length() ) {
1243         // No root path set? Then bail ...
1244         SG_LOG( SG_GENERAL, SG_ALERT,
1245                 "Cannot continue without a path to the base package "
1246                 << "being defined." );
1247         exit(-1);
1248     }
1249     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1250
1251     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1252
1253     char buf[512], *cwd = getcwd(buf, 511);
1254     buf[511] = '\0';
1255     SGPropertyNode *curr = fgGetNode("/sim", true);
1256     curr->removeChild("fg-current", 0, false);
1257     curr = curr->getChild("fg-current", 0, true);
1258     curr->setStringValue(cwd ? cwd : "");
1259     curr->setAttribute(SGPropertyNode::WRITE, false);
1260
1261     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1262     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1263     return true;
1264 }
1265
1266 // Initialize view parameters
1267 void fgInitView() {
1268   // force update of model so that viewer can get some data...
1269   globals->get_aircraft_model()->update(0);
1270   // run update for current view so that data is current...
1271   globals->get_viewmgr()->update(0);
1272 }
1273
1274 // This is the top level init routine which calls all the other
1275 // initialization routines.  If you are adding a subsystem to flight
1276 // gear, its initialization call should located in this routine.
1277 // Returns non-zero if a problem encountered.
1278 bool fgInitSubsystems() {
1279     // static const SGPropertyNode *longitude
1280     //     = fgGetNode("/sim/presets/longitude-deg");
1281     // static const SGPropertyNode *latitude
1282     //     = fgGetNode("/sim/presets/latitude-deg");
1283     // static const SGPropertyNode *altitude
1284     //     = fgGetNode("/sim/presets/altitude-ft");
1285
1286     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1287     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1288
1289     ////////////////////////////////////////////////////////////////////
1290     // Initialize the event manager subsystem.
1291     ////////////////////////////////////////////////////////////////////
1292
1293     globals->get_event_mgr()->init();
1294     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1295
1296     ////////////////////////////////////////////////////////////////////
1297     // Initialize the property interpolator subsystem. Put into the INIT
1298     // group because the "nasal" subsystem may need it at GENERAL take-down.
1299     ////////////////////////////////////////////////////////////////////
1300     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1301
1302
1303     ////////////////////////////////////////////////////////////////////
1304     // Add the FlightGear property utilities.
1305     ////////////////////////////////////////////////////////////////////
1306     globals->add_subsystem("properties", new FGProperties);
1307
1308     ////////////////////////////////////////////////////////////////////
1309     // Initialize the material property subsystem.
1310     ////////////////////////////////////////////////////////////////////
1311
1312     SGPath mpath( globals->get_fg_root() );
1313     mpath.append( "materials.xml" );
1314     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1315             globals->get_props()) ) {
1316         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1317         exit(-1);
1318     }
1319
1320
1321     ////////////////////////////////////////////////////////////////////
1322     // Initialize the scenery management subsystem.
1323     ////////////////////////////////////////////////////////////////////
1324
1325     if ( globals->get_tile_mgr()->init() ) {
1326         // Load the local scenery data
1327         double visibility_meters = fgGetDouble("/environment/visibility-m");
1328         globals->get_tile_mgr()->update( visibility_meters );
1329     } else {
1330         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1331         exit(-1);
1332     }
1333
1334     globals->get_scenery()->get_scene_graph()
1335         ->addChild(simgear::Particles::getCommonRoot());
1336     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1337
1338     ////////////////////////////////////////////////////////////////////
1339     // Initialize the flight model subsystem.
1340     ////////////////////////////////////////////////////////////////////
1341
1342     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1343
1344     ////////////////////////////////////////////////////////////////////
1345     // Initialize the weather subsystem.
1346     ////////////////////////////////////////////////////////////////////
1347
1348     // Initialize the weather modeling subsystem
1349     globals->add_subsystem("environment", new FGEnvironmentMgr);
1350
1351     ////////////////////////////////////////////////////////////////////
1352     // Initialize the aircraft systems and instrumentation (before the
1353     // autopilot.)
1354     ////////////////////////////////////////////////////////////////////
1355
1356     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1357     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1358
1359     ////////////////////////////////////////////////////////////////////
1360     // Initialize the XML Autopilot subsystem.
1361     ////////////////////////////////////////////////////////////////////
1362
1363     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1364     globals->add_subsystem( "route-manager", new FGRouteMgr );
1365     
1366     ////////////////////////////////////////////////////////////////////
1367     // Initialize the view manager subsystem.
1368     ////////////////////////////////////////////////////////////////////
1369
1370     fgInitView();
1371
1372     ////////////////////////////////////////////////////////////////////
1373     // Initialize the Input-Output subsystem
1374     ////////////////////////////////////////////////////////////////////
1375     globals->add_subsystem( "io", new FGIO );
1376
1377     ////////////////////////////////////////////////////////////////////
1378     // Create and register the logger.
1379     ////////////////////////////////////////////////////////////////////
1380     
1381     globals->add_subsystem("logger", new FGLogger);
1382
1383     ////////////////////////////////////////////////////////////////////
1384     // Create and register the XML GUI.
1385     ////////////////////////////////////////////////////////////////////
1386
1387     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1388
1389     ////////////////////////////////////////////////////////////////////
1390     // Initialize the lighting subsystem.
1391     ////////////////////////////////////////////////////////////////////
1392
1393     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1394
1395     //////////////////////////////////////////////////////////////////////
1396     // Initialize the 2D cloud subsystem.
1397     ////////////////////////////////////////////////////////////////////
1398     fgGetBool("/sim/rendering/bump-mapping", false);
1399
1400 #ifdef ENABLE_AUDIO_SUPPORT
1401     ////////////////////////////////////////////////////////////////////
1402     // Initialize the sound-effects subsystem.
1403     ////////////////////////////////////////////////////////////////////
1404     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1405 #endif
1406
1407     ////////////////////////////////////////////////////////////////////
1408     // Initialise the ATC Manager 
1409     ////////////////////////////////////////////////////////////////////
1410
1411 #if ENABLE_ATCDCL
1412     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1413     globals->set_ATC_mgr(new FGATCMgr);
1414     globals->get_ATC_mgr()->init(); 
1415 #else
1416     ////////////////////////////////////////////////////////////////////
1417     // Initialise the ATIS Manager
1418     ////////////////////////////////////////////////////////////////////
1419     globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1420 #endif
1421     ////////////////////////////////////////////////////////////////////
1422     // Initialise the AI Model Manager
1423     ////////////////////////////////////////////////////////////////////
1424     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1425     globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1426     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1427
1428
1429     // It's probably a good idea to initialize the top level traffic manager
1430     // After the AI and ATC systems have been initialized properly.
1431     // AI Traffic manager
1432     globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1433
1434
1435     if( fgCockpitInit()) {
1436         // Cockpit initialized ok.
1437     } else {
1438         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1439         exit(-1);
1440     }
1441
1442
1443     ////////////////////////////////////////////////////////////////////
1444     // Add a new 2D panel.
1445     ////////////////////////////////////////////////////////////////////
1446
1447     string panel_path = fgGetString("/sim/panel/path",
1448                                     "Panels/Default/default.xml");
1449
1450     globals->set_current_panel( fgReadPanel(panel_path) );
1451     if (globals->get_current_panel() == 0) {
1452         SG_LOG( SG_INPUT, SG_ALERT,
1453                 "Error reading new panel from " << panel_path );
1454     } else {
1455         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1456         globals->get_current_panel()->init();
1457         globals->get_current_panel()->bind();
1458     }
1459
1460
1461     ////////////////////////////////////////////////////////////////////
1462     // Initialize the controls subsystem.
1463     ////////////////////////////////////////////////////////////////////
1464
1465     globals->get_controls()->init();
1466     globals->get_controls()->bind();
1467
1468
1469     ////////////////////////////////////////////////////////////////////
1470     // Initialize the input subsystem.
1471     ////////////////////////////////////////////////////////////////////
1472
1473     globals->add_subsystem("input", new FGInput);
1474
1475
1476     ////////////////////////////////////////////////////////////////////
1477     // Initialize the replay subsystem
1478     ////////////////////////////////////////////////////////////////////
1479     globals->add_subsystem("replay", new FGReplay);
1480
1481
1482     ////////////////////////////////////////////////////////////////////
1483     // Bind and initialize subsystems.
1484     ////////////////////////////////////////////////////////////////////
1485
1486     globals->get_subsystem_mgr()->bind();
1487     globals->get_subsystem_mgr()->init();
1488
1489     ////////////////////////////////////////////////////////////////////
1490     // Initialize multiplayer subsystem
1491     ////////////////////////////////////////////////////////////////////
1492
1493     globals->set_multiplayer_mgr(new FGMultiplayMgr);
1494     globals->get_multiplayer_mgr()->init();
1495
1496     ////////////////////////////////////////////////////////////////////////
1497     // Initialize the Nasal interpreter.
1498     // Do this last, so that the loaded scripts see initialized state
1499     ////////////////////////////////////////////////////////////////////////
1500     FGNasalSys* nasal = new FGNasalSys();
1501     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1502     nasal->init();
1503
1504     // initialize methods that depend on other subsystems.
1505     globals->get_subsystem_mgr()->postinit();
1506
1507     ////////////////////////////////////////////////////////////////////////
1508     // End of subsystem initialization.
1509     ////////////////////////////////////////////////////////////////////
1510
1511     SG_LOG( SG_GENERAL, SG_INFO, endl);
1512
1513                                 // Save the initial state for future
1514                                 // reference.
1515     globals->saveInitialState();
1516     
1517     return true;
1518 }
1519
1520
1521 void fgReInitSubsystems()
1522 {
1523     // static const SGPropertyNode *longitude
1524     //     = fgGetNode("/sim/presets/longitude-deg");
1525     // static const SGPropertyNode *latitude
1526     //     = fgGetNode("/sim/presets/latitude-deg");
1527     static const SGPropertyNode *altitude
1528         = fgGetNode("/sim/presets/altitude-ft");
1529     static const SGPropertyNode *master_freeze
1530         = fgGetNode("/sim/freeze/master");
1531
1532     SG_LOG( SG_GENERAL, SG_INFO,
1533             "fgReInitSubsystems(): /position/altitude = "
1534             << altitude->getDoubleValue() );
1535
1536     bool freeze = master_freeze->getBoolValue();
1537     if ( !freeze ) {
1538         fgSetBool("/sim/freeze/master", true);
1539     }
1540     fgSetBool("/sim/crashed", false);
1541
1542     // Force reupdating the positions of the ai 3d models. They are used for
1543     // initializing ground level for the FDM.
1544     globals->get_subsystem("ai_model")->reinit();
1545
1546     // Initialize the FDM
1547     globals->get_subsystem("flight")->reinit();
1548
1549     // reload offsets from config defaults
1550     globals->get_viewmgr()->reinit();
1551
1552     fgInitView();
1553
1554     globals->get_controls()->reset_all();
1555
1556     globals->get_subsystem("time")->reinit();
1557
1558     if ( !freeze ) {
1559         fgSetBool("/sim/freeze/master", false);
1560     }
1561     fgSetBool("/sim/sceneryloaded",false);
1562 }
1563
1564
1565 void doSimulatorReset(void)  // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1566 {
1567     static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1568
1569     bool freeze = master_freeze->getBoolValue();
1570     if (!freeze)
1571         master_freeze->setBoolValue(true);
1572
1573     fgSetBool("/sim/signals/reinit", true);
1574
1575     globals->get_subsystem("flight")->unbind();
1576
1577     globals->restoreInitialState();
1578
1579     // update our position based on current presets
1580     fgInitPosition();
1581
1582     fgReInitSubsystems();
1583
1584     globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1585     fgSetBool("/sim/signals/reinit", false);
1586
1587     if (!freeze)
1588         master_freeze->setBoolValue(false);
1589 }
1590
1591 ///////////////////////////////////////////////////////////////////////////////
1592 // helper object to implement the --show-aircraft command.
1593 // resides here so we can share the fgFindAircraftInDir template above,
1594 // and hence ensure this command lists exectly the same aircraft as the normal
1595 // loading path.
1596 class ShowAircraft 
1597 {
1598 public:
1599   ShowAircraft()
1600   {
1601     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1602   }
1603   
1604   
1605   void show(const SGPath& path)
1606   {
1607     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1608   
1609     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1610     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1611     cout << "Available aircraft:" << endl;
1612     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1613         cout << _aircraft[i] << endl;
1614     }
1615   }
1616   
1617 private:
1618   bool processAircraft(const SGPath& path)
1619   {
1620     SGPropertyNode root;
1621     try {
1622        readProperties(path.str(), &root);
1623     } catch (sg_exception& ) {
1624        return false;
1625     }
1626   
1627     int maturity = 0;
1628     string descStr("   ");
1629     descStr += path.file();
1630   // trim common suffix from file names
1631     int nPos = descStr.rfind("-set.xml");
1632     if (nPos == (int)(descStr.size() - 8)) {
1633       descStr.resize(nPos);
1634     }
1635     
1636     SGPropertyNode *node = root.getNode("sim");
1637     if (node) {
1638       SGPropertyNode* desc = node->getNode("description");
1639       // if a status tag is found, read it in
1640       if (node->hasValue("status")) {
1641         maturity = getNumMaturity(node->getStringValue("status"));
1642       }
1643       
1644       if (desc) {
1645         if (descStr.size() <= 27+3) {
1646           descStr.append(29+3-descStr.size(), ' ');
1647         } else {
1648           descStr += '\n';
1649           descStr.append( 32, ' ');
1650         }
1651         descStr += desc->getStringValue();
1652       }
1653     } // of have 'sim' node
1654     
1655     if (maturity < _minStatus) {
1656       return false;
1657     }
1658
1659     _aircraft.push_back(descStr);
1660     return false;
1661   }
1662
1663
1664   int getNumMaturity(const char * str) 
1665   {
1666     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1667     // $FG_ROOT/data/Translations/string-default.xml
1668     const char* levels[] = {"alpha","beta","early-production","production"}; 
1669
1670     if (!strcmp(str, "all")) {
1671       return 0;
1672     }
1673
1674     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1675       if (strcmp(str,levels[i])==0)
1676         return i;
1677
1678     return 0;
1679   }
1680
1681   // recommended in Meyers, Effective STL when internationalization and embedded
1682   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1683   struct ciLessLibC : public std::binary_function<string, string, bool>
1684   {
1685     bool operator()(const std::string &lhs, const std::string &rhs) const
1686     {
1687       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1688     }
1689   };
1690
1691   int _minStatus;
1692   string_list _aircraft;
1693 };
1694
1695 void fgShowAircraft(const SGPath &path)
1696 {
1697     ShowAircraft s;
1698     s.show(path);
1699         
1700 #ifdef _MSC_VER
1701     cout << "Hit a key to continue..." << endl;
1702     cin.get();
1703 #endif
1704 }
1705
1706