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