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