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