]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
0c9fbd52192f0913d8ab1f39871924a5db1ea709
[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 <GL/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/timing/sg_time.hxx>
67 #include <simgear/timing/lowleveltime.h>
68
69 #include <Aircraft/aircraft.hxx>
70 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
71 #include <Airports/runways.hxx>
72 #include <Airports/simple.hxx>
73 #include <ATC/ATCdisplay.hxx>
74 #include <ATC/ATCmgr.hxx>
75 #include <ATC/atislist.hxx>
76 #include <ATC/towerlist.hxx>
77 #include <ATC/approachlist.hxx>
78 #include <ATC/AIMgr.hxx>
79 #include <Autopilot/auto_gui.hxx>
80 #include <Autopilot/newauto.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/radiostack.hxx>
83 #include <Cockpit/panel.hxx>
84 #include <Cockpit/panel_io.hxx>
85 #include <FDM/ADA.hxx>
86 #include <FDM/Balloon.h>
87 #include <FDM/External.hxx>
88 #include <FDM/ExternalNet.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim.hxx>
91 #include <FDM/MagicCarpet.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <Include/general.hxx>
95 #include <Input/input.hxx>
96 // #include <Joystick/joystick.hxx>
97 #include <Objects/matlib.hxx>
98 #include <Model/acmodel.hxx>
99 #include <Navaids/fixlist.hxx>
100 #include <Navaids/ilslist.hxx>
101 #include <Navaids/mkrbeacons.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Sound/fg_fx.hxx>
106 #include <Sound/soundmgr.hxx>
107 #include <Time/FGEventMgr.hxx>
108 #include <Time/light.hxx>
109 #include <Time/sunpos.hxx>
110 #include <Time/moonpos.hxx>
111 #include <Time/tmp.hxx>
112
113 #ifndef FG_NEW_ENVIRONMENT
114 #  include <WeatherCM/FGLocalWeatherDatabase.h>
115 #else
116 #  include <Environment/environment_mgr.hxx>
117 #endif
118
119 #include "fg_init.hxx"
120 #include "fg_io.hxx"
121 #include "fg_commands.hxx"
122 #include "fg_props.hxx"
123 #include "options.hxx"
124 #include "globals.hxx"
125 #include "logger.hxx"
126 #include "viewmgr.hxx"
127
128 #if defined(FX) && defined(XMESA)
129 #include <GL/xmesa.h>
130 #endif
131
132 SG_USING_STD(string);
133
134 extern const char *default_root;
135
136
137 // Read in configuration (file and command line) and just set fg_root
138 bool fgInitFGRoot ( int argc, char **argv ) {
139     string root;
140     char* envp;
141
142     // First parse command line options looking for fg-root, this will
143     // override anything specified in a config file
144     root = fgScanForRoot(argc, argv);
145
146 #if defined( unix ) || defined( __CYGWIN__ )
147     // Next check home directory for .fgfsrc.hostname file
148     if ( root.empty() ) {
149         envp = ::getenv( "HOME" );
150         if ( envp != NULL ) {
151             SGPath config( envp );
152             config.append( ".fgfsrc" );
153             char name[256];
154             gethostname( name, 256 );
155             config.concat( "." );
156             config.concat( name );
157             root = fgScanForRoot(config.str());
158         }
159     }
160 #endif
161
162     // Next check home directory for .fgfsrc file
163     if ( root.empty() ) {
164         envp = ::getenv( "HOME" );
165         if ( envp != NULL ) {
166             SGPath config( envp );
167             config.append( ".fgfsrc" );
168             root = fgScanForRoot(config.str());
169         }
170     }
171     
172     // Next check if fg-root is set as an env variable
173     if ( root.empty() ) {
174         envp = ::getenv( "FG_ROOT" );
175         if ( envp != NULL ) {
176             root = envp;
177         }
178     }
179
180     // Otherwise, default to a random compiled-in location if we can't
181     // find fg-root any other way.
182     if ( root.empty() ) {
183 #if defined( __CYGWIN__ )
184         root = "/FlightGear";
185 #elif defined( WIN32 )
186         root = "\\FlightGear";
187 #elif defined( macintosh )
188         root = "";
189 #else
190         root = PKGLIBDIR;
191 #endif
192     }
193
194     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
195     globals->set_fg_root(root);
196
197     return true;
198 }
199
200
201 // Return the current base package version
202 string fgBasePackageVersion() {
203     SGPath base_path( globals->get_fg_root() );
204     base_path.append("version");
205
206     sg_gzifstream in( base_path.str() );
207     if ( !in.is_open() ) {
208         SGPath old_path( globals->get_fg_root() );
209         old_path.append( "Thanks" );
210         sg_gzifstream old( old_path.str() );
211         if ( !old.is_open() ) {
212             return "[none]";
213         } else {
214             return "[old version]";
215         }
216     }
217
218     string version;
219     in >> version;
220
221     return version;
222 }
223
224
225 // Read in configuration (file and command line)
226 bool fgInitConfig ( int argc, char **argv ) {
227
228                                 // First, set some sane default values
229     fgSetDefaults();
230
231     // Read global preferences from $FG_ROOT/preferences.xml
232     SGPath props_path(globals->get_fg_root());
233     props_path.append("preferences.xml");
234     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
235     readProperties(props_path.str(), globals->get_props());
236     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
237
238     // Read the default aircraft config file.
239     string aircraft = fgGetString("/sim/aircraft", "");
240     if (aircraft.size() > 0) {
241       SGPath aircraft_path(globals->get_fg_root());
242       aircraft_path.append("Aircraft");
243       aircraft_path.append(aircraft);
244       aircraft_path.concat("-set.xml");
245       SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
246              << " from " << aircraft_path.str());
247       try {
248         readProperties(aircraft_path.str(), globals->get_props());
249       } catch (const sg_exception &e) {
250         string message = "Error reading default aircraft: ";
251         message += e.getFormattedMessage();
252         SG_LOG(SG_INPUT, SG_ALERT, message);
253         exit(2);
254       }
255     } else {
256       SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
257     }
258
259     // Attempt to locate and parse the various config files in order
260     // from least precidence to greatest precidence
261
262     // Check for $fg_root/system.fgfsrc
263     SGPath config( globals->get_fg_root() );
264     config.append( "system.fgfsrc" );
265     fgParseOptions(config.str());
266
267     char name[256];
268 #if defined( unix ) || defined( __CYGWIN__ )
269     // Check for $fg_root/system.fgfsrc.hostname
270     gethostname( name, 256 );
271     config.concat( "." );
272     config.concat( name );
273     fgParseOptions(config.str());
274 #endif
275
276     // Check for ~/.fgfsrc
277     char* envp = ::getenv( "HOME" );
278     if ( envp != NULL ) {
279         config.set( envp );
280         config.append( ".fgfsrc" );
281         fgParseOptions(config.str());
282     }
283
284 #if defined( unix ) || defined( __CYGWIN__ )
285     // Check for ~/.fgfsrc.hostname
286     gethostname( name, 256 );
287     config.concat( "." );
288     config.concat( name );
289     fgParseOptions(config.str());
290 #endif
291
292     // Parse remaining command line options
293     // These will override anything specified in a config file
294     fgParseArgs(argc, argv);
295
296     return true;
297 }
298
299
300 // find basic airport location info from airport database
301 bool fgFindAirportID( const string& id, FGAirport *a ) {
302     if ( id.length() ) {
303         SGPath path( globals->get_fg_root() );
304         path.append( "Airports" );
305         path.append( "simple.mk4" );
306         FGAirports airports( path.c_str() );
307
308         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
309
310         if ( ! airports.search( id, a ) ) {
311             SG_LOG( SG_GENERAL, SG_ALERT,
312                     "Failed to find " << id << " in " << path.str() );
313             return false;
314         }
315     } else {
316         return false;
317     }
318
319     SG_LOG( SG_GENERAL, SG_INFO,
320             "Position for " << id << " is ("
321             << a->longitude << ", "
322             << a->latitude << ")" );
323
324     return true;
325 }
326
327
328 // Set current_options lon/lat given an airport id
329 bool fgSetPosFromAirportID( const string& id ) {
330     FGAirport a;
331     // double lon, lat;
332
333     SG_LOG( SG_GENERAL, SG_INFO,
334             "Attempting to set starting position from airport code " << id );
335
336     if ( fgFindAirportID( id, &a ) ) {
337         fgSetDouble("/position/longitude-deg",  a.longitude );
338         fgSetDouble("/position/latitude-deg",  a.latitude );
339         SG_LOG( SG_GENERAL, SG_INFO,
340                 "Position for " << id << " is ("
341                 << a.longitude << ", "
342                 << a.latitude << ")" );
343
344         return true;
345     } else {
346         return false;
347     }
348
349 }
350
351
352
353 // Set current tower position lon/lat given an airport id
354 bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
355     FGAirport a;
356     // tower height hard coded for now...
357     float towerheight=50.0f;
358
359     // make a little off the heading for 1 runway airports...
360     float fudge_lon = fabs(sin(hdg)) * .003f;
361     float fudge_lat = .003f - fudge_lon;
362
363     if ( fgFindAirportID( id, &a ) ) {
364         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
365         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
366         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
367         return true;
368     } else {
369         return false;
370     }
371
372 }
373
374
375 // Set current_options lon/lat given an airport id and heading (degrees)
376 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
377     FGRunway r;
378     FGRunway found_r;
379     double found_dir = 0.0;
380
381     if ( id.length() ) {
382         // set initial position from runway and heading
383
384         SGPath path( globals->get_fg_root() );
385         path.append( "Airports" );
386         path.append( "runways.mk4" );
387         FGRunways runways( path.c_str() );
388
389         SG_LOG( SG_GENERAL, SG_INFO,
390                 "Attempting to set starting position from runway code "
391                 << id << " heading " << tgt_hdg );
392
393         // SGPath inpath( globals->get_fg_root() );
394         // inpath.append( "Airports" );
395         // inpath.append( "apt_simple" );
396         // airports.load( inpath.c_str() );
397
398         // SGPath outpath( globals->get_fg_root() );
399         // outpath.append( "Airports" );
400         // outpath.append( "simple.gdbm" );
401         // airports.dump_gdbm( outpath.c_str() );
402
403         if ( ! runways.search( id, &r ) ) {
404             SG_LOG( SG_GENERAL, SG_ALERT,
405                     "Failed to find " << id << " in database." );
406             return false;
407         }
408
409         double diff;
410         double min_diff = 360.0;
411
412         while ( r.id == id ) {
413             // forward direction
414             diff = tgt_hdg - r.heading;
415             while ( diff < -180.0 ) { diff += 360.0; }
416             while ( diff >  180.0 ) { diff -= 360.0; }
417             diff = fabs(diff);
418             SG_LOG( SG_GENERAL, SG_INFO,
419                     "Runway " << r.rwy_no << " heading = " << r.heading <<
420                     " diff = " << diff );
421             if ( diff < min_diff ) {
422                 min_diff = diff;
423                 found_r = r;
424                 found_dir = 0;
425             }
426
427             // reverse direction
428             diff = tgt_hdg - r.heading - 180.0;
429             while ( diff < -180.0 ) { diff += 360.0; }
430             while ( diff >  180.0 ) { diff -= 360.0; }
431             diff = fabs(diff);
432             SG_LOG( SG_GENERAL, SG_INFO,
433                     "Runway -" << r.rwy_no << " heading = " <<
434                     r.heading + 180.0 <<
435                     " diff = " << diff );
436             if ( diff < min_diff ) {
437                 min_diff = diff;
438                 found_r = r;
439                 found_dir = 180.0;
440             }
441
442             runways.next( &r );
443         }
444
445         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
446                 << " + " << found_dir );
447
448     } else {
449         return false;
450     }
451
452     double heading = found_r.heading + found_dir;
453     while ( heading >= 360.0 ) { heading -= 360.0; }
454
455     double lat2, lon2, az2;
456     double azimuth = found_r.heading + found_dir + 180.0;
457     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
458
459     SG_LOG( SG_GENERAL, SG_INFO,
460             "runway =  " << found_r.lon << ", " << found_r.lat
461             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
462             << " heading = " << azimuth );
463     
464     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
465                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
466                         &lat2, &lon2, &az2 );
467
468     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > SG_EPSILON ) {
469         double olat, olon;
470         double odist = fgGetDouble("/sim/startup/offset-distance");
471         odist *= SG_NM_TO_METER;
472         double oaz = azimuth;
473         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > SG_EPSILON ) {
474             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
475         }
476         while ( oaz >= 360.0 ) { oaz -= 360.0; }
477         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
478         lat2=olat;
479         lon2=olon;
480     }
481         
482     fgSetDouble("/position/longitude-deg",  lon2 );
483     fgSetDouble("/position/latitude-deg",  lat2 );
484     fgSetDouble("/orientation/heading-deg", heading );
485
486     SG_LOG( SG_GENERAL, SG_INFO,
487             "Position for " << id << " is ("
488             << lon2 << ", "
489             << lat2 << ") new heading is "
490             << heading );
491
492     return true;
493 }
494
495 void fgSetPosFromGlideSlope(void) {
496     double gs = fgGetDouble("/velocities/glideslope");
497     double od = fgGetDouble("/sim/startup/offset-distance");
498     double alt = fgGetDouble("/position/altitude-ft");
499     
500     //if glideslope and offset-distance are set and altitude is
501     //not, calculate the initial altitude
502     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
503         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
504         alt = fabs(od*tan(gs));
505         fgSetDouble("/position/altitude-ft",alt);
506         fgSetBool("/sim/startup/onground", false);
507         SG_LOG(SG_GENERAL,SG_INFO, "Calculated altitude as: " << alt  << " ft");
508     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
509         od  = alt/tan(gs);
510         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
511         fgSetDouble("/sim/startup/offset-distance",od);
512         SG_LOG(SG_GENERAL,SG_INFO, "Calculated offset distance as: " 
513                                        << od  << " nm");
514     } else if( fabs(gs) > 0.01 ) {
515         SG_LOG(SG_GENERAL,SG_ALERT, "Glideslope given but not altitude" 
516                                   << " or offset-distance.  Resetting"
517                                   << " glideslope to zero" );
518         fgSetDouble("/velocities/glideslope",0);                                  
519     }                              
520                                       
521 }                       
522
523 // General house keeping initializations
524 bool fgInitGeneral( void ) {
525     string root;
526
527 #if defined(FX) && defined(XMESA)
528     char *mesa_win_state;
529 #endif
530
531     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
532     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
533
534     root = globals->get_fg_root();
535     if ( ! root.length() ) {
536         // No root path set? Then bail ...
537         SG_LOG( SG_GENERAL, SG_ALERT,
538                 "Cannot continue without a path to the base package "
539                 << "being defined." );
540         exit(-1);
541     }
542     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
543
544 #if defined(FX) && defined(XMESA)
545     // initialize full screen flag
546     globals->set_fullscreen(false);
547     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
548         // Test for the MESA_GLX_FX env variable
549         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
550             // test if we are fullscreen mesa/glide
551             if ( (mesa_win_state[0] == 'f') ||
552                  (mesa_win_state[0] == 'F') ) {
553                 globals->set_fullscreen(true);
554             }
555         }
556     }
557 #endif
558
559     return true;
560 }
561
562
563 // Initialize the flight model subsystem.  This just creates the
564 // object.  The actual fdm initialization is delayed until we get a
565 // proper scenery elevation hit.  This is checked for in main.cxx
566
567 void fgInitFDM() {
568
569     if ( cur_fdm_state ) {
570         delete cur_fdm_state;
571         cur_fdm_state = 0;
572     }
573
574     double dt = 1.0 / fgGetInt("/sim/model-hz");
575     aircraft_dir = fgGetString("/sim/aircraft-dir");
576     const string &model = fgGetString("/sim/flight-model");
577
578     try {
579         if ( model == "larcsim" ) {
580             cur_fdm_state = new FGLaRCsim( dt );
581         } else if ( model == "jsb" ) {
582             cur_fdm_state = new FGJSBsim( dt );
583         } else if ( model == "ada" ) {
584             cur_fdm_state = new FGADA( dt );
585         } else if ( model == "balloon" ) {
586             cur_fdm_state = new FGBalloonSim( dt );
587         } else if ( model == "magic" ) {
588             cur_fdm_state = new FGMagicCarpet( dt );
589         } else if ( model == "external" ) {
590             cur_fdm_state = new FGExternal( dt );
591         } else if ( model.find("network,") == 0 ) {
592             string host = "localhost";
593             int port1 = 5501;
594             int port2 = 5502;
595             int port3 = 5503;
596             string net_options = model.substr(8);
597             string::size_type begin, end;
598             begin = 0;
599             // host
600             end = net_options.find( ",", begin );
601             if ( end != string::npos ) {
602                 host = net_options.substr(begin, end - begin);
603                 begin = end + 1;
604             }
605             // port1
606             end = net_options.find( ",", begin );
607             if ( end != string::npos ) {
608                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
609                 begin = end + 1;
610             }
611             // port2
612             end = net_options.find( ",", begin );
613             if ( end != string::npos ) {
614                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
615                 begin = end + 1;
616             }
617             // port3
618             end = net_options.find( ",", begin );
619             if ( end != string::npos ) {
620                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
621                 begin = end + 1;
622             }
623             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
624         } else if ( model == "null" ) {
625             cur_fdm_state = new FGNullFDM( dt );
626         } else if ( model == "yasim" ) {
627             cur_fdm_state = new YASim( dt );
628         } else {
629             SG_LOG(SG_GENERAL, SG_ALERT,
630                    "Unrecognized flight model '" << model
631                    << "', cannot init flight dynamics model.");
632             exit(-1);
633         }
634     } catch ( ... ) {
635         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
636         exit(-1);
637     }
638 }
639
640
641 // Initialize view parameters
642 void fgInitView() {
643   // force update of model so that viewer can get some data...
644   globals->get_aircraft_model()->update(0);
645   globals->get_viewmgr()->update(0);
646 }
647
648
649 SGTime *fgInitTime() {
650     // Initialize time
651     static const SGPropertyNode *longitude
652         = fgGetNode("/position/longitude-deg");
653     static const SGPropertyNode *latitude
654         = fgGetNode("/position/latitude-deg");
655     static const SGPropertyNode *cur_time_override
656         = fgGetNode("/sim/time/cur-time-override", true);
657
658     SGPath zone( globals->get_fg_root() );
659     zone.append( "Timezone" );
660     SGTime *t = new SGTime( longitude->getDoubleValue()
661                               * SGD_DEGREES_TO_RADIANS,
662                             latitude->getDoubleValue()
663                               * SGD_DEGREES_TO_RADIANS,
664                             zone.str(),
665                             cur_time_override->getLongValue() );
666
667     // Handle potential user specified time offsets
668     time_t cur_time = t->get_cur_time();
669     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
670     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
671     time_t aircraftLocalTime = 
672         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
673
674     // Okay, we now have six possible scenarios
675     int offset = fgGetInt("/sim/startup/time-offset");
676     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
677     if (offset_type == "system-offset") {
678         globals->set_warp( offset );
679     } else if (offset_type == "gmt-offset") {
680         globals->set_warp( offset - (currGMT - systemLocalTime) );
681     } else if (offset_type == "latitude-offset") {
682         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
683     } else if (offset_type == "system") {
684         globals->set_warp( offset - cur_time );
685     } else if (offset_type == "gmt") {
686         globals->set_warp( offset - currGMT );
687     } else if (offset_type == "latitude") {
688         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
689                            cur_time ); 
690     } else {
691         SG_LOG( SG_GENERAL, SG_ALERT,
692                 "FG_TIME::Unsupported offset type " << offset_type );
693         exit( -1 );
694     }
695
696     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
697             << globals->get_warp() );
698
699     globals->set_warp_delta( 0 );
700
701     t->update( 0.0, 0.0,
702                cur_time_override->getLongValue(),
703                globals->get_warp() );
704
705     return t;
706 }
707
708
709 // This is the top level init routine which calls all the other
710 // initialization routines.  If you are adding a subsystem to flight
711 // gear, its initialization call should located in this routine.
712 // Returns non-zero if a problem encountered.
713 bool fgInitSubsystems( void ) {
714     static const SGPropertyNode *longitude
715         = fgGetNode("/position/longitude-deg");
716     static const SGPropertyNode *latitude
717         = fgGetNode("/position/latitude-deg");
718     static const SGPropertyNode *altitude
719         = fgGetNode("/position/altitude-ft");
720
721     fgLIGHT *l = &cur_light_params;
722
723     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
724     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
725
726
727     ////////////////////////////////////////////////////////////////////
728     // Initialize the material property subsystem.
729     ////////////////////////////////////////////////////////////////////
730
731     SGPath mpath( globals->get_fg_root() );
732     mpath.append( "materials.xml" );
733     if ( ! material_lib.load( mpath.str() ) ) {
734         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
735         exit(-1);
736     }
737
738
739     ////////////////////////////////////////////////////////////////////
740     // Initialize the scenery management subsystem.
741     ////////////////////////////////////////////////////////////////////
742
743     scenery.init();
744     scenery.bind();
745
746     if ( global_tile_mgr.init() ) {
747         // Load the local scenery data
748         double visibility_meters = fgGetDouble("/environment/visibility-m");
749                 
750         global_tile_mgr.update( longitude->getDoubleValue(),
751                                 latitude->getDoubleValue(),
752                                 visibility_meters );
753     } else {
754         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
755         exit(-1);
756     }
757
758     SG_LOG( SG_GENERAL, SG_DEBUG,
759             "Current terrain elevation after tile mgr init " <<
760             scenery.get_cur_elev() );
761
762
763     ////////////////////////////////////////////////////////////////////
764     // Initialize the flight model subsystem.
765     ////////////////////////////////////////////////////////////////////
766
767     fgInitFDM();
768         
769     // allocates structures so must happen before any of the flight
770     // model or control parameters are set
771     fgAircraftInit();   // In the future this might not be the case.
772
773
774     ////////////////////////////////////////////////////////////////////
775     // Initialize the view manager subsystem.
776     ////////////////////////////////////////////////////////////////////
777
778     fgInitView();
779
780
781     ////////////////////////////////////////////////////////////////////
782     // Initialize the event manager subsystem.
783     ////////////////////////////////////////////////////////////////////
784
785     global_events.init();
786
787     // Output event stats every 60 seconds
788     global_events.Register( "FGEventMgr::print_stats()",
789                             &global_events, &FGEventMgr::print_stats,
790                             60000 );
791
792
793     ////////////////////////////////////////////////////////////////////
794     // Initialize the lighting subsystem.
795     ////////////////////////////////////////////////////////////////////
796
797     // fgUpdateSunPos() needs a few position and view parameters set
798     // so it can calculate local relative sun angle and a few other
799     // things for correctly orienting the sky.
800     fgUpdateSunPos();
801     fgUpdateMoonPos();
802     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
803                             60000);
804     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
805                             60000);
806
807     // Initialize Lighting interpolation tables
808     l->Init();
809
810     // force one lighting update to make it right to start with...
811     l->Update();
812     // update the lighting parameters (based on sun angle)
813     global_events.Register( "fgLight::Update()",
814                             &cur_light_params, &fgLIGHT::Update,
815                             30000 );
816
817
818     ////////////////////////////////////////////////////////////////////
819     // Initialize the logger.
820     ////////////////////////////////////////////////////////////////////
821     
822     globals->set_logger(new FGLogger);
823     globals->get_logger()->init();
824     globals->get_logger()->bind();
825
826
827     ////////////////////////////////////////////////////////////////////
828     // Initialize the local time subsystem.
829     ////////////////////////////////////////////////////////////////////
830
831     // update the current timezone each 30 minutes
832     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
833                             30*60*1000 );
834
835
836     ////////////////////////////////////////////////////////////////////
837     // Initialize the weather subsystem.
838     ////////////////////////////////////////////////////////////////////
839
840     // Initialize the weather modeling subsystem
841 #ifndef FG_NEW_ENVIRONMENT
842     // Initialize the WeatherDatabase
843     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
844     sgVec3 position;
845     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
846                current_aircraft.fdm_state->get_Longitude(),
847                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
848     double init_vis = fgGetDouble("/environment/visibility-m");
849
850     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
851
852     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
853     {
854       working_type = FGLocalWeatherDatabase::use_internet;
855     } else {
856       working_type = FGLocalWeatherDatabase::default_mode;
857     }
858     
859     if ( init_vis > 0 ) {
860       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
861         new FGLocalWeatherDatabase( position,
862                                     globals->get_fg_root(),
863                                     working_type,
864                                     init_vis );
865     } else {
866       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
867         new FGLocalWeatherDatabase( position,
868                                     globals->get_fg_root(),
869                                     working_type );
870     }
871
872     // cout << theFGLocalWeatherDatabase << endl;
873     // cout << "visibility = " 
874     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
875
876     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
877
878     // register the periodic update of the weather
879     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
880                             30000);
881 #else
882     globals->get_environment_mgr()->init();
883     globals->get_environment_mgr()->bind();
884 #endif
885
886     ////////////////////////////////////////////////////////////////////
887     // Initialize vor/ndb/ils/fix list management and query systems
888     ////////////////////////////////////////////////////////////////////
889
890     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
891
892     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
893     current_navlist = new FGNavList;
894     SGPath p_nav( globals->get_fg_root() );
895     p_nav.append( "Navaids/default.nav" );
896     current_navlist->init( p_nav );
897
898     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
899     current_beacons = new FGMarkerBeacons;
900     current_beacons->init();
901     current_ilslist = new FGILSList;
902     SGPath p_ils( globals->get_fg_root() );
903     p_ils.append( "Navaids/default.ils" );
904     current_ilslist->init( p_ils );
905
906     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
907     current_fixlist = new FGFixList;
908     SGPath p_fix( globals->get_fg_root() );
909     p_fix.append( "Navaids/default.fix" );
910     current_fixlist->init( p_fix );
911
912     ////////////////////////////////////////////////////////////////////
913     // Initialize ATC list management and query systems
914     ////////////////////////////////////////////////////////////////////
915
916     SG_LOG(SG_GENERAL, SG_INFO, "  ATIS");
917     current_atislist = new FGATISList;
918     SGPath p_atis( globals->get_fg_root() );
919     p_atis.append( "ATC/default.atis" );
920     current_atislist->init( p_atis );
921
922     SG_LOG(SG_GENERAL, SG_INFO, "  Tower");
923     current_towerlist = new FGTowerList;
924     SGPath p_tower( globals->get_fg_root() );
925     p_tower.append( "ATC/default.tower" );
926     current_towerlist->init( p_tower );
927
928     SG_LOG(SG_GENERAL, SG_INFO, "  Approach");
929     current_approachlist = new FGApproachList;
930     SGPath p_approach( globals->get_fg_root() );
931     p_approach.append( "ATC/default.approach" );
932     current_approachlist->init( p_approach );
933
934     ////////////////////////////////////////////////////////////////////
935     // Initialise ATC display system
936     ////////////////////////////////////////////////////////////////////
937
938     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
939     globals->set_ATC_display(new FGATCDisplay);
940     globals->get_ATC_display()->init(); 
941
942     ////////////////////////////////////////////////////////////////////
943     // Initialise the ATC Manager 
944     ////////////////////////////////////////////////////////////////////
945
946     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
947     globals->set_ATC_mgr(new FGATCMgr);
948     globals->get_ATC_mgr()->init(); 
949     
950     ////////////////////////////////////////////////////////////////////
951     // Initialise the AI Manager 
952     ////////////////////////////////////////////////////////////////////
953
954     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
955     globals->set_AI_mgr(new FGAIMgr);
956     globals->get_AI_mgr()->init();     
957
958     ////////////////////////////////////////////////////////////////////
959     // Initialize the built-in commands.
960     ////////////////////////////////////////////////////////////////////
961     fgInitCommands();
962
963
964 #ifdef ENABLE_AUDIO_SUPPORT
965     ////////////////////////////////////////////////////////////////////
966     // Initialize the sound subsystem.
967     ////////////////////////////////////////////////////////////////////
968
969     globals->set_soundmgr(new FGSoundMgr);
970     globals->get_soundmgr()->init();
971     globals->get_soundmgr()->bind();
972
973
974     ////////////////////////////////////////////////////////////////////
975     // Initialize the sound-effects subsystem.
976     ////////////////////////////////////////////////////////////////////
977     globals->set_fx(new FGFX);
978     globals->get_fx()->init();
979     globals->get_fx()->bind();
980
981 #endif
982
983     ////////////////////////////////////////////////////////////////////
984     // Initialize the radio stack subsystem.
985     ////////////////////////////////////////////////////////////////////
986
987                                 // A textbook example of how FGSubsystem
988                                 // should work...
989     current_radiostack = new FGRadioStack;
990     current_radiostack->init();
991     current_radiostack->bind();
992
993
994     ////////////////////////////////////////////////////////////////////
995     // Initialize the cockpit subsystem
996     ////////////////////////////////////////////////////////////////////
997
998     if( fgCockpitInit( &current_aircraft )) {
999         // Cockpit initialized ok.
1000     } else {
1001         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1002         exit(-1);
1003     }
1004
1005
1006     ////////////////////////////////////////////////////////////////////
1007     // Initialize the autopilot subsystem.
1008     ////////////////////////////////////////////////////////////////////
1009
1010     globals->set_autopilot(new FGAutopilot);
1011     globals->get_autopilot()->init();
1012     globals->get_autopilot()->bind();
1013
1014                                 // FIXME: these should go in the
1015                                 // GUI initialization code, not here.
1016     fgAPAdjustInit();
1017     NewTgtAirportInit();
1018     NewHeadingInit();
1019     NewAltitudeInit();
1020
1021     ////////////////////////////////////////////////////////////////////
1022     // Initialize I/O subsystem.
1023     ////////////////////////////////////////////////////////////////////
1024
1025 #if ! defined( macintosh )
1026     fgIOInit();
1027 #endif
1028
1029     // Initialize the 2D panel.
1030     string panel_path = fgGetString("/sim/panel/path",
1031                                     "Panels/Default/default.xml");
1032     current_panel = fgReadPanel(panel_path);
1033     if (current_panel == 0) {
1034         SG_LOG( SG_INPUT, SG_ALERT, 
1035                 "Error reading new panel from " << panel_path );
1036     } else {
1037         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1038         current_panel->init();
1039         current_panel->bind();
1040     }
1041
1042     
1043     ////////////////////////////////////////////////////////////////////
1044     // Initialize the default (kludged) properties.
1045     ////////////////////////////////////////////////////////////////////
1046
1047     fgInitProps();
1048
1049
1050     ////////////////////////////////////////////////////////////////////
1051     // Initialize the controls subsystem.
1052     ////////////////////////////////////////////////////////////////////
1053
1054     globals->get_controls()->init();
1055     globals->get_controls()->bind();
1056
1057
1058     ////////////////////////////////////////////////////////////////////
1059     // Initialize the input subsystem.
1060     ////////////////////////////////////////////////////////////////////
1061
1062     current_input.init();
1063     current_input.bind();
1064
1065
1066     ////////////////////////////////////////////////////////////////////////
1067     // End of subsystem initialization.
1068     ////////////////////////////////////////////////////////////////////
1069
1070     SG_LOG( SG_GENERAL, SG_INFO, endl);
1071
1072                                 // Save the initial state for future
1073                                 // reference.
1074     globals->saveInitialState();
1075
1076     return true;
1077 }
1078
1079
1080 void fgReInitSubsystems( void )
1081 {
1082     static const SGPropertyNode *longitude
1083         = fgGetNode("/position/longitude-deg");
1084     static const SGPropertyNode *latitude
1085         = fgGetNode("/position/latitude-deg");
1086     static const SGPropertyNode *altitude
1087         = fgGetNode("/position/altitude-ft");
1088     static const SGPropertyNode *master_freeze
1089         = fgGetNode("/sim/freeze/master");
1090
1091     SG_LOG( SG_GENERAL, SG_INFO,
1092             "/position/altitude = " << altitude->getDoubleValue() );
1093
1094     bool freeze = master_freeze->getBoolValue();
1095     if ( !freeze ) {
1096         fgSetBool("/sim/freeze/master", true);
1097     }
1098     
1099     // Initialize the Scenery Management subsystem
1100     scenery.init();
1101
1102 #if 0
1103     if( global_tile_mgr.init() ) {
1104         Load the local scenery data
1105         global_tile_mgr.update( longitude->getDoubleValue(),
1106                                 latitude->getDoubleValue() );
1107     } else {
1108         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1109         exit(-1);
1110     }
1111 #endif
1112
1113     fgInitFDM();
1114     
1115     // allocates structures so must happen before any of the flight
1116     // model or control parameters are set
1117     fgAircraftInit();   // In the future this might not be the case.
1118
1119     fgInitView();
1120
1121     globals->get_controls()->reset_all();
1122     globals->get_autopilot()->reset();
1123
1124     fgUpdateSunPos();
1125     fgUpdateMoonPos();
1126     cur_light_params.Update();
1127     fgUpdateLocalTime();
1128
1129     if ( !freeze ) {
1130         fgSetBool("/sim/freeze/master", false);
1131     }
1132 }
1133