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