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