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