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