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