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