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