]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
847fcf9d5f896745deba526bcc6fcbee98064610
[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  - curt@infoplane.com
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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 // For BC 5.01 this must be included before OpenGL includes.
30 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #ifdef HAVE_WINDOWS_H
35 #  include <windows.h>
36 #endif
37
38 #include GLUT_H
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>             // strcmp()
43
44
45 #if defined( unix ) || defined( __CYGWIN__ )
46 #  include <unistd.h>           // for gethostname()
47 #endif
48
49 // work around a stdc++ lib bug in some versions of linux, but doesn't
50 // seem to hurt to have this here for all versions of Linux.
51 #ifdef linux
52 #  define _G_NO_EXTERN_TEMPLATES
53 #endif
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/exception.hxx>
57
58 #include STL_STRING
59
60 #include <simgear/constants.h>
61 #include <simgear/debug/logstream.hxx>
62 #include <simgear/math/point3d.hxx>
63 #include <simgear/math/polar3d.hxx>
64 #include <simgear/math/sg_geodesy.hxx>
65 #include <simgear/misc/sg_path.hxx>
66 #ifdef FG_USE_CLOUDS_3D
67 #  include <simgear/sky/clouds3d/SkySceneLoader.hpp>
68 #  include <simgear/sky/clouds3d/SkyUtil.hpp>
69 #endif
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
72
73 #include <Aircraft/aircraft.hxx>
74 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
75 #include <Airports/runways.hxx>
76 #include <Airports/simple.hxx>
77 #include <ATC/ATCdisplay.hxx>
78 #include <ATC/ATCmgr.hxx>
79 #include <ATC/AIMgr.hxx>
80 #include <Autopilot/auto_gui.hxx>
81 #include <Autopilot/newauto.hxx>
82 #include <Cockpit/cockpit.hxx>
83 #include <Cockpit/radiostack.hxx>
84 #include <Cockpit/panel.hxx>
85 #include <Cockpit/panel_io.hxx>
86 #include <FDM/ADA.hxx>
87 #include <FDM/Balloon.h>
88 #include <FDM/ExternalNet/ExternalNet.hxx>
89 #include <FDM/ExternalPipe/ExternalPipe.hxx>
90 #include <FDM/JSBSim/JSBSim.hxx>
91 #include <FDM/LaRCsim.hxx>
92 #include <FDM/MagicCarpet.hxx>
93 #include <FDM/UFO.hxx>
94 #include <FDM/NullFDM.hxx>
95 #include <FDM/YASim/YASim.hxx>
96 #include <GUI/new_gui.hxx>
97 #include <Include/general.hxx>
98 #include <Input/input.hxx>
99 #include <Instrumentation/instrument_mgr.hxx>
100 // #include <Joystick/joystick.hxx>
101 #include <Objects/matlib.hxx>
102 #include <Model/acmodel.hxx>
103 #include <Navaids/fixlist.hxx>
104 #include <Navaids/ilslist.hxx>
105 #include <Navaids/mkrbeacons.hxx>
106 #include <Navaids/navlist.hxx>
107 #include <Scenery/scenery.hxx>
108 #include <Scenery/tilemgr.hxx>
109 #if defined(HAVE_PLIB_PSL)
110 #include <Scripting/scriptmgr.hxx>
111 #endif
112 #include <Sound/fg_fx.hxx>
113 #include <Systems/system_mgr.hxx>
114 #include <Time/FGEventMgr.hxx>
115 #include <Time/light.hxx>
116 #include <Time/sunpos.hxx>
117 #include <Time/moonpos.hxx>
118 #include <Time/tmp.hxx>
119
120 #ifdef FG_MPLAYER_AS
121 #include <MultiPlayer/multiplaytxmgr.hxx>
122 #include <MultiPlayer/multiplayrxmgr.hxx>
123 #endif
124
125 #ifdef FG_WEATHERCM
126 #  include <WeatherCM/FGLocalWeatherDatabase.h>
127 #else
128 #  include <Environment/environment_mgr.hxx>
129 #endif
130
131 #include "fg_init.hxx"
132 #include "fg_io.hxx"
133 #include "fg_commands.hxx"
134 #include "fg_props.hxx"
135 #include "options.hxx"
136 #include "globals.hxx"
137 #include "logger.hxx"
138 #include "viewmgr.hxx"
139
140 #if defined(FX) && defined(XMESA)
141 #include <GL/xmesa.h>
142 #endif
143
144 SG_USING_STD(string);
145
146
147 class Sound;
148
149 extern const char *default_root;
150
151 #ifdef FG_USE_CLOUDS_3D
152   SkySceneLoader *sgCloud3d;
153 #endif
154
155
156 // Scan the command line options for the specified option and return
157 // the value.
158 static string fgScanForOption( const string& option, int argc, char **argv ) {
159     int i = 1;
160
161     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
162
163     int len = option.length();
164
165     while ( i < argc ) {
166         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
167
168         string arg = argv[i];
169         if ( arg.find( option ) == 0 ) {
170             return arg.substr( len );
171         }
172
173         i++;
174     }
175
176     return "";
177 }
178
179
180 // Scan the user config files for the specified option and return
181 // the value.
182 static string fgScanForOption( const string& option, const string& path ) {
183     sg_gzifstream in( path );
184     if ( !in.is_open() ) {
185         return "";
186     }
187
188     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
189
190     int len = option.length();
191
192     in >> skipcomment;
193 #ifndef __MWERKS__
194     while ( ! in.eof() ) {
195 #else
196     char c = '\0';
197     while ( in.get(c) && c != '\0' ) {
198         in.putback(c);
199 #endif
200         string line;
201
202 #if defined( macintosh )
203         getline( in, line, '\r' );
204 #else
205         getline( in, line, '\n' );
206 #endif
207
208         // catch extraneous (DOS) line ending character
209         if ( line[line.length() - 1] < 32 ) {
210             line = line.substr( 0, line.length()-1 );
211         }
212
213         if ( line.find( option ) == 0 ) {
214             return line.substr( len );
215         }
216
217         in >> skipcomment;
218     }
219
220     return "";
221 }
222
223
224 // Read in configuration (files and command line options) but only set
225 // fg_root
226 bool fgInitFGRoot ( int argc, char **argv ) {
227     string root;
228     char* envp;
229
230     // First parse command line options looking for --fg-root=, this
231     // will override anything specified in a config file
232     root = fgScanForOption( "--fg-root=", argc, argv);
233
234 #if defined( unix ) || defined( __CYGWIN__ )
235     // Next check home directory for .fgfsrc.hostname file
236     if ( root.empty() ) {
237         envp = ::getenv( "HOME" );
238         if ( envp != NULL ) {
239             SGPath config( envp );
240             config.append( ".fgfsrc" );
241             char name[256];
242             gethostname( name, 256 );
243             config.concat( "." );
244             config.concat( name );
245             root = fgScanForOption( "--fg-root=", config.str() );
246         }
247     }
248 #endif
249
250     // Next check home directory for .fgfsrc file
251     if ( root.empty() ) {
252         envp = ::getenv( "HOME" );
253         if ( envp != NULL ) {
254             SGPath config( envp );
255             config.append( ".fgfsrc" );
256             root = fgScanForOption( "--fg-root=", config.str() );
257         }
258     }
259     
260     // Next check if fg-root is set as an env variable
261     if ( root.empty() ) {
262         envp = ::getenv( "FG_ROOT" );
263         if ( envp != NULL ) {
264             root = envp;
265         }
266     }
267
268     // Otherwise, default to a random compiled-in location if we can't
269     // find fg-root any other way.
270     if ( root.empty() ) {
271 #if defined( __CYGWIN__ )
272         root = "/FlightGear";
273 #elif defined( WIN32 )
274         root = "\\FlightGear";
275 #elif defined( macintosh )
276         root = "";
277 #else
278         root = PKGLIBDIR;
279 #endif
280     }
281
282     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
283     globals->set_fg_root(root);
284
285     return true;
286 }
287
288
289 // Read in configuration (files and command line options) but only set
290 // aircraft
291 bool fgInitFGAircraft ( int argc, char **argv ) {
292     string aircraft;
293     char* envp;
294
295     // First parse command line options looking for --aircraft=, this
296     // will override anything specified in a config file
297     aircraft = fgScanForOption( "--aircraft=", argc, argv );
298
299 #if defined( unix ) || defined( __CYGWIN__ )
300     // Next check home directory for .fgfsrc.hostname file
301     if ( aircraft.empty() ) {
302         envp = ::getenv( "HOME" );
303         if ( envp != NULL ) {
304             SGPath config( envp );
305             config.append( ".fgfsrc" );
306             char name[256];
307             gethostname( name, 256 );
308             config.concat( "." );
309             config.concat( name );
310             aircraft = fgScanForOption( "--aircraft=", config.str() );
311         }
312     }
313 #endif
314
315     // Next check home directory for .fgfsrc file
316     if ( aircraft.empty() ) {
317         envp = ::getenv( "HOME" );
318         if ( envp != NULL ) {
319             SGPath config( envp );
320             config.append( ".fgfsrc" );
321             aircraft = fgScanForOption( "--aircraft=", config.str() );
322         }
323     }
324
325     // if an aircraft was specified, set the property name
326     if ( !aircraft.empty() ) {
327         SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
328         fgSetString("/sim/aircraft", aircraft.c_str() );
329     } else {
330         SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
331     }
332
333     return true;
334 }
335
336
337 // Return the current base package version
338 string fgBasePackageVersion() {
339     SGPath base_path( globals->get_fg_root() );
340     base_path.append("version");
341
342     sg_gzifstream in( base_path.str() );
343     if ( !in.is_open() ) {
344         SGPath old_path( globals->get_fg_root() );
345         old_path.append( "Thanks" );
346         sg_gzifstream old( old_path.str() );
347         if ( !old.is_open() ) {
348             return "[none]";
349         } else {
350             return "[old version]";
351         }
352     }
353
354     string version;
355     in >> version;
356
357     return version;
358 }
359
360
361 // Initialize the localization
362 SGPropertyNode *fgInitLocale(const char *language) {
363    SGPropertyNode *c_node = NULL, *d_node = NULL;
364    SGPropertyNode *intl = fgGetNode("/sim/intl");
365
366    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
367
368    // localization not defined
369    if (!intl)
370       return NULL;
371
372    //
373    // Select the proper language from the list
374    //
375    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
376    for (unsigned int i = 0; i < locale.size(); i++) {
377
378       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
379       for (unsigned int j = 0; j < lang.size(); j++) {
380
381          if (!strcmp(lang[j]->getStringValue(), language)) {
382             c_node = locale[i];
383             break;
384          }
385       }
386    }
387
388
389    // Get the defaults
390    d_node = intl->getChild("locale");
391    if (!c_node)
392       c_node = d_node;
393
394    // Check for localized font
395    SGPropertyNode *font_n = c_node->getNode("font", true);
396    if ( !strcmp(font_n->getStringValue(), "") )
397       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
398
399
400    //
401    // Load the default strings
402    //
403    SGPath d_path( globals->get_fg_root() );
404
405    const char *d_path_str = d_node->getStringValue("strings");
406    if (!d_path_str) {
407       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
408       return NULL;
409    }
410
411    d_path.append(d_path_str);
412    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
413                                   << d_path.str());
414
415    SGPropertyNode *strings = c_node->getNode("strings");
416    try {
417       readProperties(d_path.str(), strings);
418    } catch (const sg_exception &e) {
419       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
420       return NULL;
421    }
422
423    //
424    // Load the language specific strings
425    //
426    if (c_node != d_node) {
427       SGPath c_path( globals->get_fg_root() );
428
429       const char *c_path_str = c_node->getStringValue("strings");
430       if (!c_path_str) {
431          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
432          return NULL;
433       }
434
435       c_path.append(c_path_str);
436       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
437                                      << c_path.str());
438
439       try {
440          readProperties(c_path.str(), strings);
441       } catch (const sg_exception &e) {
442          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
443          return NULL;
444       }
445    }
446
447    return c_node;
448 }
449
450
451
452 // Initialize the localization routines
453 bool fgDetectLanguage() {
454     char *language = ::getenv("LANG");
455
456     if (language == NULL) {
457         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
458         language = "C";
459     }
460
461     SGPropertyNode *locale = fgInitLocale(language);
462     if (!locale) {
463        SG_LOG(SG_GENERAL, SG_ALERT,
464               "No internationalization settings specified in preferences.xml" );
465
466        return false;
467     }
468
469     globals->set_locale( locale );
470
471     return true;
472 }
473
474 // Attempt to locate and parse the various non-XML config files in order
475 // from least precidence to greatest precidence
476 static void
477 do_options (int argc, char ** argv)
478 {
479     // Check for $fg_root/system.fgfsrc
480     SGPath config( globals->get_fg_root() );
481     config.append( "system.fgfsrc" );
482     fgParseOptions(config.str());
483
484 #if defined( unix ) || defined( __CYGWIN__ )
485     char name[256];
486     // Check for $fg_root/system.fgfsrc.hostname
487     gethostname( name, 256 );
488     config.concat( "." );
489     config.concat( name );
490     fgParseOptions(config.str());
491 #endif
492
493     // Check for ~/.fgfsrc
494     char* envp = ::getenv( "HOME" );
495     if ( envp != NULL ) {
496         config.set( envp );
497         config.append( ".fgfsrc" );
498         fgParseOptions(config.str());
499     }
500
501 #if defined( unix ) || defined( __CYGWIN__ )
502     // Check for ~/.fgfsrc.hostname
503     gethostname( name, 256 );
504     config.concat( "." );
505     config.concat( name );
506     fgParseOptions(config.str());
507 #endif
508
509     // Parse remaining command line options
510     // These will override anything specified in a config file
511     fgParseArgs(argc, argv);
512 }
513
514
515 // Read in configuration (file and command line)
516 bool fgInitConfig ( int argc, char **argv ) {
517
518     // First, set some sane default values
519     fgSetDefaults();
520
521     // Read global preferences from $FG_ROOT/preferences.xml
522     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
523     fgLoadProps("preferences.xml", globals->get_props());
524     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
525
526     // Detect the required language as early as possible
527     if ( !fgDetectLanguage() ) {
528         return false;
529     }
530
531     // Scan user config files and command line for a specified aircraft.
532     fgInitFGAircraft(argc, argv);
533
534     string aircraft = fgGetString("/sim/aircraft", "");
535     if ( aircraft.size() > 0 ) {
536         SGPath aircraft_path(globals->get_fg_root());
537         aircraft_path.append("Aircraft");
538         aircraft_path.append(aircraft);
539         aircraft_path.concat("-set.xml");
540         SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
541                << " from " << aircraft_path.str());
542         try {
543             readProperties(aircraft_path.str(), globals->get_props());
544         } catch (const sg_exception &e) {
545             string message = "Error reading default aircraft: ";
546             message += e.getFormattedMessage();
547             SG_LOG(SG_INPUT, SG_ALERT, message);
548             exit(2);
549         }
550     } else {
551         SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
552     }
553
554     // parse options after loading aircraft to ensure any user
555     // overrides of defaults are honored.
556     do_options(argc, argv);
557
558     return true;
559 }
560
561
562 // find basic airport location info from airport database
563 bool fgFindAirportID( const string& id, FGAirport *a ) {
564     if ( id.length() ) {
565         SGPath path( globals->get_fg_root() );
566         path.append( "Airports" );
567         path.append( "simple.mk4" );
568         FGAirports airports( path.c_str() );
569
570         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
571
572         if ( ! airports.search( id, a ) ) {
573             SG_LOG( SG_GENERAL, SG_ALERT,
574                     "Failed to find " << id << " in " << path.str() );
575             return false;
576         }
577     } else {
578         return false;
579     }
580
581     SG_LOG( SG_GENERAL, SG_INFO,
582             "Position for " << id << " is ("
583             << a->longitude << ", "
584             << a->latitude << ")" );
585
586     return true;
587 }
588
589
590 // get airport elevation
591 static double fgGetAirportElev( const string& id ) {
592     FGAirport a;
593     // double lon, lat;
594
595     SG_LOG( SG_GENERAL, SG_INFO,
596             "Finding elevation for airport: " << id );
597
598     if ( fgFindAirportID( id, &a ) ) {
599         return a.elevation;
600     } else {
601         return -9999.0;
602     }
603 }
604
605
606 // Preset lon/lat given an airport id
607 static bool fgSetPosFromAirportID( const string& id ) {
608     FGAirport a;
609     // double lon, lat;
610
611     SG_LOG( SG_GENERAL, SG_INFO,
612             "Attempting to set starting position from airport code " << id );
613
614     if ( fgFindAirportID( id, &a ) ) {
615         // presets
616         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
617         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
618
619         // other code depends on the actual postition being set so set
620         // that as well
621         fgSetDouble("/position/longitude-deg", a.longitude );
622         fgSetDouble("/position/latitude-deg", a.latitude );
623
624         SG_LOG( SG_GENERAL, SG_INFO,
625                 "Position for " << id << " is (" << a.longitude
626                 << ", " << a.latitude << ")" );
627
628         return true;
629     } else {
630         return false;
631     }
632 }
633
634
635 // Set current tower position lon/lat given an airport id
636 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
637     FGAirport a;
638     // tower height hard coded for now...
639     float towerheight=50.0f;
640
641     // make a little off the heading for 1 runway airports...
642     float fudge_lon = fabs(sin(hdg)) * .003f;
643     float fudge_lat = .003f - fudge_lon;
644
645     if ( fgFindAirportID( id, &a ) ) {
646         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
647         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
648         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
649         return true;
650     } else {
651         return false;
652     }
653
654 }
655
656
657 // Set current_options lon/lat given an airport id and heading (degrees)
658 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
659     FGRunway r;
660
661     if ( id.length() ) {
662         // set initial position from runway and heading
663
664         SGPath path( globals->get_fg_root() );
665         path.append( "Airports" );
666         path.append( "runways.mk4" );
667         FGRunways runways( path.c_str() );
668
669         SG_LOG( SG_GENERAL, SG_INFO,
670                 "Attempting to set starting position from airport code "
671                 << id << " heading " << tgt_hdg );
672                 
673         if ( ! runways.search( id, (int)tgt_hdg, &r ) ) {
674             SG_LOG( SG_GENERAL, SG_ALERT,
675                     "Failed to find a good runway for " << id << '\n' );
676             return false;
677         }       
678     } else {
679         return false;
680     }
681
682     double lat2, lon2, az2;
683     double heading = r.heading;
684     double azimuth = heading + 180.0;
685     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
686
687     SG_LOG( SG_GENERAL, SG_INFO,
688             "runway =  " << r.lon << ", " << r.lat
689             << " length = " << r.length * SG_FEET_TO_METER 
690             << " heading = " << azimuth );
691             
692     geo_direct_wgs_84 ( 0, r.lat, r.lon, azimuth, 
693                         r.length * SG_FEET_TO_METER * 0.5 - 5.0,
694                         &lat2, &lon2, &az2 );
695
696     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
697         double olat, olon;
698         double odist = fgGetDouble("/sim/presets/offset-distance");
699         odist *= SG_NM_TO_METER;
700         double oaz = azimuth;
701         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
702             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
703         }
704         while ( oaz >= 360.0 ) { oaz -= 360.0; }
705         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
706         lat2=olat;
707         lon2=olon;
708     }
709
710     // presets
711     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
712     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
713     fgSetDouble("/sim/presets/heading-deg", heading );
714
715     // other code depends on the actual values being set ...
716     fgSetDouble("/position/longitude-deg",  lon2 );
717     fgSetDouble("/position/latitude-deg",  lat2 );
718     fgSetDouble("/orientation/heading-deg", heading );
719
720     SG_LOG( SG_GENERAL, SG_INFO,
721             "Position for " << id << " is ("
722             << lon2 << ", "
723             << lat2 << ") new heading is "
724             << heading );
725             
726     return true;
727 }
728
729
730 // Set current_options lon/lat given an airport id and runway number
731 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
732     FGRunway r;
733
734     if ( id.length() ) {
735         // set initial position from airport and runway number
736
737         SGPath path( globals->get_fg_root() );
738         path.append( "Airports" );
739         path.append( "runways.mk4" );
740         FGRunways runways( path.c_str() );
741
742         SG_LOG( SG_GENERAL, SG_INFO,
743                 "Attempting to set starting position for "
744                 << id << ":" << rwy );
745
746         if ( ! runways.search( id, rwy, &r ) ) {
747             SG_LOG( SG_GENERAL, SG_ALERT,
748                     "Failed to find runway " << rwy << 
749                     " at airport " << id );
750             return false;
751         }
752     } else {
753         return false;
754     }
755
756     double lat2, lon2, az2;
757     double heading = r.heading;
758     double azimuth = heading + 180.0;
759     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
760     
761     SG_LOG( SG_GENERAL, SG_INFO,
762     "runway =  " << r.lon << ", " << r.lat
763     << " length = " << r.length * SG_FEET_TO_METER 
764     << " heading = " << azimuth );
765     
766     geo_direct_wgs_84 ( 0, r.lat, r.lon, 
767     azimuth,
768     r.length * SG_FEET_TO_METER * 0.5 - 5.0,
769     &lat2, &lon2, &az2 );
770     
771     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
772     {
773         double olat, olon;
774         double odist = fgGetDouble("/sim/presets/offset-distance");
775         odist *= SG_NM_TO_METER;
776         double oaz = azimuth;
777         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
778         {
779             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
780         }
781         while ( oaz >= 360.0 ) { oaz -= 360.0; }
782         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
783         lat2=olat;
784         lon2=olon;
785     }
786     
787     // presets
788     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
789     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
790     fgSetDouble("/sim/presets/heading-deg", heading );
791     
792     // other code depends on the actual values being set ...
793     fgSetDouble("/position/longitude-deg",  lon2 );
794     fgSetDouble("/position/latitude-deg",  lat2 );
795     fgSetDouble("/orientation/heading-deg", heading );
796     
797     SG_LOG( SG_GENERAL, SG_INFO,
798     "Position for " << id << " is ("
799     << lon2 << ", "
800     << lat2 << ") new heading is "
801     << heading );
802     
803     return true;
804 }
805
806
807 static void fgSetDistOrAltFromGlideSlope() {
808     string apt_id = fgGetString("/sim/presets/airport-id");
809     double gs = fgGetDouble("/sim/presets/glideslope-deg")
810         * SG_DEGREES_TO_RADIANS ;
811     double od = fgGetDouble("/sim/presets/offset-distance");
812     double alt = fgGetDouble("/sim/presets/altitude-ft");
813
814     double apt_elev = 0.0;
815     if ( ! apt_id.empty() ) {
816         apt_elev = fgGetAirportElev( apt_id );
817         if ( apt_elev < -9990.0 ) {
818             apt_elev = 0.0;
819         }
820     } else {
821         apt_elev = 0.0;
822     }
823
824     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
825         // set altitude from glideslope and offset-distance
826         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
827         alt = fabs(od*tan(gs)) + apt_elev;
828         fgSetDouble("/sim/presets/altitude-ft", alt);
829         fgSetBool("/sim/presets/onground", false);
830         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
831                 << alt  << " ft" );
832     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
833         // set offset-distance from glideslope and altitude
834         od  = (alt - apt_elev) / tan(gs);
835         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
836         fgSetDouble("/sim/presets/offset-distance", od);
837         fgSetBool("/sim/presets/onground", false);
838         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
839                 << od  << " nm" );
840     } else if( fabs(gs) > 0.01 ) {
841         SG_LOG( SG_GENERAL, SG_ALERT,
842                 "Glideslope given but not altitude or offset-distance." );
843         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
844         fgSetDouble("/sim/presets/glideslope-deg", 0);
845         fgSetBool("/sim/presets/onground", true);
846     }                              
847 }                       
848
849
850 // Set current_options lon/lat given an airport id and heading (degrees)
851 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
852     FGNav *nav = current_navlist->findByIdentAndFreq( id.c_str(), freq );
853
854     // set initial position from runway and heading
855     if ( nav != NULL ) {
856         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
857                 << id << ":" << freq );
858
859         double lon = nav->get_lon();
860         double lat = nav->get_lat();
861
862         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
863         {
864             double odist = fgGetDouble("/sim/presets/offset-distance")
865                 * SG_NM_TO_METER;
866             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
867                 + 180.0;
868             while ( oaz >= 360.0 ) { oaz -= 360.0; }
869             double olat, olon, az2;
870             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
871
872             lat = olat;
873             lon = olon;
874         }
875
876         // presets
877         fgSetDouble("/sim/presets/longitude-deg",  lon );
878         fgSetDouble("/sim/presets/latitude-deg",  lat );
879
880         // other code depends on the actual values being set ...
881         fgSetDouble("/position/longitude-deg",  lon );
882         fgSetDouble("/position/latitude-deg",  lat );
883         fgSetDouble("/orientation/heading-deg", 
884                     fgGetDouble("/sim/presets/heading-deg") );
885
886         SG_LOG( SG_GENERAL, SG_INFO,
887                 "Position for " << id << ":" << freq << " is ("
888                 << lon << ", "<< lat << ")" );
889
890         return true;
891     } else {
892         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
893                 << id << ":" << freq );
894         return false;
895     }
896 }
897
898
899 // Set current_options lon/lat given an airport id and heading (degrees)
900 static bool fgSetPosFromFix( const string& id ) {
901     FGFix fix;
902
903     // set initial position from runway and heading
904     if ( current_fixlist->query( id.c_str(), &fix ) ) {
905         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
906                 << id );
907
908         double lon = fix.get_lon();
909         double lat = fix.get_lat();
910
911         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
912         {
913             double odist = fgGetDouble("/sim/presets/offset-distance")
914                 * SG_NM_TO_METER;
915             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
916                 + 180.0;
917             while ( oaz >= 360.0 ) { oaz -= 360.0; }
918             double olat, olon, az2;
919             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
920
921             lat = olat;
922             lon = olon;
923         }
924
925         // presets
926         fgSetDouble("/sim/presets/longitude-deg",  lon );
927         fgSetDouble("/sim/presets/latitude-deg",  lat );
928
929         // other code depends on the actual values being set ...
930         fgSetDouble("/position/longitude-deg",  lon );
931         fgSetDouble("/position/latitude-deg",  lat );
932         fgSetDouble("/orientation/heading-deg", 
933                     fgGetDouble("/sim/presets/heading-deg") );
934
935         SG_LOG( SG_GENERAL, SG_INFO,
936                 "Position for " << id << " is ("
937                 << lon << ", "<< lat << ")" );
938
939         return true;
940     } else {
941         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
942                 << id );
943         return false;
944     }
945 }
946
947
948 /**
949  * Initialize vor/ndb/ils/fix list management and query systems
950  */
951 bool
952 fgInitNav ()
953 {
954     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
955
956     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
957     current_navlist = new FGNavList;
958     SGPath p_nav( globals->get_fg_root() );
959     p_nav.append( "Navaids/default.nav" );
960     current_navlist->init( p_nav );
961
962     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
963     current_beacons = new FGMarkerBeacons;
964     current_beacons->init();
965     current_ilslist = new FGILSList;
966     SGPath p_ils( globals->get_fg_root() );
967     p_ils.append( "Navaids/default.ils" );
968     current_ilslist->init( p_ils );
969
970     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
971     current_fixlist = new FGFixList;
972     SGPath p_fix( globals->get_fg_root() );
973     p_fix.append( "Navaids/default.fix" );
974     current_fixlist->init( p_fix );
975
976     return true;
977 }
978
979
980 // Set the initial position based on presets (or defaults)
981 bool fgInitPosition() {
982     bool set_pos = false;
983
984     // Do a first guess if we should be on the ground or in the air
985     // (to be refined later based on other input.
986     if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
987         fgSetBool("/sim/presets/onground", false);
988     } else {
989         fgSetBool("/sim/presets/onground", true);
990     }
991
992     // If glideslope is specified, then calculate offset-distance or
993     // altitude relative to glide slope if either of those was not
994     // specified.
995     fgSetDistOrAltFromGlideSlope();
996
997     // If we have an explicit, in-range lon/lat, don't change it, just use it.
998     // If not, check for an airport-id and use that.
999     // If not, default to the middle of the KSFO field.
1000     // The default values for lon/lat are deliberately out of range
1001     // so that the airport-id can take effect; valid lon/lat will
1002     // override airport-id, however.
1003     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1004     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1005     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1006          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1007     {
1008         set_pos = true;
1009     }
1010
1011     string apt = fgGetString("/sim/presets/airport-id");
1012     string rwy_no = fgGetString("/sim/presets/runway");
1013     double hdg = fgGetDouble("/sim/presets/heading-deg");
1014     string vor = fgGetString("/sim/presets/vor-id");
1015     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1016     string ndb = fgGetString("/sim/presets/ndb-id");
1017     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1018     string fix = fgGetString("/sim/presets/fix");
1019     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1020         // An airport + runway is requested
1021         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1022             // set position (a little off the heading for single
1023             // runway airports)
1024             fgSetTowerPosFromAirportID( apt, hdg );
1025
1026             set_pos = true;
1027         }
1028     }
1029     if ( !set_pos && !apt.empty() ) {
1030         // An airport is requested (find runway closest to hdg)
1031         bool ok = false;
1032         if (fgGetDouble("/sim/presets/altitude-ft") <= 0 &&
1033             fgGetDouble("/sim/presets/offset-distance") == 0)
1034             ok = fgSetPosFromAirportIDandHdg( apt, hdg );
1035         else
1036             ok = fgSetPosFromAirportID( apt );
1037             
1038         if (ok) {
1039                 // set position (a little off the heading for single
1040                 // runway airports)
1041                 fgSetTowerPosFromAirportID( apt, hdg );
1042
1043             set_pos = true;
1044         }
1045     }
1046     if ( !set_pos && !vor.empty() ) {
1047         // a VOR is requested
1048         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1049             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1050                 fgSetBool("/sim/presets/onground", false);
1051             } else {
1052                 fgSetBool("/sim/presets/onground", true);
1053             }
1054             set_pos = true;
1055         }
1056     }
1057     if ( !set_pos && !ndb.empty() ) {
1058         // an NDB is requested
1059         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1060             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1061                 fgSetBool("/sim/presets/onground", false);
1062             } else {
1063                 fgSetBool("/sim/presets/onground", true);
1064             }
1065             set_pos = true;
1066         }
1067     }
1068     if ( !set_pos && !fix.empty() ) {
1069         // a Fix is requested
1070         if ( fgSetPosFromFix( fix ) ) {
1071             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1072                 fgSetBool("/sim/presets/onground", false);
1073             } else {
1074                 fgSetBool("/sim/presets/onground", true);
1075             }
1076             set_pos = true;
1077         }
1078     }
1079
1080     if ( !set_pos ) {
1081         // No lon/lat specified, no airport specified, default to
1082         // middle of KSFO field.
1083         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1084         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1085     }
1086
1087     fgSetDouble( "/position/longitude-deg",
1088                  fgGetDouble("/sim/presets/longitude-deg") );
1089     fgSetDouble( "/position/latitude-deg",
1090                  fgGetDouble("/sim/presets/latitude-deg") );
1091     fgSetDouble( "/orientation/heading-deg",
1092                  fgGetDouble("/sim/presets/heading-deg") );
1093
1094     return true;
1095 }
1096
1097
1098 // General house keeping initializations
1099 bool fgInitGeneral() {
1100     string root;
1101
1102 #if defined(FX) && defined(XMESA)
1103     char *mesa_win_state;
1104 #endif
1105
1106     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1107     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1108
1109     root = globals->get_fg_root();
1110     if ( ! root.length() ) {
1111         // No root path set? Then bail ...
1112         SG_LOG( SG_GENERAL, SG_ALERT,
1113                 "Cannot continue without a path to the base package "
1114                 << "being defined." );
1115         exit(-1);
1116     }
1117     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1118
1119 #if defined(FX) && defined(XMESA)
1120     // initialize full screen flag
1121     globals->set_fullscreen(false);
1122     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1123         // Test for the MESA_GLX_FX env variable
1124         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1125             // test if we are fullscreen mesa/glide
1126             if ( (mesa_win_state[0] == 'f') ||
1127                  (mesa_win_state[0] == 'F') ) {
1128                 globals->set_fullscreen(true);
1129             }
1130         }
1131     }
1132 #endif
1133
1134     return true;
1135 }
1136
1137
1138 // Initialize the flight model subsystem.  This just creates the
1139 // object.  The actual fdm initialization is delayed until we get a
1140 // proper scenery elevation hit.  This is checked for in main.cxx
1141
1142 void fgInitFDM() {
1143
1144     if ( cur_fdm_state ) {
1145         delete cur_fdm_state;
1146         cur_fdm_state = 0;
1147     }
1148
1149     double dt = 1.0 / fgGetInt("/sim/model-hz");
1150     aircraft_dir = fgGetString("/sim/aircraft-dir");
1151     const string &model = fgGetString("/sim/flight-model");
1152
1153     try {
1154         if ( model == "larcsim" ) {
1155             cur_fdm_state = new FGLaRCsim( dt );
1156         } else if ( model == "jsb" ) {
1157             cur_fdm_state = new FGJSBsim( dt );
1158         } else if ( model == "ada" ) {
1159             cur_fdm_state = new FGADA( dt );
1160         } else if ( model == "balloon" ) {
1161             cur_fdm_state = new FGBalloonSim( dt );
1162         } else if ( model == "magic" ) {
1163             cur_fdm_state = new FGMagicCarpet( dt );
1164         } else if ( model == "ufo" ) {
1165             cur_fdm_state = new FGUFO( dt );
1166         } else if ( model == "external" ) {
1167             // external is a synonym for "--fdm=null" and is
1168             // maintained here for backwards compatibility
1169             cur_fdm_state = new FGNullFDM( dt );
1170         } else if ( model.find("network") == 0 ) {
1171             string host = "localhost";
1172             int port1 = 5501;
1173             int port2 = 5502;
1174             int port3 = 5503;
1175             string net_options = model.substr(8);
1176             string::size_type begin, end;
1177             begin = 0;
1178             // host
1179             end = net_options.find( ",", begin );
1180             if ( end != string::npos ) {
1181                 host = net_options.substr(begin, end - begin);
1182                 begin = end + 1;
1183             }
1184             // port1
1185             end = net_options.find( ",", begin );
1186             if ( end != string::npos ) {
1187                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1188                 begin = end + 1;
1189             }
1190             // port2
1191             end = net_options.find( ",", begin );
1192             if ( end != string::npos ) {
1193                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1194                 begin = end + 1;
1195             }
1196             // port3
1197             end = net_options.find( ",", begin );
1198             if ( end != string::npos ) {
1199                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1200                 begin = end + 1;
1201             }
1202             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1203         } else if ( model.find("pipe") == 0 ) {
1204             string pipe_path = model.substr(5);
1205             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1206         } else if ( model == "null" ) {
1207             cur_fdm_state = new FGNullFDM( dt );
1208         } else if ( model == "yasim" ) {
1209             cur_fdm_state = new YASim( dt );
1210         } else {
1211             SG_LOG(SG_GENERAL, SG_ALERT,
1212                    "Unrecognized flight model '" << model
1213                    << "', cannot init flight dynamics model.");
1214             exit(-1);
1215         }
1216     } catch ( ... ) {
1217         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1218         exit(-1);
1219     }
1220 }
1221
1222 static void printMat(const sgVec4 *mat, char *name="")
1223 {
1224     int i;
1225     SG_LOG(SG_GENERAL, SG_BULK, name );
1226     for(i=0; i<4; i++) {
1227         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1228                                     << " " << mat[i][2] << " " << mat[i][3] );
1229     }
1230 }
1231
1232 // Initialize view parameters
1233 void fgInitView() {
1234   // force update of model so that viewer can get some data...
1235   globals->get_aircraft_model()->update(0);
1236   // run update for current view so that data is current...
1237   globals->get_viewmgr()->update(0);
1238
1239   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1240   printMat(globals->get_current_view()->get_UP(),"UP");
1241   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1242   
1243 }
1244
1245
1246 SGTime *fgInitTime() {
1247     // Initialize time
1248     static const SGPropertyNode *longitude
1249         = fgGetNode("/position/longitude-deg");
1250     static const SGPropertyNode *latitude
1251         = fgGetNode("/position/latitude-deg");
1252     static const SGPropertyNode *cur_time_override
1253         = fgGetNode("/sim/time/cur-time-override", true);
1254
1255     SGPath zone( globals->get_fg_root() );
1256     zone.append( "Timezone" );
1257     SGTime *t = new SGTime( longitude->getDoubleValue()
1258                               * SGD_DEGREES_TO_RADIANS,
1259                             latitude->getDoubleValue()
1260                               * SGD_DEGREES_TO_RADIANS,
1261                             zone.str(),
1262                             cur_time_override->getLongValue() );
1263
1264     // Handle potential user specified time offsets
1265     time_t cur_time = t->get_cur_time();
1266     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1267     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1268     time_t aircraftLocalTime = 
1269         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1270
1271     // Okay, we now have six possible scenarios
1272     int offset = fgGetInt("/sim/startup/time-offset");
1273     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1274     if (offset_type == "system-offset") {
1275         globals->set_warp( offset );
1276     } else if (offset_type == "gmt-offset") {
1277         globals->set_warp( offset - (currGMT - systemLocalTime) );
1278     } else if (offset_type == "latitude-offset") {
1279         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1280     } else if (offset_type == "system") {
1281         globals->set_warp( offset - cur_time );
1282     } else if (offset_type == "gmt") {
1283         globals->set_warp( offset - currGMT );
1284     } else if (offset_type == "latitude") {
1285         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1286                            cur_time ); 
1287     } else {
1288         SG_LOG( SG_GENERAL, SG_ALERT,
1289                 "FG_TIME::Unsupported offset type " << offset_type );
1290         exit( -1 );
1291     }
1292
1293     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1294             << globals->get_warp() );
1295
1296     globals->set_warp_delta( 0 );
1297
1298     t->update( 0.0, 0.0,
1299                cur_time_override->getLongValue(),
1300                globals->get_warp() );
1301
1302     return t;
1303 }
1304
1305
1306 // This is the top level init routine which calls all the other
1307 // initialization routines.  If you are adding a subsystem to flight
1308 // gear, its initialization call should located in this routine.
1309 // Returns non-zero if a problem encountered.
1310 bool fgInitSubsystems() {
1311     // static const SGPropertyNode *longitude
1312     //     = fgGetNode("/sim/presets/longitude-deg");
1313     // static const SGPropertyNode *latitude
1314     //     = fgGetNode("/sim/presets/latitude-deg");
1315     // static const SGPropertyNode *altitude
1316     //     = fgGetNode("/sim/presets/altitude-ft");
1317
1318     fgLIGHT *l = &cur_light_params;
1319
1320     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1321     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1322
1323
1324     ////////////////////////////////////////////////////////////////////
1325     // Initialize the material property subsystem.
1326     ////////////////////////////////////////////////////////////////////
1327
1328     SGPath mpath( globals->get_fg_root() );
1329     mpath.append( "materials.xml" );
1330     if ( ! material_lib.load( mpath.str() ) ) {
1331         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1332         exit(-1);
1333     }
1334
1335     ////////////////////////////////////////////////////////////////////
1336     // Initialize the event manager subsystem.
1337     ////////////////////////////////////////////////////////////////////
1338
1339     global_events.init();
1340
1341     // Output event stats every 60 seconds
1342     global_events.Register( "FGEventMgr::print_stats()",
1343                             &global_events, &FGEventMgr::print_stats,
1344                             60000 );
1345
1346
1347     ////////////////////////////////////////////////////////////////////
1348     // Initialize the scenery management subsystem.
1349     ////////////////////////////////////////////////////////////////////
1350
1351     if ( globals->get_tile_mgr()->init() ) {
1352         // Load the local scenery data
1353         double visibility_meters = fgGetDouble("/environment/visibility-m");
1354                 
1355         globals->get_tile_mgr()->update( visibility_meters );
1356     } else {
1357         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1358         exit(-1);
1359     }
1360
1361     // cause refresh of viewer scenery timestamps every 15 seconds...
1362     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1363                             globals->get_tile_mgr(),
1364                             &FGTileMgr::refresh_view_timestamps,
1365                             15000 );
1366
1367     SG_LOG( SG_GENERAL, SG_DEBUG,
1368             "Current terrain elevation after tile mgr init " <<
1369             globals->get_scenery()->get_cur_elev() );
1370
1371
1372     ////////////////////////////////////////////////////////////////////
1373     // Initialize the flight model subsystem.
1374     ////////////////////////////////////////////////////////////////////
1375
1376     fgInitFDM();
1377         
1378     // allocates structures so must happen before any of the flight
1379     // model or control parameters are set
1380     fgAircraftInit();   // In the future this might not be the case.
1381
1382
1383     ////////////////////////////////////////////////////////////////////
1384     // Initialize the view manager subsystem.
1385     ////////////////////////////////////////////////////////////////////
1386
1387     fgInitView();
1388
1389
1390     ////////////////////////////////////////////////////////////////////
1391     // Initialize the lighting subsystem.
1392     ////////////////////////////////////////////////////////////////////
1393
1394     // fgUpdateSunPos() needs a few position and view parameters set
1395     // so it can calculate local relative sun angle and a few other
1396     // things for correctly orienting the sky.
1397     fgUpdateSunPos();
1398     fgUpdateMoonPos();
1399     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1400                             60000);
1401     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1402                             60000);
1403
1404     // Initialize Lighting interpolation tables
1405     l->Init();
1406
1407     // force one lighting update to make it right to start with...
1408     l->Update();
1409     // update the lighting parameters (based on sun angle)
1410     global_events.Register( "fgLight::Update()",
1411                             &cur_light_params, &fgLIGHT::Update,
1412                             30000 );
1413
1414
1415     ////////////////////////////////////////////////////////////////////
1416     // Create and register the logger.
1417     ////////////////////////////////////////////////////////////////////
1418     
1419     globals->add_subsystem("logger", new FGLogger);
1420
1421
1422 #if defined(HAVE_PLIB_PSL)
1423     ////////////////////////////////////////////////////////////////////
1424     // Create and register the script manager.
1425     ////////////////////////////////////////////////////////////////////
1426
1427     globals->add_subsystem("scripting", new FGScriptMgr);
1428 #endif // HAVE_PLIB_PSL
1429
1430
1431     ////////////////////////////////////////////////////////////////////
1432     // Create and register the XML GUI.
1433     ////////////////////////////////////////////////////////////////////
1434
1435     globals->add_subsystem("gui", new NewGUI, FGSubsystemMgr::INIT);
1436
1437
1438     ////////////////////////////////////////////////////////////////////
1439     // Initialize the local time subsystem.
1440     ////////////////////////////////////////////////////////////////////
1441
1442     // update the current timezone each 30 minutes
1443     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1444                             30*60*1000 );
1445
1446
1447     ////////////////////////////////////////////////////////////////////
1448     // Initialize the weather subsystem.
1449     ////////////////////////////////////////////////////////////////////
1450
1451     // Initialize the weather modeling subsystem
1452 #ifdef FG_WEATHERCM
1453     // Initialize the WeatherDatabase
1454     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1455     sgVec3 position;
1456     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1457                current_aircraft.fdm_state->get_Longitude(),
1458                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1459     double init_vis = fgGetDouble("/environment/visibility-m");
1460
1461     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1462
1463     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1464     {
1465       working_type = FGLocalWeatherDatabase::use_internet;
1466     } else {
1467       working_type = FGLocalWeatherDatabase::default_mode;
1468     }
1469     
1470     if ( init_vis > 0 ) {
1471       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1472         new FGLocalWeatherDatabase( position,
1473                                     globals->get_fg_root(),
1474                                     working_type,
1475                                     init_vis );
1476     } else {
1477       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1478         new FGLocalWeatherDatabase( position,
1479                                     globals->get_fg_root(),
1480                                     working_type );
1481     }
1482
1483     // cout << theFGLocalWeatherDatabase << endl;
1484     // cout << "visibility = " 
1485     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1486
1487     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1488
1489     // register the periodic update of the weather
1490     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1491                             30000);
1492 #else
1493     globals->get_environment_mgr()->init();
1494     globals->get_environment_mgr()->bind();
1495 #endif
1496
1497 #ifdef FG_USE_CLOUDS_3D
1498     ////////////////////////////////////////////////////////////////////
1499     // Initialize the 3D cloud subsystem.
1500     ////////////////////////////////////////////////////////////////////
1501     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1502         SGPath cloud_path(globals->get_fg_root());
1503         cloud_path.append("large.sky");
1504         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1505         if ( !sgCloud3d->Load( cloud_path.str(),
1506                                latitude->getDoubleValue(),
1507                                longitude->getDoubleValue()) )
1508         {
1509             fgSetBool("/sim/rendering/clouds3d", false);
1510             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1511         }
1512         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1513     }
1514 #endif
1515
1516     ////////////////////////////////////////////////////////////////////
1517     // Initialise ATC display system
1518     ////////////////////////////////////////////////////////////////////
1519
1520     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1521     globals->set_ATC_display(new FGATCDisplay);
1522     globals->get_ATC_display()->init(); 
1523
1524     ////////////////////////////////////////////////////////////////////
1525     // Initialise the ATC Manager 
1526     ////////////////////////////////////////////////////////////////////
1527
1528     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1529     globals->set_ATC_mgr(new FGATCMgr);
1530     globals->get_ATC_mgr()->init(); 
1531     
1532     ////////////////////////////////////////////////////////////////////
1533     // Initialise the AI Manager 
1534     ////////////////////////////////////////////////////////////////////
1535
1536     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1537     globals->set_AI_mgr(new FGAIMgr);
1538     globals->get_AI_mgr()->init();
1539
1540
1541 #ifdef ENABLE_AUDIO_SUPPORT
1542     ////////////////////////////////////////////////////////////////////
1543     // Initialize the sound subsystem.
1544     ////////////////////////////////////////////////////////////////////
1545
1546     globals->set_soundmgr(new SGSoundMgr);
1547     globals->get_soundmgr()->init();
1548     globals->get_soundmgr()->bind();
1549
1550
1551     ////////////////////////////////////////////////////////////////////
1552     // Initialize the sound-effects subsystem.
1553     ////////////////////////////////////////////////////////////////////
1554
1555     globals->add_subsystem("fx", new FGFX);
1556     
1557 #endif
1558
1559     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1560     globals->add_subsystem("systems", new FGSystemMgr);
1561
1562     ////////////////////////////////////////////////////////////////////
1563     // Initialize the radio stack subsystem.
1564     ////////////////////////////////////////////////////////////////////
1565
1566     current_radiostack = new FGRadioStack;
1567     current_radiostack->init();
1568     current_radiostack->bind();
1569
1570
1571     ////////////////////////////////////////////////////////////////////
1572     // Initialize the cockpit subsystem
1573     ////////////////////////////////////////////////////////////////////
1574
1575     if( fgCockpitInit( &current_aircraft )) {
1576         // Cockpit initialized ok.
1577     } else {
1578         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1579         exit(-1);
1580     }
1581
1582
1583     ////////////////////////////////////////////////////////////////////
1584     // Initialize the autopilot subsystem.
1585     ////////////////////////////////////////////////////////////////////
1586
1587     globals->set_autopilot(new FGAutopilot);
1588     globals->get_autopilot()->init();
1589     globals->get_autopilot()->bind();
1590
1591                                 // FIXME: these should go in the
1592                                 // GUI initialization code, not here.
1593     fgAPAdjustInit();
1594     NewTgtAirportInit();
1595     NewHeadingInit();
1596     NewAltitudeInit();
1597
1598     ////////////////////////////////////////////////////////////////////
1599     // Initialize I/O subsystem.
1600     ////////////////////////////////////////////////////////////////////
1601
1602     globals->get_io()->init();
1603     globals->get_io()->bind();
1604
1605
1606     ////////////////////////////////////////////////////////////////////
1607     // Add a new 2D panel.
1608     ////////////////////////////////////////////////////////////////////
1609
1610     string panel_path = fgGetString("/sim/panel/path",
1611                                     "Panels/Default/default.xml");
1612
1613     globals->set_current_panel( fgReadPanel(panel_path) );
1614     if (globals->get_current_panel() == 0) {
1615         SG_LOG( SG_INPUT, SG_ALERT, 
1616                 "Error reading new panel from " << panel_path );
1617     } else {
1618         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1619         globals->get_current_panel()->init();
1620         globals->get_current_panel()->bind();
1621     }
1622
1623     
1624     ////////////////////////////////////////////////////////////////////
1625     // Initialize the default (kludged) properties.
1626     ////////////////////////////////////////////////////////////////////
1627
1628     fgInitProps();
1629
1630
1631     ////////////////////////////////////////////////////////////////////
1632     // Initialize the controls subsystem.
1633     ////////////////////////////////////////////////////////////////////
1634
1635     globals->get_controls()->init();
1636     globals->get_controls()->bind();
1637
1638
1639     ////////////////////////////////////////////////////////////////////
1640     // Initialize the input subsystem.
1641     ////////////////////////////////////////////////////////////////////
1642
1643     globals->add_subsystem("input", new FGInput);
1644
1645
1646     ////////////////////////////////////////////////////////////////////
1647     // Bind and initialize subsystems.
1648     ////////////////////////////////////////////////////////////////////
1649
1650     globals->get_subsystem_mgr()->bind();
1651     globals->get_subsystem_mgr()->init();
1652
1653
1654 #ifdef FG_MPLAYER_AS
1655     ////////////////////////////////////////////////////////////////////
1656     // Initialize multiplayer subsystem
1657     ////////////////////////////////////////////////////////////////////
1658
1659     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1660     globals->get_multiplayer_tx_mgr()->init();
1661
1662     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1663     globals->get_multiplayer_rx_mgr()->init();
1664 #endif
1665
1666     ////////////////////////////////////////////////////////////////////////
1667     // End of subsystem initialization.
1668     ////////////////////////////////////////////////////////////////////
1669
1670     SG_LOG( SG_GENERAL, SG_INFO, endl);
1671
1672                                 // Save the initial state for future
1673                                 // reference.
1674     globals->saveInitialState();
1675
1676     return true;
1677 }
1678
1679
1680 void fgReInitSubsystems()
1681 {
1682     // static const SGPropertyNode *longitude
1683     //     = fgGetNode("/sim/presets/longitude-deg");
1684     // static const SGPropertyNode *latitude
1685     //     = fgGetNode("/sim/presets/latitude-deg");
1686     static const SGPropertyNode *altitude
1687         = fgGetNode("/sim/presets/altitude-ft");
1688     static const SGPropertyNode *master_freeze
1689         = fgGetNode("/sim/freeze/master");
1690
1691     SG_LOG( SG_GENERAL, SG_INFO,
1692             "fgReInitSubsystems(): /position/altitude = "
1693             << altitude->getDoubleValue() );
1694
1695     bool freeze = master_freeze->getBoolValue();
1696     if ( !freeze ) {
1697         fgSetBool("/sim/freeze/master", true);
1698     }
1699
1700     // Initialize the FDM
1701     fgInitFDM();
1702     
1703     // allocates structures so must happen before any of the flight
1704     // model or control parameters are set
1705     fgAircraftInit();   // In the future this might not be the case.
1706
1707     // reload offsets from config defaults
1708     globals->get_viewmgr()->reinit();
1709
1710     fgInitView();
1711
1712     globals->get_controls()->reset_all();
1713     globals->get_autopilot()->reset();
1714
1715     fgUpdateSunPos();
1716     fgUpdateMoonPos();
1717     cur_light_params.Update();
1718     fgUpdateLocalTime();
1719
1720     if ( !freeze ) {
1721         fgSetBool("/sim/freeze/master", false);
1722     }
1723 }
1724