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