]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Only test for --fg-root and --aircraft in ~/.fgfsrc et all if it wasn't specified...
[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
39 #if defined( unix ) || defined( __CYGWIN__ )
40 #  include <unistd.h>           // for gethostname()
41 #endif
42
43 // work around a stdc++ lib bug in some versions of linux, but doesn't
44 // seem to hurt to have this here for all versions of Linux.
45 #ifdef linux
46 #  define _G_NO_EXTERN_TEMPLATES
47 #endif
48
49 #include <simgear/compiler.h>
50
51 #include STL_STRING
52
53 #include <simgear/constants.h>
54 #include <simgear/debug/logstream.hxx>
55 #include <simgear/structure/exception.hxx>
56 #include <simgear/structure/event_mgr.hxx>
57 #include <simgear/math/point3d.hxx>
58 #include <simgear/math/polar3d.hxx>
59 #include <simgear/math/sg_geodesy.hxx>
60 #include <simgear/misc/sg_path.hxx>
61 #include <simgear/misc/interpolator.hxx>
62 #include <simgear/scene/material/matlib.hxx>
63 #include <simgear/timing/sg_time.hxx>
64 #include <simgear/timing/lowleveltime.h>
65
66 #include <Aircraft/aircraft.hxx>
67 #include <Aircraft/replay.hxx>
68 #include <Airports/apt_loader.hxx>
69 #include <Airports/runways.hxx>
70 #include <Airports/simple.hxx>
71 #include <AIModel/AIManager.hxx>
72 #include <ATC/ATCdisplay.hxx>
73 #include <ATC/ATCmgr.hxx>
74 #include <ATC/AIMgr.hxx>
75 #include <Autopilot/auto_gui.hxx>
76 #include <Autopilot/route_mgr.hxx>
77 #include <Autopilot/xmlauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
81 #ifdef ENABLE_SP_FMDS
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
84 #endif
85 #include <FDM/Balloon.h>
86 #include <FDM/ExternalNet/ExternalNet.hxx>
87 #include <FDM/ExternalPipe/ExternalPipe.hxx>
88 #include <FDM/JSBSim/JSBSim.hxx>
89 #include <FDM/LaRCsim/LaRCsim.hxx>
90 #include <FDM/MagicCarpet.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Scenery/scenery.hxx>
104 #include <Scenery/tilemgr.hxx>
105 #include <Scripting/NasalSys.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     SG_LOG(SG_GENERAL, SG_INFO, "Scanning command line for: " << option );
149
150     int len = option.length();
151
152     while ( i < argc ) {
153         SG_LOG( SG_GENERAL, SG_DEBUG, "argv[" << i << "] = " << argv[i] );
154
155         string arg = argv[i];
156         if ( arg.find( option ) == 0 ) {
157             return arg.substr( len );
158         }
159
160         i++;
161     }
162
163     return "";
164 }
165
166
167 // Scan the user config files for the specified option and return
168 // the value.
169 static string fgScanForOption( const string& option, const string& path ) {
170     sg_gzifstream in( path );
171     if ( !in.is_open() ) {
172         return "";
173     }
174
175     SG_LOG( SG_GENERAL, SG_INFO, "Scanning " << path << " for: " << option );
176
177     int len = option.length();
178
179     in >> skipcomment;
180 #ifndef __MWERKS__
181     while ( ! in.eof() ) {
182 #else
183     char c = '\0';
184     while ( in.get(c) && c != '\0' ) {
185         in.putback(c);
186 #endif
187         string line;
188
189 #if defined( macintosh )
190         getline( in, line, '\r' );
191 #else
192         getline( in, line, '\n' );
193 #endif
194
195         // catch extraneous (DOS) line ending character
196         if ( line[line.length() - 1] < 32 ) {
197             line = line.substr( 0, line.length()-1 );
198         }
199
200         if ( line.find( option ) == 0 ) {
201             return line.substr( len );
202         }
203
204         in >> skipcomment;
205     }
206
207     return "";
208 }
209
210 // Scan the user config files for the specified option and return
211 // the value.
212 static string fgScanForOption( const string& option ) {
213     string arg("");
214
215     if (hostname == NULL)
216     {
217         char _hostname[256];
218         gethostname(_hostname, 256);
219         hostname = strdup(_hostname);
220         free_hostname = true;
221     }
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 // find basic airport location info from airport database
629 bool fgFindAirportID( const string& id, FGAirport *a ) {
630     const FGAirport* result;
631     if ( id.length() ) {
632         SG_LOG( SG_GENERAL, SG_INFO, "Searching for airport code = " << id );
633
634         result = globals->get_airports()->search( id );
635
636         if ( result == NULL ) {
637             SG_LOG( SG_GENERAL, SG_ALERT,
638                     "Failed to find " << id << " in apt.dat.gz" );
639             return false;
640         }
641     } else {
642         return false;
643     }
644
645     *a = *result;
646
647     SG_LOG( SG_GENERAL, SG_INFO,
648             "Position for " << id << " is ("
649             << a->getLongitude() << ", "
650             << a->getLatitude() << ")" );
651
652     return true;
653 }
654
655
656 // get airport elevation
657 static double fgGetAirportElev( const string& id ) {
658     FGAirport a;
659     // double lon, lat;
660
661     SG_LOG( SG_GENERAL, SG_INFO,
662             "Finding elevation for airport: " << id );
663
664     if ( fgFindAirportID( id, &a ) ) {
665         return a.getElevation();
666     } else {
667         return -9999.0;
668     }
669 }
670
671
672 #if 0 
673   // 
674   // This function is never used, but maybe useful in the future ???
675   //
676
677 // Preset lon/lat given an airport id
678 static bool fgSetPosFromAirportID( const string& id ) {
679     FGAirport a;
680     // double lon, lat;
681
682     SG_LOG( SG_GENERAL, SG_INFO,
683             "Attempting to set starting position from airport code " << id );
684
685     if ( fgFindAirportID( id, &a ) ) {
686         // presets
687         fgSetDouble("/sim/presets/longitude-deg", a.longitude );
688         fgSetDouble("/sim/presets/latitude-deg", a.latitude );
689
690         // other code depends on the actual postition being set so set
691         // that as well
692         fgSetDouble("/position/longitude-deg", a.longitude );
693         fgSetDouble("/position/latitude-deg", a.latitude );
694
695         SG_LOG( SG_GENERAL, SG_INFO,
696                 "Position for " << id << " is (" << a.longitude
697                 << ", " << a.latitude << ")" );
698
699         return true;
700     } else {
701         return false;
702     }
703 }
704 #endif
705
706
707 // Set current tower position lon/lat given an airport id
708 static bool fgSetTowerPosFromAirportID( const string& id, double hdg ) {
709     FGAirport a;
710     // tower height hard coded for now...
711     float towerheight=50.0f;
712
713     // make a little off the heading for 1 runway airports...
714     float fudge_lon = fabs(sin(hdg)) * .003f;
715     float fudge_lat = .003f - fudge_lon;
716
717     if ( fgFindAirportID( id, &a ) ) {
718         fgSetDouble("/sim/tower/longitude-deg",  a.getLongitude() + fudge_lon);
719         fgSetDouble("/sim/tower/latitude-deg",  a.getLatitude() + fudge_lat);
720         fgSetDouble("/sim/tower/altitude-ft", a.getElevation() + towerheight);
721         return true;
722     } else {
723         return false;
724     }
725
726 }
727
728 struct FGTowerLocationListener : SGPropertyChangeListener {
729     void valueChanged(SGPropertyNode* node) {
730         const double hdg = fgGetDouble( "/orientation/heading-deg", 0);
731         const string id(node->getStringValue());
732         fgSetTowerPosFromAirportID(id, hdg);
733     }
734 };
735
736 static void fgInitTowerLocationListener() {
737     fgGetNode("/sim/tower/airport-id",  true)
738         ->addChangeListener( new FGTowerLocationListener() );
739 }
740
741 // Set current_options lon/lat given an airport id and heading (degrees)
742 static bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
743     FGRunway r;
744
745     if ( id.length() ) {
746         // set initial position from runway and heading
747
748         SG_LOG( SG_GENERAL, SG_INFO,
749                 "Attempting to set starting position from airport code "
750                 << id << " heading " << tgt_hdg );
751                 
752         if ( ! globals->get_runways()->search( id, (int)tgt_hdg, &r ) ) {
753             SG_LOG( SG_GENERAL, SG_ALERT,
754                     "Failed to find a good runway for " << id << '\n' );
755             return false;
756         }       
757     } else {
758         return false;
759     }
760
761     double lat2, lon2, az2;
762     double heading = r._heading;
763     double azimuth = heading + 180.0;
764     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
765
766     SG_LOG( SG_GENERAL, SG_INFO,
767             "runway =  " << r._lon << ", " << r._lat
768             << " length = " << r._length * SG_FEET_TO_METER 
769             << " heading = " << azimuth );
770             
771     geo_direct_wgs_84 ( 0, r._lat, r._lon, azimuth, 
772                         r._length * SG_FEET_TO_METER * 0.5 - 5.0,
773                         &lat2, &lon2, &az2 );
774
775     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON ) {
776         double olat, olon;
777         double odist = fgGetDouble("/sim/presets/offset-distance");
778         odist *= SG_NM_TO_METER;
779         double oaz = azimuth;
780         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON ) {
781             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
782             heading = tgt_hdg;
783         }
784         while ( oaz >= 360.0 ) { oaz -= 360.0; }
785         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
786         lat2=olat;
787         lon2=olon;
788     }
789
790     // presets
791     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
792     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
793     fgSetDouble("/sim/presets/heading-deg", heading );
794
795     // other code depends on the actual values being set ...
796     fgSetDouble("/position/longitude-deg",  lon2 );
797     fgSetDouble("/position/latitude-deg",  lat2 );
798     fgSetDouble("/orientation/heading-deg", heading );
799
800     SG_LOG( SG_GENERAL, SG_INFO,
801             "Position for " << id << " is ("
802             << lon2 << ", "
803             << lat2 << ") new heading is "
804             << heading );
805             
806     return true;
807 }
808
809
810 // Set current_options lon/lat given an airport id and runway number
811 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy ) {
812     FGRunway r;
813
814     if ( id.length() ) {
815         // set initial position from airport and runway number
816
817         SG_LOG( SG_GENERAL, SG_INFO,
818                 "Attempting to set starting position for "
819                 << id << ":" << rwy );
820
821         if ( ! globals->get_runways()->search( id, rwy, &r ) ) {
822             SG_LOG( SG_GENERAL, SG_ALERT,
823                     "Failed to find runway " << rwy << 
824                     " at airport " << id );
825             return false;
826         }
827     } else {
828         return false;
829     }
830
831     double lat2, lon2, az2;
832     double heading = r._heading;
833     double azimuth = heading + 180.0;
834     while ( azimuth >= 360.0 ) { azimuth -= 360.0; }
835     
836     SG_LOG( SG_GENERAL, SG_INFO,
837     "runway =  " << r._lon << ", " << r._lat
838     << " length = " << r._length * SG_FEET_TO_METER 
839     << " heading = " << azimuth );
840     
841     geo_direct_wgs_84 ( 0, r._lat, r._lon, 
842     azimuth,
843     r._length * SG_FEET_TO_METER * 0.5 - 5.0,
844     &lat2, &lon2, &az2 );
845     
846     if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
847     {
848         double olat, olon;
849         double odist = fgGetDouble("/sim/presets/offset-distance");
850         odist *= SG_NM_TO_METER;
851         double oaz = azimuth;
852         if ( fabs(fgGetDouble("/sim/presets/offset-azimuth")) > SG_EPSILON )
853         {
854             oaz = fgGetDouble("/sim/presets/offset-azimuth") + 180;
855             heading = fgGetDouble("/sim/presets/heading-deg");
856         }
857         while ( oaz >= 360.0 ) { oaz -= 360.0; }
858         geo_direct_wgs_84 ( 0, lat2, lon2, oaz, odist, &olat, &olon, &az2 );
859         lat2=olat;
860         lon2=olon;
861     }
862     
863     // presets
864     fgSetDouble("/sim/presets/longitude-deg",  lon2 );
865     fgSetDouble("/sim/presets/latitude-deg",  lat2 );
866     fgSetDouble("/sim/presets/heading-deg", heading );
867     
868     // other code depends on the actual values being set ...
869     fgSetDouble("/position/longitude-deg",  lon2 );
870     fgSetDouble("/position/latitude-deg",  lat2 );
871     fgSetDouble("/orientation/heading-deg", heading );
872     
873     SG_LOG( SG_GENERAL, SG_INFO,
874     "Position for " << id << " is ("
875     << lon2 << ", "
876     << lat2 << ") new heading is "
877     << heading );
878     
879     return true;
880 }
881
882
883 static void fgSetDistOrAltFromGlideSlope() {
884     // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
885     string apt_id = fgGetString("/sim/presets/airport-id");
886     double gs = fgGetDouble("/sim/presets/glideslope-deg")
887         * SG_DEGREES_TO_RADIANS ;
888     double od = fgGetDouble("/sim/presets/offset-distance");
889     double alt = fgGetDouble("/sim/presets/altitude-ft");
890
891     double apt_elev = 0.0;
892     if ( ! apt_id.empty() ) {
893         apt_elev = fgGetAirportElev( apt_id );
894         if ( apt_elev < -9990.0 ) {
895             apt_elev = 0.0;
896         }
897     } else {
898         apt_elev = 0.0;
899     }
900
901     if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
902         // set altitude from glideslope and offset-distance
903         od *= SG_NM_TO_METER * SG_METER_TO_FEET;
904         alt = fabs(od*tan(gs)) + apt_elev;
905         fgSetDouble("/sim/presets/altitude-ft", alt);
906         fgSetBool("/sim/presets/onground", false);
907         SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
908                 << alt  << " ft" );
909     } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
910         // set offset-distance from glideslope and altitude
911         od  = (alt - apt_elev) / tan(gs);
912         od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
913         fgSetDouble("/sim/presets/offset-distance", od);
914         fgSetBool("/sim/presets/onground", false);
915         SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: " 
916                 << od  << " nm" );
917     } else if( fabs(gs) > 0.01 ) {
918         SG_LOG( SG_GENERAL, SG_ALERT,
919                 "Glideslope given but not altitude or offset-distance." );
920         SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
921         fgSetDouble("/sim/presets/glideslope-deg", 0);
922         fgSetBool("/sim/presets/onground", true);
923     }                              
924 }
925
926
927 // Set current_options lon/lat given an airport id and heading (degrees)
928 static bool fgSetPosFromNAV( const string& id, const double& freq ) {
929     FGNavRecord *nav
930         = globals->get_navlist()->findByIdentAndFreq( id.c_str(), freq );
931
932     // set initial position from runway and heading
933     if ( nav != NULL ) {
934         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
935                 << id << ":" << freq );
936
937         double lon = nav->get_lon();
938         double lat = nav->get_lat();
939
940         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
941         {
942             double odist = fgGetDouble("/sim/presets/offset-distance")
943                 * SG_NM_TO_METER;
944             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
945                 + 180.0;
946             while ( oaz >= 360.0 ) { oaz -= 360.0; }
947             double olat, olon, az2;
948             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
949
950             lat = olat;
951             lon = olon;
952         }
953
954         // presets
955         fgSetDouble("/sim/presets/longitude-deg",  lon );
956         fgSetDouble("/sim/presets/latitude-deg",  lat );
957
958         // other code depends on the actual values being set ...
959         fgSetDouble("/position/longitude-deg",  lon );
960         fgSetDouble("/position/latitude-deg",  lat );
961         fgSetDouble("/orientation/heading-deg", 
962                     fgGetDouble("/sim/presets/heading-deg") );
963
964         SG_LOG( SG_GENERAL, SG_INFO,
965                 "Position for " << id << ":" << freq << " is ("
966                 << lon << ", "<< lat << ")" );
967
968         return true;
969     } else {
970         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
971                 << id << ":" << freq );
972         return false;
973     }
974 }
975
976 // Set current_options lon/lat given an aircraft carrier id
977 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
978
979     // set initial position from runway and heading
980     Point3D geodPos;
981     double heading;
982     sgdVec3 uvw;
983     if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
984         double lon = geodPos.lon() * SGD_RADIANS_TO_DEGREES;
985         double lat = geodPos.lat() * SGD_RADIANS_TO_DEGREES;
986         double alt = geodPos.elev() * SG_METER_TO_FEET;
987
988         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
989                 << carrier << " at lat = " << lat << ", lon = " << lon
990                 << ", alt = " << alt << ", heading = " << heading);
991
992         fgSetDouble("/sim/presets/longitude-deg",  lon);
993         fgSetDouble("/sim/presets/latitude-deg",  lat);
994         fgSetDouble("/sim/presets/altitude-ft", alt);
995         fgSetDouble("/sim/presets/heading-deg", heading);
996         fgSetDouble("/position/longitude-deg",  lon);
997         fgSetDouble("/position/latitude-deg",  lat);
998         fgSetDouble("/position/altitude-ft", alt);
999         fgSetDouble("/orientation/heading-deg", heading);
1000
1001         fgSetString("/sim/presets/speed-set", "UVW");
1002         fgSetDouble("/velocities/uBody-fps", uvw[0]);
1003         fgSetDouble("/velocities/vBody-fps", uvw[1]);
1004         fgSetDouble("/velocities/wBody-fps", uvw[2]);
1005         fgSetDouble("/sim/presets/uBody-fps", uvw[0]);
1006         fgSetDouble("/sim/presets/vBody-fps", uvw[1]);
1007         fgSetDouble("/sim/presets/wBody-fps", uvw[2]);
1008
1009         fgSetBool("/sim/presets/onground", true);
1010
1011         return true;
1012     } else {
1013         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
1014                 << carrier );
1015         return false;
1016     }
1017 }
1018  
1019 // Set current_options lon/lat given an airport id and heading (degrees)
1020 static bool fgSetPosFromFix( const string& id ) {
1021     FGFix fix;
1022
1023     // set initial position from runway and heading
1024     if ( globals->get_fixlist()->query( id.c_str(), &fix ) ) {
1025         SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
1026                 << id );
1027
1028         double lon = fix.get_lon();
1029         double lat = fix.get_lat();
1030
1031         if ( fabs( fgGetDouble("/sim/presets/offset-distance") ) > SG_EPSILON )
1032         {
1033             double odist = fgGetDouble("/sim/presets/offset-distance")
1034                 * SG_NM_TO_METER;
1035             double oaz = fabs(fgGetDouble("/sim/presets/offset-azimuth"))
1036                 + 180.0;
1037             while ( oaz >= 360.0 ) { oaz -= 360.0; }
1038             double olat, olon, az2;
1039             geo_direct_wgs_84 ( 0, lat, lon, oaz, odist, &olat, &olon, &az2 );
1040
1041             lat = olat;
1042             lon = olon;
1043         }
1044
1045         // presets
1046         fgSetDouble("/sim/presets/longitude-deg",  lon );
1047         fgSetDouble("/sim/presets/latitude-deg",  lat );
1048
1049         // other code depends on the actual values being set ...
1050         fgSetDouble("/position/longitude-deg",  lon );
1051         fgSetDouble("/position/latitude-deg",  lat );
1052         fgSetDouble("/orientation/heading-deg", 
1053                     fgGetDouble("/sim/presets/heading-deg") );
1054
1055         SG_LOG( SG_GENERAL, SG_INFO,
1056                 "Position for " << id << " is ("
1057                 << lon << ", "<< lat << ")" );
1058
1059         return true;
1060     } else {
1061         SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
1062                 << id );
1063         return false;
1064     }
1065 }
1066  
1067 static void parseWaypoints() {
1068     string_list *waypoints = globals->get_initial_waypoints();
1069     if (waypoints) {
1070         vector<string>::iterator i;
1071         for (i = waypoints->begin(); 
1072              i  != waypoints->end();
1073              i++)
1074         {
1075             NewWaypoint(*i);
1076         }
1077         // Now were done using the way points we can deallocate the
1078         // memory they used
1079         while (waypoints->begin() != waypoints->end()) {
1080             waypoints->pop_back();
1081         }
1082         delete waypoints;
1083         globals->set_initial_waypoints(0);
1084     }
1085 }
1086
1087  
1088  
1089
1090
1091 /**
1092  * Initialize vor/ndb/ils/fix list management and query systems (as
1093  * well as simple airport db list)
1094  */
1095 bool
1096 fgInitNav ()
1097 {
1098     SG_LOG(SG_GENERAL, SG_INFO, "Loading Airport Database ...");
1099
1100     SGPath aptdb( globals->get_fg_root() );
1101     aptdb.append( "Airports/apt.dat" );
1102
1103     SGPath p_metar( globals->get_fg_root() );
1104     p_metar.append( "Airports/metar.dat" );
1105
1106     FGAirportList *airports = new FGAirportList();
1107     globals->set_airports( airports );
1108     FGRunwayList *runways = new FGRunwayList();
1109     globals->set_runways( runways );
1110
1111     fgAirportDBLoad( airports, runways, aptdb.str(), p_metar.str() );
1112
1113     FGNavList *navlist = new FGNavList;
1114     FGNavList *loclist = new FGNavList;
1115     FGNavList *gslist = new FGNavList;
1116     FGNavList *dmelist = new FGNavList;
1117     FGNavList *mkrlist = new FGNavList;
1118     FGNavList *tacanlist = new FGNavList;
1119     FGNavList *carrierlist = new FGNavList;
1120     FGTACANList *channellist = new FGTACANList;
1121
1122     globals->set_navlist( navlist );
1123     globals->set_loclist( loclist );
1124     globals->set_gslist( gslist );
1125     globals->set_dmelist( dmelist );
1126     globals->set_mkrlist( mkrlist );
1127     globals->set_tacanlist( tacanlist );
1128     globals->set_carrierlist( carrierlist );
1129     globals->set_channellist( channellist );
1130
1131     if ( !fgNavDBInit(airports, navlist, loclist, gslist, dmelist, mkrlist, tacanlist, carrierlist, channellist) ) {
1132         SG_LOG( SG_GENERAL, SG_ALERT,
1133                 "Problems loading one or more navigational database" );
1134     }
1135
1136     if ( fgGetBool("/sim/navdb/localizers/auto-align", true) ) {
1137         // align all the localizers with their corresponding runways
1138         // since data sources are good for cockpit navigation
1139         // purposes, but not always to the error tolerances needed to
1140         // exactly place these items.
1141         double threshold
1142             = fgGetDouble( "/sim/navdb/localizers/auto-align-threshold-deg",
1143                            5.0 );
1144         fgNavDBAlignLOCwithRunway( runways, loclist, threshold );
1145     }
1146
1147     SG_LOG(SG_GENERAL, SG_INFO, "  Fixes");
1148     SGPath p_fix( globals->get_fg_root() );
1149     p_fix.append( "Navaids/fix.dat" );
1150     FGFixList *fixlist = new FGFixList;
1151     fixlist->init( p_fix );
1152     globals->set_fixlist( fixlist );
1153
1154     return true;
1155 }
1156
1157
1158 // Set the initial position based on presets (or defaults)
1159 bool fgInitPosition() {
1160     // cout << "fgInitPosition()" << endl;
1161     double gs = fgGetDouble("/sim/presets/glideslope-deg")
1162         * SG_DEGREES_TO_RADIANS ;
1163     double od = fgGetDouble("/sim/presets/offset-distance");
1164     double alt = fgGetDouble("/sim/presets/altitude-ft");
1165
1166     bool set_pos = false;
1167
1168     // If glideslope is specified, then calculate offset-distance or
1169     // altitude relative to glide slope if either of those was not
1170     // specified.
1171     if ( fabs( gs ) > 0.01 ) {
1172         fgSetDistOrAltFromGlideSlope();
1173     }
1174
1175
1176     // If we have an explicit, in-range lon/lat, don't change it, just use it.
1177     // If not, check for an airport-id and use that.
1178     // If not, default to the middle of the KSFO field.
1179     // The default values for lon/lat are deliberately out of range
1180     // so that the airport-id can take effect; valid lon/lat will
1181     // override airport-id, however.
1182     double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
1183     double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
1184     if ( lon_deg >= -180.0 && lon_deg <= 180.0
1185          && lat_deg >= -90.0 && lat_deg <= 90.0 )
1186     {
1187         set_pos = true;
1188     }
1189
1190     string apt = fgGetString("/sim/presets/airport-id");
1191     string rwy_no = fgGetString("/sim/presets/runway");
1192     double hdg = fgGetDouble("/sim/presets/heading-deg");
1193     string vor = fgGetString("/sim/presets/vor-id");
1194     double vor_freq = fgGetDouble("/sim/presets/vor-freq");
1195     string ndb = fgGetString("/sim/presets/ndb-id");
1196     double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
1197     string carrier = fgGetString("/sim/presets/carrier");
1198     string parkpos = fgGetString("/sim/presets/parkpos");
1199     string fix = fgGetString("/sim/presets/fix");
1200
1201     fgSetDouble( "/orientation/heading-deg", hdg );
1202     fgInitTowerLocationListener();
1203
1204     if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
1205         // An airport + runway is requested
1206         if ( fgSetPosFromAirportIDandRwy( apt, rwy_no ) ) {
1207             // set tower position (a little off the heading for single
1208             // runway airports)
1209             fgSetString("/sim/tower/airport-id",  apt.c_str());
1210             set_pos = true;
1211         }
1212     }
1213
1214     if ( !set_pos && !apt.empty() ) {
1215         // An airport is requested (find runway closest to hdg)
1216         if ( fgSetPosFromAirportIDandHdg( apt, hdg ) ) {
1217             // set tower position (a little off the heading for single
1218             // runway airports)
1219             fgSetString("/sim/tower/airport-id",  apt.c_str());
1220             set_pos = true;
1221         }
1222     }
1223
1224     if ( !set_pos && !vor.empty() ) {
1225         // a VOR is requested
1226         if ( fgSetPosFromNAV( vor, vor_freq ) ) {
1227             set_pos = true;
1228         }
1229     }
1230
1231     if ( !set_pos && !ndb.empty() ) {
1232         // an NDB is requested
1233         if ( fgSetPosFromNAV( ndb, ndb_freq ) ) {
1234             set_pos = true;
1235         }
1236     }
1237
1238     if ( !set_pos && !carrier.empty() ) {
1239         // an aircraft carrier is requested
1240         if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
1241             set_pos = true;
1242         }
1243     }
1244
1245     if ( !set_pos && !fix.empty() ) {
1246         // a Fix is requested
1247         if ( fgSetPosFromFix( fix ) ) {
1248             set_pos = true;
1249         }
1250     }
1251
1252     if ( !set_pos ) {
1253         // No lon/lat specified, no airport specified, default to
1254         // middle of KSFO field.
1255         fgSetDouble("/sim/presets/longitude-deg", -122.374843);
1256         fgSetDouble("/sim/presets/latitude-deg", 37.619002);
1257     }
1258
1259     fgSetDouble( "/position/longitude-deg",
1260                  fgGetDouble("/sim/presets/longitude-deg") );
1261     fgSetDouble( "/position/latitude-deg",
1262                  fgGetDouble("/sim/presets/latitude-deg") );
1263
1264     // determine if this should be an on-ground or in-air start
1265     if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
1266         fgSetBool("/sim/presets/onground", false);
1267     } else {
1268         fgSetBool("/sim/presets/onground", true);
1269     }                              
1270
1271     return true;
1272 }
1273
1274
1275 // General house keeping initializations
1276 bool fgInitGeneral() {
1277     string root;
1278
1279 #if defined(FX) && defined(XMESA)
1280     char *mesa_win_state;
1281 #endif
1282
1283     SG_LOG( SG_GENERAL, SG_INFO, "General Initialization" );
1284     SG_LOG( SG_GENERAL, SG_INFO, "======= ==============" );
1285
1286     root = globals->get_fg_root();
1287     if ( ! root.length() ) {
1288         // No root path set? Then bail ...
1289         SG_LOG( SG_GENERAL, SG_ALERT,
1290                 "Cannot continue without a path to the base package "
1291                 << "being defined." );
1292         exit(-1);
1293     }
1294     SG_LOG( SG_GENERAL, SG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
1295
1296 #if defined(FX) && defined(XMESA)
1297     // initialize full screen flag
1298     globals->set_fullscreen(false);
1299     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1300         // Test for the MESA_GLX_FX env variable
1301         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
1302             // test if we are fullscreen mesa/glide
1303             if ( (mesa_win_state[0] == 'f') ||
1304                  (mesa_win_state[0] == 'F') ) {
1305                 globals->set_fullscreen(true);
1306             }
1307         }
1308     }
1309 #endif
1310
1311     return true;
1312 }
1313
1314
1315 // Initialize the flight model subsystem.  This just creates the
1316 // object.  The actual fdm initialization is delayed until we get a
1317 // proper scenery elevation hit.  This is checked for in main.cxx
1318
1319 void fgInitFDM() {
1320
1321     if ( cur_fdm_state ) {
1322         delete cur_fdm_state;
1323         cur_fdm_state = 0;
1324     }
1325
1326     double dt = 1.0 / fgGetInt("/sim/model-hz");
1327     string model = fgGetString("/sim/flight-model");
1328
1329     try {
1330         if ( model == "larcsim" ) {
1331             cur_fdm_state = new FGLaRCsim( dt );
1332         } else if ( model == "jsb" ) {
1333             cur_fdm_state = new FGJSBsim( dt );
1334 #if ENABLE_SP_FDMS
1335         } else if ( model == "ada" ) {
1336             cur_fdm_state = new FGADA( dt );
1337         } else if ( model == "acms" ) {
1338             cur_fdm_state = new FGACMS( dt );
1339 #endif
1340         } else if ( model == "balloon" ) {
1341             cur_fdm_state = new FGBalloonSim( dt );
1342         } else if ( model == "magic" ) {
1343             cur_fdm_state = new FGMagicCarpet( dt );
1344         } else if ( model == "ufo" ) {
1345             cur_fdm_state = new FGUFO( dt );
1346         } else if ( model == "external" ) {
1347             // external is a synonym for "--fdm=null" and is
1348             // maintained here for backwards compatibility
1349             cur_fdm_state = new FGNullFDM( dt );
1350         } else if ( model.find("network") == 0 ) {
1351             string host = "localhost";
1352             int port1 = 5501;
1353             int port2 = 5502;
1354             int port3 = 5503;
1355             string net_options = model.substr(8);
1356             string::size_type begin, end;
1357             begin = 0;
1358             // host
1359             end = net_options.find( ",", begin );
1360             if ( end != string::npos ) {
1361                 host = net_options.substr(begin, end - begin);
1362                 begin = end + 1;
1363             }
1364             // port1
1365             end = net_options.find( ",", begin );
1366             if ( end != string::npos ) {
1367                 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
1368                 begin = end + 1;
1369             }
1370             // port2
1371             end = net_options.find( ",", begin );
1372             if ( end != string::npos ) {
1373                 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
1374                 begin = end + 1;
1375             }
1376             // port3
1377             end = net_options.find( ",", begin );
1378             if ( end != string::npos ) {
1379                 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
1380                 begin = end + 1;
1381             }
1382             cur_fdm_state = new FGExternalNet( dt, host, port1, port2, port3 );
1383         } else if ( model.find("pipe") == 0 ) {
1384             // /* old */ string pipe_path = model.substr(5);
1385             // /* old */ cur_fdm_state = new FGExternalPipe( dt, pipe_path );
1386             string pipe_path = "";
1387             string pipe_protocol = "";
1388             string pipe_options = model.substr(5);
1389             string::size_type begin, end;
1390             begin = 0;
1391             // pipe file path
1392             end = pipe_options.find( ",", begin );
1393             if ( end != string::npos ) {
1394                 pipe_path = pipe_options.substr(begin, end - begin);
1395                 begin = end + 1;
1396             }
1397             // protocol (last option)
1398             pipe_protocol = pipe_options.substr(begin);
1399             cur_fdm_state = new FGExternalPipe( dt, pipe_path, pipe_protocol );
1400         } else if ( model == "null" ) {
1401             cur_fdm_state = new FGNullFDM( dt );
1402         } else if ( model == "yasim" ) {
1403             cur_fdm_state = new YASim( dt );
1404         } else {
1405             SG_LOG(SG_GENERAL, SG_ALERT,
1406                    "Unrecognized flight model '" << model
1407                    << "', cannot init flight dynamics model.");
1408             exit(-1);
1409         }
1410     } catch ( ... ) {
1411         SG_LOG(SG_GENERAL, SG_ALERT, "FlightGear aborting\n\n");
1412         exit(-1);
1413     }
1414 }
1415
1416 static void printMat(const sgVec4 *mat, char *name="")
1417 {
1418     int i;
1419     SG_LOG(SG_GENERAL, SG_BULK, name );
1420     for(i=0; i<4; i++) {
1421         SG_LOG(SG_GENERAL, SG_BULK, "  " << mat[i][0] << " " << mat[i][1]
1422                                     << " " << mat[i][2] << " " << mat[i][3] );
1423     }
1424 }
1425
1426 // Initialize view parameters
1427 void fgInitView() {
1428   // force update of model so that viewer can get some data...
1429   globals->get_aircraft_model()->update(0);
1430   // run update for current view so that data is current...
1431   globals->get_viewmgr()->update(0);
1432
1433   printMat(globals->get_current_view()->get_VIEW(),"VIEW");
1434   printMat(globals->get_current_view()->get_UP(),"UP");
1435   // printMat(globals->get_current_view()->get_LOCAL(),"LOCAL");
1436   
1437 }
1438
1439
1440 SGTime *fgInitTime() {
1441     // Initialize time
1442     static const SGPropertyNode *longitude
1443         = fgGetNode("/position/longitude-deg");
1444     static const SGPropertyNode *latitude
1445         = fgGetNode("/position/latitude-deg");
1446     static const SGPropertyNode *cur_time_override
1447         = fgGetNode("/sim/time/cur-time-override", true);
1448
1449     SGPath zone( globals->get_fg_root() );
1450     zone.append( "Timezone" );
1451     SGTime *t = new SGTime( longitude->getDoubleValue()
1452                               * SGD_DEGREES_TO_RADIANS,
1453                             latitude->getDoubleValue()
1454                               * SGD_DEGREES_TO_RADIANS,
1455                             zone.str(),
1456                             cur_time_override->getLongValue() );
1457
1458     globals->set_warp_delta( 0 );
1459
1460     t->update( 0.0, 0.0,
1461                cur_time_override->getLongValue(),
1462                globals->get_warp() );
1463
1464     return t;
1465 }
1466
1467
1468 // set up a time offset (aka warp) if one is specified
1469 void fgInitTimeOffset() {
1470     static const SGPropertyNode *longitude
1471         = fgGetNode("/position/longitude-deg");
1472     static const SGPropertyNode *latitude
1473         = fgGetNode("/position/latitude-deg");
1474     static const SGPropertyNode *cur_time_override
1475         = fgGetNode("/sim/time/cur-time-override", true);
1476
1477     // Handle potential user specified time offsets
1478     int orig_warp = globals->get_warp();
1479     SGTime *t = globals->get_time_params();
1480     time_t cur_time = t->get_cur_time();
1481     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1482     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1483     time_t aircraftLocalTime = 
1484         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1485
1486     // Okay, we now have several possible scenarios
1487     int offset = fgGetInt("/sim/startup/time-offset");
1488     string offset_type = fgGetString("/sim/startup/time-offset-type");
1489
1490     int warp = 0;
1491     if ( offset_type == "real" ) {
1492         warp = 0;
1493     } else if ( offset_type == "dawn" ) {
1494         warp = fgTimeSecondsUntilSunAngle( cur_time,
1495                                            longitude->getDoubleValue()
1496                                              * SGD_DEGREES_TO_RADIANS,
1497                                            latitude->getDoubleValue()
1498                                              * SGD_DEGREES_TO_RADIANS,
1499                                            90.0, true ); 
1500     } else if ( offset_type == "morning" ) {
1501         warp = fgTimeSecondsUntilSunAngle( cur_time,
1502                                            longitude->getDoubleValue()
1503                                              * SGD_DEGREES_TO_RADIANS,
1504                                            latitude->getDoubleValue()
1505                                              * SGD_DEGREES_TO_RADIANS,
1506                                            75.0, true ); 
1507     } else if ( offset_type == "noon" ) {
1508         warp = fgTimeSecondsUntilSunAngle( cur_time,
1509                                            longitude->getDoubleValue()
1510                                              * SGD_DEGREES_TO_RADIANS,
1511                                            latitude->getDoubleValue()
1512                                              * SGD_DEGREES_TO_RADIANS,
1513                                            0.0, true ); 
1514     } else if ( offset_type == "afternoon" ) {
1515         warp = fgTimeSecondsUntilSunAngle( cur_time,
1516                                            longitude->getDoubleValue()
1517                                              * SGD_DEGREES_TO_RADIANS,
1518                                            latitude->getDoubleValue()
1519                                              * SGD_DEGREES_TO_RADIANS,
1520                                            60.0, false ); 
1521      } else if ( offset_type == "dusk" ) {
1522         warp = fgTimeSecondsUntilSunAngle( cur_time,
1523                                            longitude->getDoubleValue()
1524                                              * SGD_DEGREES_TO_RADIANS,
1525                                            latitude->getDoubleValue()
1526                                              * SGD_DEGREES_TO_RADIANS,
1527                                            90.0, false ); 
1528      } else if ( offset_type == "evening" ) {
1529         warp = fgTimeSecondsUntilSunAngle( cur_time,
1530                                            longitude->getDoubleValue()
1531                                              * SGD_DEGREES_TO_RADIANS,
1532                                            latitude->getDoubleValue()
1533                                              * SGD_DEGREES_TO_RADIANS,
1534                                            100.0, false ); 
1535     } else if ( offset_type == "midnight" ) {
1536         warp = fgTimeSecondsUntilSunAngle( cur_time,
1537                                            longitude->getDoubleValue()
1538                                              * SGD_DEGREES_TO_RADIANS,
1539                                            latitude->getDoubleValue()
1540                                              * SGD_DEGREES_TO_RADIANS,
1541                                            180.0, false ); 
1542     } else if ( offset_type == "system-offset" ) {
1543         warp = offset;
1544     } else if ( offset_type == "gmt-offset" ) {
1545         warp = offset - (currGMT - systemLocalTime);
1546     } else if ( offset_type == "latitude-offset" ) {
1547         warp = offset - (aircraftLocalTime - systemLocalTime);
1548     } else if ( offset_type == "system" ) {
1549         warp = offset - cur_time;
1550     } else if ( offset_type == "gmt" ) {
1551         warp = offset - currGMT;
1552     } else if ( offset_type == "latitude" ) {
1553         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1554     } else {
1555         SG_LOG( SG_GENERAL, SG_ALERT,
1556                 "FG_TIME::Unsupported offset type " << offset_type );
1557         exit( -1 );
1558     }
1559     globals->set_warp( orig_warp + warp );
1560     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1561                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1562                cur_time_override->getLongValue(),
1563                globals->get_warp() );
1564
1565     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1566             << globals->get_warp() );
1567 }
1568
1569
1570 // This is the top level init routine which calls all the other
1571 // initialization routines.  If you are adding a subsystem to flight
1572 // gear, its initialization call should located in this routine.
1573 // Returns non-zero if a problem encountered.
1574 bool fgInitSubsystems() {
1575     // static const SGPropertyNode *longitude
1576     //     = fgGetNode("/sim/presets/longitude-deg");
1577     // static const SGPropertyNode *latitude
1578     //     = fgGetNode("/sim/presets/latitude-deg");
1579     // static const SGPropertyNode *altitude
1580     //     = fgGetNode("/sim/presets/altitude-ft");
1581
1582     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1583     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1584
1585     ////////////////////////////////////////////////////////////////////
1586     // Initialize the event manager subsystem.
1587     ////////////////////////////////////////////////////////////////////
1588
1589     globals->get_event_mgr()->init();
1590     globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
1591
1592     ////////////////////////////////////////////////////////////////////
1593     // Initialize the property interpolator subsystem
1594     ////////////////////////////////////////////////////////////////////
1595     globals->add_subsystem("interpolator", new SGInterpolator);
1596
1597
1598     ////////////////////////////////////////////////////////////////////
1599     // Add the FlightGear property utilities.
1600     ////////////////////////////////////////////////////////////////////
1601     globals->add_subsystem("properties", new FGProperties);
1602
1603     ////////////////////////////////////////////////////////////////////
1604     // Initialize the material property subsystem.
1605     ////////////////////////////////////////////////////////////////////
1606
1607     SGPath mpath( globals->get_fg_root() );
1608     mpath.append( "materials.xml" );
1609     string season = fgGetString("/sim/startup/season", "summer");
1610     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(), season.c_str()) ) {
1611         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1612         exit(-1);
1613     }
1614
1615
1616     ////////////////////////////////////////////////////////////////////
1617     // Initialize the scenery management subsystem.
1618     ////////////////////////////////////////////////////////////////////
1619
1620     if ( globals->get_tile_mgr()->init() ) {
1621         // Load the local scenery data
1622         double visibility_meters = fgGetDouble("/environment/visibility-m");
1623                 
1624         globals->get_tile_mgr()->update( visibility_meters );
1625     } else {
1626         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1627         exit(-1);
1628     }
1629
1630     // cause refresh of viewer scenery timestamps every 15 seconds...
1631     globals->get_event_mgr()->addTask( "FGTileMgr::refresh_view_timestamps()",
1632                                        globals->get_tile_mgr(),
1633                                        &FGTileMgr::refresh_view_timestamps,
1634                                        15 );
1635
1636
1637     ////////////////////////////////////////////////////////////////////
1638     // Initialize the flight model subsystem.
1639     ////////////////////////////////////////////////////////////////////
1640
1641     fgInitFDM();
1642         
1643     // allocates structures so must happen before any of the flight
1644     // model or control parameters are set
1645     fgAircraftInit();   // In the future this might not be the case.
1646
1647
1648     ////////////////////////////////////////////////////////////////////
1649     // Initialize the XML Autopilot subsystem.
1650     ////////////////////////////////////////////////////////////////////
1651
1652     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1653     globals->add_subsystem( "route-manager", new FGRouteMgr );
1654
1655   
1656     ////////////////////////////////////////////////////////////////////
1657     // Initialize the view manager subsystem.
1658     ////////////////////////////////////////////////////////////////////
1659
1660     fgInitView();
1661
1662     ////////////////////////////////////////////////////////////////////
1663     // Create and register the logger.
1664     ////////////////////////////////////////////////////////////////////
1665     
1666     globals->add_subsystem("logger", new FGLogger);
1667
1668     ////////////////////////////////////////////////////////////////////
1669     // Create and register the XML GUI.
1670     ////////////////////////////////////////////////////////////////////
1671
1672     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1673
1674
1675     ////////////////////////////////////////////////////////////////////
1676     // Initialize the local time subsystem.
1677     ////////////////////////////////////////////////////////////////////
1678
1679     // update the current timezone each 30 minutes
1680     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1681                                        &fgUpdateLocalTime, 30*60 );
1682     fgInitTimeOffset();         // the environment subsystem needs this
1683
1684
1685     ////////////////////////////////////////////////////////////////////
1686     // Initialize the weather subsystem.
1687     ////////////////////////////////////////////////////////////////////
1688
1689     // Initialize the weather modeling subsystem
1690     globals->add_subsystem("environment", new FGEnvironmentMgr);
1691
1692
1693     ////////////////////////////////////////////////////////////////////
1694     // Initialize the lighting subsystem.
1695     ////////////////////////////////////////////////////////////////////
1696
1697     globals->add_subsystem("lighting", new FGLight);
1698
1699     //////////////////////////////////////////////////////////////////////
1700     // Initialize the 2D cloud subsystem.
1701     ////////////////////////////////////////////////////////////////////
1702     fgGetBool("/sim/rendering/bump-mapping", false);
1703
1704 #ifdef ENABLE_AUDIO_SUPPORT
1705     ////////////////////////////////////////////////////////////////////
1706     // Initialize the sound subsystem.
1707     ////////////////////////////////////////////////////////////////////
1708
1709     init_volume = fgGetFloat("/sim/sound/volume");
1710     fgSetFloat("/sim/sound/volume", 0.0f);
1711     globals->set_soundmgr(new SGSoundMgr);
1712     globals->get_soundmgr()->init();
1713     globals->get_soundmgr()->bind();
1714
1715
1716     ////////////////////////////////////////////////////////////////////
1717     // Initialize the sound-effects subsystem.
1718     ////////////////////////////////////////////////////////////////////
1719
1720     globals->add_subsystem("fx", new FGFX);
1721     
1722 #endif
1723
1724     ////////////////////////////////////////////////////////////////////
1725     // Initialise ATC display system
1726     ////////////////////////////////////////////////////////////////////
1727
1728     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1729     globals->set_ATC_display(new FGATCDisplay);
1730     globals->get_ATC_display()->init(); 
1731
1732     ////////////////////////////////////////////////////////////////////
1733     // Initialise the ATC Manager 
1734     ////////////////////////////////////////////////////////////////////
1735
1736     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1737     globals->set_ATC_mgr(new FGATCMgr);
1738     globals->get_ATC_mgr()->init(); 
1739     
1740     ////////////////////////////////////////////////////////////////////
1741     // Initialise the AI Manager 
1742     ////////////////////////////////////////////////////////////////////
1743
1744     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1745     globals->set_AI_mgr(new FGAIMgr);
1746     globals->get_AI_mgr()->init();
1747
1748     ////////////////////////////////////////////////////////////////////
1749     // Initialise the AI Model Manager
1750     ////////////////////////////////////////////////////////////////////
1751     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1752     globals->add_subsystem("ai_model", new FGAIManager);
1753     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1754
1755
1756      // It's probably a good idea to initialize the top level traffic manager
1757      // After the AI and ATC systems have been initialized properly.
1758      // AI Traffic manager
1759      globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1760              FGTrafficManager *dispatcher = 
1761              (FGTrafficManager*) globals->get_subsystem("Traffic Manager");
1762              SGPath path = globals->get_fg_root();
1763              path.append("/Traffic/fgtraffic.xml");
1764      readXML(path.str(),
1765         *dispatcher);
1766              //globals->get_subsystem("Traffic Manager")->init();
1767
1768     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1769     globals->add_subsystem("systems", new FGSystemMgr);
1770
1771
1772
1773     ////////////////////////////////////////////////////////////////////
1774     // Initialize the cockpit subsystem
1775     ////////////////////////////////////////////////////////////////////
1776     if( fgCockpitInit( &current_aircraft )) {
1777         // Cockpit initialized ok.
1778     } else {
1779         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1780         exit(-1);
1781     }
1782
1783
1784     ////////////////////////////////////////////////////////////////////
1785     // Initialize the autopilot subsystem.
1786     ////////////////////////////////////////////////////////////////////
1787
1788                                 // FIXME: these should go in the
1789                                 // GUI initialization code, not here.
1790     // fgAPAdjustInit();
1791     NewTgtAirportInit();
1792     NewHeadingInit();
1793     NewAltitudeInit();
1794
1795     ////////////////////////////////////////////////////////////////////
1796     // Initialize I/O subsystem.
1797     ////////////////////////////////////////////////////////////////////
1798
1799     globals->get_io()->init();
1800     globals->get_io()->bind();
1801
1802
1803     ////////////////////////////////////////////////////////////////////
1804     // Add a new 2D panel.
1805     ////////////////////////////////////////////////////////////////////
1806
1807     string panel_path = fgGetString("/sim/panel/path",
1808                                     "Panels/Default/default.xml");
1809
1810     globals->set_current_panel( fgReadPanel(panel_path) );
1811     if (globals->get_current_panel() == 0) {
1812         SG_LOG( SG_INPUT, SG_ALERT, 
1813                 "Error reading new panel from " << panel_path );
1814     } else {
1815         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1816         globals->get_current_panel()->init();
1817         globals->get_current_panel()->bind();
1818     }
1819
1820     
1821     ////////////////////////////////////////////////////////////////////
1822     // Initialize the controls subsystem.
1823     ////////////////////////////////////////////////////////////////////
1824
1825     globals->get_controls()->init();
1826     globals->get_controls()->bind();
1827
1828
1829     ////////////////////////////////////////////////////////////////////
1830     // Initialize the input subsystem.
1831     ////////////////////////////////////////////////////////////////////
1832
1833     globals->add_subsystem("input", new FGInput);
1834
1835
1836     ////////////////////////////////////////////////////////////////////
1837     // Initialize the replay subsystem
1838     ////////////////////////////////////////////////////////////////////
1839     globals->add_subsystem("replay", new FGReplay);
1840
1841     ////////////////////////////////////////////////////////////////////
1842     // Bind and initialize subsystems.
1843     ////////////////////////////////////////////////////////////////////
1844
1845     globals->get_subsystem_mgr()->bind();
1846     globals->get_subsystem_mgr()->init();
1847
1848 #ifdef FG_MPLAYER_AS
1849     ////////////////////////////////////////////////////////////////////
1850     // Initialize multiplayer subsystem
1851     ////////////////////////////////////////////////////////////////////
1852
1853     globals->set_multiplayer_mgr(new FGMultiplayMgr);
1854     globals->get_multiplayer_mgr()->init();
1855 #endif
1856
1857     ////////////////////////////////////////////////////////////////////////
1858     // Initialize the Nasal interpreter.
1859     // Do this last, so that the loaded scripts see initialized state
1860     ////////////////////////////////////////////////////////////////////////
1861     FGNasalSys* nasal = new FGNasalSys();
1862     globals->add_subsystem("nasal", nasal);
1863     nasal->init();
1864
1865     ////////////////////////////////////////////////////////////////////
1866     // At this point we could try and parse the waypoint options
1867     ///////////////////////////////////////////////////////////////////
1868     parseWaypoints();
1869
1870     // initialize methods that depend on other subsystems.
1871     globals->get_subsystem_mgr()->postinit();
1872
1873     ////////////////////////////////////////////////////////////////////////
1874     // End of subsystem initialization.
1875     ////////////////////////////////////////////////////////////////////
1876
1877     SG_LOG( SG_GENERAL, SG_INFO, endl);
1878
1879                                 // Save the initial state for future
1880                                 // reference.
1881     globals->saveInitialState();
1882
1883     return true;
1884 }
1885
1886
1887 void fgReInitSubsystems()
1888 {
1889     // static const SGPropertyNode *longitude
1890     //     = fgGetNode("/sim/presets/longitude-deg");
1891     // static const SGPropertyNode *latitude
1892     //     = fgGetNode("/sim/presets/latitude-deg");
1893     static const SGPropertyNode *altitude
1894         = fgGetNode("/sim/presets/altitude-ft");
1895     static const SGPropertyNode *master_freeze
1896         = fgGetNode("/sim/freeze/master");
1897
1898     SG_LOG( SG_GENERAL, SG_INFO,
1899             "fgReInitSubsystems(): /position/altitude = "
1900             << altitude->getDoubleValue() );
1901
1902     bool freeze = master_freeze->getBoolValue();
1903     if ( !freeze ) {
1904         fgSetBool("/sim/freeze/master", true);
1905     }
1906     fgSetBool("/sim/crashed", false);
1907
1908     // Force reupdating the positions of the ai 3d models. They are used for
1909     // initializing ground level for the FDM.
1910     globals->get_subsystem("ai_model")->reinit();
1911
1912     // Initialize the FDM
1913     fgInitFDM();
1914     
1915     // allocates structures so must happen before any of the flight
1916     // model or control parameters are set
1917     fgAircraftInit();   // In the future this might not be the case.
1918
1919     // reload offsets from config defaults
1920     globals->get_viewmgr()->reinit();
1921
1922     fgInitView();
1923
1924     globals->get_controls()->reset_all();
1925
1926     fgUpdateLocalTime();
1927
1928     // re-init to proper time of day setting
1929     fgInitTimeOffset();
1930
1931     if ( !freeze ) {
1932         fgSetBool("/sim/freeze/master", false);
1933     }
1934     fgSetBool("/sim/sceneryloaded",false);
1935 }
1936