]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
0731cc05c8435f92285d955589763f84a1f2cf54
[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 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 #ifdef FG_USE_CLOUDS_3D
67 #  include <simgear/sky/clouds3d/SkySceneLoader.hpp>
68 #  include <simgear/sky/clouds3d/SkyUtil.hpp>
69 #endif
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
72
73 #include <Aircraft/aircraft.hxx>
74 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
75 #include <Airports/runways.hxx>
76 #include <Airports/simple.hxx>
77 #include <ATC/ATCdisplay.hxx>
78 #include <ATC/ATCmgr.hxx>
79 #include <ATC/AIMgr.hxx>
80 #include <Autopilot/auto_gui.hxx>
81 #include <Autopilot/newauto.hxx>
82 #include <Cockpit/cockpit.hxx>
83 #include <Cockpit/radiostack.hxx>
84 #include <Cockpit/panel.hxx>
85 #include <Cockpit/panel_io.hxx>
86 #include <FDM/ADA.hxx>
87 #include <FDM/Balloon.h>
88 #include <FDM/ExternalNet/ExternalNet.hxx>
89 #include <FDM/ExternalPipe/ExternalPipe.hxx>
90 #include <FDM/JSBSim/JSBSim.hxx>
91 #include <FDM/LaRCsim.hxx>
92 #include <FDM/MagicCarpet.hxx>
93 #include <FDM/UFO.hxx>
94 #include <FDM/NullFDM.hxx>
95 #include <FDM/YASim/YASim.hxx>
96 #include <GUI/new_gui.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 #if defined(HAVE_PLIB_PSL)
110 #include <Scripting/scriptmgr.hxx>
111 #endif
112 #include <Sound/fg_fx.hxx>
113 #include <Sound/soundmgr.hxx>
114 #include <Systems/system_mgr.hxx>
115 #include <Time/FGEventMgr.hxx>
116 #include <Time/light.hxx>
117 #include <Time/sunpos.hxx>
118 #include <Time/moonpos.hxx>
119 #include <Time/tmp.hxx>
120
121 #ifdef FG_MPLAYER_AS
122 #include <MultiPlayer/multiplaytxmgr.hxx>
123 #include <MultiPlayer/multiplayrxmgr.hxx>
124 #endif
125
126 #ifdef FG_WEATHERCM
127 #  include <WeatherCM/FGLocalWeatherDatabase.h>
128 #else
129 #  include <Environment/environment_mgr.hxx>
130 #endif
131
132 #include "fg_init.hxx"
133 #include "fg_io.hxx"
134 #include "fg_commands.hxx"
135 #include "fg_props.hxx"
136 #include "options.hxx"
137 #include "globals.hxx"
138 #include "logger.hxx"
139 #include "viewmgr.hxx"
140
141 #if defined(FX) && defined(XMESA)
142 #include <GL/xmesa.h>
143 #endif
144
145 SG_USING_STD(string);
146
147 extern const char *default_root;
148
149 #ifdef FG_USE_CLOUDS_3D
150   SkySceneLoader *sgCloud3d;
151 #endif
152
153
154 // Scan the command line options for the specified option and return
155 // the value.
156 static string fgScanForOption( const string& option, int argc, char **argv ) {
157     int i = 1;
158
159     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
160
161     int len = option.length();
162
163     while ( i < argc ) {
164         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
165
166         string arg = argv[i];
167         if ( arg.find( option ) == 0 ) {
168             return arg.substr( len );
169         }
170
171         i++;
172     }
173
174     return "";
175 }
176
177
178 // Scan the user config files for the specified option and return
179 // the value.
180 static string fgScanForOption( const string& option, const string& path ) {
181     sg_gzifstream in( path );
182     if ( !in.is_open() ) {
183         return "";
184     }
185
186     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
187
188     int len = option.length();
189
190     in >> skipcomment;
191 #ifndef __MWERKS__
192     while ( ! in.eof() ) {
193 #else
194     char c = '\0';
195     while ( in.get(c) && c != '\0' ) {
196         in.putback(c);
197 #endif
198         string line;
199
200 #if defined( macintosh )
201         getline( in, line, '\r' );
202 #else
203         getline( in, line, '\n' );
204 #endif
205
206         // catch extraneous (DOS) line ending character
207         if ( line[line.length() - 1] < 32 ) {
208             line = line.substr( 0, line.length()-1 );
209         }
210
211         if ( line.find( option ) == 0 ) {
212             return line.substr( len );
213         }
214
215         in >> skipcomment;
216     }
217
218     return "";
219 }
220
221
222 // Read in configuration (files and command line options) but only set
223 // fg_root
224 bool fgInitFGRoot ( int argc, char **argv ) {
225     string root;
226     char* envp;
227
228     // First parse command line options looking for --fg-root=, this
229     // will override anything specified in a config file
230     root = fgScanForOption( "--fg-root=", argc, argv);
231
232 #if defined( unix ) || defined( __CYGWIN__ )
233     // Next check home directory for .fgfsrc.hostname file
234     if ( root.empty() ) {
235         envp = ::getenv( "HOME" );
236         if ( envp != NULL ) {
237             SGPath config( envp );
238             config.append( ".fgfsrc" );
239             char name[256];
240             gethostname( name, 256 );
241             config.concat( "." );
242             config.concat( name );
243             root = fgScanForOption( "--fg-root=", config.str() );
244         }
245     }
246 #endif
247
248     // Next check home directory for .fgfsrc file
249     if ( root.empty() ) {
250         envp = ::getenv( "HOME" );
251         if ( envp != NULL ) {
252             SGPath config( envp );
253             config.append( ".fgfsrc" );
254             root = fgScanForOption( "--fg-root=", config.str() );
255         }
256     }
257
258     // Next check if fg-root is set as an env variable
259     if ( root.empty() ) {
260         envp = ::getenv( "FG_ROOT" );
261         if ( envp != NULL ) {
262             root = envp;
263         }
264     }
265
266     // Otherwise, default to a random compiled-in location if we can't
267     // find fg-root any other way.
268     if ( root.empty() ) {
269 #if defined( __CYGWIN__ )
270         root = "/FlightGear";
271 #elif defined( WIN32 )
272         root = "\\FlightGear";
273 #elif defined( macintosh )
274         root = "";
275 #else
276         root = PKGLIBDIR;
277 #endif
278     }
279
280     SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
281     globals->set_fg_root(root);
282
283     return true;
284 }
285
286
287 // Read in configuration (files and command line options) but only set
288 // aircraft
289 bool fgInitFGAircraft ( int argc, char **argv ) {
290     string aircraft;
291     char* envp;
292
293     // First parse command line options looking for --aircraft=, this
294     // will override anything specified in a config file
295     aircraft = fgScanForOption( "--aircraft=", argc, argv );
296
297 #if defined( unix ) || defined( __CYGWIN__ )
298     // Next check home directory for .fgfsrc.hostname file
299     if ( aircraft.empty() ) {
300         envp = ::getenv( "HOME" );
301         if ( envp != NULL ) {
302             SGPath config( envp );
303             config.append( ".fgfsrc" );
304             char name[256];
305             gethostname( name, 256 );
306             config.concat( "." );
307             config.concat( name );
308             aircraft = fgScanForOption( "--aircraft=", config.str() );
309         }
310     }
311 #endif
312
313     // Next check home directory for .fgfsrc file
314     if ( aircraft.empty() ) {
315         envp = ::getenv( "HOME" );
316         if ( envp != NULL ) {
317             SGPath config( envp );
318             config.append( ".fgfsrc" );
319             aircraft = fgScanForOption( "--aircraft=", config.str() );
320         }
321     }
322
323     // if an aircraft was specified, set the property name
324     if ( !aircraft.empty() ) {
325         SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
326         fgSetString("/sim/aircraft", aircraft.c_str() );
327     } else {
328         SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
329     }
330
331     return true;
332 }
333
334
335 // Return the current base package version
336 string fgBasePackageVersion() {
337     SGPath base_path( globals->get_fg_root() );
338     base_path.append("version");
339
340     sg_gzifstream in( base_path.str() );
341     if ( !in.is_open() ) {
342         SGPath old_path( globals->get_fg_root() );
343         old_path.append( "Thanks" );
344         sg_gzifstream old( old_path.str() );
345         if ( !old.is_open() ) {
346             return "[none]";
347         } else {
348             return "[old version]";
349         }
350     }
351
352     string version;
353     in >> version;
354
355     return version;
356 }
357
358
359 // Initialize the localization
360 SGPropertyNode *fgInitLocale(const char *language) {
361    SGPropertyNode *c_node = NULL, *d_node = NULL;
362    SGPropertyNode *intl = fgGetNode("/sim/intl");
363
364    SG_LOG(SG_GENERAL, SG_INFO, "Selecting language: " << language );
365
366    // localization not defined
367    if (!intl)
368       return NULL;
369
370    //
371    // Select the proper language from the list
372    //
373    vector<SGPropertyNode_ptr> locale = intl->getChildren("locale");
374    for (unsigned int i = 0; i < locale.size(); i++) {
375
376       vector<SGPropertyNode_ptr> lang = locale[i]->getChildren("lang");
377       for (unsigned int j = 0; j < lang.size(); j++) {
378
379          if (!strcmp(lang[j]->getStringValue(), language)) {
380             c_node = locale[i];
381             break;
382          }
383       }
384    }
385
386
387    // Get the defaults
388    d_node = intl->getChild("locale");
389    if (!c_node)
390       c_node = d_node;
391
392    // Check for localized font
393    SGPropertyNode *font_n = c_node->getNode("font", true);
394    if ( !strcmp(font_n->getStringValue(), "") )
395       font_n->setStringValue(d_node->getStringValue("font", "typewriter.txf"));
396
397
398    //
399    // Load the default strings
400    //
401    SGPath d_path( globals->get_fg_root() );
402
403    const char *d_path_str = d_node->getStringValue("strings");
404    if (!d_path_str) {
405       SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
406       return NULL;
407    }
408
409    d_path.append(d_path_str);
410    SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
411                                   << d_path.str());
412
413    SGPropertyNode *strings = c_node->getNode("strings");
414    try {
415       readProperties(d_path.str(), strings);
416    } catch (const sg_exception &e) {
417       SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
418       return NULL;
419    }
420
421    //
422    // Load the language specific strings
423    //
424    if (c_node != d_node) {
425       SGPath c_path( globals->get_fg_root() );
426
427       const char *c_path_str = c_node->getStringValue("strings");
428       if (!c_path_str) {
429          SG_LOG(SG_GENERAL, SG_ALERT, "Incorrect path in configuration file.");
430          return NULL;
431       }
432
433       c_path.append(c_path_str);
434       SG_LOG(SG_GENERAL, SG_INFO, "Reading localized strings from "
435                                      << c_path.str());
436
437       try {
438          readProperties(c_path.str(), strings);
439       } catch (const sg_exception &e) {
440          SG_LOG(SG_GENERAL, SG_ALERT, "Unable to read the localized strings");
441          return NULL;
442       }
443    }
444
445    return c_node;
446 }
447
448
449
450 // Initialize the localization routines
451 bool fgDetectLanguage() {
452     char *language = ::getenv("LANG");
453
454     if (language == NULL) {
455         SG_LOG(SG_GENERAL, SG_INFO, "Unable to detect the language" );
456         language = "C";
457     }
458
459     SGPropertyNode *locale = fgInitLocale(language);
460     if (!locale) {
461        cerr << "No internationalization settings specified in preferences.xml"
462             << endl;
463
464        return false;
465     }
466
467     globals->set_locale( locale );
468
469     return true;
470 }
471
472 // Attempt to locate and parse the various non-XML config files in order
473 // from least precidence to greatest precidence
474 static void
475 do_options (int argc, char ** argv)
476 {
477     // Check for $fg_root/system.fgfsrc
478     SGPath config( globals->get_fg_root() );
479     config.append( "system.fgfsrc" );
480     fgParseOptions(config.str());
481
482 #if defined( unix ) || defined( __CYGWIN__ )
483     char name[256];
484     // Check for $fg_root/system.fgfsrc.hostname
485     gethostname( name, 256 );
486     config.concat( "." );
487     config.concat( name );
488     fgParseOptions(config.str());
489 #endif
490
491     // Check for ~/.fgfsrc
492     char* envp = ::getenv( "HOME" );
493     if ( envp != NULL ) {
494         config.set( envp );
495         config.append( ".fgfsrc" );
496         fgParseOptions(config.str());
497     }
498
499 #if defined( unix ) || defined( __CYGWIN__ )
500     // Check for ~/.fgfsrc.hostname
501     gethostname( name, 256 );
502     config.concat( "." );
503     config.concat( name );
504     fgParseOptions(config.str());
505 #endif
506
507     // Parse remaining command line options
508     // These will override anything specified in a config file
509     fgParseArgs(argc, argv);
510 }
511
512
513 // Read in configuration (file and command line)
514 bool fgInitConfig ( int argc, char **argv ) {
515
516     // First, set some sane default values
517     fgSetDefaults();
518
519     // Read global preferences from $FG_ROOT/preferences.xml
520     SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
521     fgLoadProps("preferences.xml", globals->get_props());
522     SG_LOG(SG_INPUT, SG_INFO, "Finished Reading global preferences");
523
524     // Detect the required language as early as possible
525     if ( !fgDetectLanguage() ) {
526         return false;
527     }
528
529     // Scan user config files and command line for a specified aircraft.
530     fgInitFGAircraft(argc, argv);
531
532     string aircraft = fgGetString("/sim/aircraft", "");
533     if ( aircraft.size() > 0 ) {
534         SGPath aircraft_path(globals->get_fg_root());
535         aircraft_path.append("Aircraft");
536         aircraft_path.append(aircraft);
537         aircraft_path.concat("-set.xml");
538         SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft
539                << " from " << aircraft_path.str());
540         try {
541             readProperties(aircraft_path.str(), globals->get_props());
542         } catch (const sg_exception &e) {
543             string message = "Error reading default aircraft: ";
544             message += e.getFormattedMessage();
545             SG_LOG(SG_INPUT, SG_ALERT, message);
546             exit(2);
547         }
548     } else {
549         SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified");
550     }
551
552     // parse options after loading aircraft to ensure any user
553     // overrides of defaults are honored.
554     do_options(argc, argv);
555
556     return true;
557 }
558
559
560 // find basic airport location info from airport database
561 bool fgFindAirportID( const string& id, FGAirport *a ) {
562     if ( id.length() ) {
563         SGPath path( globals->get_fg_root() );
564         path.append( "Airports" );
565         path.append( "simple.mk4" );
566         FGAirports airports( path.c_str() );
567
568         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
569
570         if ( ! airports.search( id, a ) ) {
571             SG_LOG( SG_GENERAL, SG_ALERT,
572                     "Failed to find " << id << " in " << path.str() );
573             return false;
574         }
575     } else {
576         return false;
577     }
578
579     SG_LOG( SG_GENERAL, SG_INFO,
580             "Position for " << id << " is ("
581             << a->longitude << ", "
582             << a->latitude << ")" );
583
584     return true;
585 }
586
587
588 // get airport elevation
589 static double fgGetAirportElev( const string& id ) {
590     FGAirport a;
591     // double lon, lat;
592
593     SG_LOG( SG_GENERAL, SG_INFO,
594             "Finding elevation for airport: " << id );
595
596     if ( fgFindAirportID( id, &a ) ) {
597         return a.elevation;
598     } else {
599         return -9999.0;
600     }
601 }
602
603
604 // Preset lon/lat given an airport id
605 static bool fgSetPosFromAirportID( const string& id ) {
606     FGAirport a;
607     // double lon, lat;
608
609     SG_LOG( SG_GENERAL, SG_INFO,
610             "Attempting to set starting position from airport code " << id );
611
612     if ( fgFindAirportID( id, &a ) ) {
613         // presets
614         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
615         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
616
617         // other code depends on the actual postition being set so set
618         // that as well
619         fgSetDouble("/position/longitude-deg", a.longitude );
620         fgSetDouble("/position/latitude-deg", a.latitude );
621
622         SG_LOG( SG_GENERAL, SG_INFO,
623                 "Position for " << id << " is (" << a.longitude
624                 << ", " << a.latitude << ")" );
625
626         return true;
627     } else {
628         return false;
629     }
630 }
631
632
633 // Set current tower position lon/lat given an airport id
634 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
635     FGAirport a;
636     // tower height hard coded for now...
637     float towerheight=50.0f;
638
639     // make a little off the heading for 1 runway airports...
640     float fudge_lon = fabs(sin(hdg)) * .003f;
641     float fudge_lat = .003f - fudge_lon;
642
643     if ( fgFindAirportID( id, &a ) ) {
644         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
645         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
646         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
647         return true;
648     } else {
649         return false;
650     }
651
652 }
653
654
655 // Set current_options lon/lat given an airport id and heading (degrees)
656 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
657     FGRunway r;
658     FGRunway found_r;
659     double found_dir = 0.0;
660
661     if ( id.length() ) {
662         // set initial position from runway and heading
663
664         SGPath path( globals->get_fg_root() );
665         path.append( "Airports" );
666         path.append( "runways.mk4" );
667         FGRunways runways( path.c_str() );
668
669         SG_LOG( SG_GENERAL, SG_INFO,
670                 "Attempting to set starting position from runway code "
671                 << id << " heading " << tgt_hdg );
672
673         if ( ! runways.search( id, &r ) ) {
674             SG_LOG( SG_GENERAL, SG_ALERT,
675                     "Failed to find " << id << " in database." );
676             return false;
677         }
678
679         double diff;
680         double min_diff = 360.0;
681
682         while ( r.id == id ) {
683             // forward direction
684             diff = tgt_hdg - r.heading;
685             while ( diff < -180.0 ) { diff += 360.0; }
686             while ( diff >  180.0 ) { diff -= 360.0; }
687             diff = fabs(diff);
688             SG_LOG( SG_GENERAL, SG_INFO,
689                     "Runway " << r.rwy_no << " heading = " << r.heading <<
690                     " diff = " << diff );
691             if ( diff < min_diff ) {
692                 min_diff = diff;
693                 found_r = r;
694                 found_dir = 0;
695             }
696
697             // reverse direction
698             diff = tgt_hdg - r.heading - 180.0;
699             while ( diff < -180.0 ) { diff += 360.0; }
700             while ( diff >  180.0 ) { diff -= 360.0; }
701             diff = fabs(diff);
702             SG_LOG( SG_GENERAL, SG_INFO,
703                     "Runway -" << r.rwy_no << " heading = " <<
704                     r.heading + 180.0 <<
705                     " diff = " << diff );
706             if ( diff < min_diff ) {
707                 min_diff = diff;
708                 found_r = r;
709                 found_dir = 180.0;
710             }
711
712             runways.next( &r );
713         }
714
715         SG_LOG( SG_GENERAL, SG_INFO, "closest runway = " << found_r.rwy_no
716                 << " + " << found_dir );
717
718     } else {
719         return false;
720     }
721
722     double heading = found_r.heading + found_dir;
723     while ( heading >= 360.0 ) { heading -= 360.0; }
724
725     double lat2, lon2, az2;
726     double azimuth = found_r.heading + found_dir + 180.0;
727     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
728
729     SG_LOG( SG_GENERAL, SG_INFO,
730             "runway =  " << found_r.lon << ", " << found_r.lat
731             << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
732             << " heading = " << azimuth );
733     
734     geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
735                         azimuth, found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
736                         &lat2, &lon2, &az2 );
737
738     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
739         double olat, olon;
740         double odist = fgGetDouble("/sim/presets/offset-distance");
741         odist *= SG_NM_TO_METER;
742         double oaz = azimuth;
743         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
744             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
745         }
746         while ( oaz >= 360.0 ) { oaz -= 360.0; }
747         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
748         lat2=olat;
749         lon2=olon;
750     }
751
752     // presets
753     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
754     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
755     fgSetDouble("/sim/presets/heading-deg", heading );
756
757     // other code depends on the actual values being set ...
758     fgSetDouble("/position/longitude-deg",  lon2 );
759     fgSetDouble("/position/latitude-deg",  lat2 );
760     fgSetDouble("/orientation/heading-deg", heading );
761
762     SG_LOG( SG_GENERAL, SG_INFO,
763             "Position for " << id << " is ("
764             << lon2 << ", "
765             << lat2 << ") new heading is "
766             << heading );
767
768     return true;
769 }
770
771
772 // Set current_options lon/lat given an airport id and heading (degrees)
773 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
774     FGRunway r;
775     FGRunway found_r;
776     double heading = 0.0;
777     string runway;
778     bool match = false;
779
780     // standardize input number
781     string tmp = rwy.substr(1, 1);
782     if ( tmp == "L" || tmp == "R" || tmp == "C" ) {
783         runway = "0";
784         runway += rwy;
785     } else {
786         runway = rwy;
787     }
788
789     if ( id.length() ) {
790         // set initial position from runway and heading
791
792         SGPath path( globals->get_fg_root() );
793         path.append( "Airports" );
794         path.append( "runways.mk4" );
795         FGRunways runways( path.c_str() );
796
797         SG_LOG( SG_GENERAL, SG_INFO,
798                 "Attempting to set starting position for "
799                 << id << ":" << runway );
800
801         if ( ! runways.search( id, &r ) ) {
802             SG_LOG( SG_GENERAL, SG_ALERT,
803                     "Failed to find " << id << " in database." );
804             return false;
805         }
806
807         while ( r.id == id ) {
808             // forward direction
809             if ( r.rwy_no == runway ) {
810                 found_r = r;
811                 heading = r.heading;
812                 match = true;
813                 SG_LOG( SG_GENERAL, SG_INFO,
814                         "Runway " << r.rwy_no << " heading = " << heading );
815             }
816
817             // calculate reciprocal runway number
818             string snum = r.rwy_no;
819             int len = snum.length();
820             string letter = "";
821             string rev_letter = "";
822             int i;
823             for ( i = 0; i < len; ++i ) {
824                 string tmp = snum.substr(i, 1);
825                 if ( tmp == "L" ) {
826                     letter = "L";
827                     rev_letter = "R";
828                 } else if ( tmp == "R" ) {
829                     letter = "R";
830                     rev_letter = "L";
831                 } else if ( tmp == "C" ) {
832                     letter == "C";
833                     rev_letter = "C";
834                 }
835             }
836             for ( i = 0; i < len; ++i ) {
837                 string tmp = snum.substr(i, 1);
838                 if ( tmp == "L" || tmp == "R" || tmp == "C" || tmp == " " ) {
839                     snum = snum.substr(0, i);
840                 }
841             }
842             SG_LOG(SG_GENERAL, SG_DEBUG, "Runway num = '" << snum << "'");
843             int num = atoi( snum.c_str() ) + 18;
844             while ( num > 36 ) { num -= 36; }
845             while ( num <= 0 ) { num += 36; }
846
847             char recip_no[10];
848             snprintf( recip_no, 10, "%02d%s", num, rev_letter.c_str() );
849
850             // reverse direction
851             if ( (string)recip_no == runway ) {
852                 found_r = r;
853                 heading = r.heading + 180;
854                 while ( heading > 360.0 ) { heading -= 360; }
855                 match = true;
856                 SG_LOG( SG_GENERAL, SG_INFO,
857                         "Runway " << r.rwy_no << " heading = " << heading );
858             }
859
860             runways.next( &r );
861         }
862     } else {
863         return false;
864     }
865
866     if ( match ) {
867         double lat2, lon2, az2;
868         double azimuth = heading + 180.0;
869         while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
870
871         SG_LOG( SG_GENERAL, SG_INFO,
872                 "runway =  " << found_r.lon << ", " << found_r.lat
873                 << " length = " << found_r.length * SG_FEET_TO_METER * 0.5 
874                 << " heading = " << azimuth );
875     
876         geo_direct_wgs_84 ( 0, found_r.lat, found_r.lon, 
877                             azimuth,
878                             found_r.length * SG_FEET_TO_METER * 0.5 - 5.0,
879                             &lat2, &lon2, &az2 );
880
881         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
882         {
883             double olat, olon;
884             double odist = fgGetDouble("/sim/presets/offset-distance");
885             odist *= SG_NM_TO_METER;
886             double oaz = azimuth;
887             if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
888             {
889                 oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
890             }
891             while ( oaz >= 360.0 ) { oaz -= 360.0; }
892             geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
893             lat2=olat;
894             lon2=olon;
895         }
896
897         // presets
898         fgSetDouble("/sim/presets/longitude-deg",  lon2 );
899         fgSetDouble("/sim/presets/latitude-deg",  lat2 );
900         fgSetDouble("/sim/presets/heading-deg", heading );
901
902         // other code depends on the actual values being set ...
903         fgSetDouble("/position/longitude-deg",  lon2 );
904         fgSetDouble("/position/latitude-deg",  lat2 );
905         fgSetDouble("/orientation/heading-deg", heading );
906
907         SG_LOG( SG_GENERAL, SG_INFO,
908                 "Position for " << id << " is ("
909                 << lon2 << ", "
910                 << lat2 << ") new heading is "
911                 << heading );
912
913         return true;
914     } else {
915         return false;
916     }
917 }
918
919
920 static void fgSetDistOrAltFromGlideSlope() {
921     string apt_id = fgGetString("/sim/presets/airport-id");
922     double gs = fgGetDouble("/sim/presets/glideslope-deg")
923         * SG_DEGREES_TO_RADIANS ;
924     double od = fgGetDouble("/sim/presets/offset-distance");
925     double alt = fgGetDouble("/sim/presets/altitude-ft");
926
927     double apt_elev = 0.0;
928     if ( ! apt_id.empty() ) {
929         apt_elev = fgGetAirportElev( apt_id );
930         if ( apt_elev < -9990.0 ) {
931             apt_elev = 0.0;
932         }
933     } else {
934         apt_elev = 0.0;
935     }
936
937     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
938         // set altitude from glideslope and offset-distance
939         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
940         alt = fabs(od*tan(gs)) + apt_elev;
941         fgSetDouble("/sim/presets/altitude-ft", alt);
942         fgSetBool("/sim/presets/onground", false);
943         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
944                 << alt  << " ft" );
945     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
946         // set offset-distance from glideslope and altitude
947         od  = (alt - apt_elev) / tan(gs);
948         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
949         fgSetDouble("/sim/presets/offset-distance", od);
950         fgSetBool("/sim/presets/onground", false);
951         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
952                 << od  << " nm" );
953     } else if( fabs(gs) > 0.01 ) {
954         SG_LOG( SG_GENERAL, SG_ALERT,
955                 "Glideslope given but not altitude or offset-distance." );
956         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
957         fgSetDouble("/sim/presets/glideslope-deg", 0);
958         fgSetBool("/sim/presets/onground", true);
959     }
960 }                       
961
962
963 // Set current_options lon/lat given an airport id and heading (degrees)
964 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
965     FGNav *nav = current_navlist->findByIdentAndFreq( id.c_str(), freq );
966
967     // set initial position from runway and heading
968     if ( nav != NULL ) {
969         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
970                 << id << ":" << freq );
971
972         double lon = nav->get_lon();
973         double lat = nav->get_lat();
974
975         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
976         {
977             double odist = fgGetDouble("/sim/presets/offset-distance")
978                 * SG_NM_TO_METER;
979             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
980                 + 180.0;
981             while ( oaz >= 360.0 ) { oaz -= 360.0; }
982             double olat, olon, az2;
983             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
984
985             lat = olat;
986             lon = olon;
987         }
988
989         // presets
990         fgSetDouble("/sim/presets/longitude-deg",  lon );
991         fgSetDouble("/sim/presets/latitude-deg",  lat );
992
993         // other code depends on the actual values being set ...
994         fgSetDouble("/position/longitude-deg",  lon );
995         fgSetDouble("/position/latitude-deg",  lat );
996         fgSetDouble("/orientation/heading-deg", 
997                     fgGetDouble("/sim/presets/heading-deg") );
998
999         SG_LOG( SG_GENERAL, SG_INFO,
1000                 "Position for " << id << ":" << freq << " is ("
1001                 << lon << ", "<< lat << ")" );
1002
1003         return true;
1004     } else {
1005         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1006                 << id << ":" << freq );
1007         return false;
1008     }
1009 }
1010
1011
1012 // Set current_options lon/lat given an airport id and heading (degrees)
1013 static bool fgSetPosFromFix( const string& id ) {
1014     FGFix fix;
1015
1016     // set initial position from runway and heading
1017     if ( current_fixlist->query( id.c_str(), &fix ) ) {
1018         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1019                 << id );
1020
1021         double lon = fix.get_lon();
1022         double lat = fix.get_lat();
1023
1024         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1025         {
1026             double odist = fgGetDouble("/sim/presets/offset-distance")
1027                 * SG_NM_TO_METER;
1028             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1029                 + 180.0;
1030             while ( oaz >= 360.0 ) { oaz -= 360.0; }
1031             double olat, olon, az2;
1032             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1033
1034             lat = olat;
1035             lon = olon;
1036         }
1037
1038         // presets
1039         fgSetDouble("/sim/presets/longitude-deg",  lon );
1040         fgSetDouble("/sim/presets/latitude-deg",  lat );
1041
1042         // other code depends on the actual values being set ...
1043         fgSetDouble("/position/longitude-deg",  lon );
1044         fgSetDouble("/position/latitude-deg",  lat );
1045         fgSetDouble("/orientation/heading-deg", 
1046                     fgGetDouble("/sim/presets/heading-deg") );
1047
1048         SG_LOG( SG_GENERAL, SG_INFO,
1049                 "Position for " << id << " is ("
1050                 << lon << ", "<< lat << ")" );
1051
1052         return true;
1053     } else {
1054         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1055                 << id );
1056         return false;
1057     }
1058 }
1059
1060
1061 /**
1062  * Initialize vor/ndb/ils/fix list management and query systems
1063  */
1064 bool
1065 fgInitNav ()
1066 {
1067     SG_LOG(SG_GENERAL, SG_INFO, "Loading Navaids");
1068
1069     SG_LOG(SG_GENERAL, SG_INFO, "  VOR/NDB");
1070     current_navlist = new FGNavList;
1071     SGPath p_nav( globals->get_fg_root() );
1072     p_nav.append( "Navaids/default.nav" );
1073     current_navlist->init( p_nav );
1074
1075     SG_LOG(SG_GENERAL, SG_INFO, "  ILS and Marker Beacons");
1076     current_beacons = new FGMarkerBeacons;
1077     current_beacons->init();
1078     current_ilslist = new FGILSList;
1079     SGPath p_ils( globals->get_fg_root() );
1080     p_ils.append( "Navaids/default.ils" );
1081     current_ilslist->init( p_ils );
1082
1083     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1084     current_fixlist = new FGFixList;
1085     SGPath p_fix( globals->get_fg_root() );
1086     p_fix.append( "Navaids/default.fix" );
1087     current_fixlist->init( p_fix );
1088
1089     return true;
1090 }
1091
1092
1093 // Set the initial position based on presets (or defaults)
1094 bool fgInitPosition() {
1095     bool set_pos = false;
1096
1097     // If glideslope is specified, then calculate offset-distance or
1098     // altitude relative to glide slope if either of those was not
1099     // specified.
1100     fgSetDistOrAltFromGlideSlope();
1101
1102     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1103     // If not, check for an airport-id and use that.
1104     // If not, default to the middle of the KSFO field.
1105     // The default values for lon/lat are deliberately out of range
1106     // so that the airport-id can take effect; valid lon/lat will
1107     // override airport-id, however.
1108     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1109     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1110     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1111          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1112     {
1113         set_pos = true;
1114     }
1115
1116     string apt = fgGetString("/sim/presets/airport-id");
1117     string rwy_no = fgGetString("/sim/presets/runway");
1118     double hdg = fgGetDouble("/sim/presets/heading-deg");
1119     string vor = fgGetString("/sim/presets/vor-id");
1120     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1121     string ndb = fgGetString("/sim/presets/ndb-id");
1122     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1123     string fix = fgGetString("/sim/presets/fix");
1124     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1125         // An airport + runway is requested
1126         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1127             // set position (a little off the heading for single
1128             // runway airports)
1129             fgSetTowerPosFromAirportID( apt, hdg );
1130
1131             set_pos = true;
1132         }
1133     }
1134     if ( !set_pos && !apt.empty() ) {
1135         // An airport is requested (find runway closest to hdg)
1136         bool ok = false;
1137         if (fgGetDouble("/sim/presets/altitude-ft") <= 0 &&
1138             fgGetDouble("/sim/presets/offset-distance") == 0)
1139             ok = fgSetPosFromAirportIDandHdg( apt, hdg );
1140         else
1141             ok = fgSetPosFromAirportID( apt );
1142             
1143         if (ok) {
1144                 // set position (a little off the heading for single
1145                 // runway airports)
1146                 fgSetTowerPosFromAirportID( apt, hdg );
1147
1148             set_pos = true;
1149         }
1150     }
1151     if ( !set_pos && !vor.empty() ) {
1152         // a VOR is requested
1153         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1154             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1155                 fgSetBool("/sim/presets/onground", false);
1156             } else {
1157                 fgSetBool("/sim/presets/onground", true);
1158             }
1159             set_pos = true;
1160         }
1161     }
1162     if ( !set_pos && !ndb.empty() ) {
1163         // an NDB is requested
1164         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1165             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1166                 fgSetBool("/sim/presets/onground", false);
1167             } else {
1168                 fgSetBool("/sim/presets/onground", true);
1169             }
1170             set_pos = true;
1171         }
1172     }
1173     if ( !set_pos && !fix.empty() ) {
1174         // a Fix is requested
1175         if ( fgSetPosFromFix( fix ) ) {
1176             if ( fgGetDouble("/sim/presets/altitude-ft") > -9990.0 ) {
1177                 fgSetBool("/sim/presets/onground", false);
1178             } else {
1179                 fgSetBool("/sim/presets/onground", true);
1180             }
1181             set_pos = true;
1182         }
1183     }
1184
1185     if ( !set_pos ) {
1186         // No lon/lat specified, no airport specified, default to
1187         // middle of KSFO field.
1188         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1189         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1190     }
1191
1192     fgSetDouble( "/position/longitude-deg",
1193                  fgGetDouble("/sim/presets/longitude-deg") );
1194     fgSetDouble( "/position/latitude-deg",
1195                  fgGetDouble("/sim/presets/latitude-deg") );
1196     fgSetDouble( "/orientation/heading-deg",
1197                  fgGetDouble("/sim/presets/heading-deg") );
1198
1199     return true;
1200 }
1201
1202
1203 // General house keeping initializations
1204 bool fgInitGeneral() {
1205     string root;
1206
1207 #if defined(FX) && defined(XMESA)
1208     char *mesa_win_state;
1209 #endif
1210
1211     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1212     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1213
1214     root = globals->get_fg_root();
1215     if ( ! root.length() ) {
1216         // No root path set? Then bail ...
1217         SG_LOG( SG_GENERAL, SG_ALERT,
1218                 "Cannot continue without a path to the base package "
1219                 << "being defined." );
1220         exit(-1);
1221     }
1222     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1223
1224 #if defined(FX) && defined(XMESA)
1225     // initialize full screen flag
1226     globals->set_fullscreen(false);
1227     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1228         // Test for the MESA_GLX_FX env variable
1229         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1230             // test if we are fullscreen mesa/glide
1231             if ( (mesa_win_state[0] == 'f') ||
1232                  (mesa_win_state[0] == 'F') ) {
1233                 globals->set_fullscreen(true);
1234             }
1235         }
1236     }
1237 #endif
1238
1239     return true;
1240 }
1241
1242
1243 // Initialize the flight model subsystem.  This just creates the
1244 // object.  The actual fdm initialization is delayed until we get a
1245 // proper scenery elevation hit.  This is checked for in main.cxx
1246
1247 void fgInitFDM() {
1248
1249     if ( cur_fdm_state ) {
1250         delete cur_fdm_state;
1251         cur_fdm_state = 0;
1252     }
1253
1254     double dt = 1.0 / fgGetInt("/sim/model-hz");
1255     aircraft_dir = fgGetString("/sim/aircraft-dir");
1256     const string &model = fgGetString("/sim/flight-model");
1257
1258     try {
1259         if ( model == "larcsim" ) {
1260             cur_fdm_state = new FGLaRCsim( dt );
1261         } else if ( model == "jsb" ) {
1262             cur_fdm_state = new FGJSBsim( dt );
1263         } else if ( model == "ada" ) {
1264             cur_fdm_state = new FGADA( dt );
1265         } else if ( model == "balloon" ) {
1266             cur_fdm_state = new FGBalloonSim( dt );
1267         } else if ( model == "magic" ) {
1268             cur_fdm_state = new FGMagicCarpet( dt );
1269         } else if ( model == "ufo" ) {
1270             cur_fdm_state = new FGUFO( dt );
1271         } else if ( model == "external" ) {
1272             // external is a synonym for "--fdm=null" and is
1273             // maintained here for backwards compatibility
1274             cur_fdm_state = new FGNullFDM( dt );
1275         } else if ( model.find("network") == 0 ) {
1276             string host = "localhost";
1277             int port1 = 5501;
1278             int port2 = 5502;
1279             int port3 = 5503;
1280             string net_options = model.substr(8);
1281             string::size_type begin, end;
1282             begin = 0;
1283             // host
1284             end = net_options.find( ",", begin );
1285             if ( end != string::npos ) {
1286                 host = net_options.substr(begin, end - begin);
1287                 begin = end + 1;
1288             }
1289             // port1
1290             end = net_options.find( ",", begin );
1291             if ( end != string::npos ) {
1292                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1293                 begin = end + 1;
1294             }
1295             // port2
1296             end = net_options.find( ",", begin );
1297             if ( end != string::npos ) {
1298                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1299                 begin = end + 1;
1300             }
1301             // port3
1302             end = net_options.find( ",", begin );
1303             if ( end != string::npos ) {
1304                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1305                 begin = end + 1;
1306             }
1307             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1308         } else if ( model.find("pipe") == 0 ) {
1309             string pipe_path = model.substr(5);
1310             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1311         } else if ( model == "null" ) {
1312             cur_fdm_state = new FGNullFDM( dt );
1313         } else if ( model == "yasim" ) {
1314             cur_fdm_state = new YASim( dt );
1315         } else {
1316             SG_LOG(SG_GENERAL, SG_ALERT,
1317                    "Unrecognized flight model '" << model
1318                    << "', cannot init flight dynamics model.");
1319             exit(-1);
1320         }
1321     } catch ( ... ) {
1322         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1323         exit(-1);
1324     }
1325 }
1326
1327 static void printMat(const sgVec4 *mat, char *name="")
1328 {
1329     int i;
1330     cout << name << endl;
1331     for(i=0; i<4; i++) {
1332         cout <<"  "<<mat[i][0]<<" "<<mat[i][1]<<" "<<mat[i][2]<<" "<<mat[i][3]<<endl;
1333     }
1334     cout << endl;
1335 }
1336
1337 // Initialize view parameters
1338 void fgInitView() {
1339   // force update of model so that viewer can get some data...
1340   globals->get_aircraft_model()->update(0);
1341   // run update for current view so that data is current...
1342   globals->get_viewmgr()->update(0);
1343
1344   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1345   printMat(globals->get_current_view()->get_UP(),"UP");
1346   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1347   
1348 }
1349
1350
1351 SGTime *fgInitTime() {
1352     // Initialize time
1353     static const SGPropertyNode *longitude
1354         = fgGetNode("/position/longitude-deg");
1355     static const SGPropertyNode *latitude
1356         = fgGetNode("/position/latitude-deg");
1357     static const SGPropertyNode *cur_time_override
1358         = fgGetNode("/sim/time/cur-time-override", true);
1359
1360     SGPath zone( globals->get_fg_root() );
1361     zone.append( "Timezone" );
1362     SGTime *t = new SGTime( longitude->getDoubleValue()
1363                               * SGD_DEGREES_TO_RADIANS,
1364                             latitude->getDoubleValue()
1365                               * SGD_DEGREES_TO_RADIANS,
1366                             zone.str(),
1367                             cur_time_override->getLongValue() );
1368
1369     // Handle potential user specified time offsets
1370     time_t cur_time = t->get_cur_time();
1371     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1372     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1373     time_t aircraftLocalTime = 
1374         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1375
1376     // Okay, we now have six possible scenarios
1377     int offset = fgGetInt("/sim/startup/time-offset");
1378     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1379     if (offset_type == "system-offset") {
1380         globals->set_warp( offset );
1381     } else if (offset_type == "gmt-offset") {
1382         globals->set_warp( offset - (currGMT - systemLocalTime) );
1383     } else if (offset_type == "latitude-offset") {
1384         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1385     } else if (offset_type == "system") {
1386         globals->set_warp( offset - cur_time );
1387     } else if (offset_type == "gmt") {
1388         globals->set_warp( offset - currGMT );
1389     } else if (offset_type == "latitude") {
1390         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1391                            cur_time ); 
1392     } else {
1393         SG_LOG( SG_GENERAL, SG_ALERT,
1394                 "FG_TIME::Unsupported offset type " << offset_type );
1395         exit( -1 );
1396     }
1397
1398     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1399             << globals->get_warp() );
1400
1401     globals->set_warp_delta( 0 );
1402
1403     t->update( 0.0, 0.0,
1404                cur_time_override->getLongValue(),
1405                globals->get_warp() );
1406
1407     return t;
1408 }
1409
1410
1411 // This is the top level init routine which calls all the other
1412 // initialization routines.  If you are adding a subsystem to flight
1413 // gear, its initialization call should located in this routine.
1414 // Returns non-zero if a problem encountered.
1415 bool fgInitSubsystems() {
1416     static const SGPropertyNode *longitude
1417         = fgGetNode("/sim/presets/longitude-deg");
1418     static const SGPropertyNode *latitude
1419         = fgGetNode("/sim/presets/latitude-deg");
1420     static const SGPropertyNode *altitude
1421         = fgGetNode("/sim/presets/altitude-ft");
1422
1423     fgLIGHT *l = &cur_light_params;
1424
1425     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1426     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1427
1428
1429     ////////////////////////////////////////////////////////////////////
1430     // Initialize the material property subsystem.
1431     ////////////////////////////////////////////////////////////////////
1432
1433     SGPath mpath( globals->get_fg_root() );
1434     mpath.append( "materials.xml" );
1435     if ( ! material_lib.load( mpath.str() ) ) {
1436         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1437         exit(-1);
1438     }
1439
1440     ////////////////////////////////////////////////////////////////////
1441     // Initialize the event manager subsystem.
1442     ////////////////////////////////////////////////////////////////////
1443
1444     global_events.init();
1445
1446     // Output event stats every 60 seconds
1447     global_events.Register( "FGEventMgr::print_stats()",
1448                             &global_events, &FGEventMgr::print_stats,
1449                             60000 );
1450
1451
1452     ////////////////////////////////////////////////////////////////////
1453     // Initialize the scenery management subsystem.
1454     ////////////////////////////////////////////////////////////////////
1455
1456     if ( globals->get_tile_mgr()->init() ) {
1457         // Load the local scenery data
1458         double visibility_meters = fgGetDouble("/environment/visibility-m");
1459                 
1460         globals->get_tile_mgr()->update( visibility_meters );
1461     } else {
1462         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1463         exit(-1);
1464     }
1465
1466     // cause refresh of viewer scenery timestamps every 15 seconds...
1467     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1468                             globals->get_tile_mgr(),
1469                             &FGTileMgr::refresh_view_timestamps,
1470                             15000 );
1471
1472     SG_LOG( SG_GENERAL, SG_DEBUG,
1473             "Current terrain elevation after tile mgr init " <<
1474             globals->get_scenery()->get_cur_elev() );
1475
1476
1477     ////////////////////////////////////////////////////////////////////
1478     // Initialize the flight model subsystem.
1479     ////////////////////////////////////////////////////////////////////
1480
1481     fgInitFDM();
1482         
1483     // allocates structures so must happen before any of the flight
1484     // model or control parameters are set
1485     fgAircraftInit();   // In the future this might not be the case.
1486
1487
1488     ////////////////////////////////////////////////////////////////////
1489     // Initialize the view manager subsystem.
1490     ////////////////////////////////////////////////////////////////////
1491
1492     fgInitView();
1493
1494
1495     ////////////////////////////////////////////////////////////////////
1496     // Initialize the lighting subsystem.
1497     ////////////////////////////////////////////////////////////////////
1498
1499     // fgUpdateSunPos() needs a few position and view parameters set
1500     // so it can calculate local relative sun angle and a few other
1501     // things for correctly orienting the sky.
1502     fgUpdateSunPos();
1503     fgUpdateMoonPos();
1504     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1505                             60000);
1506     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1507                             60000);
1508
1509     // Initialize Lighting interpolation tables
1510     l->Init();
1511
1512     // force one lighting update to make it right to start with...
1513     l->Update();
1514     // update the lighting parameters (based on sun angle)
1515     global_events.Register( "fgLight::Update()",
1516                             &cur_light_params, &fgLIGHT::Update,
1517                             30000 );
1518
1519
1520     ////////////////////////////////////////////////////////////////////
1521     // Create and register the logger.
1522     ////////////////////////////////////////////////////////////////////
1523     
1524     globals->add_subsystem("logger", new FGLogger);
1525
1526
1527 #if defined(HAVE_PLIB_PSL)
1528     ////////////////////////////////////////////////////////////////////
1529     // Create and register the script manager.
1530     ////////////////////////////////////////////////////////////////////
1531
1532     globals->add_subsystem("scripting", new FGScriptMgr);
1533 #endif // HAVE_PLIB_PSL
1534
1535
1536     ////////////////////////////////////////////////////////////////////
1537     // Create and register the XML GUI.
1538     ////////////////////////////////////////////////////////////////////
1539
1540     globals->add_subsystem("gui", new NewGUI, FGSubsystemMgr::INIT);
1541
1542
1543     ////////////////////////////////////////////////////////////////////
1544     // Initialize the local time subsystem.
1545     ////////////////////////////////////////////////////////////////////
1546
1547     // update the current timezone each 30 minutes
1548     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1549                             30*60*1000 );
1550
1551
1552     ////////////////////////////////////////////////////////////////////
1553     // Initialize the weather subsystem.
1554     ////////////////////////////////////////////////////////////////////
1555
1556     // Initialize the weather modeling subsystem
1557 #ifdef FG_WEATHERCM
1558     // Initialize the WeatherDatabase
1559     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1560     sgVec3 position;
1561     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1562                current_aircraft.fdm_state->get_Longitude(),
1563                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1564     double init_vis = fgGetDouble("/environment/visibility-m");
1565
1566     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1567
1568     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1569     {
1570       working_type = FGLocalWeatherDatabase::use_internet;
1571     } else {
1572       working_type = FGLocalWeatherDatabase::default_mode;
1573     }
1574     
1575     if ( init_vis > 0 ) {
1576       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1577         new FGLocalWeatherDatabase( position,
1578                                     globals->get_fg_root(),
1579                                     working_type,
1580                                     init_vis );
1581     } else {
1582       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1583         new FGLocalWeatherDatabase( position,
1584                                     globals->get_fg_root(),
1585                                     working_type );
1586     }
1587
1588     // cout << theFGLocalWeatherDatabase << endl;
1589     // cout << "visibility = " 
1590     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1591
1592     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1593
1594     // register the periodic update of the weather
1595     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1596                             30000);
1597 #else
1598     globals->get_environment_mgr()->init();
1599     globals->get_environment_mgr()->bind();
1600 #endif
1601
1602 #ifdef FG_USE_CLOUDS_3D
1603     ////////////////////////////////////////////////////////////////////
1604     // Initialize the 3D cloud subsystem.
1605     ////////////////////////////////////////////////////////////////////
1606     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1607         SGPath cloud_path(globals->get_fg_root());
1608         cloud_path.append("large.sky");
1609         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1610         if ( !sgCloud3d->Load( cloud_path.str(),
1611                                latitude->getDoubleValue(),
1612                                longitude->getDoubleValue()) )
1613         {
1614             fgSetBool("/sim/rendering/clouds3d", false);
1615             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1616         }
1617         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1618     }
1619 #endif
1620
1621     ////////////////////////////////////////////////////////////////////
1622     // Initialise ATC display system
1623     ////////////////////////////////////////////////////////////////////
1624
1625     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1626     globals->set_ATC_display(new FGATCDisplay);
1627     globals->get_ATC_display()->init(); 
1628
1629     ////////////////////////////////////////////////////////////////////
1630     // Initialise the ATC Manager 
1631     ////////////////////////////////////////////////////////////////////
1632
1633     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1634     globals->set_ATC_mgr(new FGATCMgr);
1635     globals->get_ATC_mgr()->init(); 
1636     
1637     ////////////////////////////////////////////////////////////////////
1638     // Initialise the AI Manager 
1639     ////////////////////////////////////////////////////////////////////
1640
1641     if (fgGetBool("/sim/ai-traffic/enabled")) {
1642         SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1643         globals->set_AI_mgr(new FGAIMgr);
1644         globals->get_AI_mgr()->init();
1645     }
1646
1647 #ifdef ENABLE_AUDIO_SUPPORT
1648     ////////////////////////////////////////////////////////////////////
1649     // Initialize the sound subsystem.
1650     ////////////////////////////////////////////////////////////////////
1651
1652     globals->set_soundmgr(new FGSoundMgr);
1653     globals->get_soundmgr()->init();
1654     globals->get_soundmgr()->bind();
1655
1656
1657     ////////////////////////////////////////////////////////////////////
1658     // Initialize the sound-effects subsystem.
1659     ////////////////////////////////////////////////////////////////////
1660
1661     globals->add_subsystem("fx", new FGFX);
1662     
1663 #endif
1664
1665     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1666     globals->add_subsystem("systems", new FGSystemMgr);
1667
1668     ////////////////////////////////////////////////////////////////////
1669     // Initialize the radio stack subsystem.
1670     ////////////////////////////////////////////////////////////////////
1671
1672     current_radiostack = new FGRadioStack;
1673     current_radiostack->init();
1674     current_radiostack->bind();
1675
1676
1677     ////////////////////////////////////////////////////////////////////
1678     // Initialize the cockpit subsystem
1679     ////////////////////////////////////////////////////////////////////
1680
1681     if( fgCockpitInit( &current_aircraft )) {
1682         // Cockpit initialized ok.
1683     } else {
1684         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1685         exit(-1);
1686     }
1687
1688
1689     ////////////////////////////////////////////////////////////////////
1690     // Initialize the autopilot subsystem.
1691     ////////////////////////////////////////////////////////////////////
1692
1693     globals->set_autopilot(new FGAutopilot);
1694     globals->get_autopilot()->init();
1695     globals->get_autopilot()->bind();
1696
1697                                 // FIXME: these should go in the
1698                                 // GUI initialization code, not here.
1699     fgAPAdjustInit();
1700     NewTgtAirportInit();
1701     NewHeadingInit();
1702     NewAltitudeInit();
1703
1704     ////////////////////////////////////////////////////////////////////
1705     // Initialize I/O subsystem.
1706     ////////////////////////////////////////////////////////////////////
1707
1708     globals->get_io()->init();
1709     globals->get_io()->bind();
1710
1711     // Initialize the 2D panel.
1712     string panel_path = fgGetString("/sim/panel/path",
1713                                     "Panels/Default/default.xml");
1714     current_panel = fgReadPanel(panel_path);
1715     if (current_panel == 0) {
1716         SG_LOG( SG_INPUT, SG_ALERT, 
1717                 "Error reading new panel from " << panel_path );
1718     } else {
1719         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1720         current_panel->init();
1721         current_panel->bind();
1722     }
1723
1724
1725     ////////////////////////////////////////////////////////////////////
1726     // Initialize the default (kludged) properties.
1727     ////////////////////////////////////////////////////////////////////
1728
1729     fgInitProps();
1730
1731
1732     ////////////////////////////////////////////////////////////////////
1733     // Initialize the controls subsystem.
1734     ////////////////////////////////////////////////////////////////////
1735
1736     globals->get_controls()->init();
1737     globals->get_controls()->bind();
1738
1739
1740     ////////////////////////////////////////////////////////////////////
1741     // Initialize the input subsystem.
1742     ////////////////////////////////////////////////////////////////////
1743
1744     globals->add_subsystem("input", new FGInput);
1745
1746
1747     ////////////////////////////////////////////////////////////////////
1748     // Bind and initialize subsystems.
1749     ////////////////////////////////////////////////////////////////////
1750
1751     globals->get_subsystem_mgr()->bind();
1752     globals->get_subsystem_mgr()->init();
1753
1754
1755 #ifdef FG_MPLAYER_AS
1756     ////////////////////////////////////////////////////////////////////
1757     // Initialize multiplayer subsystem
1758     ////////////////////////////////////////////////////////////////////
1759
1760     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1761     globals->get_multiplayer_tx_mgr()->init();
1762
1763     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1764     globals->get_multiplayer_rx_mgr()->init();
1765 #endif
1766
1767     ////////////////////////////////////////////////////////////////////////
1768     // End of subsystem initialization.
1769     ////////////////////////////////////////////////////////////////////
1770
1771     SG_LOG( SG_GENERAL, SG_INFO, endl);
1772
1773                                 // Save the initial state for future
1774                                 // reference.
1775     globals->saveInitialState();
1776
1777     return true;
1778 }
1779
1780
1781 void fgReInitSubsystems()
1782 {
1783     static const SGPropertyNode *longitude
1784         = fgGetNode("/sim/presets/longitude-deg");
1785     static const SGPropertyNode *latitude
1786         = fgGetNode("/sim/presets/latitude-deg");
1787     static const SGPropertyNode *altitude
1788         = fgGetNode("/sim/presets/altitude-ft");
1789     static const SGPropertyNode *master_freeze
1790         = fgGetNode("/sim/freeze/master");
1791
1792     SG_LOG( SG_GENERAL, SG_INFO,
1793             "fgReInitSubsystems(): /position/altitude = "
1794             << altitude->getDoubleValue() );
1795
1796     bool freeze = master_freeze->getBoolValue();
1797     if ( !freeze ) {
1798         fgSetBool("/sim/freeze/master", true);
1799     }
1800
1801     // Initialize the FDM
1802     fgInitFDM();
1803     
1804     // allocates structures so must happen before any of the flight
1805     // model or control parameters are set
1806     fgAircraftInit();   // In the future this might not be the case.
1807
1808     // reload offsets from config defaults
1809     globals->get_viewmgr()->reinit();
1810
1811     fgInitView();
1812
1813     globals->get_controls()->reset_all();
1814     globals->get_autopilot()->reset();
1815
1816     fgUpdateSunPos();
1817     fgUpdateMoonPos();
1818     cur_light_params.Update();
1819     fgUpdateLocalTime();
1820
1821     if ( !freeze ) {
1822         fgSetBool("/sim/freeze/master", false);
1823     }
1824 }
1825