]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Initial support for marker beacons.
[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     }
385
386     // if requested altitude is below ground level
387     if ( scenery.cur_elev > fgGetDouble("/position/altitude") - 1) {
388         fgSetDouble("/position/altitude", scenery.cur_elev + 1 );
389     }
390
391     FG_LOG( FG_GENERAL, FG_INFO,
392             "starting altitude is = " <<
393             fgGetDouble("/position/altitude") );
394
395     f->set_Altitude( fgGetDouble("/position/altitude") );
396     FG_LOG( FG_GENERAL, FG_INFO,
397             "Initial position is: ("
398             << (f->get_Longitude() * RAD_TO_DEG) << ", "
399             << (f->get_Latitude() * RAD_TO_DEG) << ", "
400             << (f->get_Altitude() * FEET_TO_METER) << ")" );
401
402     return true;
403 }
404
405
406 // General house keeping initializations
407 bool fgInitGeneral( void ) {
408     string root;
409
410 #if defined(FX) && defined(XMESA)
411     char *mesa_win_state;
412 #endif
413
414     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
415     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
416
417     root = globals->get_fg_root();
418     if ( ! root.length() ) {
419         // No root path set? Then bail ...
420         FG_LOG( FG_GENERAL, FG_ALERT,
421                 "Cannot continue without environment variable FG_ROOT"
422                 << "being defined." );
423         exit(-1);
424     }
425     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
426
427 #if defined(FX) && defined(XMESA)
428     // initialize full screen flag
429     global_fullscreen = false;
430     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
431         // Test for the MESA_GLX_FX env variable
432         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
433             // test if we are fullscreen mesa/glide
434             if ( (mesa_win_state[0] == 'f') ||
435                  (mesa_win_state[0] == 'F') ) {
436                 global_fullscreen = true;
437             }
438         }
439     }
440 #endif
441
442     return true;
443 }
444
445
446 // set initial aircraft speed
447 void
448 fgVelocityInit( void ) 
449 {
450   if (!fgHasValue("/sim/startup/speed-set")) {
451     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
452     return;
453   }
454
455   const string speedset = fgGetString("/sim/startup/speed-set");
456   if (speedset == "knots" || speedset == "KNOTS") {
457     current_aircraft.fdm_state
458       ->set_V_calibrated_kts(fgGetDouble("/velocities/airspeed"));
459   } else if (speedset == "mach" || speedset == "MACH") {
460     current_aircraft.fdm_state
461       ->set_Mach_number(fgGetDouble("/velocities/mach"));
462   } else if (speedset == "UVW" || speedset == "uvw") {
463     current_aircraft.fdm_state
464       ->set_Velocities_Wind_Body(fgGetDouble("/velocities/uBody"),
465                                  fgGetDouble("/velocities/vBody"),
466                                  fgGetDouble("/velocities/wBody"));
467   } else if (speedset == "NED" || speedset == "ned") {
468     current_aircraft.fdm_state
469       ->set_Velocities_Local(fgGetDouble("/velocities/speed-north"),
470                              fgGetDouble("/velocities/speed-east"),
471                              fgGetDouble("/velocities/speed-down"));
472   } else {
473     FG_LOG(FG_GENERAL, FG_ALERT,
474            "Unrecognized value for /sim/startup/speed-set: " << speedset);
475     current_aircraft.fdm_state->set_V_calibrated_kts(0.0);
476   }
477 }             
478
479         
480 // This is the top level init routine which calls all the other
481 // initialization routines.  If you are adding a subsystem to flight
482 // gear, its initialization call should located in this routine.
483 // Returns non-zero if a problem encountered.
484 bool fgInitSubsystems( void ) {
485     fgLIGHT *l = &cur_light_params;
486
487     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
488     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
489
490     // Initialize the material property lib
491     FGPath mpath( globals->get_fg_root() );
492     mpath.append( "materials" );
493     if ( material_lib.load( mpath.str() ) ) {
494     } else {
495         FG_LOG( FG_GENERAL, FG_ALERT, "Error loading material lib!" );
496         exit(-1);
497     }
498
499     // Initialize the Scenery Management subsystem
500     if ( fgSceneryInit() ) {
501         // Material lib initialized ok.
502     } else {
503         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
504         exit(-1);
505     }
506
507     if ( global_tile_mgr.init() ) {
508         // Load the local scenery data
509         global_tile_mgr.update( fgGetDouble("/position/longitude"),
510                                 fgGetDouble("/position/latitude") );
511     } else {
512         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
513         exit(-1);
514     }
515
516     FG_LOG( FG_GENERAL, FG_DEBUG,
517             "Current terrain elevation after tile mgr init " <<
518             scenery.cur_elev );
519
520     double dt = 1.0 / fgGetInt("/sim/model-hz");
521     // cout << "dt = " << dt << endl;
522
523     aircraft_dir = fgGetString("/sim/aircraft-dir");
524     const string &model = fgGetString("/sim/flight-model");
525     if (model == "larcsim") {
526         cur_fdm_state = new FGLaRCsim( dt );
527     } else if (model == "jsb") {
528         cur_fdm_state = new FGJSBsim( dt );
529     } else if (model == "ada") {
530         cur_fdm_state = new FGADA( dt );
531     } else if (model == "balloon") {
532         cur_fdm_state = new FGBalloonSim( dt );
533     } else if (model == "magic") {
534         cur_fdm_state = new FGMagicCarpet( dt );
535     } else if (model == "external") {
536         cur_fdm_state = new FGExternal( dt );
537     } else {
538         FG_LOG(FG_GENERAL, FG_ALERT,
539                "Unrecognized flight model '" << model
540                << ", can't init aircraft");
541         exit(-1);
542     }
543     cur_fdm_state->stamp();
544     cur_fdm_state->set_remainder( 0 );
545
546     // allocates structures so must happen before any of the flight
547     // model or control parameters are set
548     fgAircraftInit();   // In the future this might not be the case.
549
550     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"),
551                              scenery.cur_elev );
552     
553     // set the initial position
554     fgInitPosition();
555
556     // Calculate ground elevation at starting point (we didn't have
557     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
558     //
559     // calculalate a cartesian point somewhere along the line between
560     // the center of the earth and our view position.  Doesn't have to
561     // be the exact elevation (this is good because we don't know it
562     // yet :-)
563
564     // now handled inside of the fgTileMgrUpdate()
565
566     // Reset our altitude if we are below ground
567     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
568             << cur_fdm_state->get_Altitude() );
569     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
570             cur_fdm_state->get_Runway_altitude() );
571
572     if ( cur_fdm_state->get_Altitude() < cur_fdm_state->get_Runway_altitude() +
573          3.758099) {
574         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
575                                      3.758099 );
576     }
577
578     FG_LOG( FG_GENERAL, FG_INFO,
579             "Updated position (after elevation adj): ("
580             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
581             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
582             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
583
584     // We need to calculate a few sea_level_radius here so we can pass
585     // the correct value to the view class
586     double sea_level_radius_meters;
587     double lat_geoc;
588     sgGeodToGeoc( cur_fdm_state->get_Latitude(),
589                   cur_fdm_state->get_Altitude(),
590                   &sea_level_radius_meters, &lat_geoc);
591     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
592                                          METER_TO_FEET );
593
594     // The following section sets up the flight model EOM parameters
595     // and should really be read in from one or more files.
596
597     // Initial Velocity
598     fgVelocityInit();
599
600     // Initial Orientation
601 //     cur_fdm_state->
602 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
603 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
604 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
605
606     // Initialize the event manager
607     global_events.Init();
608
609     // Output event stats every 60 seconds
610     global_events.Register( "fgEVENT_MGR::PrintStats()",
611                             fgMethodCallback<fgEVENT_MGR>( &global_events,
612                                                    &fgEVENT_MGR::PrintStats),
613                             fgEVENT::FG_EVENT_READY, 60000 );
614
615     // Initialize win_ratio parameters
616     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
617         globals->get_viewmgr()->get_view(i)->
618             set_win_ratio( fgGetInt("/sim/startup/xsize") /
619                            fgGetInt("/sim/startup/ysize") );
620     }
621
622     // Initialize pilot view
623     FGViewerRPH *pilot_view =
624         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
625
626     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
627                                    cur_fdm_state->get_Lat_geocentric(), 
628                                    cur_fdm_state->get_Altitude() *
629                                    FEET_TO_METER );
630     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
631                                       FEET_TO_METER ); 
632     pilot_view->set_rph( cur_fdm_state->get_Phi(),
633                          cur_fdm_state->get_Theta(),
634                          cur_fdm_state->get_Psi() );
635
636     // set current view to 0 (first) which is our main pilot view
637     globals->set_current_view( pilot_view );
638
639     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
640             << globals->get_current_view()->get_abs_view_pos());
641
642     // fgUpdateSunPos() needs a few position and view parameters set
643     // so it can calculate local relative sun angle and a few other
644     // things for correctly orienting the sky.
645     fgUpdateSunPos();
646     fgUpdateMoonPos();
647     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
648                             fgEVENT::FG_EVENT_READY, 60000);
649     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
650                             fgEVENT::FG_EVENT_READY, 60000);
651
652     // Initialize Lighting interpolation tables
653     l->Init();
654
655     // update the lighting parameters (based on sun angle)
656     global_events.Register( "fgLight::Update()",
657                             fgMethodCallback<fgLIGHT>( &cur_light_params,
658                                                        &fgLIGHT::Update),
659                             fgEVENT::FG_EVENT_READY, 30000 );
660     // update the current timezone each 30 minutes
661     global_events.Register( "fgUpdateLocalTime()", fgUpdateLocalTime,
662                             fgEVENT::FG_EVENT_READY, 1800000);
663
664     // Initialize the weather modeling subsystem
665 #ifndef FG_OLD_WEATHER
666     // Initialize the WeatherDatabase
667     FG_LOG(FG_GENERAL, FG_INFO, "Creating LocalWeatherDatabase");
668     sgVec3 position;
669     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
670                current_aircraft.fdm_state->get_Longitude(),
671                current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER );
672     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
673         new FGLocalWeatherDatabase( position,
674                                     globals->get_fg_root() );
675     // cout << theFGLocalWeatherDatabase << endl;
676     // cout << "visibility = " 
677     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
678
679     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
680     
681     double init_vis = fgGetDouble("/environment/visibility");
682     if ( init_vis > 0 ) {
683         WeatherDatabase->setWeatherVisibility( init_vis );
684     }
685
686     // register the periodic update of the weather
687     global_events.Register( "weather update", fgUpdateWeatherDatabase,
688                             fgEVENT::FG_EVENT_READY, 30000);
689 #else
690     current_weather.Init();
691 #endif
692
693     // Initialize vor/ndb/ils/fix list management and query systems
694     FG_LOG(FG_GENERAL, FG_INFO, "Loading Navaids");
695
696     FG_LOG(FG_GENERAL, FG_INFO, "  VOR/NDB");
697     current_navlist = new FGNavList;
698     FGPath p_nav( globals->get_fg_root() );
699     p_nav.append( "Navaids/default.nav" );
700     current_navlist->init( p_nav );
701
702     FG_LOG(FG_GENERAL, FG_INFO, "  ILS and Marker Beacons");
703     current_beacons = new FGMarkerBeacons;
704     current_beacons->init();
705     current_ilslist = new FGILSList;
706     FGPath p_ils( globals->get_fg_root() );
707     p_ils.append( "Navaids/default.ils" );
708     current_ilslist->init( p_ils );
709
710     FG_LOG(FG_GENERAL, FG_INFO, "  Fixes");
711     current_fixlist = new FGFixList;
712     FGPath p_fix( globals->get_fg_root() );
713     p_fix.append( "Navaids/default.fix" );
714     current_fixlist->init( p_fix );
715
716     // Radio stack subsystem.
717     current_radiostack = new FGRadioStack;
718     current_radiostack->init();
719     current_radiostack->bind();
720
721     // Initialize the Cockpit subsystem
722     if( fgCockpitInit( &current_aircraft )) {
723         // Cockpit initialized ok.
724     } else {
725         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
726         exit(-1);
727     }
728
729     // Initialize the flight model subsystem data structures base on
730     // above values
731
732     cur_fdm_state->init();
733     cur_fdm_state->bind();
734 //     if ( cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") ) ) {
735 //      // fdm init successful
736 //     } else {
737 //      FG_LOG( FG_GENERAL, FG_ALERT, "FDM init() failed!  Cannot continue." );
738 //      exit(-1);
739 //     }
740
741     // *ABCD* I'm just sticking this here for now, it should probably
742     // move eventually
743     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
744
745     if ( cur_fdm_state->get_Altitude() <
746          cur_fdm_state->get_Runway_altitude() + 3.758099)
747     {
748         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
749                                      3.758099 );
750     }
751
752     FG_LOG( FG_GENERAL, FG_INFO,
753             "Updated position (after elevation adj): ("
754             << (cur_fdm_state->get_Latitude() * RAD_TO_DEG) << ", "
755             << (cur_fdm_state->get_Longitude() * RAD_TO_DEG) << ", "
756             << (cur_fdm_state->get_Altitude() * FEET_TO_METER) << ")" );
757     // *ABCD* end of thing that I just stuck in that I should probably
758     // move
759
760     // Joystick support
761     if ( ! fgJoystickInit() ) {
762         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
763     }
764
765     // Autopilot init
766     current_autopilot = new FGAutopilot;
767     current_autopilot->init();
768
769     // initialize the gui parts of the autopilot
770     NewTgtAirportInit();
771     fgAPAdjustInit() ;
772     NewHeadingInit();
773     NewAltitudeInit();
774
775     // Initialize I/O channels
776 #if ! defined( macintosh )
777     fgIOInit();
778 #endif
779
780     // Initialize the 2D panel.
781     string panel_path = fgGetString("/sim/panel/path",
782                                     "Panels/Default/default.xml");
783     current_panel = fgReadPanel(panel_path);
784     if (current_panel == 0) {
785         FG_LOG( FG_INPUT, FG_ALERT, 
786                 "Error reading new panel from " << panel_path );
787     } else {
788         FG_LOG( FG_INPUT, FG_INFO, "Loaded new panel from " << panel_path );
789         current_panel->init();
790         current_panel->bind();
791     }
792
793     // Initialize the BFI
794     FGBFI::init();
795
796     controls.init();
797     controls.bind();
798
799     FG_LOG( FG_GENERAL, FG_INFO, endl);
800
801                                 // Save the initial state for future
802                                 // reference.
803     globals->saveInitialState();
804
805     return true;
806 }
807
808
809 void fgReInitSubsystems( void )
810 {
811     FG_LOG( FG_GENERAL, FG_INFO,
812             "/position/altitude = " << fgGetDouble("/position/altitude") );
813
814     bool freeze = globals->get_freeze();
815     if( !freeze )
816         globals->set_freeze( true );
817     
818     // Initialize the Scenery Management subsystem
819     if ( ! fgSceneryInit() ) {
820         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
821         exit(-1);
822     }
823
824     if( global_tile_mgr.init() ) {
825         // Load the local scenery data
826         global_tile_mgr.update( fgGetDouble("/position/longitude"),
827                                 fgGetDouble("/position/latitude") );
828     } else {
829         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
830                 exit(-1);
831     }
832
833     // cout << "current scenery elev = " << scenery.cur_elev << endl;
834
835     fgFDMSetGroundElevation( fgGetString("/sim/flight-model"), 
836                              scenery.cur_elev );
837     fgInitPosition();
838
839     // Reset our altitude if we are below ground
840     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = "
841             << cur_fdm_state->get_Altitude() );
842     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = "
843             << cur_fdm_state->get_Runway_altitude() );
844
845     if ( cur_fdm_state->get_Altitude() <
846          cur_fdm_state->get_Runway_altitude() + 3.758099)
847     {
848         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
849                                      3.758099 );
850     }
851     double sea_level_radius_meters;
852     double lat_geoc;
853     sgGeodToGeoc( cur_fdm_state->get_Latitude(), cur_fdm_state->get_Altitude(), 
854                   &sea_level_radius_meters, &lat_geoc);
855     cur_fdm_state->set_Sea_level_radius( sea_level_radius_meters *
856                                          METER_TO_FEET );
857         
858     // The following section sets up the flight model EOM parameters
859     // and should really be read in from one or more files.
860
861     // Initial Velocity
862     fgVelocityInit();
863
864     // Initial Orientation
865 //     cur_fdm_state->
866 //      set_Euler_Angles( fgGetDouble("/orientation/roll") * DEG_TO_RAD,
867 //                        fgGetDouble("/orientation/pitch") * DEG_TO_RAD,
868 //                        fgGetDouble("/orientation/heading") * DEG_TO_RAD );
869
870     // Initialize view parameters
871     FGViewerRPH *pilot_view =
872         (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
873
874     pilot_view->set_view_offset( 0.0 );
875     pilot_view->set_goal_view_offset( 0.0 );
876
877     pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
878                                    cur_fdm_state->get_Lat_geocentric(), 
879                                    cur_fdm_state->get_Altitude() *
880                                    FEET_TO_METER );
881     pilot_view->set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
882                                       FEET_TO_METER ); 
883     pilot_view->set_rph( cur_fdm_state->get_Phi(),
884                          cur_fdm_state->get_Theta(),
885                          cur_fdm_state->get_Psi() );
886
887     // set current view to 0 (first) which is our main pilot view
888     globals->set_current_view( pilot_view );
889
890     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = "
891             << globals->get_current_view()->get_abs_view_pos());
892
893     cur_fdm_state->init();
894 //     cur_fdm_state->bind();
895 //     cur_fdm_state->init( 1.0 / fgGetInt("/sim/model-hz") );
896
897     scenery.cur_elev = cur_fdm_state->get_Runway_altitude() * FEET_TO_METER;
898
899     if ( cur_fdm_state->get_Altitude() <
900          cur_fdm_state->get_Runway_altitude() + 3.758099)
901     {
902         cur_fdm_state->set_Altitude( cur_fdm_state->get_Runway_altitude() +
903                                      3.758099 );
904     }
905
906     controls.reset_all();
907     current_autopilot->reset();
908
909     if( !freeze )
910         globals->set_freeze( false );
911 }