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