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