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