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