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