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