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