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