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