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