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