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