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