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