]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
d2e5bb305701593c6e9a2cf4a49e9e3378e393e0
[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 FG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #include <GL/glut.h>
35 #include <simgear/xgl/xgl.h>
36
37 #include <stdio.h>
38 #include <stdlib.h>
39
40 // work around a stdc++ lib bug in some versions of linux, but doesn't
41 // seem to hurt to have this here for all versions of Linux.
42 #ifdef linux
43 #  define _G_NO_EXTERN_TEMPLATES
44 #endif
45
46 #include <simgear/compiler.h>
47
48 #include STL_STRING
49
50 #include <simgear/constants.h>
51 #include <simgear/debug/logstream.hxx>
52 #include <simgear/math/point3d.hxx>
53 #include <simgear/math/polar3d.hxx>
54 #include <simgear/math/sg_geodesy.hxx>
55 #include <simgear/misc/fgpath.hxx>
56 #include <simgear/timing/sg_time.hxx>
57
58 #include <Aircraft/aircraft.hxx>
59 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
60 #include <Airports/runways.hxx>
61 #include <Airports/simple.hxx>
62 #include <Autopilot/auto_gui.hxx>
63 #include <Autopilot/newauto.hxx>
64 #include <Cockpit/cockpit.hxx>
65 #include <Cockpit/radiostack.hxx>
66 #include <Cockpit/panel.hxx>
67 #include <Cockpit/panel_io.hxx>
68 #include <FDM/ADA.hxx>
69 #include <FDM/Balloon.h>
70 #include <FDM/External.hxx>
71 #include <FDM/JSBSim.hxx>
72 #include <FDM/LaRCsim.hxx>
73 #include <FDM/MagicCarpet.hxx>
74 #include <Include/general.hxx>
75 #include <Joystick/joystick.hxx>
76 #include <Objects/matlib.hxx>
77 #include <Navaids/fixlist.hxx>
78 #include <Navaids/ilslist.hxx>
79 #include <Navaids/mkrbeacons.hxx>
80 #include <Navaids/navlist.hxx>
81 #include <Scenery/scenery.hxx>
82 #include <Scenery/tilemgr.hxx>
83 #include <Time/event.hxx>
84 #include <Time/light.hxx>
85 #include <Time/sunpos.hxx>
86 #include <Time/moonpos.hxx>
87 #include <Time/tmp.hxx>
88
89 #ifndef FG_OLD_WEATHER
90 #  include <WeatherCM/FGLocalWeatherDatabase.h>
91 #else
92 #  include <Weather/weather.hxx>
93 #endif
94
95 #include "fg_init.hxx"
96 #include "fg_io.hxx"
97 #include "options.hxx"
98 #include "globals.hxx"
99 #include "bfi.hxx"
100
101 #if defined(FX) && defined(XMESA)
102 #include <GL/xmesa.h>
103 #endif
104
105 FG_USING_STD(string);
106
107 extern const char *default_root;
108
109
110 // Read in configuration (file and command line) and just set fg_root
111 bool fgInitFGRoot ( int argc, char **argv ) {
112     string root;
113     char* envp;
114
115     // First parse command line options looking for fg-root, this will
116     // override anything specified in a config file
117     root = fgScanForRoot(argc, argv);
118
119     // Next check home directory for .fgfsrc file
120     if ( root == "" ) {
121         envp = ::getenv( "HOME" );
122         if ( envp != NULL ) {
123             FGPath config( envp );
124             config.append( ".fgfsrc" );
125             root = fgScanForRoot(config.str());
126         }
127     }
128     
129     // Next check if fg-root is set as an env variable
130     if ( root == "" ) {
131         envp = ::getenv( "FG_ROOT" );
132         if ( envp != NULL ) {
133             root = envp;
134         }
135     }
136
137     // Otherwise, default to a random compiled-in location if we can't
138     // find fg-root any other way.
139     if ( root == "" ) {
140 #if defined( WIN32 )
141         root = "\\FlightGear";
142 #elif defined( macintosh )
143         root = "";
144 #else
145         root = PKGLIBDIR;
146 #endif
147     }
148
149     FG_LOG(FG_INPUT, FG_INFO, "fg_root = " << root );
150     globals->set_fg_root(root);
151
152     return true;
153 }
154
155
156 // Read in configuration (file and command line)
157 bool fgInitConfig ( int argc, char **argv ) {
158
159                                 // First, set some sane default values
160     fgSetDefaults();
161
162     // Read global preferences from $FG_ROOT/preferences.xml
163     FGPath props_path(globals->get_fg_root());
164     props_path.append("preferences.xml");
165     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
166     if (!readProperties(props_path.str(), globals->get_props())) {
167       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
168              << props_path.str());
169     } else {
170       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
171     }
172
173     // Attempt to locate and parse a config file
174     // First check fg_root
175     FGPath config( globals->get_fg_root() );
176     config.append( "system.fgfsrc" );
177     fgParseOptions(config.str());
178
179     // Next check home directory
180     char* envp = ::getenv( "HOME" );
181     if ( envp != NULL ) {
182         config.set( envp );
183         config.append( ".fgfsrc" );
184         fgParseOptions(config.str());
185     }
186
187     // Parse remaining command line options
188     // These will override anything specified in a config file
189     fgParseOptions(argc, argv);
190
191     return true;
192 }
193
194
195 // find basic airport location info from airport database
196 bool fgFindAirportID( const string& id, FGAirport *a ) {
197     if ( id.length() ) {
198         FGPath path( globals->get_fg_root() );
199         path.append( "Airports" );
200         path.append( "simple.mk4" );
201         FGAirports airports( path.c_str() );
202
203         FG_LOG( FG_GENERAL, FG_INFO, "Searching for airport code = " << id );
204
205         if ( ! airports.search( id, a ) ) {
206             FG_LOG( FG_GENERAL, FG_ALERT,
207                     "Failed to find " << id << " in " << path.str() );
208             return false;
209         }
210     } else {
211         return false;
212     }
213
214     FG_LOG( FG_GENERAL, FG_INFO,
215             "Position for " << id << " is ("
216             << a->longitude << ", "
217             << a->latitude << ")" );
218
219     return true;
220 }
221
222
223 // Set current_options lon/lat given an airport id
224 bool fgSetPosFromAirportID( const string& id ) {
225     FGAirport a;
226     // double lon, lat;
227
228     FG_LOG( FG_GENERAL, FG_INFO,
229             "Attempting to set starting position from airport code " << id );
230
231     if ( fgFindAirportID( id, &a ) ) {
232         fgSetDouble("/position/longitude",  a.longitude );
233         fgSetDouble("/position/latitude",  a.latitude );
234         FG_LOG( FG_GENERAL, FG_INFO,
235                 "Position for " << id << " is ("
236                 << a.longitude << ", "
237                 << a.latitude << ")" );
238
239         return true;
240     } else {
241         return false;
242     }
243
244 }
245
246
247 // Set current_options lon/lat given an airport id and heading (degrees)
248 bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
249     FGRunway r;
250     FGRunway found_r;
251     double found_dir = 0.0;
252
253     if ( id.length() ) {
254         // set initial position from runway and heading
255
256         FGPath path( globals->get_fg_root() );
257         path.append( "Airports" );
258         path.append( "runways.mk4" );
259         FGRunways runways( path.c_str() );
260
261         FG_LOG( FG_GENERAL, FG_INFO,
262                 "Attempting to set starting position from runway code "
263                 << id << " heading " << tgt_hdg );
264
265         // FGPath inpath( globals->get_fg_root() );
266         // inpath.append( "Airports" );
267         // inpath.append( "apt_simple" );
268         // airports.load( inpath.c_str() );
269
270         // FGPath outpath( globals->get_fg_root() );
271         // outpath.append( "Airports" );
272         // outpath.append( "simple.gdbm" );
273         // airports.dump_gdbm( outpath.c_str() );
274
275         if ( ! runways.search( id, &r ) ) {
276             FG_LOG( FG_GENERAL, FG_ALERT,
277                     "Failed to find " << id << " in database." );
278             return false;
279         }
280
281         double diff;
282         double min_diff = 360.0;
283
284         while ( r.id == id ) {
285             // forward direction
286             diff = tgt_hdg - r.heading;
287             while ( diff < -180.0 ) { diff += 360.0; }
288             while ( diff >  180.0 ) { diff -= 360.0; }
289             diff = fabs(diff);
290             FG_LOG( FG_GENERAL, FG_INFO,
291                     "Runway " << r.rwy_no << " heading = " << r.heading <<
292                     " diff = " << diff );
293             if ( diff < min_diff ) {
294                 min_diff = diff;
295                 found_r = r;
296                 found_dir = 0;
297             }
298
299             // reverse direction
300             diff = tgt_hdg - r.heading - 180.0;
301             while ( diff < -180.0 ) { diff += 360.0; }
302             while ( diff >  180.0 ) { diff -= 360.0; }
303             diff = fabs(diff);
304             FG_LOG( FG_GENERAL, FG_INFO,
305                     "Runway -" << r.rwy_no << " heading = " <<
306                     r.heading + 180.0 <<
307                     " diff = " << diff );
308             if ( diff < min_diff ) {
309                 min_diff = diff;
310                 found_r = r;
311                 found_dir = 180.0;
312             }
313
314             runways.next( &r );
315         }
316
317         FG_LOG( FG_GENERAL, FG_INFO, "closest runway = " << found_r.rwy_no
318                 << " + " << found_dir );
319
320     } else {
321         return false;
322     }
323
324     double heading = found_r.heading + found_dir;
325     while ( heading >= 360.0 ) { heading -= 360.0; }
326
327     double lat2, lon2, az2;
328     double azimuth = found_r.heading + found_dir + 180.0;
329     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
330
331     FG_LOG( FG_GENERAL, FG_INFO,
332             "runway =  " << found_r.lon << ", " << found_r.lat
333             << " length = " << found_r.length * FEET_TO_METER * 0.5 
334             << " heading = " << azimuth );
335     
336     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
337                         azimuth, found_r.length * FEET_TO_METER * 0.5 - 5.0,
338                         &lat2, &lon2, &az2 );
339
340     if ( fabs( fgGetDouble("/sim/startup/offset-distance") ) > FG_EPSILON ) {
341         double olat, olon;
342         double odist = fgGetDouble("/sim/startup/offset-distance");
343         odist *= NM_TO_METER;
344         double oaz = azimuth;
345         if ( fabs(fgGetDouble("/sim/startup/offset-azimuth")) > FG_EPSILON ) {
346             oaz = fgGetDouble("/sim/startup/offset-azimuth") + 180;
347         }
348         while ( oaz >= 360.0 ) { oaz -= 360.0; }
349         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
350         lat2=olat;
351         lon2=olon;
352     }
353     fgSetDouble("/position/longitude",  lon2 );
354     fgSetDouble("/position/latitude",  lat2 );
355     fgSetDouble("/orientation/heading", heading );
356
357     FG_LOG( FG_GENERAL, FG_INFO,
358             "Position for " << id << " is ("
359             << lon2 << ", "
360             << lat2 << ") new heading is "
361             << heading );
362
363     return true;
364 }
365
366
367 // Set initial position and orientation
368 bool fgInitPosition( void ) {
369     FGInterface *f = current_aircraft.fdm_state;
370     string id = fgGetString("/sim/startup/airport-id");
371
372     // set initial position from default or command line coordinates
373     f->set_Longitude( fgGetDouble("/position/longitude") * DEG_TO_RAD );
374     f->set_Latitude( fgGetDouble("/position/latitude") * DEG_TO_RAD );
375
376     FG_LOG( FG_GENERAL, FG_INFO,
377             "scenery.cur_elev = " << scenery.cur_elev );
378     FG_LOG( FG_GENERAL, FG_INFO,
379             "/position/altitude = " << fgGetDouble("/position/altitude") );
380
381     // if we requested on ground startups
382     if ( fgGetBool( "/sim/startup/onground" ) ) {
383         fgSetDouble( "/position/altitude", (scenery.cur_elev + 1)
384                      * METERS_TO_FEET );
385     }
386
387     // if requested altitude is below ground level
388     if ( scenery.cur_elev >
389          fgGetDouble("/position/altitude") * METERS_TO_FEET - 1) {
390         fgSetDouble("/position/altitude",
391                     (scenery.cur_elev + 1) * METERS_TO_FEET );
392     }
393
394     FG_LOG( FG_GENERAL, FG_INFO,
395             "starting altitude is = " <<
396             fgGetDouble("/position/altitude") );
397
398     f->set_Altitude( fgGetDouble("/position/altitude") );
399     FG_LOG( FG_GENERAL, FG_INFO,
400             "Initial position is: ("
401             << (f->get_Longitude() * RAD_TO_DEG) << ", "
402             << (f->get_Latitude() * RAD_TO_DEG) << ", "
403             << (f->get_Altitude() * FEET_TO_METER) << ")" );
404
405     return true;
406 }
407
408
409 // General house keeping initializations
410 bool fgInitGeneral( void ) {
411     string root;
412
413 #if defined(FX) && defined(XMESA)
414     char *mesa_win_state;
415 #endif
416
417     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
418     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
419
420     root = globals->get_fg_root();
421     if ( ! root.length() ) {
422         // No root path set? Then bail ...
423         FG_LOG( FG_GENERAL, FG_ALERT,
424                 "Cannot continue without environment variable FG_ROOT"
425                 << "being defined." );
426         exit(-1);
427     }
428     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
429
430 #if defined(FX) && defined(XMESA)
431     // initialize full screen flag
432     global_fullscreen = false;
433     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
434         // Test for the MESA_GLX_FX env variable
435         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
436             // test if we are fullscreen mesa/glide
437             if ( (mesa_win_state[0] == 'f') ||
438                  (mesa_win_state[0] == 'F') ) {
439                 global_fullscreen = true;
440             }
441         }
442     }
443 #endif
444
445     return true;
446 }
447
448
449 // set initial aircraft speed
450 void
451 fgVelocityInit( void ) 
452 {
453   if (!fgHasValue("/sim/startup/speed-set")) {
454     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
455     return;
456   }
457
458   const string speedset = fgGetString("/sim/startup/speed-set");
459   if (speedset == "knots" || speedset == "KNOTS") {
460     current_aircraft.fdm_state
461       ->set_V_calibrated_kts(fgGetDouble("/velocities/airspeed"));
462   } else if (speedset == "mach" || speedset == "MACH") {
463     current_aircraft.fdm_state
464       ->set_Mach_number(fgGetDouble("/velocities/mach"));
465   } else if (speedset == "UVW" || speedset == "uvw") {
466     current_aircraft.fdm_state
467       ->set_Velocities_Wind_Body(fgGetDouble("/velocities/uBody"),
468                                  fgGetDouble("/velocities/vBody"),
469                                  fgGetDouble("/velocities/wBody"));
470   } else if (speedset == "NED" || speedset == "ned") {
471     current_aircraft.fdm_state
472       ->set_Velocities_Local(fgGetDouble("/velocities/speed-north"),
473                              fgGetDouble("/velocities/speed-east"),
474                              fgGetDouble("/velocities/speed-down"));
475   } else {
476     FG_LOG(FG_GENERAL, FG_ALERT,
477            "Unrecognized value for /sim/startup/speed-set: " << speedset);
478     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
479   }
480 }             
481
482         
483 // This is the top level init routine which calls all the other
484 // initialization routines.  If you are adding a subsystem to flight
485 // gear, its initialization call should located in this routine.
486 // Returns non-zero if a problem encountered.
487 bool fgInitSubsystems( void ) {
488     fgLIGHT *l = &cur_light_params;
489
490     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
491     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
492
493     // Initialize the material property lib
494     FGPath mpath( globals->get_fg_root() );
495     mpath.append( "materials" );
496     if ( material_lib.load( mpath.str() ) ) {
497     } else {
498         FG_LOG( FG_GENERAL, FG_ALERT, "Error loading material lib!" );
499         exit(-1);
500     }
501
502     // Initialize the Scenery Management subsystem
503     if ( fgSceneryInit() ) {
504         // Material lib initialized ok.
505     } else {
506         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
507         exit(-1);
508     }
509
510     if ( global_tile_mgr.init() ) {
511         // Load the local scenery data
512         global_tile_mgr.update( fgGetDouble("/position/longitude"),
513                                 fgGetDouble("/position/latitude") );
514     } else {
515         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
516         exit(-1);
517     }
518
519     FG_LOG( FG_GENERAL, FG_DEBUG,
520             "Current terrain elevation after tile mgr init " <<
521             scenery.cur_elev );
522
523     double dt = 1.0 / fgGetInt("/sim/model-hz");
524     // cout << "dt = " << dt << endl;
525
526     aircraft_dir = fgGetString("/sim/aircraft-dir");
527     const string &model = fgGetString("/sim/flight-model");
528     if (model == "larcsim") {
529         cur_fdm_state = new FGLaRCsim( dt );
530     } else if (model == "jsb") {
531         cur_fdm_state = new FGJSBsim( dt );
532     } else if (model == "ada") {
533         cur_fdm_state = new FGADA( dt );
534     } else if (model == "balloon") {
535         cur_fdm_state = new FGBalloonSim( dt );
536     } else if (model == "magic") {
537         cur_fdm_state = new FGMagicCarpet( dt );
538     } else if (model == "external") {
539         cur_fdm_state = new FGExternal( dt );
540     } else {
541         FG_LOG(FG_GENERAL, FG_ALERT,
542                "Unrecognized flight model '" << model
543                << ", can't init aircraft");
544         exit(-1);
545     }
546     cur_fdm_state->stamp();
547     cur_fdm_state->set_remainder( 0 );
548
549     // allocates structures so must happen before any of the flight
550     // model or control parameters are set
551     fgAircraftInit();   // In the future this might not be the case.
552
553     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"),
554                              scenery.cur_elev );
555     
556     // set the initial position
557     fgInitPosition();
558
559     // Calculate ground elevation at starting point (we didn't have
560     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
561     //
562     // calculalate a cartesian point somewhere along the line between
563     // the center of the earth and our view position.  Doesn't have to
564     // be the exact elevation (this is good because we don't know it
565     // yet :-)
566
567     // now handled inside of the fgTileMgrUpdate()
568
569     // Reset our altitude if we are below ground
570     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
571             << cur_fdm_state->get_Altitude() );
572     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
573             cur_fdm_state->get_Runway_altitude() );
574
575     if ( cur_fdm_state->get_Altitude() < cur_fdm_state->get_Runway_altitude() +
576          3.758099) {
577         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
578                                      3.758099 );
579     }
580
581     FG_LOG( FG_GENERAL, FG_INFO,
582             "Updated position (after elevation adj): ("
583             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
584             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
585             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
586
587     // We need to calculate a few sea_level_radius here so we can pass
588     // the correct value to the view class
589     double sea_level_radius_meters;
590     double lat_geoc;
591     sgGeodToGeoc( cur_fdm_state->get_Latitude(),
592                   cur_fdm_state->get_Altitude(),
593                   &sea_level_radius_meters, &lat_geoc);
594     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
595                                          METER_TO_FEET );
596
597     // The following section sets up the flight model EOM parameters
598     // and should really be read in from one or more files.
599
600     // Initial Velocity
601     fgVelocityInit();
602
603     // Initial Orientation
604 //     cur_fdm_state->
605 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
606 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
607 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
608
609     // Initialize the event manager
610     global_events.Init();
611
612     // Output event stats every 60 seconds
613     global_events.Register( "fgEVENT_MGR::PrintStats()",
614                             fgMethodCallback<fgEVENT_MGR>( &global_events,
615                                                    &fgEVENT_MGR::PrintStats),
616                             fgEVENT::FG_EVENT_READY, 60000 );
617
618     // Initialize win_ratio parameters
619     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
620         globals->get_viewmgr()->get_view(i)->
621             set_win_ratio( fgGetInt("/sim/startup/xsize") /
622                            fgGetInt("/sim/startup/ysize") );
623     }
624
625     // Initialize pilot view
626     FGViewerRPH *pilot_view =
627         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
628
629     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
630                                    cur_fdm_state->get_Lat_geocentric(), 
631                                    cur_fdm_state->get_Altitude() *
632                                    FEET_TO_METER );
633     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
634                                       FEET_TO_METER ); 
635     pilot_view->set_rph( cur_fdm_state->get_Phi(),
636                          cur_fdm_state->get_Theta(),
637                          cur_fdm_state->get_Psi() );
638
639     // set current view to 0 (first) which is our main pilot view
640     globals->set_current_view( pilot_view );
641
642     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
643             << globals->get_current_view()->get_abs_view_pos());
644
645     // fgUpdateSunPos() needs a few position and view parameters set
646     // so it can calculate local relative sun angle and a few other
647     // things for correctly orienting the sky.
648     fgUpdateSunPos();
649     fgUpdateMoonPos();
650     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
651                             fgEVENT::FG_EVENT_READY, 60000);
652     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
653                             fgEVENT::FG_EVENT_READY, 60000);
654
655     // Initialize Lighting interpolation tables
656     l->Init();
657
658     // update the lighting parameters (based on sun angle)
659     global_events.Register( "fgLight::Update()",
660                             fgMethodCallback<fgLIGHT>( &cur_light_params,
661                                                        &fgLIGHT::Update),
662                             fgEVENT::FG_EVENT_READY, 30000 );
663     // update the current timezone each 30 minutes
664     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
665                             fgEVENT::FG_EVENT_READY, 1800000);
666
667     // Initialize the weather modeling subsystem
668 #ifndef FG_OLD_WEATHER
669     // Initialize the WeatherDatabase
670     FG_LOG(FG_GENERAL, FG_INFO, "Creating LocalWeatherDatabase");
671     sgVec3 position;
672     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
673                current_aircraft.fdm_state->get_Longitude(),
674                current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER );
675     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
676         new FGLocalWeatherDatabase( position,
677                                     globals->get_fg_root() );
678     // cout << theFGLocalWeatherDatabase << endl;
679     // cout << "visibility = " 
680     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
681
682     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
683     
684     double init_vis = fgGetDouble("/environment/visibility");
685     if ( init_vis > 0 ) {
686         WeatherDatabase->setWeatherVisibility( init_vis );
687     }
688
689     // register the periodic update of the weather
690     global_events.Register( "weather update", fgUpdateWeatherDatabase,
691                             fgEVENT::FG_EVENT_READY, 30000);
692 #else
693     current_weather.Init();
694 #endif
695
696     // Initialize vor/ndb/ils/fix list management and query systems
697     FG_LOG(FG_GENERAL, FG_INFO, "Loading Navaids");
698
699     FG_LOG(FG_GENERAL, FG_INFO, "  VOR/NDB");
700     current_navlist = new FGNavList;
701     FGPath p_nav( globals->get_fg_root() );
702     p_nav.append( "Navaids/default.nav" );
703     current_navlist->init( p_nav );
704
705     FG_LOG(FG_GENERAL, FG_INFO, "  ILS and Marker Beacons");
706     current_beacons = new FGMarkerBeacons;
707     current_beacons->init();
708     current_ilslist = new FGILSList;
709     FGPath p_ils( globals->get_fg_root() );
710     p_ils.append( "Navaids/default.ils" );
711     current_ilslist->init( p_ils );
712
713     FG_LOG(FG_GENERAL, FG_INFO, "  Fixes");
714     current_fixlist = new FGFixList;
715     FGPath p_fix( globals->get_fg_root() );
716     p_fix.append( "Navaids/default.fix" );
717     current_fixlist->init( p_fix );
718
719     // Radio stack subsystem.
720     current_radiostack = new FGRadioStack;
721     current_radiostack->init();
722     current_radiostack->bind();
723
724     // Initialize the Cockpit subsystem
725     if( fgCockpitInit( &current_aircraft )) {
726         // Cockpit initialized ok.
727     } else {
728         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
729         exit(-1);
730     }
731
732     // Initialize the flight model subsystem data structures base on
733     // above values
734
735     cur_fdm_state->init();
736     cur_fdm_state->bind();
737 //     if ( cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") ) ) {
738 //      // fdm init successful
739 //     } else {
740 //      FG_LOG( FG_GENERAL, FG_ALERT, "FDM init() failed!  Cannot continue." );
741 //      exit(-1);
742 //     }
743
744     // *ABCD* I'm just sticking this here for now, it should probably
745     // move eventually
746     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
747
748     if ( cur_fdm_state->get_Altitude() <
749          cur_fdm_state->get_Runway_altitude() + 3.758099)
750     {
751         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
752                                      3.758099 );
753     }
754
755     FG_LOG( FG_GENERAL, FG_INFO,
756             "Updated position (after elevation adj): ("
757             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
758             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
759             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
760     // *ABCD* end of thing that I just stuck in that I should probably
761     // move
762
763     // Joystick support
764     if ( ! fgJoystickInit() ) {
765         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
766     }
767
768     // Autopilot init
769     current_autopilot = new FGAutopilot;
770     current_autopilot->init();
771
772     // initialize the gui parts of the autopilot
773     NewTgtAirportInit();
774     fgAPAdjustInit() ;
775     NewHeadingInit();
776     NewAltitudeInit();
777
778     // Initialize I/O channels
779 #if ! defined( macintosh )
780     fgIOInit();
781 #endif
782
783     // Initialize the 2D panel.
784     string panel_path = fgGetString("/sim/panel/path",
785                                     "Panels/Default/default.xml");
786     current_panel = fgReadPanel(panel_path);
787     if (current_panel == 0) {
788         FG_LOG( FG_INPUT, FG_ALERT, 
789                 "Error reading new panel from " << panel_path );
790     } else {
791         FG_LOG( FG_INPUT, FG_INFO, "Loaded new panel from " << panel_path );
792         current_panel->init();
793         current_panel->bind();
794     }
795
796     // Initialize the BFI
797     FGBFI::init();
798
799     controls.init();
800     controls.bind();
801
802     FG_LOG( FG_GENERAL, FG_INFO, endl);
803
804                                 // Save the initial state for future
805                                 // reference.
806     globals->saveInitialState();
807
808     return true;
809 }
810
811
812 void fgReInitSubsystems( void )
813 {
814     FG_LOG( FG_GENERAL, FG_INFO,
815             "/position/altitude = " << fgGetDouble("/position/altitude") );
816
817     bool freeze = globals->get_freeze();
818     if( !freeze )
819         globals->set_freeze( true );
820     
821     // Initialize the Scenery Management subsystem
822     if ( ! fgSceneryInit() ) {
823         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
824         exit(-1);
825     }
826
827     if( global_tile_mgr.init() ) {
828         // Load the local scenery data
829         global_tile_mgr.update( fgGetDouble("/position/longitude"),
830                                 fgGetDouble("/position/latitude") );
831     } else {
832         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
833                 exit(-1);
834     }
835
836     // cout << "current scenery elev = " << scenery.cur_elev << endl;
837
838     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"), 
839                              scenery.cur_elev );
840     fgInitPosition();
841
842     // Reset our altitude if we are below ground
843     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
844             << cur_fdm_state->get_Altitude() );
845     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = "
846             << cur_fdm_state->get_Runway_altitude() );
847
848     if ( cur_fdm_state->get_Altitude() <
849          cur_fdm_state->get_Runway_altitude() + 3.758099)
850     {
851         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
852                                      3.758099 );
853     }
854     double sea_level_radius_meters;
855     double lat_geoc;
856     sgGeodToGeoc( cur_fdm_state->get_Latitude(), cur_fdm_state->get_Altitude(), 
857                   &sea_level_radius_meters, &lat_geoc);
858     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
859                                          METER_TO_FEET );
860         
861     // The following section sets up the flight model EOM parameters
862     // and should really be read in from one or more files.
863
864     // Initial Velocity
865     fgVelocityInit();
866
867     // Initial Orientation
868 //     cur_fdm_state->
869 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
870 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
871 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
872
873     // Initialize view parameters
874     FGViewerRPH *pilot_view =
875         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
876
877     pilot_view->set_view_offset( 0.0 );
878     pilot_view->set_goal_view_offset( 0.0 );
879
880     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
881                                    cur_fdm_state->get_Lat_geocentric(), 
882                                    cur_fdm_state->get_Altitude() *
883                                    FEET_TO_METER );
884     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
885                                       FEET_TO_METER ); 
886     pilot_view->set_rph( cur_fdm_state->get_Phi(),
887                          cur_fdm_state->get_Theta(),
888                          cur_fdm_state->get_Psi() );
889
890     // set current view to 0 (first) which is our main pilot view
891     globals->set_current_view( pilot_view );
892
893     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
894             << globals->get_current_view()->get_abs_view_pos());
895
896     cur_fdm_state->init();
897 //     cur_fdm_state->bind();
898 //     cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") );
899
900     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
901
902     if ( cur_fdm_state->get_Altitude() <
903          cur_fdm_state->get_Runway_altitude() + 3.758099)
904     {
905         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
906                                      3.758099 );
907     }
908
909     controls.reset_all();
910     current_autopilot->reset();
911
912     if( !freeze )
913         globals->set_freeze( false );
914 }