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