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