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