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