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