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