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