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