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