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