]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
958a91ad075ca58365ad7112a6b158a67b455007
[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 <Autopilot/autobrake.hxx>
77
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/panel.hxx>
80 #include <Cockpit/panel_io.hxx>
81 #ifdef ENABLE_SP_FDM
82 #include <FDM/SP/ADA.hxx>
83 #include <FDM/SP/ACMS.hxx>
84 #include <FDM/SP/MagicCarpet.hxx>
85 #include <FDM/SP/Balloon.h>
86 #endif
87 #include <FDM/ExternalNet/ExternalNet.hxx>
88 #include <FDM/ExternalPipe/ExternalPipe.hxx>
89 #include <FDM/JSBSim/JSBSim.hxx>
90 #include <FDM/LaRCsim/LaRCsim.hxx>
91 #include <FDM/UFO.hxx>
92 #include <FDM/NullFDM.hxx>
93 #include <FDM/YASim/YASim.hxx>
94 #include <GUI/new_gui.hxx>
95 #include <Include/general.hxx>
96 #include <Input/input.hxx>
97 #include <Instrumentation/instrument_mgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <AIModel/submodel.hxx>
100 #include <AIModel/AIManager.hxx>
101 #include <Navaids/navdb.hxx>
102 #include <Navaids/navlist.hxx>
103 #include <Navaids/fix.hxx>
104 #include <Navaids/fixlist.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 #include <Environment/ridge_lift.hxx>
121
122 #include "fg_init.hxx"
123 #include "fg_io.hxx"
124 #include "fg_commands.hxx"
125 #include "fg_props.hxx"
126 #include "options.hxx"
127 #include "globals.hxx"
128 #include "logger.hxx"
129 #include "renderer.hxx"
130 #include "viewmgr.hxx"
131 #include "main.hxx"
132
133 #ifdef __APPLE__
134 #  include <CoreFoundation/CoreFoundation.h>
135 #endif
136
137 using std::string;
138
139 class Sound;
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     fgAirportDBLoad( aptdb.str(), p_metar.str() );
974
975     FGNavList *navlist = new FGNavList;
976     FGNavList *loclist = new FGNavList;
977     FGNavList *gslist = new FGNavList;
978     FGNavList *dmelist = new FGNavList;
979     FGNavList *tacanlist = new FGNavList;
980     FGNavList *carrierlist = new FGNavList;
981     FGTACANList *channellist = new FGTACANList;
982
983     globals->set_navlist( navlist );
984     globals->set_loclist( loclist );
985     globals->set_gslist( gslist );
986     globals->set_dmelist( dmelist );
987     globals->set_tacanlist( tacanlist );
988     globals->set_carrierlist( carrierlist );
989     globals->set_channellist( channellist );
990
991     if ( !fgNavDBInit(navlist, loclist, gslist, dmelist, 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;
1000     fixlist.init( p_fix );  // adds fixes to the DB in positioned.cxx
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_exception(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     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
1471             globals->get_props()) ) {
1472         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1473         exit(-1);
1474     }
1475
1476
1477     ////////////////////////////////////////////////////////////////////
1478     // Initialize the scenery management subsystem.
1479     ////////////////////////////////////////////////////////////////////
1480
1481     if ( globals->get_tile_mgr()->init() ) {
1482         // Load the local scenery data
1483         double visibility_meters = fgGetDouble("/environment/visibility-m");
1484                 
1485         globals->get_tile_mgr()->update( visibility_meters );
1486     } else {
1487         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1488         exit(-1);
1489     }
1490
1491     globals->get_scenery()->get_scene_graph()
1492         ->addChild(simgear::Particles::getCommonRoot());
1493     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
1494
1495     ////////////////////////////////////////////////////////////////////
1496     // Initialize the flight model subsystem.
1497     ////////////////////////////////////////////////////////////////////
1498
1499     fgInitFDM();
1500         
1501     // allocates structures so must happen before any of the flight
1502     // model or control parameters are set
1503     fgAircraftInit();   // In the future this might not be the case.
1504
1505
1506     ////////////////////////////////////////////////////////////////////
1507     // Initialize the weather subsystem.
1508     ////////////////////////////////////////////////////////////////////
1509
1510     // Initialize the weather modeling subsystem
1511     globals->add_subsystem("environment", new FGEnvironmentMgr);
1512
1513     ////////////////////////////////////////////////////////////////////
1514     // Initialize the ridge lift simulation.
1515     ////////////////////////////////////////////////////////////////////
1516
1517     // Initialize the ridgelift subsystem
1518     globals->add_subsystem("ridgelift", new FGRidgeLift);
1519
1520
1521     ////////////////////////////////////////////////////////////////////
1522     // Initialize the aircraft systems and instrumentation (before the
1523     // autopilot.)
1524     ////////////////////////////////////////////////////////////////////
1525
1526     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1527     globals->add_subsystem("systems", new FGSystemMgr);
1528
1529     ////////////////////////////////////////////////////////////////////
1530     // Initialize the XML Autopilot subsystem.
1531     ////////////////////////////////////////////////////////////////////
1532
1533     globals->add_subsystem( "xml-autopilot", new FGXMLAutopilot );
1534     globals->add_subsystem( "route-manager", new FGRouteMgr );
1535     globals->add_subsystem( "autobrake", new FGAutoBrake );
1536     
1537     ////////////////////////////////////////////////////////////////////
1538     // Initialize the view manager subsystem.
1539     ////////////////////////////////////////////////////////////////////
1540
1541     fgInitView();
1542
1543     ////////////////////////////////////////////////////////////////////
1544     // Initialize the Input-Output subsystem
1545     ////////////////////////////////////////////////////////////////////
1546     globals->add_subsystem( "io", new FGIO );
1547
1548     ////////////////////////////////////////////////////////////////////
1549     // Create and register the logger.
1550     ////////////////////////////////////////////////////////////////////
1551     
1552     globals->add_subsystem("logger", new FGLogger);
1553
1554     ////////////////////////////////////////////////////////////////////
1555     // Create and register the XML GUI.
1556     ////////////////////////////////////////////////////////////////////
1557
1558     globals->add_subsystem("gui", new NewGUI, SGSubsystemMgr::INIT);
1559
1560
1561     ////////////////////////////////////////////////////////////////////
1562     // Initialize the local time subsystem.
1563     ////////////////////////////////////////////////////////////////////
1564
1565     // update the current timezone each 30 minutes
1566     globals->get_event_mgr()->addTask( "fgUpdateLocalTime()",
1567                                        &fgUpdateLocalTime, 30*60 );
1568     fgInitTimeOffset();         // the environment subsystem needs this
1569
1570
1571     ////////////////////////////////////////////////////////////////////
1572     // Initialize the lighting subsystem.
1573     ////////////////////////////////////////////////////////////////////
1574
1575     globals->add_subsystem("lighting", new FGLight);
1576
1577     //////////////////////////////////////////////////////////////////////
1578     // Initialize the 2D cloud subsystem.
1579     ////////////////////////////////////////////////////////////////////
1580     fgGetBool("/sim/rendering/bump-mapping", false);
1581
1582 #ifdef ENABLE_AUDIO_SUPPORT
1583     ////////////////////////////////////////////////////////////////////
1584     // Initialize the sound subsystem.
1585     ////////////////////////////////////////////////////////////////////
1586
1587     init_volume = fgGetFloat("/sim/sound/volume");
1588     fgSetFloat("/sim/sound/volume", 0.0f);
1589     globals->set_soundmgr(new SGSoundMgr);
1590     globals->get_soundmgr()->init();
1591     globals->get_soundmgr()->bind();
1592
1593
1594     ////////////////////////////////////////////////////////////////////
1595     // Initialize the sound-effects subsystem.
1596     ////////////////////////////////////////////////////////////////////
1597
1598     globals->add_subsystem("fx", new FGFX);
1599     globals->add_subsystem("voice", new FGVoiceMgr);
1600 #endif
1601
1602     ////////////////////////////////////////////////////////////////////
1603     // Initialise the ATC Manager 
1604     ////////////////////////////////////////////////////////////////////
1605
1606     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1607     globals->set_ATC_mgr(new FGATCMgr);
1608     globals->get_ATC_mgr()->init(); 
1609     
1610     ////////////////////////////////////////////////////////////////////
1611     // Initialise the AI Manager 
1612     ////////////////////////////////////////////////////////////////////
1613
1614     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1615     globals->set_AI_mgr(new FGAIMgr);
1616     globals->get_AI_mgr()->init();
1617
1618     ////////////////////////////////////////////////////////////////////
1619     // Initialise the AI Model Manager
1620     ////////////////////////////////////////////////////////////////////
1621     SG_LOG(SG_GENERAL, SG_INFO, "  AI Model Manager");
1622     globals->add_subsystem("ai_model", new FGAIManager);
1623     globals->add_subsystem("submodel_mgr", new FGSubmodelMgr);
1624
1625
1626     // It's probably a good idea to initialize the top level traffic manager
1627     // After the AI and ATC systems have been initialized properly.
1628     // AI Traffic manager
1629     globals->add_subsystem("Traffic Manager", new FGTrafficManager);
1630
1631
1632     ////////////////////////////////////////////////////////////////////
1633     // Initialize the cockpit subsystem
1634     ////////////////////////////////////////////////////////////////////
1635     if( fgCockpitInit( &current_aircraft )) {
1636         // Cockpit initialized ok.
1637     } else {
1638         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1639         exit(-1);
1640     }
1641
1642
1643     ////////////////////////////////////////////////////////////////////
1644     // Add a new 2D panel.
1645     ////////////////////////////////////////////////////////////////////
1646
1647     string panel_path = fgGetString("/sim/panel/path",
1648                                     "Panels/Default/default.xml");
1649
1650     globals->set_current_panel( fgReadPanel(panel_path) );
1651     if (globals->get_current_panel() == 0) {
1652         SG_LOG( SG_INPUT, SG_ALERT,
1653                 "Error reading new panel from " << panel_path );
1654     } else {
1655         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1656         globals->get_current_panel()->init();
1657         globals->get_current_panel()->bind();
1658     }
1659
1660
1661     ////////////////////////////////////////////////////////////////////
1662     // Initialize the controls subsystem.
1663     ////////////////////////////////////////////////////////////////////
1664
1665     globals->get_controls()->init();
1666     globals->get_controls()->bind();
1667
1668
1669     ////////////////////////////////////////////////////////////////////
1670     // Initialize the input subsystem.
1671     ////////////////////////////////////////////////////////////////////
1672
1673     globals->add_subsystem("input", new FGInput);
1674
1675
1676     ////////////////////////////////////////////////////////////////////
1677     // Initialize the replay subsystem
1678     ////////////////////////////////////////////////////////////////////
1679     globals->add_subsystem("replay", new FGReplay);
1680
1681     ////////////////////////////////////////////////////////////////////
1682     // Bind and initialize subsystems.
1683     ////////////////////////////////////////////////////////////////////
1684
1685     globals->get_subsystem_mgr()->bind();
1686     globals->get_subsystem_mgr()->init();
1687
1688     ////////////////////////////////////////////////////////////////////
1689     // Initialize multiplayer subsystem
1690     ////////////////////////////////////////////////////////////////////
1691
1692     globals->set_multiplayer_mgr(new FGMultiplayMgr);
1693     globals->get_multiplayer_mgr()->init();
1694
1695     ////////////////////////////////////////////////////////////////////////
1696     // Initialize the Nasal interpreter.
1697     // Do this last, so that the loaded scripts see initialized state
1698     ////////////////////////////////////////////////////////////////////////
1699     FGNasalSys* nasal = new FGNasalSys();
1700     globals->add_subsystem("nasal", nasal, SGSubsystemMgr::INIT);
1701     nasal->init();
1702
1703     // initialize methods that depend on other subsystems.
1704     globals->get_subsystem_mgr()->postinit();
1705
1706     ////////////////////////////////////////////////////////////////////////
1707     // End of subsystem initialization.
1708     ////////////////////////////////////////////////////////////////////
1709
1710     SG_LOG( SG_GENERAL, SG_INFO, endl);
1711
1712                                 // Save the initial state for future
1713                                 // reference.
1714     globals->saveInitialState();
1715     
1716     return true;
1717 }
1718
1719
1720 void fgReInitSubsystems()
1721 {
1722     // static const SGPropertyNode *longitude
1723     //     = fgGetNode("/sim/presets/longitude-deg");
1724     // static const SGPropertyNode *latitude
1725     //     = fgGetNode("/sim/presets/latitude-deg");
1726     static const SGPropertyNode *altitude
1727         = fgGetNode("/sim/presets/altitude-ft");
1728     static const SGPropertyNode *master_freeze
1729         = fgGetNode("/sim/freeze/master");
1730
1731     SG_LOG( SG_GENERAL, SG_INFO,
1732             "fgReInitSubsystems(): /position/altitude = "
1733             << altitude->getDoubleValue() );
1734
1735     bool freeze = master_freeze->getBoolValue();
1736     if ( !freeze ) {
1737         fgSetBool("/sim/freeze/master", true);
1738     }
1739     fgSetBool("/sim/crashed", false);
1740
1741     // Force reupdating the positions of the ai 3d models. They are used for
1742     // initializing ground level for the FDM.
1743     globals->get_subsystem("ai_model")->reinit();
1744
1745     // Initialize the FDM
1746     fgInitFDM();
1747     
1748     // allocates structures so must happen before any of the flight
1749     // model or control parameters are set
1750     fgAircraftInit();   // In the future this might not be the case.
1751
1752     // reload offsets from config defaults
1753     globals->get_viewmgr()->reinit();
1754
1755     fgInitView();
1756
1757     globals->get_controls()->reset_all();
1758
1759     fgUpdateLocalTime();
1760
1761     // re-init to proper time of day setting
1762     fgInitTimeOffset();
1763
1764     if ( !freeze ) {
1765         fgSetBool("/sim/freeze/master", false);
1766     }
1767     fgSetBool("/sim/sceneryloaded",false);
1768 }
1769
1770
1771 void reInit(void)  // from gui_local.cxx -- TODO merge with fgReInitSubsystems()
1772 {
1773     static SGPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master", true);
1774
1775     bool freeze = master_freeze->getBoolValue();
1776     if (!freeze)
1777         master_freeze->setBoolValue(true);
1778
1779     fgSetBool("/sim/signals/reinit", true);
1780     cur_fdm_state->unbind();
1781
1782     // in case user has changed window size as
1783     // restoreInitialState() overwrites these
1784     int xsize = fgGetInt("/sim/startup/xsize");
1785     int ysize = fgGetInt("/sim/startup/ysize");
1786
1787     // viewports also needs to be saved/restored as
1788     // restoreInitialState() overwrites these
1789     SGPropertyNode *guiNode = new SGPropertyNode;
1790     SGPropertyNode *cameraNode = new SGPropertyNode;
1791     SGPropertyNode *cameraGroupNode = fgGetNode("/sim/rendering/camera-group");
1792     copyProperties(cameraGroupNode->getChild("camera"), cameraNode);
1793     copyProperties(cameraGroupNode->getChild("gui"), guiNode);
1794
1795     globals->restoreInitialState();
1796
1797     // update our position based on current presets
1798     fgInitPosition();
1799
1800     // We don't know how to resize the window, so keep the last values
1801     //  for xsize and ysize, and don't use the one set initially
1802     fgSetInt("/sim/startup/xsize", xsize);
1803     fgSetInt("/sim/startup/ysize", ysize);
1804
1805     copyProperties(cameraNode, cameraGroupNode->getChild("camera"));
1806     copyProperties(guiNode, cameraGroupNode->getChild("gui"));
1807
1808     delete guiNode;
1809     delete cameraNode;
1810
1811     SGTime *t = globals->get_time_params();
1812     delete t;
1813     t = fgInitTime();
1814     globals->set_time_params(t);
1815
1816     fgReInitSubsystems();
1817
1818     globals->get_tile_mgr()->update(fgGetDouble("/environment/visibility-m"));
1819     globals->get_renderer()->resize(xsize, ysize);
1820     fgSetBool("/sim/signals/reinit", false);
1821
1822     if (!freeze)
1823         master_freeze->setBoolValue(false);
1824 }
1825