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