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