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