]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Make sound audiable not until after the scenery is loaded.
[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  - http://www.flightgear.org/~curt
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/panel.hxx>
83 #include <Cockpit/panel_io.hxx>
84 #ifdef ENABLE_SP_FMDS
85 #include <FDM/SP/ADA.hxx>
86 #include <FDM/SP/ACMS.hxx>
87 #endif
88 #include <FDM/Balloon.h>
89 #include <FDM/ExternalNet/ExternalNet.hxx>
90 #include <FDM/ExternalPipe/ExternalPipe.hxx>
91 #include <FDM/JSBSim/JSBSim.hxx>
92 #include <FDM/LaRCsim/LaRCsim.hxx>
93 #include <FDM/MagicCarpet.hxx>
94 #include <FDM/UFO.hxx>
95 #include <FDM/NullFDM.hxx>
96 #include <FDM/YASim/YASim.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Include/general.hxx>
99 #include <Input/input.hxx>
100 #include <Instrumentation/instrument_mgr.hxx>
101 #include <Model/acmodel.hxx>
102 #include <AIModel/submodel.hxx>
103 #include <AIModel/AIManager.hxx>
104 #include <Navaids/navdb.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 <Sound/beacon.hxx>
112 #include <Sound/morse.hxx>
113 #include <Systems/system_mgr.hxx>
114 #include <Time/light.hxx>
115 #include <Time/moonpos.hxx>
116 #include <Time/sunpos.hxx>
117 #include <Time/sunsolver.hxx>
118 #include <Time/tmp.hxx>
119 #include <Traffic/TrafficMgr.hxx>
120
121 #ifdef FG_MPLAYER_AS
122 #include <MultiPlayer/multiplaytxmgr.hxx>
123 #include <MultiPlayer/multiplayrxmgr.hxx>
124 #endif
125
126 #include <Environment/environment_mgr.hxx>
127
128 #include "fg_init.hxx"
129 #include "fg_io.hxx"
130 #include "fg_commands.hxx"
131 #include "fg_props.hxx"
132 #include "options.hxx"
133 #include "globals.hxx"
134 #include "logger.hxx"
135 #include "viewmgr.hxx"
136
137 #if defined(FX) && defined(XMESA)
138 #include <GL/xmesa.h>
139 #endif
140
141 SG_USING_STD(string);
142
143
144 class Sound;
145 extern const char *default_root;
146 float init_volume;
147
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 #if 0 
669   // 
670   // This function is never used, but maybe useful in the future ???
671   //
672
673 // Preset lon/lat given an airport id
674 static bool fgSetPosFromAirportID( const string& id ) {
675     FGAirport a;
676     // double lon, lat;
677
678     SG_LOG( SG_GENERAL, SG_INFO,
679             "Attempting to set starting position from airport code " << id );
680
681     if ( fgFindAirportID( id, &a ) ) {
682         // presets
683         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
684         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
685
686         // other code depends on the actual postition being set so set
687         // that as well
688         fgSetDouble("/position/longitude-deg", a.longitude );
689         fgSetDouble("/position/latitude-deg", a.latitude );
690
691         SG_LOG( SG_GENERAL, SG_INFO,
692                 "Position for " << id << " is (" << a.longitude
693                 << ", " << a.latitude << ")" );
694
695         return true;
696     } else {
697         return false;
698     }
699 }
700 #endif
701
702
703 // Set current tower position lon/lat given an airport id
704 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
705     FGAirport a;
706     // tower height hard coded for now...
707     float towerheight=50.0f;
708
709     // make a little off the heading for 1 runway airports...
710     float fudge_lon = fabs(sin(hdg)) * .003f;
711     float fudge_lat = .003f - fudge_lon;
712
713     if ( fgFindAirportID( id, &a ) ) {
714         fgSetDouble("/sim/tower/longitude-deg",  a.longitude + fudge_lon);
715         fgSetDouble("/sim/tower/latitude-deg",  a.latitude + fudge_lat);
716         fgSetDouble("/sim/tower/altitude-ft", a.elevation + towerheight);
717         return true;
718     } else {
719         return false;
720     }
721
722 }
723
724
725 // Set current_options lon/lat given an airport id and heading (degrees)
726 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
727     FGRunway r;
728
729     if ( id.length() ) {
730         // set initial position from runway and heading
731
732         SG_LOG( SG_GENERAL, SG_INFO,
733                 "Attempting to set starting position from airport code "
734                 << id << " heading " << tgt_hdg );
735                 
736         if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
737             SG_LOG( SG_GENERAL, SG_ALERT,
738                     "Failed to find a good runway for " << id << '\n' );
739             return false;
740         }       
741     } else {
742         return false;
743     }
744
745     double lat2, lon2, az2;
746     double heading = r.heading;
747     double azimuth = heading + 180.0;
748     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
749
750     SG_LOG( SG_GENERAL, SG_INFO,
751             "runway =  " << r.lon << ", " << r.lat
752             << " length = " << r.length * SG_FEET_TO_METER 
753             << " heading = " << azimuth );
754             
755     geo_direct_wgs_84 ( 0, r.lat, r.lon, azimuth, 
756                         r.length * SG_FEET_TO_METER * 0.5 - 5.0,
757                         &lat2, &lon2, &az2 );
758
759     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
760         double olat, olon;
761         double odist = fgGetDouble("/sim/presets/offset-distance");
762         odist *= SG_NM_TO_METER;
763         double oaz = azimuth;
764         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
765             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
766             heading = tgt_hdg;
767         }
768         while ( oaz >= 360.0 ) { oaz -= 360.0; }
769         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
770         lat2=olat;
771         lon2=olon;
772     }
773
774     // presets
775     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
776     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
777     fgSetDouble("/sim/presets/heading-deg", heading );
778
779     // other code depends on the actual values being set ...
780     fgSetDouble("/position/longitude-deg",  lon2 );
781     fgSetDouble("/position/latitude-deg",  lat2 );
782     fgSetDouble("/orientation/heading-deg", heading );
783
784     SG_LOG( SG_GENERAL, SG_INFO,
785             "Position for " << id << " is ("
786             << lon2 << ", "
787             << lat2 << ") new heading is "
788             << heading );
789             
790     return true;
791 }
792
793
794 // Set current_options lon/lat given an airport id and runway number
795 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
796     FGRunway r;
797
798     if ( id.length() ) {
799         // set initial position from airport and runway number
800
801         SG_LOG( SG_GENERAL, SG_INFO,
802                 "Attempting to set starting position for "
803                 << id << ":" << rwy );
804
805         if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
806             SG_LOG( SG_GENERAL, SG_ALERT,
807                     "Failed to find runway " << rwy << 
808                     " at airport " << id );
809             return false;
810         }
811     } else {
812         return false;
813     }
814
815     double lat2, lon2, az2;
816     double heading = r.heading;
817     double azimuth = heading + 180.0;
818     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
819     
820     SG_LOG( SG_GENERAL, SG_INFO,
821     "runway =  " << r.lon << ", " << r.lat
822     << " length = " << r.length * SG_FEET_TO_METER 
823     << " heading = " << azimuth );
824     
825     geo_direct_wgs_84 ( 0, r.lat, r.lon, 
826     azimuth,
827     r.length * SG_FEET_TO_METER * 0.5 - 5.0,
828     &lat2, &lon2, &az2 );
829     
830     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
831     {
832         double olat, olon;
833         double odist = fgGetDouble("/sim/presets/offset-distance");
834         odist *= SG_NM_TO_METER;
835         double oaz = azimuth;
836         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
837         {
838             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
839             heading = fgGetDouble("/sim/presets/heading-deg");
840         }
841         while ( oaz >= 360.0 ) { oaz -= 360.0; }
842         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
843         lat2=olat;
844         lon2=olon;
845     }
846     
847     // presets
848     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
849     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
850     fgSetDouble("/sim/presets/heading-deg", heading );
851     
852     // other code depends on the actual values being set ...
853     fgSetDouble("/position/longitude-deg",  lon2 );
854     fgSetDouble("/position/latitude-deg",  lat2 );
855     fgSetDouble("/orientation/heading-deg", heading );
856     
857     SG_LOG( SG_GENERAL, SG_INFO,
858     "Position for " << id << " is ("
859     << lon2 << ", "
860     << lat2 << ") new heading is "
861     << heading );
862     
863     return true;
864 }
865
866
867 static void fgSetDistOrAltFromGlideSlope() {
868     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
869     string apt_id = fgGetString("/sim/presets/airport-id");
870     double gs = fgGetDouble("/sim/presets/glideslope-deg")
871         * SG_DEGREES_TO_RADIANS ;
872     double od = fgGetDouble("/sim/presets/offset-distance");
873     double alt = fgGetDouble("/sim/presets/altitude-ft");
874
875     double apt_elev = 0.0;
876     if ( ! apt_id.empty() ) {
877         apt_elev = fgGetAirportElev( apt_id );
878         if ( apt_elev < -9990.0 ) {
879             apt_elev = 0.0;
880         }
881     } else {
882         apt_elev = 0.0;
883     }
884
885     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
886         // set altitude from glideslope and offset-distance
887         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
888         alt = fabs(od*tan(gs)) + apt_elev;
889         fgSetDouble("/sim/presets/altitude-ft", alt);
890         fgSetBool("/sim/presets/onground", false);
891         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
892                 << alt  << " ft" );
893     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
894         // set offset-distance from glideslope and altitude
895         od  = (alt - apt_elev) / tan(gs);
896         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
897         fgSetDouble("/sim/presets/offset-distance", od);
898         fgSetBool("/sim/presets/onground", false);
899         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
900                 << od  << " nm" );
901     } else if( fabs(gs) > 0.01 ) {
902         SG_LOG( SG_GENERAL, SG_ALERT,
903                 "Glideslope given but not altitude or offset-distance." );
904         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
905         fgSetDouble("/sim/presets/glideslope-deg", 0);
906         fgSetBool("/sim/presets/onground", true);
907     }                              
908 }
909
910
911 // Set current_options lon/lat given an airport id and heading (degrees)
912 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
913     FGNavRecord *nav
914         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
915
916     // set initial position from runway and heading
917     if ( nav != NULL ) {
918         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
919                 << id << ":" << freq );
920
921         double lon = nav->get_lon();
922         double lat = nav->get_lat();
923
924         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
925         {
926             double odist = fgGetDouble("/sim/presets/offset-distance")
927                 * SG_NM_TO_METER;
928             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
929                 + 180.0;
930             while ( oaz >= 360.0 ) { oaz -= 360.0; }
931             double olat, olon, az2;
932             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
933
934             lat = olat;
935             lon = olon;
936         }
937
938         // presets
939         fgSetDouble("/sim/presets/longitude-deg",  lon );
940         fgSetDouble("/sim/presets/latitude-deg",  lat );
941
942         // other code depends on the actual values being set ...
943         fgSetDouble("/position/longitude-deg",  lon );
944         fgSetDouble("/position/latitude-deg",  lat );
945         fgSetDouble("/orientation/heading-deg", 
946                     fgGetDouble("/sim/presets/heading-deg") );
947
948         SG_LOG( SG_GENERAL, SG_INFO,
949                 "Position for " << id << ":" << freq << " is ("
950                 << lon << ", "<< lat << ")" );
951
952         return true;
953     } else {
954         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
955                 << id << ":" << freq );
956         return false;
957     }
958 }
959
960
961 // Set current_options lon/lat given an airport id and heading (degrees)
962 static bool fgSetPosFromFix( const string& id ) {
963     FGFix fix;
964
965     // set initial position from runway and heading
966     if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
967         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
968                 << id );
969
970         double lon = fix.get_lon();
971         double lat = fix.get_lat();
972
973         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
974         {
975             double odist = fgGetDouble("/sim/presets/offset-distance")
976                 * SG_NM_TO_METER;
977             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
978                 + 180.0;
979             while ( oaz >= 360.0 ) { oaz -= 360.0; }
980             double olat, olon, az2;
981             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
982
983             lat = olat;
984             lon = olon;
985         }
986
987         // presets
988         fgSetDouble("/sim/presets/longitude-deg",  lon );
989         fgSetDouble("/sim/presets/latitude-deg",  lat );
990
991         // other code depends on the actual values being set ...
992         fgSetDouble("/position/longitude-deg",  lon );
993         fgSetDouble("/position/latitude-deg",  lat );
994         fgSetDouble("/orientation/heading-deg", 
995                     fgGetDouble("/sim/presets/heading-deg") );
996
997         SG_LOG( SG_GENERAL, SG_INFO,
998                 "Position for " << id << " is ("
999                 << lon << ", "<< lat << ")" );
1000
1001         return true;
1002     } else {
1003         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1004                 << id );
1005         return false;
1006     }
1007 }
1008  
1009 static void parseWaypoints() {
1010     string_list *waypoints = globals->get_initial_waypoints();
1011     if (waypoints) {
1012         vector<string>::iterator i;
1013         for (i = waypoints->begin(); 
1014              i  != waypoints->end();
1015              i++)
1016         {
1017             NewWaypoint(*i);
1018         }
1019         // Now were done using the way points we can deallocate the
1020         // memory they used
1021         while (waypoints->begin() != waypoints->end()) {
1022             waypoints->pop_back();
1023         }
1024         delete waypoints;
1025         globals->set_initial_waypoints(0);
1026     }
1027 }
1028
1029  
1030  
1031
1032
1033 /**
1034  * Initialize vor/ndb/ils/fix list management and query systems (as
1035  * well as simple airport db list)
1036  */
1037 bool
1038 fgInitNav ()
1039 {
1040     SG_LOG(SG_GENERAL, SG_INFO, "Loading Simple Airport List");
1041     SGPath p_simple( globals->get_fg_root() );
1042     p_simple.append( "Airports/basic.dat" );
1043     SGPath p_metar( globals->get_fg_root() );
1044     p_metar.append( "Airports/metar.dat" );
1045     FGAirportList *airports = new FGAirportList(p_simple.str(), p_metar.str());
1046     globals->set_airports( airports );
1047
1048     SG_LOG(SG_GENERAL, SG_INFO, "Loading Runway List");
1049     SGPath p_runway( globals->get_fg_root() );
1050     p_runway.append( "Airports/runways.dat" );
1051     FGRunwayList *runways = new FGRunwayList( p_runway.str() );
1052     globals->set_runways( runways );
1053
1054     FGNavList *navlist = new FGNavList;
1055     FGNavList *loclist = new FGNavList;
1056     FGNavList *gslist = new FGNavList;
1057     FGNavList *dmelist = new FGNavList;
1058     FGNavList *mkrlist = new FGNavList;
1059
1060     globals->set_navlist( navlist );
1061     globals->set_loclist( loclist );
1062     globals->set_gslist( gslist );
1063     globals->set_dmelist( dmelist );
1064     globals->set_mkrlist( mkrlist );
1065
1066     if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist) ) {
1067         SG_LOG( SG_GENERAL, SG_ALERT,
1068                 "Problems loading one or more navigational database" );
1069     }
1070
1071     if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1072         // align all the localizers with their corresponding runways
1073         // since data sources are good for cockpit navigation
1074         // purposes, but not always to the error tolerances needed to
1075         // exactly place these items.
1076         double threshold
1077             = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1078                            5.0 );
1079         fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1080     }
1081
1082     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1083     SGPath p_fix( globals->get_fg_root() );
1084     p_fix.append( "Navaids/fix.dat" );
1085     FGFixList *fixlist = new FGFixList;
1086     fixlist->init( p_fix );
1087     globals->set_fixlist( fixlist );
1088
1089     return true;
1090 }
1091
1092
1093 // Set the initial position based on presets (or defaults)
1094 bool fgInitPosition() {
1095     // cout << "fgInitPosition()" << endl;
1096     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1097         * SG_DEGREES_TO_RADIANS ;
1098     double od = fgGetDouble("/sim/presets/offset-distance");
1099     double alt = fgGetDouble("/sim/presets/altitude-ft");
1100
1101     bool set_pos = false;
1102
1103     // If glideslope is specified, then calculate offset-distance or
1104     // altitude relative to glide slope if either of those was not
1105     // specified.
1106     if ( fabs( gs ) > 0.01 ) {
1107         fgSetDistOrAltFromGlideSlope();
1108     }
1109
1110
1111     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1112     // If not, check for an airport-id and use that.
1113     // If not, default to the middle of the KSFO field.
1114     // The default values for lon/lat are deliberately out of range
1115     // so that the airport-id can take effect; valid lon/lat will
1116     // override airport-id, however.
1117     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1118     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1119     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1120          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1121     {
1122         set_pos = true;
1123     }
1124
1125     string apt = fgGetString("/sim/presets/airport-id");
1126     string rwy_no = fgGetString("/sim/presets/runway");
1127     double hdg = fgGetDouble("/sim/presets/heading-deg");
1128     string vor = fgGetString("/sim/presets/vor-id");
1129     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1130     string ndb = fgGetString("/sim/presets/ndb-id");
1131     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1132     string fix = fgGetString("/sim/presets/fix");
1133
1134     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1135         // An airport + runway is requested
1136         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1137             // set tower position (a little off the heading for single
1138             // runway airports)
1139             fgSetTowerPosFromAirportID( apt, hdg );
1140             set_pos = true;
1141         }
1142     }
1143
1144     if ( !set_pos && !apt.empty() ) {
1145         // An airport is requested (find runway closest to hdg)
1146         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1147             // set tower position (a little off the heading for single
1148             // runway airports)
1149             fgSetTowerPosFromAirportID( apt, hdg );
1150             set_pos = true;
1151         }
1152     }
1153
1154     if ( !set_pos && !vor.empty() ) {
1155         // a VOR is requested
1156         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1157             set_pos = true;
1158         }
1159     }
1160
1161     if ( !set_pos && !ndb.empty() ) {
1162         // an NDB is requested
1163         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1164             set_pos = true;
1165         }
1166     }
1167
1168     if ( !set_pos && !fix.empty() ) {
1169         // a Fix is requested
1170         if ( fgSetPosFromFix( fix ) ) {
1171             set_pos = true;
1172         }
1173     }
1174
1175     if ( !set_pos ) {
1176         // No lon/lat specified, no airport specified, default to
1177         // middle of KSFO field.
1178         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1179         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1180     }
1181
1182     fgSetDouble( "/position/longitude-deg",
1183                  fgGetDouble("/sim/presets/longitude-deg") );
1184     fgSetDouble( "/position/latitude-deg",
1185                  fgGetDouble("/sim/presets/latitude-deg") );
1186     fgSetDouble( "/orientation/heading-deg",
1187                  fgGetDouble("/sim/presets/heading-deg") );
1188
1189     // determine if this should be an on-ground or in-air start
1190     if ( fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1 ) {
1191         fgSetBool("/sim/presets/onground", false);
1192     } else {
1193         fgSetBool("/sim/presets/onground", true);
1194     }                              
1195
1196     return true;
1197 }
1198
1199
1200 // General house keeping initializations
1201 bool fgInitGeneral() {
1202     string root;
1203
1204 #if defined(FX) && defined(XMESA)
1205     char *mesa_win_state;
1206 #endif
1207
1208     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1209     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1210
1211     root = globals->get_fg_root();
1212     if ( ! root.length() ) {
1213         // No root path set? Then bail ...
1214         SG_LOG( SG_GENERAL, SG_ALERT,
1215                 "Cannot continue without a path to the base package "
1216                 << "being defined." );
1217         exit(-1);
1218     }
1219     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1220
1221 #if defined(FX) && defined(XMESA)
1222     // initialize full screen flag
1223     globals->set_fullscreen(false);
1224     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1225         // Test for the MESA_GLX_FX env variable
1226         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1227             // test if we are fullscreen mesa/glide
1228             if ( (mesa_win_state[0] == 'f') ||
1229                  (mesa_win_state[0] == 'F') ) {
1230                 globals->set_fullscreen(true);
1231             }
1232         }
1233     }
1234 #endif
1235
1236     return true;
1237 }
1238
1239
1240 // Initialize the flight model subsystem.  This just creates the
1241 // object.  The actual fdm initialization is delayed until we get a
1242 // proper scenery elevation hit.  This is checked for in main.cxx
1243
1244 void fgInitFDM() {
1245
1246     if ( cur_fdm_state ) {
1247         delete cur_fdm_state;
1248         cur_fdm_state = 0;
1249     }
1250
1251     double dt = 1.0 / fgGetInt("/sim/model-hz");
1252     aircraft_dir = fgGetString("/sim/aircraft-dir");
1253     const string &model = fgGetString("/sim/flight-model");
1254
1255     try {
1256         if ( model == "larcsim" ) {
1257             cur_fdm_state = new FGLaRCsim( dt );
1258         } else if ( model == "jsb" ) {
1259             cur_fdm_state = new FGJSBsim( dt );
1260 #ifdef ENABLE_SP_FMDS
1261         } else if ( model == "ada" ) {
1262             cur_fdm_state = new FGADA( dt );
1263         } else if ( model == "acms" ) {
1264             cur_fdm_state = new FGACMS( dt );
1265 #endif
1266         } else if ( model == "balloon" ) {
1267             cur_fdm_state = new FGBalloonSim( dt );
1268         } else if ( model == "magic" ) {
1269             cur_fdm_state = new FGMagicCarpet( dt );
1270         } else if ( model == "ufo" ) {
1271             cur_fdm_state = new FGUFO( dt );
1272         } else if ( model == "external" ) {
1273             // external is a synonym for "--fdm=null" and is
1274             // maintained here for backwards compatibility
1275             cur_fdm_state = new FGNullFDM( dt );
1276         } else if ( model.find("network") == 0 ) {
1277             string host = "localhost";
1278             int port1 = 5501;
1279             int port2 = 5502;
1280             int port3 = 5503;
1281             string net_options = model.substr(8);
1282             string::size_type begin, end;
1283             begin = 0;
1284             // host
1285             end = net_options.find( ",", begin );
1286             if ( end != string::npos ) {
1287                 host = net_options.substr(begin, end - begin);
1288                 begin = end + 1;
1289             }
1290             // port1
1291             end = net_options.find( ",", begin );
1292             if ( end != string::npos ) {
1293                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1294                 begin = end + 1;
1295             }
1296             // port2
1297             end = net_options.find( ",", begin );
1298             if ( end != string::npos ) {
1299                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1300                 begin = end + 1;
1301             }
1302             // port3
1303             end = net_options.find( ",", begin );
1304             if ( end != string::npos ) {
1305                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1306                 begin = end + 1;
1307             }
1308             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1309         } else if ( model.find("pipe") == 0 ) {
1310             string pipe_path = model.substr(5);
1311             cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1312         } else if ( model == "null" ) {
1313             cur_fdm_state = new FGNullFDM( dt );
1314         } else if ( model == "yasim" ) {
1315             cur_fdm_state = new YASim( dt );
1316         } else {
1317             SG_LOG(SG_GENERAL, SG_ALERT,
1318                    "Unrecognized flight model '" << model
1319                    << "', cannot init flight dynamics model.");
1320             exit(-1);
1321         }
1322     } catch ( ... ) {
1323         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1324         exit(-1);
1325     }
1326 }
1327
1328 static void printMat(const sgVec4 *mat, char *name="")
1329 {
1330     int i;
1331     SG_LOG(SG_GENERAL, SG_BULK, name );
1332     for(i=0; i<4; i++) {
1333         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1334                                     << " " << mat[i][2] << " " << mat[i][3] );
1335     }
1336 }
1337
1338 // Initialize view parameters
1339 void fgInitView() {
1340   // force update of model so that viewer can get some data...
1341   globals->get_aircraft_model()->update(0);
1342   // run update for current view so that data is current...
1343   globals->get_viewmgr()->update(0);
1344
1345   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1346   printMat(globals->get_current_view()->get_UP(),"UP");
1347   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1348   
1349 }
1350
1351
1352 SGTime *fgInitTime() {
1353     // Initialize time
1354     static const SGPropertyNode *longitude
1355         = fgGetNode("/position/longitude-deg");
1356     static const SGPropertyNode *latitude
1357         = fgGetNode("/position/latitude-deg");
1358     static const SGPropertyNode *cur_time_override
1359         = fgGetNode("/sim/time/cur-time-override", true);
1360
1361     SGPath zone( globals->get_fg_root() );
1362     zone.append( "Timezone" );
1363     SGTime *t = new SGTime( longitude->getDoubleValue()
1364                               * SGD_DEGREES_TO_RADIANS,
1365                             latitude->getDoubleValue()
1366                               * SGD_DEGREES_TO_RADIANS,
1367                             zone.str(),
1368                             cur_time_override->getLongValue() );
1369
1370     globals->set_warp_delta( 0 );
1371
1372     t->update( 0.0, 0.0,
1373                cur_time_override->getLongValue(),
1374                globals->get_warp() );
1375
1376     return t;
1377 }
1378
1379
1380 // set up a time offset (aka warp) if one is specified
1381 void fgInitTimeOffset() {
1382     static const SGPropertyNode *longitude
1383         = fgGetNode("/position/longitude-deg");
1384     static const SGPropertyNode *latitude
1385         = fgGetNode("/position/latitude-deg");
1386     static const SGPropertyNode *cur_time_override
1387         = fgGetNode("/sim/time/cur-time-override", true);
1388
1389     // Handle potential user specified time offsets
1390     int orig_warp = globals->get_warp();
1391     SGTime *t = globals->get_time_params();
1392     time_t cur_time = t->get_cur_time();
1393     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1394     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1395     time_t aircraftLocalTime = 
1396         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1397
1398     // Okay, we now have several possible scenarios
1399     int offset = fgGetInt("/sim/startup/time-offset");
1400     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1401
1402     int warp = 0;
1403     if ( offset_type == "real" ) {
1404         warp = 0;
1405     } else if ( offset_type == "dawn" ) {
1406         warp = fgTimeSecondsUntilSunAngle( cur_time,
1407                                            longitude->getDoubleValue()
1408                                              * SGD_DEGREES_TO_RADIANS,
1409                                            latitude->getDoubleValue()
1410                                              * SGD_DEGREES_TO_RADIANS,
1411                                            90.0, true ); 
1412     } else if ( offset_type == "morning" ) {
1413         warp = fgTimeSecondsUntilSunAngle( cur_time,
1414                                            longitude->getDoubleValue()
1415                                              * SGD_DEGREES_TO_RADIANS,
1416                                            latitude->getDoubleValue()
1417                                              * SGD_DEGREES_TO_RADIANS,
1418                                            75.0, true ); 
1419     } else if ( offset_type == "noon" ) {
1420         warp = fgTimeSecondsUntilSunAngle( cur_time,
1421                                            longitude->getDoubleValue()
1422                                              * SGD_DEGREES_TO_RADIANS,
1423                                            latitude->getDoubleValue()
1424                                              * SGD_DEGREES_TO_RADIANS,
1425                                            0.0, true ); 
1426     } else if ( offset_type == "afternoon" ) {
1427         warp = fgTimeSecondsUntilSunAngle( cur_time,
1428                                            longitude->getDoubleValue()
1429                                              * SGD_DEGREES_TO_RADIANS,
1430                                            latitude->getDoubleValue()
1431                                              * SGD_DEGREES_TO_RADIANS,
1432                                            60.0, false ); 
1433      } else if ( offset_type == "dusk" ) {
1434         warp = fgTimeSecondsUntilSunAngle( cur_time,
1435                                            longitude->getDoubleValue()
1436                                              * SGD_DEGREES_TO_RADIANS,
1437                                            latitude->getDoubleValue()
1438                                              * SGD_DEGREES_TO_RADIANS,
1439                                            90.0, false ); 
1440      } else if ( offset_type == "evening" ) {
1441         warp = fgTimeSecondsUntilSunAngle( cur_time,
1442                                            longitude->getDoubleValue()
1443                                              * SGD_DEGREES_TO_RADIANS,
1444                                            latitude->getDoubleValue()
1445                                              * SGD_DEGREES_TO_RADIANS,
1446                                            100.0, false ); 
1447     } else if ( offset_type == "midnight" ) {
1448         warp = fgTimeSecondsUntilSunAngle( cur_time,
1449                                            longitude->getDoubleValue()
1450                                              * SGD_DEGREES_TO_RADIANS,
1451                                            latitude->getDoubleValue()
1452                                              * SGD_DEGREES_TO_RADIANS,
1453                                            180.0, false ); 
1454     } else if ( offset_type == "system-offset" ) {
1455         warp = offset;
1456     } else if ( offset_type == "gmt-offset" ) {
1457         warp = offset - (currGMT - systemLocalTime);
1458     } else if ( offset_type == "latitude-offset" ) {
1459         warp = offset - (aircraftLocalTime - systemLocalTime);
1460     } else if ( offset_type == "system" ) {
1461         warp = offset - cur_time;
1462     } else if ( offset_type == "gmt" ) {
1463         warp = offset - currGMT;
1464     } else if ( offset_type == "latitude" ) {
1465         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1466     } else {
1467         SG_LOG( SG_GENERAL, SG_ALERT,
1468                 "FG_TIME::Unsupported offset type " << offset_type );
1469         exit( -1 );
1470     }
1471     globals->set_warp( orig_warp + warp );
1472     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1473                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1474                cur_time_override->getLongValue(),
1475                globals->get_warp() );
1476
1477     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1478             << globals->get_warp() );
1479 }
1480
1481
1482 // This is the top level init routine which calls all the other
1483 // initialization routines.  If you are adding a subsystem to flight
1484 // gear, its initialization call should located in this routine.
1485 // Returns non-zero if a problem encountered.
1486 bool fgInitSubsystems() {
1487     // static const SGPropertyNode *longitude
1488     //     = fgGetNode("/sim/presets/longitude-deg");
1489     // static const SGPropertyNode *latitude
1490     //     = fgGetNode("/sim/presets/latitude-deg");
1491     // static const SGPropertyNode *altitude
1492     //     = fgGetNode("/sim/presets/altitude-ft");
1493
1494     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1495     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1496
1497     ////////////////////////////////////////////////////////////////////
1498     // Initialize the event manager subsystem.
1499     ////////////////////////////////////////////////////////////////////
1500
1501     globals->get_event_mgr()->init();
1502     globals->get_event_mgr()->setFreezeProperty(fgGetNode("/sim/freeze/clock"));
1503
1504     ////////////////////////////////////////////////////////////////////
1505     // Initialize the property interpolator subsystem
1506     ////////////////////////////////////////////////////////////////////
1507     globals->add_subsystem("interpolator", new SGInterpolator);
1508
1509
1510     ////////////////////////////////////////////////////////////////////
1511     // Add the FlightGear property utilities.
1512     ////////////////////////////////////////////////////////////////////
1513     globals->add_subsystem("properties", new FGProperties);
1514
1515     ////////////////////////////////////////////////////////////////////
1516     // Initialize the material property subsystem.
1517     ////////////////////////////////////////////////////////////////////
1518
1519     SGPath mpath( globals->get_fg_root() );
1520     mpath.append( "materials.xml" );
1521     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1522         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1523         exit(-1);
1524     }
1525
1526
1527     ////////////////////////////////////////////////////////////////////
1528     // Initialize the scenery management subsystem.
1529     ////////////////////////////////////////////////////////////////////
1530
1531     if ( globals->get_tile_mgr()->init() ) {
1532         // Load the local scenery data
1533         double visibility_meters = fgGetDouble("/environment/visibility-m");
1534                 
1535         globals->get_tile_mgr()->update( visibility_meters );
1536     } else {
1537         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1538         exit(-1);
1539     }
1540
1541     // cause refresh of viewer scenery timestamps every 15 seconds...
1542     globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1543                                        globals->get_tile_mgr(),
1544                                        &FGTileMgr::refresh_view_timestamps,
1545                                        15 );
1546
1547     SG_LOG( SG_GENERAL, SG_DEBUG,
1548             "Current terrain elevation after tile mgr init " <<
1549             globals->get_scenery()->get_cur_elev() );
1550
1551
1552     ////////////////////////////////////////////////////////////////////
1553     // Initialize the flight model subsystem.
1554     ////////////////////////////////////////////////////////////////////
1555
1556     fgInitFDM();
1557         
1558     // allocates structures so must happen before any of the flight
1559     // model or control parameters are set
1560     fgAircraftInit();   // In the future this might not be the case.
1561
1562
1563     ////////////////////////////////////////////////////////////////////
1564     // Initialize the XML Autopilot subsystem.
1565     ////////////////////////////////////////////////////////////////////
1566
1567     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1568     globals->add_subsystem( "route-manager", new FGRouteMgr );
1569
1570   
1571     ////////////////////////////////////////////////////////////////////
1572     // Initialize the view manager subsystem.
1573     ////////////////////////////////////////////////////////////////////
1574
1575     fgInitView();
1576
1577     ////////////////////////////////////////////////////////////////////
1578     // Create and register the logger.
1579     ////////////////////////////////////////////////////////////////////
1580     
1581     globals->add_subsystem("logger", new FGLogger);
1582
1583     ////////////////////////////////////////////////////////////////////
1584     // Create and register the XML GUI.
1585     ////////////////////////////////////////////////////////////////////
1586
1587     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1588
1589
1590     ////////////////////////////////////////////////////////////////////
1591     // Initialize the local time subsystem.
1592     ////////////////////////////////////////////////////////////////////
1593
1594     // update the current timezone each 30 minutes
1595     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1596                                        &fgUpdateLocalTime, 30*60 );
1597
1598
1599     ////////////////////////////////////////////////////////////////////
1600     // Initialize the weather subsystem.
1601     ////////////////////////////////////////////////////////////////////
1602
1603     // Initialize the weather modeling subsystem
1604     globals->add_subsystem("environment", new FGEnvironmentMgr);
1605
1606
1607     ////////////////////////////////////////////////////////////////////
1608     // Initialize the lighting subsystem.
1609     ////////////////////////////////////////////////////////////////////
1610
1611     globals->add_subsystem("lighting", new FGLight);
1612
1613     //////////////////////////////////////////////////////////////////////
1614     // Initialize the 2D cloud subsystem.
1615     ////////////////////////////////////////////////////////////////////
1616     fgGetBool("/sim/rendering/bump-mapping", false);
1617
1618 #ifdef FG_USE_CLOUDS_3D
1619     ////////////////////////////////////////////////////////////////////
1620     // Initialize the 3D cloud subsystem.
1621     ////////////////////////////////////////////////////////////////////
1622     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1623         static const SGPropertyNode *longitude
1624            = fgGetNode("/sim/presets/longitude-deg");
1625         static const SGPropertyNode *latitude
1626            = fgGetNode("/sim/presets/latitude-deg");
1627         // static const SGPropertyNode *altitude
1628         //    = fgGetNode("/sim/presets/altitude-ft");
1629
1630         SGPath cloud_path(globals->get_fg_root());
1631 #if 0
1632         cloud_path.append("Textures/Sky/scattered.rgba");
1633         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1634
1635         SGTexture tx;
1636         tx.read_rgba_texture(cloud_path.c_str());
1637         if ( !sgCloud3d->Load( tx.texture(), tx.width(),
1638 #else
1639         cloud_path.append("large.sky");
1640         if ( !sgCloud3d->Load( cloud_path.str(),
1641 #endif
1642                                latitude->getDoubleValue(),
1643                                longitude->getDoubleValue()) )
1644         {
1645             fgSetBool("/sim/rendering/clouds3d", false);
1646             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1647         }
1648         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1649     }
1650 #endif
1651
1652 #ifdef ENABLE_AUDIO_SUPPORT
1653     ////////////////////////////////////////////////////////////////////
1654     // Initialize the sound subsystem.
1655     ////////////////////////////////////////////////////////////////////
1656
1657     init_volume = fgGetFloat("/sim/sound/volume");
1658     fgSetFloat("/sim/sound/volume", 0.0f);
1659     globals->set_soundmgr(new SGSoundMgr);
1660     globals->get_soundmgr()->init();
1661     globals->get_soundmgr()->bind();
1662
1663
1664     ////////////////////////////////////////////////////////////////////
1665     // Initialize the sound-effects subsystem.
1666     ////////////////////////////////////////////////////////////////////
1667
1668     globals->add_subsystem("fx", new FGFX);
1669     
1670 #endif
1671
1672     ////////////////////////////////////////////////////////////////////
1673     // Initialise ATC display system
1674     ////////////////////////////////////////////////////////////////////
1675
1676     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1677     globals->set_ATC_display(new FGATCDisplay);
1678     globals->get_ATC_display()->init(); 
1679
1680     ////////////////////////////////////////////////////////////////////
1681     // Initialise the ATC Manager 
1682     ////////////////////////////////////////////////////////////////////
1683
1684     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1685     globals->set_ATC_mgr(new FGATCMgr);
1686     globals->get_ATC_mgr()->init(); 
1687     
1688     ////////////////////////////////////////////////////////////////////
1689     // Initialise the AI Manager 
1690     ////////////////////////////////////////////////////////////////////
1691
1692     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1693     globals->set_AI_mgr(new FGAIMgr);
1694     globals->get_AI_mgr()->init();
1695
1696     ////////////////////////////////////////////////////////////////////
1697     // Initialise the AI Model Manager
1698     ////////////////////////////////////////////////////////////////////
1699     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1700     globals->add_subsystem("ai_model", new FGAIManager);
1701     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1702
1703
1704      // It's probably a good idea to initialize the top level traffic manager
1705      // After the AI and ATC systems have been initialized properly.
1706      // AI Traffic manager
1707      globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1708              FGTrafficManager *dispatcher = 
1709              (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1710
1711      readXML(string(globals->get_fg_root() + string("/Traffic/fgtraffic.xml")),
1712              *dispatcher);
1713      globals->get_subsystem("Traffic Manager")->init();
1714
1715     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1716     globals->add_subsystem("systems", new FGSystemMgr);
1717
1718
1719
1720     ////////////////////////////////////////////////////////////////////
1721     // Initialize the cockpit subsystem
1722     ////////////////////////////////////////////////////////////////////
1723     if( fgCockpitInit( &current_aircraft )) {
1724         // Cockpit initialized ok.
1725     } else {
1726         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1727         exit(-1);
1728     }
1729
1730
1731     ////////////////////////////////////////////////////////////////////
1732     // Initialize the autopilot subsystem.
1733     ////////////////////////////////////////////////////////////////////
1734
1735                                 // FIXME: these should go in the
1736                                 // GUI initialization code, not here.
1737     // fgAPAdjustInit();
1738     NewTgtAirportInit();
1739     NewHeadingInit();
1740     NewAltitudeInit();
1741
1742     ////////////////////////////////////////////////////////////////////
1743     // Initialize I/O subsystem.
1744     ////////////////////////////////////////////////////////////////////
1745
1746     globals->get_io()->init();
1747     globals->get_io()->bind();
1748
1749
1750     ////////////////////////////////////////////////////////////////////
1751     // Add a new 2D panel.
1752     ////////////////////////////////////////////////////////////////////
1753
1754     string panel_path = fgGetString("/sim/panel/path",
1755                                     "Panels/Default/default.xml");
1756
1757     globals->set_current_panel( fgReadPanel(panel_path) );
1758     if (globals->get_current_panel() == 0) {
1759         SG_LOG( SG_INPUT, SG_ALERT, 
1760                 "Error reading new panel from " << panel_path );
1761     } else {
1762         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1763         globals->get_current_panel()->init();
1764         globals->get_current_panel()->bind();
1765     }
1766
1767     
1768     ////////////////////////////////////////////////////////////////////
1769     // Initialize the controls subsystem.
1770     ////////////////////////////////////////////////////////////////////
1771
1772     globals->get_controls()->init();
1773     globals->get_controls()->bind();
1774
1775
1776     ////////////////////////////////////////////////////////////////////
1777     // Initialize the input subsystem.
1778     ////////////////////////////////////////////////////////////////////
1779
1780     globals->add_subsystem("input", new FGInput);
1781
1782
1783     ////////////////////////////////////////////////////////////////////
1784     // Initialize the replay subsystem
1785     ////////////////////////////////////////////////////////////////////
1786     globals->add_subsystem("replay", new FGReplay);
1787
1788     ////////////////////////////////////////////////////////////////////
1789     // Bind and initialize subsystems.
1790     ////////////////////////////////////////////////////////////////////
1791
1792     globals->get_subsystem_mgr()->bind();
1793     globals->get_subsystem_mgr()->init();
1794
1795 #ifdef FG_MPLAYER_AS
1796     ////////////////////////////////////////////////////////////////////
1797     // Initialize multiplayer subsystem
1798     ////////////////////////////////////////////////////////////////////
1799
1800     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1801     globals->get_multiplayer_tx_mgr()->init();
1802
1803     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1804     globals->get_multiplayer_rx_mgr()->init();
1805 #endif
1806
1807     ////////////////////////////////////////////////////////////////////////
1808     // Initialize the Nasal interpreter.
1809     // Do this last, so that the loaded scripts see initialized state
1810     ////////////////////////////////////////////////////////////////////////
1811     FGNasalSys* nasal = new FGNasalSys();
1812     globals->add_subsystem("nasal", nasal);
1813     nasal->init();
1814
1815     ////////////////////////////////////////////////////////////////////
1816     // At this point we could try and parse the waypoint options
1817     ///////////////////////////////////////////////////////////////////
1818     parseWaypoints();
1819
1820
1821     ////////////////////////////////////////////////////////////////////////
1822     // End of subsystem initialization.
1823     ////////////////////////////////////////////////////////////////////
1824
1825     SG_LOG( SG_GENERAL, SG_INFO, endl);
1826
1827                                 // Save the initial state for future
1828                                 // reference.
1829     globals->saveInitialState();
1830
1831     return true;
1832 }
1833
1834
1835 void fgReInitSubsystems()
1836 {
1837     // static const SGPropertyNode *longitude
1838     //     = fgGetNode("/sim/presets/longitude-deg");
1839     // static const SGPropertyNode *latitude
1840     //     = fgGetNode("/sim/presets/latitude-deg");
1841     static const SGPropertyNode *altitude
1842         = fgGetNode("/sim/presets/altitude-ft");
1843     static const SGPropertyNode *master_freeze
1844         = fgGetNode("/sim/freeze/master");
1845
1846     SG_LOG( SG_GENERAL, SG_INFO,
1847             "fgReInitSubsystems(): /position/altitude = "
1848             << altitude->getDoubleValue() );
1849
1850     bool freeze = master_freeze->getBoolValue();
1851     if ( !freeze ) {
1852         fgSetBool("/sim/freeze/master", true);
1853     }
1854     fgSetBool("/sim/crashed", false);
1855
1856     // Initialize the FDM
1857     fgInitFDM();
1858     
1859     // allocates structures so must happen before any of the flight
1860     // model or control parameters are set
1861     fgAircraftInit();   // In the future this might not be the case.
1862
1863     // reload offsets from config defaults
1864     globals->get_viewmgr()->reinit();
1865
1866     fgInitView();
1867
1868     globals->get_controls()->reset_all();
1869
1870     fgUpdateLocalTime();
1871
1872     // re-init to proper time of day setting
1873     fgInitTimeOffset();
1874
1875     if ( !freeze ) {
1876         fgSetBool("/sim/freeze/master", false);
1877     }
1878     fgSetBool("/sim/sceneryloaded",false);
1879 }
1880