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