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