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