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