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