]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Automatic tower positioning
[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 #include <ATCDCL/commlist.hxx>
79 #include <ATC/atis_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 ) {
1002     FGNavRecord *nav
1003         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
1004
1005   if (!nav) {
1006     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1007                 << id << ":" << freq );
1008     return false;
1009   }
1010   
1011   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
1012   return true;
1013 }
1014
1015 // Set current_options lon/lat given an aircraft carrier id
1016 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
1017
1018     // set initial position from runway and heading
1019     SGGeod geodPos;
1020     double heading;
1021     SGVec3d uvw;
1022     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
1023         double lon = geodPos.getLongitudeDeg();
1024         double lat = geodPos.getLatitudeDeg();
1025         double alt = geodPos.getElevationFt();
1026
1027         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1028                 << carrier << " at lat = " << lat << ", lon = " << lon
1029                 << ", alt = " << alt << ", heading = " << heading);
1030
1031         fgSetDouble("/sim/presets/longitude-deg",  lon);
1032         fgSetDouble("/sim/presets/latitude-deg",  lat);
1033         fgSetDouble("/sim/presets/altitude-ft", alt);
1034         fgSetDouble("/sim/presets/heading-deg", heading);
1035         fgSetDouble("/position/longitude-deg",  lon);
1036         fgSetDouble("/position/latitude-deg",  lat);
1037         fgSetDouble("/position/altitude-ft", alt);
1038         fgSetDouble("/orientation/heading-deg", heading);
1039
1040         fgSetString("/sim/presets/speed-set", "UVW");
1041         fgSetDouble("/velocities/uBody-fps", uvw(0));
1042         fgSetDouble("/velocities/vBody-fps", uvw(1));
1043         fgSetDouble("/velocities/wBody-fps", uvw(2));
1044         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
1045         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
1046         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
1047
1048         fgSetBool("/sim/presets/onground", true);
1049
1050         return true;
1051     } else {
1052         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1053                 << carrier );
1054         return false;
1055     }
1056 }
1057  
1058 // Set current_options lon/lat given an airport id and heading (degrees)
1059 static bool fgSetPosFromFix( const string& id )
1060 {
1061   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
1062   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
1063   if (!fix) {
1064     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
1065     return false;
1066   }
1067   
1068   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
1069   return true;
1070 }
1071
1072 /**
1073  * Initialize vor/ndb/ils/fix list management and query systems (as
1074  * well as simple airport db list)
1075  */
1076 bool
1077 fgInitNav ()
1078 {
1079     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1080
1081     SGPath aptdb( globals->get_fg_root() );
1082     aptdb.append( "Airports/apt.dat" );
1083
1084     SGPath p_metar( globals->get_fg_root() );
1085     p_metar.append( "Airports/metar.dat" );
1086
1087 // Initialise the frequency search map BEFORE reading
1088 // the airport database:
1089
1090
1091
1092     current_commlist = new FGCommList;
1093     current_commlist->init( globals->get_fg_root() );
1094     fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
1095
1096     FGNavList *navlist = new FGNavList;
1097     FGNavList *loclist = new FGNavList;
1098     FGNavList *gslist = new FGNavList;
1099     FGNavList *dmelist = new FGNavList;
1100     FGNavList *tacanlist = new FGNavList;
1101     FGNavList *carrierlist = new FGNavList;
1102     FGTACANList *channellist = new FGTACANList;
1103
1104     globals->set_navlist( navlist );
1105     globals->set_loclist( loclist );
1106     globals->set_gslist( gslist );
1107     globals->set_dmelist( dmelist );
1108     globals->set_tacanlist( tacanlist );
1109     globals->set_carrierlist( carrierlist );
1110     globals->set_channellist( channellist );
1111
1112     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
1113         SG_LOG( SG_GENERAL, SG_ALERT,
1114                 "Problems loading one or more navigational database" );
1115     }
1116     
1117     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1118     SGPath p_fix( globals->get_fg_root() );
1119     p_fix.append( "Navaids/fix.dat" );
1120     FGFixList fixlist;
1121     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
1122
1123     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
1124     flightgear::Airway::load();
1125     
1126     return true;
1127 }
1128
1129
1130 // Set the initial position based on presets (or defaults)
1131 bool fgInitPosition() {
1132     // cout << "fgInitPosition()" << endl;
1133     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1134         * SG_DEGREES_TO_RADIANS ;
1135     double od = fgGetDouble("/sim/presets/offset-distance-nm");
1136     double alt = fgGetDouble("/sim/presets/altitude-ft");
1137
1138     bool set_pos = false;
1139
1140     // If glideslope is specified, then calculate offset-distance or
1141     // altitude relative to glide slope if either of those was not
1142     // specified.
1143     if ( fabs( gs ) > 0.01 ) {
1144         fgSetDistOrAltFromGlideSlope();
1145     }
1146
1147
1148     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1149     // If not, check for an airport-id and use that.
1150     // If not, default to the middle of the KSFO field.
1151     // The default values for lon/lat are deliberately out of range
1152     // so that the airport-id can take effect; valid lon/lat will
1153     // override airport-id, however.
1154     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1155     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1156     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1157          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1158     {
1159         set_pos = true;
1160     }
1161
1162     string apt = fgGetString("/sim/presets/airport-id");
1163     string rwy_no = fgGetString("/sim/presets/runway");
1164     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1165     string vor = fgGetString("/sim/presets/vor-id");
1166     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1167     string ndb = fgGetString("/sim/presets/ndb-id");
1168     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1169     string carrier = fgGetString("/sim/presets/carrier");
1170     string parkpos = fgGetString("/sim/presets/parkpos");
1171     string fix = fgGetString("/sim/presets/fix");
1172     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1173     double hdg = hdg_preset->getDoubleValue();
1174
1175     // save some start parameters, so that we can later say what the
1176     // user really requested. TODO generalize that and move it to options.cxx
1177     static bool start_options_saved = false;
1178     if (!start_options_saved) {
1179         start_options_saved = true;
1180         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1181
1182         opt->setDoubleValue("latitude-deg", lat_deg);
1183         opt->setDoubleValue("longitude-deg", lon_deg);
1184         opt->setDoubleValue("heading-deg", hdg);
1185         opt->setStringValue("airport", apt.c_str());
1186         opt->setStringValue("runway", rwy_no.c_str());
1187     }
1188
1189     if (hdg > 9990.0)
1190         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1191
1192     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1193         // An airport + parking position is requested
1194         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1195             // set tower position
1196             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1197             fgSetString("/sim/tower/airport-id",  apt.c_str());
1198             set_pos = true;
1199         }
1200     }
1201
1202     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1203         // An airport + runway is requested
1204         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1205             // set tower position (a little off the heading for single
1206             // runway airports)
1207             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1208             fgSetString("/sim/tower/airport-id",  apt.c_str());
1209             set_pos = true;
1210         }
1211     }
1212
1213     if ( !set_pos && !apt.empty() ) {
1214         // An airport is requested (find runway closest to hdg)
1215         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1216             // set tower position (a little off the heading for single
1217             // runway airports)
1218             fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
1219             fgSetString("/sim/tower/airport-id",  apt.c_str());
1220             set_pos = true;
1221         }
1222     }
1223
1224     if (hdg_preset->getDoubleValue() > 9990.0)
1225         hdg_preset->setDoubleValue(hdg);
1226
1227     if ( !set_pos && !vor.empty() ) {
1228         // a VOR is requested
1229         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1230             set_pos = true;
1231         }
1232     }
1233
1234     if ( !set_pos && !ndb.empty() ) {
1235         // an NDB is requested
1236         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1237             set_pos = true;
1238         }
1239     }
1240
1241     if ( !set_pos && !carrier.empty() ) {
1242         // an aircraft carrier is requested
1243         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1244             set_pos = true;
1245         }
1246     }
1247
1248     if ( !set_pos && !fix.empty() ) {
1249         // a Fix is requested
1250         if ( fgSetPosFromFix( fix ) ) {
1251             set_pos = true;
1252         }
1253     }
1254
1255     if ( !set_pos ) {
1256         // No lon/lat specified, no airport specified, default to
1257         // middle of KSFO field.
1258         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1259         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1260     }
1261
1262     fgSetDouble( "/position/longitude-deg",
1263                  fgGetDouble("/sim/presets/longitude-deg") );
1264     fgSetDouble( "/position/latitude-deg",
1265                  fgGetDouble("/sim/presets/latitude-deg") );
1266     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1267
1268     // determine if this should be an on-ground or in-air start
1269     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1270         fgSetBool("/sim/presets/onground", false);
1271     } else {
1272         fgSetBool("/sim/presets/onground", true);
1273     }
1274
1275     return true;
1276 }
1277
1278
1279 // General house keeping initializations
1280 bool fgInitGeneral() {
1281     string root;
1282
1283     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1284     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1285
1286     root = globals->get_fg_root();
1287     if ( ! root.length() ) {
1288         // No root path set? Then bail ...
1289         SG_LOG( SG_GENERAL, SG_ALERT,
1290                 "Cannot continue without a path to the base package "
1291                 << "being defined." );
1292         exit(-1);
1293     }
1294     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1295
1296     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1297
1298     char buf[512], *cwd = getcwd(buf, 511);
1299     buf[511] = '\0';
1300     SGPropertyNode *curr = fgGetNode("/sim", true);
1301     curr->removeChild("fg-current", 0, false);
1302     curr = curr->getChild("fg-current", 0, true);
1303     curr->setStringValue(cwd ? cwd : "");
1304     curr->setAttribute(SGPropertyNode::WRITE, false);
1305
1306     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1) != 0 );
1307     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2) != 0 );
1308     return true;
1309 }
1310
1311 // This is the top level init routine which calls all the other
1312 // initialization routines.  If you are adding a subsystem to flight
1313 // gear, its initialization call should located in this routine.
1314 // Returns non-zero if a problem encountered.
1315 bool fgInitSubsystems() {
1316     // static const SGPropertyNode *longitude
1317     //     = fgGetNode("/sim/presets/longitude-deg");
1318     // static const SGPropertyNode *latitude
1319     //     = fgGetNode("/sim/presets/latitude-deg");
1320     // static const SGPropertyNode *altitude
1321     //     = fgGetNode("/sim/presets/altitude-ft");
1322
1323     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1324     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1325
1326     ////////////////////////////////////////////////////////////////////
1327     // Initialize the event manager subsystem.
1328     ////////////////////////////////////////////////////////////////////
1329
1330     globals->get_event_mgr()->init();
1331     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1332
1333     ////////////////////////////////////////////////////////////////////
1334     // Initialize the property interpolator subsystem. Put into the INIT
1335     // group because the "nasal" subsystem may need it at GENERAL take-down.
1336     ////////////////////////////////////////////////////////////////////
1337     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1338
1339
1340     ////////////////////////////////////////////////////////////////////
1341     // Add the FlightGear property utilities.
1342     ////////////////////////////////////////////////////////////////////
1343     globals->add_subsystem("properties", new FGProperties);
1344
1345     ////////////////////////////////////////////////////////////////////
1346     // Initialize the material property subsystem.
1347     ////////////////////////////////////////////////////////////////////
1348
1349     SGPath mpath( globals->get_fg_root() );
1350     mpath.append( "materials.xml" );
1351     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1352             globals->get_props()) ) {
1353         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1354         exit(-1);
1355     }
1356
1357
1358     ////////////////////////////////////////////////////////////////////
1359     // Initialize the scenery management subsystem.
1360     ////////////////////////////////////////////////////////////////////
1361
1362     globals->get_scenery()->get_scene_graph()
1363         ->addChild(simgear::Particles::getCommonRoot());
1364     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1365
1366     ////////////////////////////////////////////////////////////////////
1367     // Initialize the flight model subsystem.
1368     ////////////////////////////////////////////////////////////////////
1369
1370     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1371
1372     ////////////////////////////////////////////////////////////////////
1373     // Initialize the weather subsystem.
1374     ////////////////////////////////////////////////////////////////////
1375
1376     // Initialize the weather modeling subsystem
1377     globals->add_subsystem("environment", new FGEnvironmentMgr);
1378
1379     ////////////////////////////////////////////////////////////////////
1380     // Initialize the aircraft systems and instrumentation (before the
1381     // autopilot.)
1382     ////////////////////////////////////////////////////////////////////
1383
1384     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1385     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1386
1387     ////////////////////////////////////////////////////////////////////
1388     // Initialize the XML Autopilot subsystem.
1389     ////////////////////////////////////////////////////////////////////
1390
1391     globals->add_subsystem( "xml-autopilot", FGXMLAutopilotGroup::createInstance(), SGSubsystemMgr::FDM );
1392     globals->add_subsystem( "route-manager", new FGRouteMgr );
1393
1394     ////////////////////////////////////////////////////////////////////
1395     // Initialize the Input-Output subsystem
1396     ////////////////////////////////////////////////////////////////////
1397     globals->add_subsystem( "io", new FGIO );
1398
1399     ////////////////////////////////////////////////////////////////////
1400     // Create and register the logger.
1401     ////////////////////////////////////////////////////////////////////
1402     
1403     globals->add_subsystem("logger", new FGLogger);
1404
1405     ////////////////////////////////////////////////////////////////////
1406     // Create and register the XML GUI.
1407     ////////////////////////////////////////////////////////////////////
1408
1409     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1410
1411     //////////////////////////////////////////////////////////////////////
1412     // Initialize the 2D cloud subsystem.
1413     ////////////////////////////////////////////////////////////////////
1414     fgGetBool("/sim/rendering/bump-mapping", false);
1415
1416
1417
1418     ////////////////////////////////////////////////////////////////////
1419     // Initialise the ATC Manager
1420     ////////////////////////////////////////////////////////////////////
1421
1422     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1423     globals->set_ATC_mgr(new FGATCMgr);
1424     globals->get_ATC_mgr()->init(); 
1425
1426     ////////////////////////////////////////////////////////////////////
1427     // Initialise the ATIS Manager
1428     ////////////////////////////////////////////////////////////////////
1429     globals->add_subsystem("atis", new FGAtisManager, SGSubsystemMgr::POST_FDM);
1430
1431
1432     ////////////////////////////////////////////////////////////////////
1433     // Initialize multiplayer subsystem
1434     ////////////////////////////////////////////////////////////////////
1435
1436     globals->add_subsystem("mp", new FGMultiplayMgr, SGSubsystemMgr::POST_FDM);
1437
1438     ////////////////////////////////////////////////////////////////////
1439     // Initialise the AI Model Manager
1440     ////////////////////////////////////////////////////////////////////
1441     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1442     globals->add_subsystem("ai_model", new FGAIManager, SGSubsystemMgr::POST_FDM);
1443     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr, SGSubsystemMgr::POST_FDM);
1444
1445
1446     // It's probably a good idea to initialize the top level traffic manager
1447     // After the AI and ATC systems have been initialized properly.
1448     // AI Traffic manager
1449     globals->add_subsystem("Traffic Manager", new FGTrafficManager, SGSubsystemMgr::POST_FDM);
1450
1451     ////////////////////////////////////////////////////////////////////
1452     // Add a new 2D panel.
1453     ////////////////////////////////////////////////////////////////////
1454
1455     string panel_path(fgGetString("/sim/panel/path"));
1456     if (!panel_path.empty()) {
1457       FGPanel* p = fgReadPanel(panel_path);
1458       if (p) {
1459         globals->set_current_panel(p);
1460         p->init();
1461         p->bind();
1462         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1463       } else {
1464         SG_LOG( SG_INPUT, SG_ALERT,
1465                 "Error reading new panel from " << panel_path );
1466       }
1467     }
1468
1469     ////////////////////////////////////////////////////////////////////
1470     // Initialize the controls subsystem.
1471     ////////////////////////////////////////////////////////////////////
1472
1473     globals->get_controls()->init();
1474     globals->get_controls()->bind();
1475
1476
1477     ////////////////////////////////////////////////////////////////////
1478     // Initialize the input subsystem.
1479     ////////////////////////////////////////////////////////////////////
1480
1481     globals->add_subsystem("input", new FGInput);
1482
1483
1484     ////////////////////////////////////////////////////////////////////
1485     // Initialize the replay subsystem
1486     ////////////////////////////////////////////////////////////////////
1487     globals->add_subsystem("replay", new FGReplay);
1488
1489 #ifdef ENABLE_AUDIO_SUPPORT
1490     ////////////////////////////////////////////////////////////////////
1491     // Initialize the sound-effects subsystem.
1492     ////////////////////////////////////////////////////////////////////
1493     globals->add_subsystem("voice", new FGVoiceMgr, SGSubsystemMgr::DISPLAY);
1494 #endif
1495
1496     ////////////////////////////////////////////////////////////////////
1497     // Initialize the lighting subsystem.
1498     ////////////////////////////////////////////////////////////////////
1499
1500     globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
1501     
1502     // ordering here is important : Nasal (via events), then models, then views
1503     globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
1504     
1505     FGAircraftModel* acm = new FGAircraftModel;
1506     globals->set_aircraft_model(acm);
1507     globals->add_subsystem("aircraft-model", acm, SGSubsystemMgr::DISPLAY);
1508
1509     FGModelMgr* mm = new FGModelMgr;
1510     globals->set_model_mgr(mm);
1511     globals->add_subsystem("model-manager", mm, SGSubsystemMgr::DISPLAY);
1512
1513     FGViewMgr *viewmgr = new FGViewMgr;
1514     globals->set_viewmgr( viewmgr );
1515     globals->add_subsystem("view-manager", viewmgr, SGSubsystemMgr::DISPLAY);
1516
1517     globals->add_subsystem("tile-manager", globals->get_tile_mgr(), 
1518       SGSubsystemMgr::DISPLAY);
1519       
1520     ////////////////////////////////////////////////////////////////////
1521     // Bind and initialize subsystems.
1522     ////////////////////////////////////////////////////////////////////
1523
1524     globals->get_subsystem_mgr()->bind();
1525     globals->get_subsystem_mgr()->init();
1526
1527     ////////////////////////////////////////////////////////////////////////
1528     // Initialize the Nasal interpreter.
1529     // Do this last, so that the loaded scripts see initialized state
1530     ////////////////////////////////////////////////////////////////////////
1531     FGNasalSys* nasal = new FGNasalSys();
1532     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1533     nasal->init();
1534
1535     // initialize methods that depend on other subsystems.
1536     globals->get_subsystem_mgr()->postinit();
1537
1538     ////////////////////////////////////////////////////////////////////////
1539     // End of subsystem initialization.
1540     ////////////////////////////////////////////////////////////////////
1541
1542     fgSetBool("/sim/initialized", true);
1543
1544     SG_LOG( SG_GENERAL, SG_INFO, endl);
1545
1546                                 // Save the initial state for future
1547                                 // reference.
1548     globals->saveInitialState();
1549     
1550     return true;
1551 }
1552
1553 // Reset: this is what the 'reset' command (and hence, GUI) is attached to
1554 void fgReInitSubsystems()
1555 {
1556     static const SGPropertyNode *master_freeze
1557         = fgGetNode("/sim/freeze/master");
1558
1559     SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
1560
1561 // setup state to begin re-init
1562     bool freeze = master_freeze->getBoolValue();
1563     if ( !freeze ) {
1564         fgSetBool("/sim/freeze/master", true);
1565     }
1566     
1567     fgSetBool("/sim/signals/reinit", true);
1568     fgSetBool("/sim/crashed", false);
1569
1570 // do actual re-init steps
1571     globals->get_subsystem("flight")->unbind();
1572     
1573   // reset control state, before restoring initial state; -set or config files
1574   // may specify values for flaps, trim tabs, magnetos, etc
1575     globals->get_controls()->reset_all();
1576         
1577     globals->restoreInitialState();
1578
1579     // update our position based on current presets
1580     fgInitPosition();
1581     
1582     // Force reupdating the positions of the ai 3d models. They are used for
1583     // initializing ground level for the FDM.
1584     globals->get_subsystem("ai_model")->reinit();
1585
1586     // Initialize the FDM
1587     globals->get_subsystem("flight")->reinit();
1588
1589     // reset replay buffers
1590     globals->get_subsystem("replay")->reinit();
1591     
1592     // reload offsets from config defaults
1593     globals->get_viewmgr()->reinit();
1594
1595     globals->get_subsystem("time")->reinit();
1596
1597     // need to bind FDMshell again, since we manually unbound it above...
1598     globals->get_subsystem("flight")->bind();
1599
1600 // setup state to end re-init
1601     fgSetBool("/sim/signals/reinit", false);
1602     if ( !freeze ) {
1603         fgSetBool("/sim/freeze/master", false);
1604     }
1605     fgSetBool("/sim/sceneryloaded",false);
1606 }
1607
1608
1609 ///////////////////////////////////////////////////////////////////////////////
1610 // helper object to implement the --show-aircraft command.
1611 // resides here so we can share the fgFindAircraftInDir template above,
1612 // and hence ensure this command lists exectly the same aircraft as the normal
1613 // loading path.
1614 class ShowAircraft 
1615 {
1616 public:
1617   ShowAircraft()
1618   {
1619     _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
1620   }
1621   
1622   
1623   void show(const SGPath& path)
1624   {
1625     fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
1626   
1627     std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
1628     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1629     cout << "Available aircraft:" << endl;
1630     for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
1631         cout << _aircraft[i] << endl;
1632     }
1633   }
1634   
1635 private:
1636   bool processAircraft(const SGPath& path)
1637   {
1638     SGPropertyNode root;
1639     try {
1640        readProperties(path.str(), &root);
1641     } catch (sg_exception& ) {
1642        return false;
1643     }
1644   
1645     int maturity = 0;
1646     string descStr("   ");
1647     descStr += path.file();
1648   // trim common suffix from file names
1649     int nPos = descStr.rfind("-set.xml");
1650     if (nPos == (int)(descStr.size() - 8)) {
1651       descStr.resize(nPos);
1652     }
1653     
1654     SGPropertyNode *node = root.getNode("sim");
1655     if (node) {
1656       SGPropertyNode* desc = node->getNode("description");
1657       // if a status tag is found, read it in
1658       if (node->hasValue("status")) {
1659         maturity = getNumMaturity(node->getStringValue("status"));
1660       }
1661       
1662       if (desc) {
1663         if (descStr.size() <= 27+3) {
1664           descStr.append(29+3-descStr.size(), ' ');
1665         } else {
1666           descStr += '\n';
1667           descStr.append( 32, ' ');
1668         }
1669         descStr += desc->getStringValue();
1670       }
1671     } // of have 'sim' node
1672     
1673     if (maturity < _minStatus) {
1674       return false;
1675     }
1676
1677     _aircraft.push_back(descStr);
1678     return false;
1679   }
1680
1681
1682   int getNumMaturity(const char * str) 
1683   {
1684     // changes should also be reflected in $FG_ROOT/data/options.xml & 
1685     // $FG_ROOT/data/Translations/string-default.xml
1686     const char* levels[] = {"alpha","beta","early-production","production"}; 
1687
1688     if (!strcmp(str, "all")) {
1689       return 0;
1690     }
1691
1692     for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++) 
1693       if (strcmp(str,levels[i])==0)
1694         return i;
1695
1696     return 0;
1697   }
1698
1699   // recommended in Meyers, Effective STL when internationalization and embedded
1700   // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
1701   struct ciLessLibC : public std::binary_function<string, string, bool>
1702   {
1703     bool operator()(const std::string &lhs, const std::string &rhs) const
1704     {
1705       return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
1706     }
1707   };
1708
1709   int _minStatus;
1710   string_list _aircraft;
1711 };
1712
1713 void fgShowAircraft(const SGPath &path)
1714 {
1715     ShowAircraft s;
1716     s.show(path);
1717         
1718 #ifdef _MSC_VER
1719     cout << "Hit a key to continue..." << endl;
1720     cin.get();
1721 #endif
1722 }
1723
1724