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