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