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