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