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