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