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