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