]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
f71573cffada0c0a89773ecebfaf5e597ee08380
[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.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     // Do a first guess if we should be on the ground or in the air
984     // (to be refined later based on other input.
985     if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
986         fgSetBool("/sim/presets/onground", false);
987     } else {
988         fgSetBool("/sim/presets/onground", true);
989     }
990
991     // If glideslope is specified, then calculate offset-distance or
992     // altitude relative to glide slope if either of those was not
993     // specified.
994     fgSetDistOrAltFromGlideSlope();
995
996     // If we have an explicit, in-range lon/lat, don't change it, just use it.
997     // If not, check for an airport-id and use that.
998     // If not, default to the middle of the KSFO field.
999     // The default values for lon/lat are deliberately out of range
1000     // so that the airport-id can take effect; valid lon/lat will
1001     // override airport-id, however.
1002     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1003     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1004     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1005          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1006     {
1007         set_pos = true;
1008     }
1009
1010     string apt = fgGetString("/sim/presets/airport-id");
1011     string rwy_no = fgGetString("/sim/presets/runway");
1012     double hdg = fgGetDouble("/sim/presets/heading-deg");
1013     string vor = fgGetString("/sim/presets/vor-id");
1014     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1015     string ndb = fgGetString("/sim/presets/ndb-id");
1016     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1017     string fix = fgGetString("/sim/presets/fix");
1018     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1019         // An airport + runway is requested
1020         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1021             // set position (a little off the heading for single
1022             // runway airports)
1023             fgSetTowerPosFromAirportID( apt, hdg );
1024
1025             set_pos = true;
1026         }
1027     }
1028     if ( !set_pos && !apt.empty() ) {
1029         // An airport is requested (find runway closest to hdg)
1030         bool ok = false;
1031         if (fgGetDouble("/sim/presets/altitude-ft") <= 0 &&
1032             fgGetDouble("/sim/presets/offset-distance") == 0)
1033             ok = fgSetPosFromAirportIDandHdg( apt, hdg );
1034         else
1035             ok = fgSetPosFromAirportID( apt );
1036             
1037         if (ok) {
1038                 // set position (a little off the heading for single
1039                 // runway airports)
1040                 fgSetTowerPosFromAirportID( apt, hdg );
1041
1042             set_pos = true;
1043         }
1044     }
1045     if ( !set_pos && !vor.empty() ) {
1046         // a VOR is requested
1047         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1048             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1049                 fgSetBool("/sim/presets/onground", false);
1050             } else {
1051                 fgSetBool("/sim/presets/onground", true);
1052             }
1053             set_pos = true;
1054         }
1055     }
1056     if ( !set_pos && !ndb.empty() ) {
1057         // an NDB is requested
1058         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1059             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1060                 fgSetBool("/sim/presets/onground", false);
1061             } else {
1062                 fgSetBool("/sim/presets/onground", true);
1063             }
1064             set_pos = true;
1065         }
1066     }
1067     if ( !set_pos && !fix.empty() ) {
1068         // a Fix is requested
1069         if ( fgSetPosFromFix( fix ) ) {
1070             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1071                 fgSetBool("/sim/presets/onground", false);
1072             } else {
1073                 fgSetBool("/sim/presets/onground", true);
1074             }
1075             set_pos = true;
1076         }
1077     }
1078
1079     if ( !set_pos ) {
1080         // No lon/lat specified, no airport specified, default to
1081         // middle of KSFO field.
1082         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1083         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1084     }
1085
1086     fgSetDouble( "/position/longitude-deg",
1087                  fgGetDouble("/sim/presets/longitude-deg") );
1088     fgSetDouble( "/position/latitude-deg",
1089                  fgGetDouble("/sim/presets/latitude-deg") );
1090     fgSetDouble( "/orientation/heading-deg",
1091                  fgGetDouble("/sim/presets/heading-deg") );
1092
1093     return true;
1094 }
1095
1096
1097 // General house keeping initializations
1098 bool fgInitGeneral() {
1099     string root;
1100
1101 #if defined(FX) && defined(XMESA)
1102     char *mesa_win_state;
1103 #endif
1104
1105     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1106     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1107
1108     root = globals->get_fg_root();
1109     if ( ! root.length() ) {
1110         // No root path set? Then bail ...
1111         SG_LOG( SG_GENERAL, SG_ALERT,
1112                 "Cannot continue without a path to the base package "
1113                 << "being defined." );
1114         exit(-1);
1115     }
1116     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1117
1118 #if defined(FX) && defined(XMESA)
1119     // initialize full screen flag
1120     globals->set_fullscreen(false);
1121     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1122         // Test for the MESA_GLX_FX env variable
1123         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1124             // test if we are fullscreen mesa/glide
1125             if ( (mesa_win_state[0] == 'f') ||
1126                  (mesa_win_state[0] == 'F') ) {
1127                 globals->set_fullscreen(true);
1128             }
1129         }
1130     }
1131 #endif
1132
1133     return true;
1134 }
1135
1136
1137 // Initialize the flight model subsystem.  This just creates the
1138 // object.  The actual fdm initialization is delayed until we get a
1139 // proper scenery elevation hit.  This is checked for in main.cxx
1140
1141 void fgInitFDM() {
1142
1143     if ( cur_fdm_state ) {
1144         delete cur_fdm_state;
1145         cur_fdm_state = 0;
1146     }
1147
1148     double dt = 1.0 / fgGetInt("/sim/model-hz");
1149     aircraft_dir = fgGetString("/sim/aircraft-dir");
1150     const string &model = fgGetString("/sim/flight-model");
1151
1152     try {
1153         if ( model == "larcsim" ) {
1154             cur_fdm_state = new FGLaRCsim( dt );
1155         } else if ( model == "jsb" ) {
1156             cur_fdm_state = new FGJSBsim( dt );
1157         } else if ( model == "ada" ) {
1158             cur_fdm_state = new FGADA( dt );
1159         } else if ( model == "balloon" ) {
1160             cur_fdm_state = new FGBalloonSim( dt );
1161         } else if ( model == "magic" ) {
1162             cur_fdm_state = new FGMagicCarpet( dt );
1163         } else if ( model == "ufo" ) {
1164             cur_fdm_state = new FGUFO( dt );
1165         } else if ( model == "external" ) {
1166             // external is a synonym for "--fdm=null" and is
1167             // maintained here for backwards compatibility
1168             cur_fdm_state = new FGNullFDM( dt );
1169         } else if ( model.find("network") == 0 ) {
1170             string host = "localhost";
1171             int port1 = 5501;
1172             int port2 = 5502;
1173             int port3 = 5503;
1174             string net_options = model.substr(8);
1175             string::size_type begin, end;
1176             begin = 0;
1177             // host
1178             end = net_options.find( ",", begin );
1179             if ( end != string::npos ) {
1180                 host = net_options.substr(begin, end - begin);
1181                 begin = end + 1;
1182             }
1183             // port1
1184             end = net_options.find( ",", begin );
1185             if ( end != string::npos ) {
1186                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1187                 begin = end + 1;
1188             }
1189             // port2
1190             end = net_options.find( ",", begin );
1191             if ( end != string::npos ) {
1192                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1193                 begin = end + 1;
1194             }
1195             // port3
1196             end = net_options.find( ",", begin );
1197             if ( end != string::npos ) {
1198                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1199                 begin = end + 1;
1200             }
1201             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1202         } else if ( model.find("pipe") == 0 ) {
1203             string pipe_path = model.substr(5);
1204             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1205         } else if ( model == "null" ) {
1206             cur_fdm_state = new FGNullFDM( dt );
1207         } else if ( model == "yasim" ) {
1208             cur_fdm_state = new YASim( dt );
1209         } else {
1210             SG_LOG(SG_GENERAL, SG_ALERT,
1211                    "Unrecognized flight model '" << model
1212                    << "', cannot init flight dynamics model.");
1213             exit(-1);
1214         }
1215     } catch ( ... ) {
1216         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1217         exit(-1);
1218     }
1219 }
1220
1221 static void printMat(const sgVec4 *mat, char *name="")
1222 {
1223     int i;
1224     SG_LOG(SG_GENERAL, SG_BULK, name );
1225     for(i=0; i<4; i++) {
1226         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1227                                     << " " << mat[i][2] << " " << mat[i][3] );
1228     }
1229 }
1230
1231 // Initialize view parameters
1232 void fgInitView() {
1233   // force update of model so that viewer can get some data...
1234   globals->get_aircraft_model()->update(0);
1235   // run update for current view so that data is current...
1236   globals->get_viewmgr()->update(0);
1237
1238   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1239   printMat(globals->get_current_view()->get_UP(),"UP");
1240   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1241   
1242 }
1243
1244
1245 SGTime *fgInitTime() {
1246     // Initialize time
1247     static const SGPropertyNode *longitude
1248         = fgGetNode("/position/longitude-deg");
1249     static const SGPropertyNode *latitude
1250         = fgGetNode("/position/latitude-deg");
1251     static const SGPropertyNode *cur_time_override
1252         = fgGetNode("/sim/time/cur-time-override", true);
1253
1254     SGPath zone( globals->get_fg_root() );
1255     zone.append( "Timezone" );
1256     SGTime *t = new SGTime( longitude->getDoubleValue()
1257                               * SGD_DEGREES_TO_RADIANS,
1258                             latitude->getDoubleValue()
1259                               * SGD_DEGREES_TO_RADIANS,
1260                             zone.str(),
1261                             cur_time_override->getLongValue() );
1262
1263     // Handle potential user specified time offsets
1264     time_t cur_time = t->get_cur_time();
1265     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1266     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1267     time_t aircraftLocalTime = 
1268         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1269
1270     // Okay, we now have six possible scenarios
1271     int offset = fgGetInt("/sim/startup/time-offset");
1272     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1273     if (offset_type == "system-offset") {
1274         globals->set_warp( offset );
1275     } else if (offset_type == "gmt-offset") {
1276         globals->set_warp( offset - (currGMT - systemLocalTime) );
1277     } else if (offset_type == "latitude-offset") {
1278         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1279     } else if (offset_type == "system") {
1280         globals->set_warp( offset - cur_time );
1281     } else if (offset_type == "gmt") {
1282         globals->set_warp( offset - currGMT );
1283     } else if (offset_type == "latitude") {
1284         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1285                            cur_time ); 
1286     } else {
1287         SG_LOG( SG_GENERAL, SG_ALERT,
1288                 "FG_TIME::Unsupported offset type " << offset_type );
1289         exit( -1 );
1290     }
1291
1292     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1293             << globals->get_warp() );
1294
1295     globals->set_warp_delta( 0 );
1296
1297     t->update( 0.0, 0.0,
1298                cur_time_override->getLongValue(),
1299                globals->get_warp() );
1300
1301     return t;
1302 }
1303
1304
1305 // This is the top level init routine which calls all the other
1306 // initialization routines.  If you are adding a subsystem to flight
1307 // gear, its initialization call should located in this routine.
1308 // Returns non-zero if a problem encountered.
1309 bool fgInitSubsystems() {
1310     // static const SGPropertyNode *longitude
1311     //     = fgGetNode("/sim/presets/longitude-deg");
1312     // static const SGPropertyNode *latitude
1313     //     = fgGetNode("/sim/presets/latitude-deg");
1314     // static const SGPropertyNode *altitude
1315     //     = fgGetNode("/sim/presets/altitude-ft");
1316
1317     fgLIGHT *l = &cur_light_params;
1318
1319     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1320     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1321
1322
1323     ////////////////////////////////////////////////////////////////////
1324     // Initialize the material property subsystem.
1325     ////////////////////////////////////////////////////////////////////
1326
1327     SGPath mpath( globals->get_fg_root() );
1328     mpath.append( "materials.xml" );
1329     if ( ! material_lib.load( globals->get_fg_root(), mpath.str() ) ) {
1330         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1331         exit(-1);
1332     }
1333
1334     ////////////////////////////////////////////////////////////////////
1335     // Initialize the event manager subsystem.
1336     ////////////////////////////////////////////////////////////////////
1337
1338     global_events.init();
1339
1340     // Output event stats every 60 seconds
1341     global_events.Register( "FGEventMgr::print_stats()",
1342                             &global_events, &FGEventMgr::print_stats,
1343                             60000 );
1344
1345
1346     ////////////////////////////////////////////////////////////////////
1347     // Initialize the scenery management subsystem.
1348     ////////////////////////////////////////////////////////////////////
1349
1350     if ( globals->get_tile_mgr()->init() ) {
1351         // Load the local scenery data
1352         double visibility_meters = fgGetDouble("/environment/visibility-m");
1353                 
1354         globals->get_tile_mgr()->update( visibility_meters );
1355     } else {
1356         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1357         exit(-1);
1358     }
1359
1360     // cause refresh of viewer scenery timestamps every 15 seconds...
1361     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1362                             globals->get_tile_mgr(),
1363                             &FGTileMgr::refresh_view_timestamps,
1364                             15000 );
1365
1366     SG_LOG( SG_GENERAL, SG_DEBUG,
1367             "Current terrain elevation after tile mgr init " <<
1368             globals->get_scenery()->get_cur_elev() );
1369
1370
1371     ////////////////////////////////////////////////////////////////////
1372     // Initialize the flight model subsystem.
1373     ////////////////////////////////////////////////////////////////////
1374
1375     fgInitFDM();
1376         
1377     // allocates structures so must happen before any of the flight
1378     // model or control parameters are set
1379     fgAircraftInit();   // In the future this might not be the case.
1380
1381
1382     ////////////////////////////////////////////////////////////////////
1383     // Initialize the view manager subsystem.
1384     ////////////////////////////////////////////////////////////////////
1385
1386     fgInitView();
1387
1388
1389     ////////////////////////////////////////////////////////////////////
1390     // Initialize the lighting subsystem.
1391     ////////////////////////////////////////////////////////////////////
1392
1393     // fgUpdateSunPos() needs a few position and view parameters set
1394     // so it can calculate local relative sun angle and a few other
1395     // things for correctly orienting the sky.
1396     fgUpdateSunPos();
1397     fgUpdateMoonPos();
1398     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1399                             60000);
1400     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1401                             60000);
1402
1403     // Initialize Lighting interpolation tables
1404     l->Init();
1405
1406     // force one lighting update to make it right to start with...
1407     l->Update();
1408     // update the lighting parameters (based on sun angle)
1409     global_events.Register( "fgLight::Update()",
1410                             &cur_light_params, &fgLIGHT::Update,
1411                             30000 );
1412
1413
1414     ////////////////////////////////////////////////////////////////////
1415     // Create and register the logger.
1416     ////////////////////////////////////////////////////////////////////
1417     
1418     globals->add_subsystem("logger", new FGLogger);
1419
1420
1421 #if defined(HAVE_PLIB_PSL)
1422     ////////////////////////////////////////////////////////////////////
1423     // Create and register the script manager.
1424     ////////////////////////////////////////////////////////////////////
1425
1426     globals->add_subsystem("scripting", new FGScriptMgr);
1427 #endif // HAVE_PLIB_PSL
1428
1429
1430     ////////////////////////////////////////////////////////////////////
1431     // Create and register the XML GUI.
1432     ////////////////////////////////////////////////////////////////////
1433
1434     globals->add_subsystem("gui", new NewGUI, FGSubsystemMgr::INIT);
1435
1436
1437     ////////////////////////////////////////////////////////////////////
1438     // Initialize the local time subsystem.
1439     ////////////////////////////////////////////////////////////////////
1440
1441     // update the current timezone each 30 minutes
1442     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1443                             30*60*1000 );
1444
1445
1446     ////////////////////////////////////////////////////////////////////
1447     // Initialize the weather subsystem.
1448     ////////////////////////////////////////////////////////////////////
1449
1450     // Initialize the weather modeling subsystem
1451 #ifdef FG_WEATHERCM
1452     // Initialize the WeatherDatabase
1453     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1454     sgVec3 position;
1455     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1456                current_aircraft.fdm_state->get_Longitude(),
1457                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1458     double init_vis = fgGetDouble("/environment/visibility-m");
1459
1460     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1461
1462     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1463     {
1464       working_type = FGLocalWeatherDatabase::use_internet;
1465     } else {
1466       working_type = FGLocalWeatherDatabase::default_mode;
1467     }
1468     
1469     if ( init_vis > 0 ) {
1470       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1471         new FGLocalWeatherDatabase( position,
1472                                     globals->get_fg_root(),
1473                                     working_type,
1474                                     init_vis );
1475     } else {
1476       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1477         new FGLocalWeatherDatabase( position,
1478                                     globals->get_fg_root(),
1479                                     working_type );
1480     }
1481
1482     // cout << theFGLocalWeatherDatabase << endl;
1483     // cout << "visibility = " 
1484     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1485
1486     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1487
1488     // register the periodic update of the weather
1489     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1490                             30000);
1491 #else
1492     globals->get_environment_mgr()->init();
1493     globals->get_environment_mgr()->bind();
1494 #endif
1495
1496 #ifdef FG_USE_CLOUDS_3D
1497     ////////////////////////////////////////////////////////////////////
1498     // Initialize the 3D cloud subsystem.
1499     ////////////////////////////////////////////////////////////////////
1500     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1501         SGPath cloud_path(globals->get_fg_root());
1502         cloud_path.append("large.sky");
1503         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1504         if ( !sgCloud3d->Load( cloud_path.str(),
1505                                latitude->getDoubleValue(),
1506                                longitude->getDoubleValue()) )
1507         {
1508             fgSetBool("/sim/rendering/clouds3d", false);
1509             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1510         }
1511         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1512     }
1513 #endif
1514
1515     ////////////////////////////////////////////////////////////////////
1516     // Initialise ATC display system
1517     ////////////////////////////////////////////////////////////////////
1518
1519     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1520     globals->set_ATC_display(new FGATCDisplay);
1521     globals->get_ATC_display()->init(); 
1522
1523     ////////////////////////////////////////////////////////////////////
1524     // Initialise the ATC Manager 
1525     ////////////////////////////////////////////////////////////////////
1526
1527     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1528     globals->set_ATC_mgr(new FGATCMgr);
1529     globals->get_ATC_mgr()->init(); 
1530     
1531     ////////////////////////////////////////////////////////////////////
1532     // Initialise the AI Manager 
1533     ////////////////////////////////////////////////////////////////////
1534
1535     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1536     globals->set_AI_mgr(new FGAIMgr);
1537     globals->get_AI_mgr()->init();
1538
1539
1540 #ifdef ENABLE_AUDIO_SUPPORT
1541     ////////////////////////////////////////////////////////////////////
1542     // Initialize the sound subsystem.
1543     ////////////////////////////////////////////////////////////////////
1544
1545     globals->set_soundmgr(new SGSoundMgr);
1546     globals->get_soundmgr()->init();
1547     globals->get_soundmgr()->bind();
1548
1549
1550     ////////////////////////////////////////////////////////////////////
1551     // Initialize the sound-effects subsystem.
1552     ////////////////////////////////////////////////////////////////////
1553
1554     globals->add_subsystem("fx", new FGFX);
1555     
1556 #endif
1557
1558     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1559     globals->add_subsystem("systems", new FGSystemMgr);
1560
1561     ////////////////////////////////////////////////////////////////////
1562     // Initialize the radio stack subsystem.
1563     ////////////////////////////////////////////////////////////////////
1564
1565     current_radiostack = new FGRadioStack;
1566     current_radiostack->init();
1567     current_radiostack->bind();
1568
1569
1570     ////////////////////////////////////////////////////////////////////
1571     // Initialize the cockpit subsystem
1572     ////////////////////////////////////////////////////////////////////
1573
1574     if( fgCockpitInit( &current_aircraft )) {
1575         // Cockpit initialized ok.
1576     } else {
1577         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1578         exit(-1);
1579     }
1580
1581
1582     ////////////////////////////////////////////////////////////////////
1583     // Initialize the autopilot subsystem.
1584     ////////////////////////////////////////////////////////////////////
1585
1586     globals->set_autopilot(new FGAutopilot);
1587     globals->get_autopilot()->init();
1588     globals->get_autopilot()->bind();
1589
1590                                 // FIXME: these should go in the
1591                                 // GUI initialization code, not here.
1592     fgAPAdjustInit();
1593     NewTgtAirportInit();
1594     NewHeadingInit();
1595     NewAltitudeInit();
1596
1597     ////////////////////////////////////////////////////////////////////
1598     // Initialize I/O subsystem.
1599     ////////////////////////////////////////////////////////////////////
1600
1601     globals->get_io()->init();
1602     globals->get_io()->bind();
1603
1604
1605     ////////////////////////////////////////////////////////////////////
1606     // Add a new 2D panel.
1607     ////////////////////////////////////////////////////////////////////
1608
1609     string panel_path = fgGetString("/sim/panel/path",
1610                                     "Panels/Default/default.xml");
1611
1612     globals->set_current_panel( fgReadPanel(panel_path) );
1613     if (globals->get_current_panel() == 0) {
1614         SG_LOG( SG_INPUT, SG_ALERT, 
1615                 "Error reading new panel from " << panel_path );
1616     } else {
1617         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1618         globals->get_current_panel()->init();
1619         globals->get_current_panel()->bind();
1620     }
1621
1622     
1623     ////////////////////////////////////////////////////////////////////
1624     // Initialize the default (kludged) properties.
1625     ////////////////////////////////////////////////////////////////////
1626
1627     fgInitProps();
1628
1629
1630     ////////////////////////////////////////////////////////////////////
1631     // Initialize the controls subsystem.
1632     ////////////////////////////////////////////////////////////////////
1633
1634     globals->get_controls()->init();
1635     globals->get_controls()->bind();
1636
1637
1638     ////////////////////////////////////////////////////////////////////
1639     // Initialize the input subsystem.
1640     ////////////////////////////////////////////////////////////////////
1641
1642     globals->add_subsystem("input", new FGInput);
1643
1644
1645     ////////////////////////////////////////////////////////////////////
1646     // Bind and initialize subsystems.
1647     ////////////////////////////////////////////////////////////////////
1648
1649     globals->get_subsystem_mgr()->bind();
1650     globals->get_subsystem_mgr()->init();
1651
1652
1653 #ifdef FG_MPLAYER_AS
1654     ////////////////////////////////////////////////////////////////////
1655     // Initialize multiplayer subsystem
1656     ////////////////////////////////////////////////////////////////////
1657
1658     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1659     globals->get_multiplayer_tx_mgr()->init();
1660
1661     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1662     globals->get_multiplayer_rx_mgr()->init();
1663 #endif
1664
1665     ////////////////////////////////////////////////////////////////////////
1666     // End of subsystem initialization.
1667     ////////////////////////////////////////////////////////////////////
1668
1669     SG_LOG( SG_GENERAL, SG_INFO, endl);
1670
1671                                 // Save the initial state for future
1672                                 // reference.
1673     globals->saveInitialState();
1674
1675     return true;
1676 }
1677
1678
1679 void fgReInitSubsystems()
1680 {
1681     // static const SGPropertyNode *longitude
1682     //     = fgGetNode("/sim/presets/longitude-deg");
1683     // static const SGPropertyNode *latitude
1684     //     = fgGetNode("/sim/presets/latitude-deg");
1685     static const SGPropertyNode *altitude
1686         = fgGetNode("/sim/presets/altitude-ft");
1687     static const SGPropertyNode *master_freeze
1688         = fgGetNode("/sim/freeze/master");
1689
1690     SG_LOG( SG_GENERAL, SG_INFO,
1691             "fgReInitSubsystems(): /position/altitude = "
1692             << altitude->getDoubleValue() );
1693
1694     bool freeze = master_freeze->getBoolValue();
1695     if ( !freeze ) {
1696         fgSetBool("/sim/freeze/master", true);
1697     }
1698
1699     // Initialize the FDM
1700     fgInitFDM();
1701     
1702     // allocates structures so must happen before any of the flight
1703     // model or control parameters are set
1704     fgAircraftInit();   // In the future this might not be the case.
1705
1706     // reload offsets from config defaults
1707     globals->get_viewmgr()->reinit();
1708
1709     fgInitView();
1710
1711     globals->get_controls()->reset_all();
1712     globals->get_autopilot()->reset();
1713
1714     fgUpdateSunPos();
1715     fgUpdateMoonPos();
1716     cur_light_params.Update();
1717     fgUpdateLocalTime();
1718
1719     if ( !freeze ) {
1720         fgSetBool("/sim/freeze/master", false);
1721     }
1722 }
1723