]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Automake updates.
[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/interpolator.hxx>
61 #include <simgear/scene/material/matlib.hxx>
62 #include <simgear/scene/model/particles.hxx>
63 #include <simgear/sound/soundmgr_openal.hxx>
64 #include <simgear/timing/sg_time.hxx>
65 #include <simgear/timing/lowleveltime.h>
66
67 #include <Aircraft/aircraft.hxx>
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
504 static string fgFindAircraftPath( const SGPath &path, const string &aircraft,
505                                   SGPropertyNode *cache, int depth = 0 )
506 {
507     const int MAXDEPTH = 1;
508
509     ulDirEnt* dire;
510     ulDir *dirp = ulOpenDir(path.str().c_str());
511     if (dirp == NULL) {
512         cerr << "Unable to open aircraft directory '" << path.str() << '\'' << endl;
513         exit(-1);
514     }
515
516     string result;
517     while ((dire = ulReadDir(dirp)) != NULL) {
518         if (dire->d_isdir) {
519             if (depth > MAXDEPTH)
520                 continue;
521
522             if (!strcmp("CVS", dire->d_name) || !strcmp(".", dire->d_name)
523                     || !strcmp("..", dire->d_name) || !strcmp("AI", dire->d_name))
524                 continue;
525
526             SGPath next = path;
527             next.append(dire->d_name);
528
529             result = fgFindAircraftPath( next, aircraft, cache, depth + 1 );
530             if ( ! result.empty() )
531                 break;
532
533         } else {
534             int len = strlen(dire->d_name);
535             if (len < 9 || strcmp(dire->d_name + len - 8, "-set.xml"))
536                 continue;
537
538             // create cache node
539             int i = 0;
540             while (1)
541                 if (!cache->getChild("aircraft", i++, false))
542                     break;
543
544             SGPropertyNode *n, *entry = cache->getChild("aircraft", --i, true);
545
546             n = entry->getNode("file", true);
547             n->setStringValue(dire->d_name);
548             n->setAttribute(SGPropertyNode::USERARCHIVE, true);
549
550             n = entry->getNode("path", true);
551             n->setStringValue(path.str().c_str());
552             n->setAttribute(SGPropertyNode::USERARCHIVE, true);
553
554             if ( boost::equals(dire->d_name, aircraft.c_str(), is_iequal()) ) {
555                 result = path.str();
556                 break;
557             }
558         }
559     }
560
561     ulCloseDir(dirp);
562     return result;
563 }
564
565
566 // Read in configuration (file and command line)
567 bool fgInitConfig ( int argc, char **argv ) {
568
569     // First, set some sane default values
570     fgSetDefaults();
571
572     // Read global preferences from $FG_ROOT/preferences.xml
573     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
574     fgLoadProps("preferences.xml", globals->get_props());
575     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
576
577     // Detect the required language as early as possible
578     if ( !fgDetectLanguage() ) {
579         return false;
580     }
581
582     SGPropertyNode autosave;
583 #ifdef _WIN32
584     char *envp = ::getenv( "APPDATA" );
585     if (envp != NULL ) {
586         SGPath config( envp );
587         config.append( "flightgear.org" );
588 #else
589     if ( homedir != NULL ) {
590         SGPath config( homedir );
591         config.append( ".fgfs" );
592 #endif
593         const char *fg_home = getenv("FG_HOME");
594         if (fg_home)
595             config = fg_home;
596
597         SGPath home_export(config.str());
598         home_export.append("Export/dummy");
599         home_export.create_dir(0777);
600
601         // Set /sim/fg-home and don't allow malign code to override it until
602         // Nasal security is set up.  Use FG_HOME if necessary.
603         SGPropertyNode *home = fgGetNode("/sim", true);
604         home->removeChild("fg-home", 0, false);
605         home = home->getChild("fg-home", 0, true);
606         home->setStringValue(config.c_str());
607         home->setAttribute(SGPropertyNode::WRITE, false);
608
609         config.append( "autosave.xml" );
610         SG_LOG(SG_INPUT, SG_INFO, "Reading user settings from " << config.str());
611         try {
612             readProperties(config.str(), &autosave, SGPropertyNode::USERARCHIVE);
613         } catch (...) {
614             SG_LOG(SG_INPUT, SG_DEBUG, "First time reading user settings");
615         }
616         SG_LOG(SG_INPUT, SG_DEBUG, "Finished Reading user settings");
617     }
618     SGPropertyNode *cache_root = autosave.getNode("sim/startup/path-cache", true);
619
620
621     // Scan user config files and command line for a specified aircraft.
622     fgInitFGAircraft(argc, argv);
623
624     string aircraft = fgGetString( "/sim/aircraft", "" );
625     if ( aircraft.size() > 0 ) {
626         SGPath aircraft_search( globals->get_fg_root() );
627         aircraft_search.append( "Aircraft" );
628
629         string aircraft_set = aircraft + "-set.xml";
630         string result;
631
632         // check if the *-set.xml file is already in the cache
633         if (globals->get_fg_root() == cache_root->getStringValue("fg-root", "")) {
634             vector<SGPropertyNode_ptr> cache = cache_root->getChildren("aircraft");
635             for (unsigned int i = 0; i < cache.size(); i++) {
636                 const char *name = cache[i]->getStringValue("file", "");
637                 if (boost::equals(aircraft_set, name, is_iequal())) {
638                     const char *path = cache[i]->getStringValue("path", "");
639                     SGPath xml(path);
640                     xml.append(name);
641                     if (xml.exists())
642                         result = path;
643                     break;
644                 }
645             }
646         }
647
648         if (result.empty()) {
649             // prepare cache for rescan
650             SGPropertyNode *n = cache_root->getNode("fg-root", true);
651             n->setStringValue(globals->get_fg_root().c_str());
652             n->setAttribute(SGPropertyNode::USERARCHIVE, true);
653             cache_root->removeChildren("aircraft");
654
655             result = fgFindAircraftPath( aircraft_search, aircraft_set, cache_root );
656         }
657
658         if ( !result.empty() ) {
659             fgSetString( "/sim/aircraft-dir", result.c_str() );
660             SGPath full_name( result );
661             full_name.append( aircraft_set );
662
663             SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
664                    << " from " << full_name.str());
665             try {
666                 readProperties( full_name.str(), globals->get_props() );
667             } catch ( const sg_exception &e ) {
668                 string message = "Error reading default aircraft: ";
669                 message += e.getFormattedMessage();
670                 SG_LOG(SG_INPUT, SG_ALERT, message);
671                 exit(2);
672             }
673         } else {
674             SG_LOG( SG_INPUT, SG_ALERT, "Cannot find specified aircraft: "
675                     << aircraft );
676             return false;
677         }
678
679     } else {
680         SG_LOG( SG_INPUT, SG_ALERT, "No default aircraft specified" );
681     }
682
683     copyProperties(&autosave, globals->get_props());
684
685     // parse options after loading aircraft to ensure any user
686     // overrides of defaults are honored.
687     do_options(argc, argv);
688
689     return true;
690 }
691
692 // Set current tower position lon/lat given an airport id
693 static bool fgSetTowerPosFromAirportID( const string& id) {
694     const FGAirport *a = fgFindAirportID( id);
695     if (a) {
696         SGGeod tower = a->getTowerLocation();
697         fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
698         fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
699         fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
700         return true;
701     } else {
702         return false;
703     }
704
705 }
706
707 struct FGTowerLocationListener : SGPropertyChangeListener {
708     void valueChanged(SGPropertyNode* node) {
709         const string id(node->getStringValue());
710         fgSetTowerPosFromAirportID(id);
711     }
712 };
713
714 void fgInitTowerLocationListener() {
715     fgGetNode("/sim/tower/airport-id",  true)
716         ->addChangeListener( new FGTowerLocationListener(), true );
717 }
718
719 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
720 {
721   SGGeod startPos(aStartPos);
722   if (aTargetHeading == HUGE_VAL) {
723     aTargetHeading = aHeading;
724   }
725   
726   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
727     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
728     offsetDistance *= SG_NM_TO_METER;
729     double offsetAzimuth = aHeading;
730     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
731       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
732       aHeading = aTargetHeading;
733     }
734
735     SGGeod offset;
736     double az2; // dummy
737     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
738     startPos = offset;
739   }
740
741   // presets
742   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
743   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
744   fgSetDouble("/sim/presets/heading-deg", aHeading );
745
746   // other code depends on the actual values being set ...
747   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
748   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
749   fgSetDouble("/orientation/heading-deg", aHeading );
750 }
751
752 // Set current_options lon/lat given an airport id and heading (degrees)
753 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
754     if ( id.empty() )
755         return false;
756
757     // set initial position from runway and heading
758     SG_LOG( SG_GENERAL, SG_INFO,
759             "Attempting to set starting position from airport code "
760             << id << " heading " << tgt_hdg );
761
762     const FGAirport* apt = fgFindAirportID(id);
763     if (!apt) return false;
764     FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
765     fgSetString("/sim/atc/runway", r->ident().c_str());
766
767     SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
768           fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
769     return true;
770 }
771
772 // Set current_options lon/lat given an airport id and parkig position name
773 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos ) {
774     if ( id.empty() )
775         return false;
776
777     // can't see an easy way around this const_cast at the moment
778     FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
779     if (!apt) {
780         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
781         return false;
782     }
783     FGAirportDynamics* dcs = apt->getDynamics();
784     if (!dcs) {
785         SG_LOG( SG_GENERAL, SG_ALERT,
786                 "Failed to find parking position " << parkpos <<
787                 " at airport " << id );
788         return false;
789     }
790     
791     int park_index = dcs->getNrOfParkings() - 1;
792     while (park_index >= 0 && dcs->getParkingName(park_index) != parkpos) park_index--;
793     if (park_index < 0) {
794         SG_LOG( SG_GENERAL, SG_ALERT,
795                 "Failed to find parking position " << parkpos <<
796                 " at airport " << id );
797         return false;
798     }
799     FGParking* parking = dcs->getParking(park_index);
800     parking->setAvailable(false);
801     fgApplyStartOffset(
802       SGGeod::fromDeg(parking->getLongitude(), parking->getLatitude()),
803       parking->getHeading());
804     return true;
805 }
806
807
808 // Set current_options lon/lat given an airport id and runway number
809 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
810     if ( id.empty() )
811         return false;
812
813     // set initial position from airport and runway number
814     SG_LOG( SG_GENERAL, SG_INFO,
815             "Attempting to set starting position for "
816             << id << ":" << rwy );
817
818     const FGAirport* apt = fgFindAirportID(id);
819     if (!apt) {
820       SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
821       return false;
822     }
823     
824     if (!apt->hasRunwayWithIdent(rwy)) {
825       SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
826                 "Failed to find runway " << rwy <<
827                 " at airport " << id << ". Using default runway." );
828       return false;
829     }
830     
831     FGRunway* r(apt->getRunwayByIdent(rwy));
832     fgSetString("/sim/atc/runway", r->ident().c_str());
833     SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
834           fgApplyStartOffset(startPos, r->headingDeg());
835     return true;
836 }
837
838
839 static void fgSetDistOrAltFromGlideSlope() {
840     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
841     string apt_id = fgGetString("/sim/presets/airport-id");
842     double gs = fgGetDouble("/sim/presets/glideslope-deg")
843         * SG_DEGREES_TO_RADIANS ;
844     double od = fgGetDouble("/sim/presets/offset-distance-nm");
845     double alt = fgGetDouble("/sim/presets/altitude-ft");
846
847     double apt_elev = 0.0;
848     if ( ! apt_id.empty() ) {
849         apt_elev = fgGetAirportElev( apt_id );
850         if ( apt_elev < -9990.0 ) {
851             apt_elev = 0.0;
852         }
853     } else {
854         apt_elev = 0.0;
855     }
856
857     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
858         // set altitude from glideslope and offset-distance
859         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
860         alt = fabs(od*tan(gs)) + apt_elev;
861         fgSetDouble("/sim/presets/altitude-ft", alt);
862         fgSetBool("/sim/presets/onground", false);
863         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
864                 << alt  << " ft" );
865     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
866         // set offset-distance from glideslope and altitude
867         od  = (alt - apt_elev) / tan(gs);
868         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
869         fgSetDouble("/sim/presets/offset-distance-nm", od);
870         fgSetBool("/sim/presets/onground", false);
871         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
872                 << od  << " nm" );
873     } else if( fabs(gs) > 0.01 ) {
874         SG_LOG( SG_GENERAL, SG_ALERT,
875                 "Glideslope given but not altitude or offset-distance." );
876         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
877         fgSetDouble("/sim/presets/glideslope-deg", 0);
878         fgSetBool("/sim/presets/onground", true);
879     }
880 }
881
882
883 // Set current_options lon/lat given an airport id and heading (degrees)
884 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
885     FGNavRecord *nav
886         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
887
888   if (!nav) {
889     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
890                 << id << ":" << freq );
891     return false;
892   }
893   
894   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
895   return true;
896 }
897
898 // Set current_options lon/lat given an aircraft carrier id
899 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
900
901     // set initial position from runway and heading
902     SGGeod geodPos;
903     double heading;
904     SGVec3d uvw;
905     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
906         double lon = geodPos.getLongitudeDeg();
907         double lat = geodPos.getLatitudeDeg();
908         double alt = geodPos.getElevationFt();
909
910         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
911                 << carrier << " at lat = " << lat << ", lon = " << lon
912                 << ", alt = " << alt << ", heading = " << heading);
913
914         fgSetDouble("/sim/presets/longitude-deg",  lon);
915         fgSetDouble("/sim/presets/latitude-deg",  lat);
916         fgSetDouble("/sim/presets/altitude-ft", alt);
917         fgSetDouble("/sim/presets/heading-deg", heading);
918         fgSetDouble("/position/longitude-deg",  lon);
919         fgSetDouble("/position/latitude-deg",  lat);
920         fgSetDouble("/position/altitude-ft", alt);
921         fgSetDouble("/orientation/heading-deg", heading);
922
923         fgSetString("/sim/presets/speed-set", "UVW");
924         fgSetDouble("/velocities/uBody-fps", uvw(0));
925         fgSetDouble("/velocities/vBody-fps", uvw(1));
926         fgSetDouble("/velocities/wBody-fps", uvw(2));
927         fgSetDouble("/sim/presets/uBody-fps", uvw(0));
928         fgSetDouble("/sim/presets/vBody-fps", uvw(1));
929         fgSetDouble("/sim/presets/wBody-fps", uvw(2));
930
931         fgSetBool("/sim/presets/onground", true);
932
933         return true;
934     } else {
935         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
936                 << carrier );
937         return false;
938     }
939 }
940  
941 // Set current_options lon/lat given an airport id and heading (degrees)
942 static bool fgSetPosFromFix( const string& id )
943 {
944   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
945   FGPositioned* fix = FGPositioned::findNextWithPartialId(NULL, id, &fixFilter);
946   if (!fix) {
947     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
948     return false;
949   }
950   
951   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
952   return true;
953 }
954
955 /**
956  * Initialize vor/ndb/ils/fix list management and query systems (as
957  * well as simple airport db list)
958  */
959 bool
960 fgInitNav ()
961 {
962     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
963
964     SGPath aptdb( globals->get_fg_root() );
965     aptdb.append( "Airports/apt.dat" );
966
967     SGPath p_metar( globals->get_fg_root() );
968     p_metar.append( "Airports/metar.dat" );
969
970 // Initialise the frequency search map BEFORE reading
971 // the airport database:
972
973
974
975     current_commlist = new FGCommList;
976     current_commlist->init( globals->get_fg_root() );
977     fgAirportDBLoad( aptdb.str(), current_commlist, p_metar.str() );
978
979     FGNavList *navlist = new FGNavList;
980     FGNavList *loclist = new FGNavList;
981     FGNavList *gslist = new FGNavList;
982     FGNavList *dmelist = new FGNavList;
983     FGNavList *tacanlist = new FGNavList;
984     FGNavList *carrierlist = new FGNavList;
985     FGTACANList *channellist = new FGTACANList;
986
987     globals->set_navlist( navlist );
988     globals->set_loclist( loclist );
989     globals->set_gslist( gslist );
990     globals->set_dmelist( dmelist );
991     globals->set_tacanlist( tacanlist );
992     globals->set_carrierlist( carrierlist );
993     globals->set_channellist( channellist );
994
995     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, tacanlist, carrierlist, channellist) ) {
996         SG_LOG( SG_GENERAL, SG_ALERT,
997                 "Problems loading one or more navigational database" );
998     }
999     
1000     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1001     SGPath p_fix( globals->get_fg_root() );
1002     p_fix.append( "Navaids/fix.dat" );
1003     FGFixList fixlist;
1004     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
1005
1006     SG_LOG(SG_GENERAL, SG_INFO, "  Airways");
1007     SGPath p_awy( globals->get_fg_root() );
1008     p_awy.append( "Navaids/awy.dat" );
1009     FGAirwayNetwork *awyNet = new FGAirwayNetwork;
1010     //cerr << "Loading Airways" << endl;
1011     awyNet->load (p_awy );
1012     awyNet->init();
1013     //cerr << "initializing airways" << endl;
1014     globals->set_airwaynet( awyNet );
1015
1016     return true;
1017 }
1018
1019
1020 // Set the initial position based on presets (or defaults)
1021 bool fgInitPosition() {
1022     // cout << "fgInitPosition()" << endl;
1023     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1024         * SG_DEGREES_TO_RADIANS ;
1025     double od = fgGetDouble("/sim/presets/offset-distance-nm");
1026     double alt = fgGetDouble("/sim/presets/altitude-ft");
1027
1028     bool set_pos = false;
1029
1030     // If glideslope is specified, then calculate offset-distance or
1031     // altitude relative to glide slope if either of those was not
1032     // specified.
1033     if ( fabs( gs ) > 0.01 ) {
1034         fgSetDistOrAltFromGlideSlope();
1035     }
1036
1037
1038     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1039     // If not, check for an airport-id and use that.
1040     // If not, default to the middle of the KSFO field.
1041     // The default values for lon/lat are deliberately out of range
1042     // so that the airport-id can take effect; valid lon/lat will
1043     // override airport-id, however.
1044     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1045     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1046     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1047          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1048     {
1049         set_pos = true;
1050     }
1051
1052     string apt = fgGetString("/sim/presets/airport-id");
1053     string rwy_no = fgGetString("/sim/presets/runway");
1054     bool rwy_req = fgGetBool("/sim/presets/runway-requested");
1055     string vor = fgGetString("/sim/presets/vor-id");
1056     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1057     string ndb = fgGetString("/sim/presets/ndb-id");
1058     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1059     string carrier = fgGetString("/sim/presets/carrier");
1060     string parkpos = fgGetString("/sim/presets/parkpos");
1061     string fix = fgGetString("/sim/presets/fix");
1062     SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
1063     double hdg = hdg_preset->getDoubleValue();
1064
1065     // save some start parameters, so that we can later say what the
1066     // user really requested. TODO generalize that and move it to options.cxx
1067     static bool start_options_saved = false;
1068     if (!start_options_saved) {
1069         start_options_saved = true;
1070         SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
1071
1072         opt->setDoubleValue("latitude-deg", lat_deg);
1073         opt->setDoubleValue("longitude-deg", lon_deg);
1074         opt->setDoubleValue("heading-deg", hdg);
1075         opt->setStringValue("airport", apt.c_str());
1076         opt->setStringValue("runway", rwy_no.c_str());
1077     }
1078
1079     if (hdg > 9990.0)
1080         hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
1081
1082     if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
1083         // An airport + parking position is requested
1084         if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
1085             // set tower position
1086             fgSetString("/sim/tower/airport-id",  apt.c_str());
1087             set_pos = true;
1088         }
1089     }
1090
1091     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1092         // An airport + runway is requested
1093         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
1094             // set tower position (a little off the heading for single
1095             // runway airports)
1096             fgSetString("/sim/tower/airport-id",  apt.c_str());
1097             set_pos = true;
1098         }
1099     }
1100
1101     if ( !set_pos && !apt.empty() ) {
1102         // An airport is requested (find runway closest to hdg)
1103         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1104             // set tower position (a little off the heading for single
1105             // runway airports)
1106             fgSetString("/sim/tower/airport-id",  apt.c_str());
1107             set_pos = true;
1108         }
1109     }
1110
1111     if (hdg_preset->getDoubleValue() > 9990.0)
1112         hdg_preset->setDoubleValue(hdg);
1113
1114     if ( !set_pos && !vor.empty() ) {
1115         // a VOR is requested
1116         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1117             set_pos = true;
1118         }
1119     }
1120
1121     if ( !set_pos && !ndb.empty() ) {
1122         // an NDB is requested
1123         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1124             set_pos = true;
1125         }
1126     }
1127
1128     if ( !set_pos && !carrier.empty() ) {
1129         // an aircraft carrier is requested
1130         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1131             set_pos = true;
1132         }
1133     }
1134
1135     if ( !set_pos && !fix.empty() ) {
1136         // a Fix is requested
1137         if ( fgSetPosFromFix( fix ) ) {
1138             set_pos = true;
1139         }
1140     }
1141
1142     if ( !set_pos ) {
1143         // No lon/lat specified, no airport specified, default to
1144         // middle of KSFO field.
1145         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1146         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1147     }
1148
1149     fgSetDouble( "/position/longitude-deg",
1150                  fgGetDouble("/sim/presets/longitude-deg") );
1151     fgSetDouble( "/position/latitude-deg",
1152                  fgGetDouble("/sim/presets/latitude-deg") );
1153     fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
1154
1155     // determine if this should be an on-ground or in-air start
1156     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1157         fgSetBool("/sim/presets/onground", false);
1158     } else {
1159         fgSetBool("/sim/presets/onground", true);
1160     }
1161
1162     return true;
1163 }
1164
1165
1166 // General house keeping initializations
1167 bool fgInitGeneral() {
1168     string root;
1169
1170     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1171     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1172
1173     root = globals->get_fg_root();
1174     if ( ! root.length() ) {
1175         // No root path set? Then bail ...
1176         SG_LOG( SG_GENERAL, SG_ALERT,
1177                 "Cannot continue without a path to the base package "
1178                 << "being defined." );
1179         exit(-1);
1180     }
1181     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1182
1183     globals->set_browser(fgGetString("/sim/startup/browser-app", "firefox %u"));
1184
1185     char buf[512], *cwd = getcwd(buf, 511);
1186     buf[511] = '\0';
1187     SGPropertyNode *curr = fgGetNode("/sim", true);
1188     curr->removeChild("fg-current", 0, false);
1189     curr = curr->getChild("fg-current", 0, true);
1190     curr->setStringValue(cwd ? cwd : "");
1191     curr->setAttribute(SGPropertyNode::WRITE, false);
1192
1193     fgSetBool("/sim/startup/stdout-to-terminal", isatty(1));
1194     fgSetBool("/sim/startup/stderr-to-terminal", isatty(2));
1195     return true;
1196 }
1197
1198 // Initialize view parameters
1199 void fgInitView() {
1200   // force update of model so that viewer can get some data...
1201   globals->get_aircraft_model()->update(0);
1202   // run update for current view so that data is current...
1203   globals->get_viewmgr()->update(0);
1204 }
1205
1206
1207 SGTime *fgInitTime() {
1208     // Initialize time
1209     static const SGPropertyNode *longitude
1210         = fgGetNode("/position/longitude-deg");
1211     static const SGPropertyNode *latitude
1212         = fgGetNode("/position/latitude-deg");
1213     static const SGPropertyNode *cur_time_override
1214         = fgGetNode("/sim/time/cur-time-override", true);
1215
1216     SGPath zone( globals->get_fg_root() );
1217     zone.append( "Timezone" );
1218     SGTime *t = new SGTime( longitude->getDoubleValue()
1219                               * SGD_DEGREES_TO_RADIANS,
1220                             latitude->getDoubleValue()
1221                               * SGD_DEGREES_TO_RADIANS,
1222                             zone.str(),
1223                             cur_time_override->getLongValue() );
1224
1225     globals->set_warp_delta( 0 );
1226
1227     t->update( 0.0, 0.0,
1228                cur_time_override->getLongValue(),
1229                globals->get_warp() );
1230
1231     return t;
1232 }
1233
1234
1235 // set up a time offset (aka warp) if one is specified
1236 void fgInitTimeOffset() {
1237     static const SGPropertyNode *longitude
1238         = fgGetNode("/position/longitude-deg");
1239     static const SGPropertyNode *latitude
1240         = fgGetNode("/position/latitude-deg");
1241     static const SGPropertyNode *cur_time_override
1242         = fgGetNode("/sim/time/cur-time-override", true);
1243
1244     // Handle potential user specified time offsets
1245     int orig_warp = globals->get_warp();
1246     SGTime *t = globals->get_time_params();
1247     time_t cur_time = t->get_cur_time();
1248     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1249     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1250     time_t aircraftLocalTime = 
1251         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1252     
1253     // Okay, we now have several possible scenarios
1254     int offset = fgGetInt("/sim/startup/time-offset");
1255     string offset_type = fgGetString("/sim/startup/time-offset-type");
1256
1257     int warp = 0;
1258     if ( offset_type == "real" ) {
1259         warp = 0;
1260     } else if ( offset_type == "dawn" ) {
1261         warp = fgTimeSecondsUntilSunAngle( cur_time,
1262                                            longitude->getDoubleValue()
1263                                              * SGD_DEGREES_TO_RADIANS,
1264                                            latitude->getDoubleValue()
1265                                              * SGD_DEGREES_TO_RADIANS,
1266                                            90.0, true ); 
1267     } else if ( offset_type == "morning" ) {
1268         warp = fgTimeSecondsUntilSunAngle( cur_time,
1269                                            longitude->getDoubleValue()
1270                                              * SGD_DEGREES_TO_RADIANS,
1271                                            latitude->getDoubleValue()
1272                                              * SGD_DEGREES_TO_RADIANS,
1273                                            75.0, true ); 
1274     } else if ( offset_type == "noon" ) {
1275         warp = fgTimeSecondsUntilSunAngle( cur_time,
1276                                            longitude->getDoubleValue()
1277                                              * SGD_DEGREES_TO_RADIANS,
1278                                            latitude->getDoubleValue()
1279                                              * SGD_DEGREES_TO_RADIANS,
1280                                            0.0, true ); 
1281     } else if ( offset_type == "afternoon" ) {
1282         warp = fgTimeSecondsUntilSunAngle( cur_time,
1283                                            longitude->getDoubleValue()
1284                                              * SGD_DEGREES_TO_RADIANS,
1285                                            latitude->getDoubleValue()
1286                                              * SGD_DEGREES_TO_RADIANS,
1287                                            60.0, false ); 
1288      } else if ( offset_type == "dusk" ) {
1289         warp = fgTimeSecondsUntilSunAngle( cur_time,
1290                                            longitude->getDoubleValue()
1291                                              * SGD_DEGREES_TO_RADIANS,
1292                                            latitude->getDoubleValue()
1293                                              * SGD_DEGREES_TO_RADIANS,
1294                                            90.0, false ); 
1295      } else if ( offset_type == "evening" ) {
1296         warp = fgTimeSecondsUntilSunAngle( cur_time,
1297                                            longitude->getDoubleValue()
1298                                              * SGD_DEGREES_TO_RADIANS,
1299                                            latitude->getDoubleValue()
1300                                              * SGD_DEGREES_TO_RADIANS,
1301                                            100.0, false ); 
1302     } else if ( offset_type == "midnight" ) {
1303         warp = fgTimeSecondsUntilSunAngle( cur_time,
1304                                            longitude->getDoubleValue()
1305                                              * SGD_DEGREES_TO_RADIANS,
1306                                            latitude->getDoubleValue()
1307                                              * SGD_DEGREES_TO_RADIANS,
1308                                            180.0, false ); 
1309     } else if ( offset_type == "system-offset" ) {
1310         warp = offset;
1311         orig_warp = 0;
1312     } else if ( offset_type == "gmt-offset" ) {
1313         warp = offset - (currGMT - systemLocalTime);
1314         orig_warp = 0;
1315     } else if ( offset_type == "latitude-offset" ) {
1316         warp = offset - (aircraftLocalTime - systemLocalTime);
1317         orig_warp = 0;
1318     } else if ( offset_type == "system" ) {
1319       warp = offset - (systemLocalTime - currGMT) - cur_time;
1320     } else if ( offset_type == "gmt" ) {
1321         warp = offset - cur_time;
1322     } else if ( offset_type == "latitude" ) {
1323         warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
1324     } else {
1325         SG_LOG( SG_GENERAL, SG_ALERT,
1326                 "FG_TIME::Unsupported offset type " << offset_type );
1327         exit( -1 );
1328     }
1329     globals->set_warp( orig_warp + warp );
1330     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1331                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1332                cur_time_override->getLongValue(),
1333                globals->get_warp() );
1334
1335     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1336             << globals->get_warp() );
1337 }
1338
1339
1340 // This is the top level init routine which calls all the other
1341 // initialization routines.  If you are adding a subsystem to flight
1342 // gear, its initialization call should located in this routine.
1343 // Returns non-zero if a problem encountered.
1344 bool fgInitSubsystems() {
1345     // static const SGPropertyNode *longitude
1346     //     = fgGetNode("/sim/presets/longitude-deg");
1347     // static const SGPropertyNode *latitude
1348     //     = fgGetNode("/sim/presets/latitude-deg");
1349     // static const SGPropertyNode *altitude
1350     //     = fgGetNode("/sim/presets/altitude-ft");
1351
1352     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1353     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1354
1355     ////////////////////////////////////////////////////////////////////
1356     // Initialize the event manager subsystem.
1357     ////////////////////////////////////////////////////////////////////
1358
1359     globals->get_event_mgr()->init();
1360     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1361
1362     ////////////////////////////////////////////////////////////////////
1363     // Initialize the property interpolator subsystem. Put into the INIT
1364     // group because the "nasal" subsystem may need it at GENERAL take-down.
1365     ////////////////////////////////////////////////////////////////////
1366     globals->add_subsystem("interpolator", new SGInterpolator, SGSubsystemMgr::INIT);
1367
1368
1369     ////////////////////////////////////////////////////////////////////
1370     // Add the FlightGear property utilities.
1371     ////////////////////////////////////////////////////////////////////
1372     globals->add_subsystem("properties", new FGProperties);
1373
1374     ////////////////////////////////////////////////////////////////////
1375     // Initialize the material property subsystem.
1376     ////////////////////////////////////////////////////////////////////
1377
1378     SGPath mpath( globals->get_fg_root() );
1379     mpath.append( "materials.xml" );
1380     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1381             globals->get_props()) ) {
1382         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1383         exit(-1);
1384     }
1385
1386
1387     ////////////////////////////////////////////////////////////////////
1388     // Initialize the scenery management subsystem.
1389     ////////////////////////////////////////////////////////////////////
1390
1391     if ( globals->get_tile_mgr()->init() ) {
1392         // Load the local scenery data
1393         double visibility_meters = fgGetDouble("/environment/visibility-m");
1394                 
1395         globals->get_tile_mgr()->update( visibility_meters );
1396     } else {
1397         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1398         exit(-1);
1399     }
1400
1401     globals->get_scenery()->get_scene_graph()
1402         ->addChild(simgear::Particles::getCommonRoot());
1403     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1404
1405     ////////////////////////////////////////////////////////////////////
1406     // Initialize the flight model subsystem.
1407     ////////////////////////////////////////////////////////////////////
1408
1409     globals->add_subsystem("flight", new FDMShell, SGSubsystemMgr::FDM);
1410         
1411     // allocates structures so must happen before any of the flight
1412     // model or control parameters are set
1413     fgAircraftInit();   // In the future this might not be the case.
1414
1415
1416     ////////////////////////////////////////////////////////////////////
1417     // Initialize the weather subsystem.
1418     ////////////////////////////////////////////////////////////////////
1419
1420     // Initialize the weather modeling subsystem
1421     globals->add_subsystem("environment", new FGEnvironmentMgr);
1422
1423     ////////////////////////////////////////////////////////////////////
1424     // Initialize the ridge lift simulation.
1425     ////////////////////////////////////////////////////////////////////
1426
1427     // Initialize the ridgelift subsystem
1428     globals->add_subsystem("ridgelift", new FGRidgeLift);
1429
1430     ////////////////////////////////////////////////////////////////////
1431     // Initialize the aircraft systems and instrumentation (before the
1432     // autopilot.)
1433     ////////////////////////////////////////////////////////////////////
1434
1435     globals->add_subsystem("instrumentation", new FGInstrumentMgr, SGSubsystemMgr::FDM);
1436     globals->add_subsystem("systems", new FGSystemMgr, SGSubsystemMgr::FDM);
1437
1438     ////////////////////////////////////////////////////////////////////
1439     // Initialize the XML Autopilot subsystem.
1440     ////////////////////////////////////////////////////////////////////
1441
1442     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilotGroup, SGSubsystemMgr::FDM );
1443     globals->add_subsystem( "route-manager", new FGRouteMgr );
1444     
1445     ////////////////////////////////////////////////////////////////////
1446     // Initialize the view manager subsystem.
1447     ////////////////////////////////////////////////////////////////////
1448
1449     fgInitView();
1450
1451     ////////////////////////////////////////////////////////////////////
1452     // Initialize the Input-Output subsystem
1453     ////////////////////////////////////////////////////////////////////
1454     globals->add_subsystem( "io", new FGIO );
1455
1456     ////////////////////////////////////////////////////////////////////
1457     // Create and register the logger.
1458     ////////////////////////////////////////////////////////////////////
1459     
1460     globals->add_subsystem("logger", new FGLogger);
1461
1462     ////////////////////////////////////////////////////////////////////
1463     // Create and register the XML GUI.
1464     ////////////////////////////////////////////////////////////////////
1465
1466     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1467
1468
1469     ////////////////////////////////////////////////////////////////////
1470     // Initialize the local time subsystem.
1471     ////////////////////////////////////////////////////////////////////
1472
1473     // update the current timezone each 30 minutes
1474     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1475                                        &fgUpdateLocalTime, 30*60 );
1476     fgInitTimeOffset();         // the environment subsystem needs this
1477
1478
1479     ////////////////////////////////////////////////////////////////////
1480     // Initialize the lighting subsystem.
1481     ////////////////////////////////////////////////////////////////////
1482
1483     globals->add_subsystem("lighting", new FGLight);
1484
1485     //////////////////////////////////////////////////////////////////////
1486     // Initialize the 2D cloud subsystem.
1487     ////////////////////////////////////////////////////////////////////
1488     fgGetBool("/sim/rendering/bump-mapping", false);
1489
1490 #ifdef ENABLE_AUDIO_SUPPORT
1491     ////////////////////////////////////////////////////////////////////
1492     // Initialize the sound-effects subsystem.
1493     ////////////////////////////////////////////////////////////////////
1494     globals->add_subsystem("voice", new FGVoiceMgr);
1495 #endif
1496
1497     ////////////////////////////////////////////////////////////////////
1498     // Initialise the ATC Manager 
1499     ////////////////////////////////////////////////////////////////////
1500
1501 #if ENABLE_ATCDCL
1502     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1503     globals->set_ATC_mgr(new FGATCMgr);
1504     globals->get_ATC_mgr()->init(); 
1505
1506     ////////////////////////////////////////////////////////////////////
1507     // Initialise the AI Manager 
1508     ////////////////////////////////////////////////////////////////////
1509
1510     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1511     globals->set_AI_mgr(new FGAIMgr);
1512     globals->get_AI_mgr()->init();
1513 #endif
1514     ////////////////////////////////////////////////////////////////////
1515     // Initialise the AI Model Manager
1516     ////////////////////////////////////////////////////////////////////
1517     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1518     globals->add_subsystem("ai_model", new FGAIManager);
1519     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1520
1521
1522     // It's probably a good idea to initialize the top level traffic manager
1523     // After the AI and ATC systems have been initialized properly.
1524     // AI Traffic manager
1525     globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1526
1527
1528     ////////////////////////////////////////////////////////////////////
1529     // Initialize the cockpit subsystem
1530     ////////////////////////////////////////////////////////////////////
1531     if( fgCockpitInit( &current_aircraft )) {
1532         // Cockpit initialized ok.
1533     } else {
1534         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1535         exit(-1);
1536     }
1537
1538
1539     ////////////////////////////////////////////////////////////////////
1540     // Add a new 2D panel.
1541     ////////////////////////////////////////////////////////////////////
1542
1543     string panel_path = fgGetString("/sim/panel/path",
1544                                     "Panels/Default/default.xml");
1545
1546     globals->set_current_panel( fgReadPanel(panel_path) );
1547     if (globals->get_current_panel() == 0) {
1548         SG_LOG( SG_INPUT, SG_ALERT,
1549                 "Error reading new panel from " << panel_path );
1550     } else {
1551         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1552         globals->get_current_panel()->init();
1553         globals->get_current_panel()->bind();
1554     }
1555
1556
1557     ////////////////////////////////////////////////////////////////////
1558     // Initialize the controls subsystem.
1559     ////////////////////////////////////////////////////////////////////
1560
1561     globals->get_controls()->init();
1562     globals->get_controls()->bind();
1563
1564
1565     ////////////////////////////////////////////////////////////////////
1566     // Initialize the input subsystem.
1567     ////////////////////////////////////////////////////////////////////
1568
1569     globals->add_subsystem("input", new FGInput);
1570
1571
1572     ////////////////////////////////////////////////////////////////////
1573     // Initialize the replay subsystem
1574     ////////////////////////////////////////////////////////////////////
1575     globals->add_subsystem("replay", new FGReplay);
1576
1577
1578     ////////////////////////////////////////////////////////////////////
1579     // Bind and initialize subsystems.
1580     ////////////////////////////////////////////////////////////////////
1581
1582     globals->get_subsystem_mgr()->bind();
1583     globals->get_subsystem_mgr()->init();
1584
1585     ////////////////////////////////////////////////////////////////////
1586     // Initialize multiplayer subsystem
1587     ////////////////////////////////////////////////////////////////////
1588
1589     globals->set_multiplayer_mgr(new FGMultiplayMgr);
1590     globals->get_multiplayer_mgr()->init();
1591
1592     ////////////////////////////////////////////////////////////////////////
1593     // Initialize the Nasal interpreter.
1594     // Do this last, so that the loaded scripts see initialized state
1595     ////////////////////////////////////////////////////////////////////////
1596     FGNasalSys* nasal = new FGNasalSys();
1597     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1598     nasal->init();
1599
1600     // initialize methods that depend on other subsystems.
1601     globals->get_subsystem_mgr()->postinit();
1602
1603     ////////////////////////////////////////////////////////////////////////
1604     // End of subsystem initialization.
1605     ////////////////////////////////////////////////////////////////////
1606
1607     SG_LOG( SG_GENERAL, SG_INFO, endl);
1608
1609                                 // Save the initial state for future
1610                                 // reference.
1611     globals->saveInitialState();
1612     
1613     return true;
1614 }
1615
1616
1617 void fgReInitSubsystems()
1618 {
1619     // static const SGPropertyNode *longitude
1620     //     = fgGetNode("/sim/presets/longitude-deg");
1621     // static const SGPropertyNode *latitude
1622     //     = fgGetNode("/sim/presets/latitude-deg");
1623     static const SGPropertyNode *altitude
1624         = fgGetNode("/sim/presets/altitude-ft");
1625     static const SGPropertyNode *master_freeze
1626         = fgGetNode("/sim/freeze/master");
1627
1628     SG_LOG( SG_GENERAL, SG_INFO,
1629             "fgReInitSubsystems(): /position/altitude = "
1630             << altitude->getDoubleValue() );
1631
1632     bool freeze = master_freeze->getBoolValue();
1633     if ( !freeze ) {
1634         fgSetBool("/sim/freeze/master", true);
1635     }
1636     fgSetBool("/sim/crashed", false);
1637
1638     // Force reupdating the positions of the ai 3d models. They are used for
1639     // initializing ground level for the FDM.
1640     globals->get_subsystem("ai_model")->reinit();
1641
1642     // Initialize the FDM
1643     globals->get_subsystem("flight")->reinit();
1644     
1645     // allocates structures so must happen before any of the flight
1646     // model or control parameters are set
1647     fgAircraftInit();   // In the future this might not be the case.
1648
1649     // reload offsets from config defaults
1650     globals->get_viewmgr()->reinit();
1651
1652     fgInitView();
1653
1654     globals->get_controls()->reset_all();
1655
1656     fgUpdateLocalTime();
1657
1658     // re-init to proper time of day setting
1659     fgInitTimeOffset();
1660
1661     if ( !freeze ) {
1662         fgSetBool("/sim/freeze/master", false);
1663     }
1664     fgSetBool("/sim/sceneryloaded",false);
1665 }
1666
1667
1668 void reInit(void)  // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1669 {
1670     static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1671
1672     bool freeze = master_freeze->getBoolValue();
1673     if (!freeze)
1674         master_freeze->setBoolValue(true);
1675
1676     fgSetBool("/sim/signals/reinit", true);
1677
1678     globals->get_subsystem("flight")->unbind();
1679
1680     // in case user has changed window size as
1681     // restoreInitialState() overwrites these
1682     int xsize = fgGetInt("/sim/startup/xsize");
1683     int ysize = fgGetInt("/sim/startup/ysize");
1684
1685     // viewports also needs to be saved/restored as
1686     // restoreInitialState() overwrites these
1687     SGPropertyNode *guiNode = new SGPropertyNode;
1688     SGPropertyNode *cameraNode = new SGPropertyNode;
1689     SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1690     copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1691     copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1692
1693     globals->restoreInitialState();
1694
1695     // update our position based on current presets
1696     fgInitPosition();
1697
1698     // We don't know how to resize the window, so keep the last values
1699     //  for xsize and ysize, and don't use the one set initially
1700     fgSetInt("/sim/startup/xsize", xsize);
1701     fgSetInt("/sim/startup/ysize", ysize);
1702
1703     copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1704     copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1705
1706     delete guiNode;
1707     delete cameraNode;
1708
1709     SGTime *t = globals->get_time_params();
1710     delete t;
1711     t = fgInitTime();
1712     globals->set_time_params(t);
1713
1714     fgReInitSubsystems();
1715
1716     globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1717     globals->get_renderer()->resize(xsize, ysize);
1718     fgSetBool("/sim/signals/reinit", false);
1719
1720     if (!freeze)
1721         master_freeze->setBoolValue(false);
1722 }
1723