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