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