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