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