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