]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
43e620e2d6440d646ebffb4f8fce388f821ff272
[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     int orig_warp = globals->get_warp();
1280     SGTime *t = globals->get_time_params();
1281     time_t cur_time = t->get_cur_time();
1282     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1283     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1284     time_t aircraftLocalTime = 
1285         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1286
1287     // Okay, we now have several possible scenarios
1288     int offset = fgGetInt("/sim/startup/time-offset");
1289     int warp = 0;
1290     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1291     if ( offset_type == "noon" ) {
1292         warp = fgTimeSecondsUntilNoon( cur_time,
1293                                        longitude->getDoubleValue()
1294                                          * SGD_DEGREES_TO_RADIANS,
1295                                        latitude->getDoubleValue()
1296                                          * SGD_DEGREES_TO_RADIANS ); 
1297     } else if ( offset_type == "midnight" ) {
1298         warp = fgTimeSecondsUntilMidnight( cur_time,
1299                                            longitude->getDoubleValue()
1300                                              * SGD_DEGREES_TO_RADIANS,
1301                                            latitude->getDoubleValue()
1302                                              * SGD_DEGREES_TO_RADIANS ); 
1303     } else if ( offset_type == "dawn" ) {
1304         warp = fgTimeSecondsUntilDawn( cur_time,
1305                                        longitude->getDoubleValue()
1306                                          * SGD_DEGREES_TO_RADIANS,
1307                                        latitude->getDoubleValue()
1308                                          * SGD_DEGREES_TO_RADIANS ); 
1309      } else if ( offset_type == "dusk" ) {
1310         warp = fgTimeSecondsUntilDusk( cur_time,
1311                                        longitude->getDoubleValue()
1312                                          * SGD_DEGREES_TO_RADIANS,
1313                                        latitude->getDoubleValue()
1314                                          * SGD_DEGREES_TO_RADIANS ); 
1315     } else if ( offset_type == "system-offset" ) {
1316         warp = offset;
1317     } else if ( offset_type == "gmt-offset" ) {
1318         warp = offset - (currGMT - systemLocalTime);
1319     } else if ( offset_type == "latitude-offset" ) {
1320         warp = offset - (aircraftLocalTime - systemLocalTime);
1321     } else if ( offset_type == "system" ) {
1322         warp = offset - cur_time;
1323     } else if ( offset_type == "gmt" ) {
1324         warp = offset - currGMT;
1325     } else if ( offset_type == "latitude" ) {
1326         warp = offset - (aircraftLocalTime - systemLocalTime) - cur_time; 
1327     } else {
1328         SG_LOG( SG_GENERAL, SG_ALERT,
1329                 "FG_TIME::Unsupported offset type " << offset_type );
1330         exit( -1 );
1331     }
1332     globals->set_warp( orig_warp + warp );
1333     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1334                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1335                cur_time_override->getLongValue(),
1336                globals->get_warp() );
1337
1338     SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
1339             << globals->get_warp() );
1340
1341     fgUpdateSkyAndLightingParams();
1342 }
1343
1344 // This is the top level init routine which calls all the other
1345 // initialization routines.  If you are adding a subsystem to flight
1346 // gear, its initialization call should located in this routine.
1347 // Returns non-zero if a problem encountered.
1348 bool fgInitSubsystems() {
1349     // static const SGPropertyNode *longitude
1350     //     = fgGetNode("/sim/presets/longitude-deg");
1351     // static const SGPropertyNode *latitude
1352     //     = fgGetNode("/sim/presets/latitude-deg");
1353     // static const SGPropertyNode *altitude
1354     //     = fgGetNode("/sim/presets/altitude-ft");
1355
1356     fgLIGHT *l = &cur_light_params;
1357
1358     SG_LOG( SG_GENERAL, SG_INFO, "Initialize Subsystems");
1359     SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
1360
1361
1362     ////////////////////////////////////////////////////////////////////
1363     // Initialize the material property subsystem.
1364     ////////////////////////////////////////////////////////////////////
1365
1366     SGPath mpath( globals->get_fg_root() );
1367     mpath.append( "materials.xml" );
1368     if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str()) ) {
1369         SG_LOG( SG_GENERAL, SG_ALERT, "Error loading material lib!" );
1370         exit(-1);
1371     }
1372
1373     ////////////////////////////////////////////////////////////////////
1374     // Initialize the event manager subsystem.
1375     ////////////////////////////////////////////////////////////////////
1376
1377     global_events.init();
1378
1379     // Output event stats every 60 seconds
1380     global_events.Register( "FGEventMgr::print_stats()",
1381                             &global_events, &FGEventMgr::print_stats,
1382                             60000 );
1383
1384
1385     ////////////////////////////////////////////////////////////////////
1386     // Initialize the scenery management subsystem.
1387     ////////////////////////////////////////////////////////////////////
1388
1389     if ( globals->get_tile_mgr()->init() ) {
1390         // Load the local scenery data
1391         double visibility_meters = fgGetDouble("/environment/visibility-m");
1392                 
1393         globals->get_tile_mgr()->update( visibility_meters );
1394     } else {
1395         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Tile Manager initialization!" );
1396         exit(-1);
1397     }
1398
1399     // cause refresh of viewer scenery timestamps every 15 seconds...
1400     global_events.Register( "FGTileMgr::refresh_view_timestamps()",
1401                             globals->get_tile_mgr(),
1402                             &FGTileMgr::refresh_view_timestamps,
1403                             15000 );
1404
1405     SG_LOG( SG_GENERAL, SG_DEBUG,
1406             "Current terrain elevation after tile mgr init " <<
1407             globals->get_scenery()->get_cur_elev() );
1408
1409
1410     ////////////////////////////////////////////////////////////////////
1411     // Initialize the flight model subsystem.
1412     ////////////////////////////////////////////////////////////////////
1413
1414     fgInitFDM();
1415         
1416     // allocates structures so must happen before any of the flight
1417     // model or control parameters are set
1418     fgAircraftInit();   // In the future this might not be the case.
1419
1420
1421     ////////////////////////////////////////////////////////////////////
1422     // Initialize the view manager subsystem.
1423     ////////////////////////////////////////////////////////////////////
1424
1425     fgInitView();
1426
1427
1428     ////////////////////////////////////////////////////////////////////
1429     // Initialize the lighting subsystem.
1430     ////////////////////////////////////////////////////////////////////
1431
1432     // fgUpdateSunPos() needs a few position and view parameters set
1433     // so it can calculate local relative sun angle and a few other
1434     // things for correctly orienting the sky.
1435     fgUpdateSunPos();
1436     fgUpdateMoonPos();
1437     global_events.Register( "fgUpdateSunPos()", &fgUpdateSunPos,
1438                             60000);
1439     global_events.Register( "fgUpdateMoonPos()", &fgUpdateMoonPos,
1440                             60000);
1441
1442     // Initialize Lighting interpolation tables
1443     l->Init();
1444
1445     // force one lighting update to make it right to start with...
1446     l->Update();
1447     // update the lighting parameters (based on sun angle)
1448     global_events.Register( "fgLight::Update()",
1449                             &cur_light_params, &fgLIGHT::Update,
1450                             30000 );
1451
1452
1453     ////////////////////////////////////////////////////////////////////
1454     // Create and register the logger.
1455     ////////////////////////////////////////////////////////////////////
1456     
1457     globals->add_subsystem("logger", new FGLogger);
1458
1459
1460 #if defined(HAVE_PLIB_PSL)
1461     ////////////////////////////////////////////////////////////////////
1462     // Create and register the script manager.
1463     ////////////////////////////////////////////////////////////////////
1464
1465     globals->add_subsystem("scripting", new FGScriptMgr);
1466 #endif // HAVE_PLIB_PSL
1467
1468
1469     ////////////////////////////////////////////////////////////////////
1470     // Create and register the XML GUI.
1471     ////////////////////////////////////////////////////////////////////
1472
1473     globals->add_subsystem("gui", new NewGUI, FGSubsystemMgr::INIT);
1474
1475
1476     ////////////////////////////////////////////////////////////////////
1477     // Initialize the local time subsystem.
1478     ////////////////////////////////////////////////////////////////////
1479
1480     // update the current timezone each 30 minutes
1481     global_events.Register( "fgUpdateLocalTime()", &fgUpdateLocalTime,
1482                             30*60*1000 );
1483
1484
1485     ////////////////////////////////////////////////////////////////////
1486     // Initialize the weather subsystem.
1487     ////////////////////////////////////////////////////////////////////
1488
1489     // Initialize the weather modeling subsystem
1490 #ifdef FG_WEATHERCM
1491     // Initialize the WeatherDatabase
1492     SG_LOG(SG_GENERAL, SG_INFO, "Creating LocalWeatherDatabase");
1493     sgVec3 position;
1494     sgSetVec3( position, current_aircraft.fdm_state->get_Latitude(),
1495                current_aircraft.fdm_state->get_Longitude(),
1496                current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER );
1497     double init_vis = fgGetDouble("/environment/visibility-m");
1498
1499     FGLocalWeatherDatabase::DatabaseWorkingType working_type;
1500
1501     if (!strcmp(fgGetString("/environment/weather/working-type"), "internet"))
1502     {
1503       working_type = FGLocalWeatherDatabase::use_internet;
1504     } else {
1505       working_type = FGLocalWeatherDatabase::default_mode;
1506     }
1507     
1508     if ( init_vis > 0 ) {
1509       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1510         new FGLocalWeatherDatabase( position,
1511                                     globals->get_fg_root(),
1512                                     working_type,
1513                                     init_vis );
1514     } else {
1515       FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
1516         new FGLocalWeatherDatabase( position,
1517                                     globals->get_fg_root(),
1518                                     working_type );
1519     }
1520
1521     // cout << theFGLocalWeatherDatabase << endl;
1522     // cout << "visibility = " 
1523     //      << theFGLocalWeatherDatabase->getWeatherVisibility() << endl;
1524
1525     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
1526
1527     // register the periodic update of the weather
1528     global_events.Register( "weather update", &fgUpdateWeatherDatabase,
1529                             30000);
1530 #else
1531     globals->add_subsystem("environment", new FGEnvironmentMgr);
1532 #endif
1533
1534 #ifdef FG_USE_CLOUDS_3D
1535     ////////////////////////////////////////////////////////////////////
1536     // Initialize the 3D cloud subsystem.
1537     ////////////////////////////////////////////////////////////////////
1538     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1539         static const SGPropertyNode *longitude
1540            = fgGetNode("/sim/presets/longitude-deg");
1541         static const SGPropertyNode *latitude
1542            = fgGetNode("/sim/presets/latitude-deg");
1543         static const SGPropertyNode *altitude
1544            = fgGetNode("/sim/presets/altitude-ft");
1545
1546         SGPath cloud_path(globals->get_fg_root());
1547 #if 0
1548         cloud_path.append("Textures/Sky/scattered.rgba");
1549         SG_LOG(SG_GENERAL, SG_INFO, "Loading CLOUDS3d from: " << cloud_path.c_str());
1550
1551         SGTexture tx;
1552         tx.read_rgba_texture(cloud_path.c_str());
1553         if ( !sgCloud3d->Load( tx.texture(), tx.width(),
1554 #else
1555         cloud_path.append("large.sky");
1556         if ( !sgCloud3d->Load( cloud_path.str(),
1557 #endif
1558                                latitude->getDoubleValue(),
1559                                longitude->getDoubleValue()) )
1560         {
1561             fgSetBool("/sim/rendering/clouds3d", false);
1562             SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d FAILED: ");
1563         }
1564         SG_LOG(SG_GENERAL, SG_INFO, "CLOUDS3d Loaded: ");
1565     }
1566 #endif
1567
1568     ////////////////////////////////////////////////////////////////////
1569     // Initialise ATC display system
1570     ////////////////////////////////////////////////////////////////////
1571
1572     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Display");
1573     globals->set_ATC_display(new FGATCDisplay);
1574     globals->get_ATC_display()->init(); 
1575
1576     ////////////////////////////////////////////////////////////////////
1577     // Initialise the ATC Manager 
1578     ////////////////////////////////////////////////////////////////////
1579
1580     SG_LOG(SG_GENERAL, SG_INFO, "  ATC Manager");
1581     globals->set_ATC_mgr(new FGATCMgr);
1582     globals->get_ATC_mgr()->init(); 
1583     
1584     ////////////////////////////////////////////////////////////////////
1585     // Initialise the AI Manager 
1586     ////////////////////////////////////////////////////////////////////
1587
1588     SG_LOG(SG_GENERAL, SG_INFO, "  AI Manager");
1589     globals->set_AI_mgr(new FGAIMgr);
1590     globals->get_AI_mgr()->init();
1591
1592
1593 #ifdef ENABLE_AUDIO_SUPPORT
1594     ////////////////////////////////////////////////////////////////////
1595     // Initialize the sound subsystem.
1596     ////////////////////////////////////////////////////////////////////
1597
1598     globals->set_soundmgr(new SGSoundMgr);
1599     globals->get_soundmgr()->init();
1600     globals->get_soundmgr()->bind();
1601
1602
1603     ////////////////////////////////////////////////////////////////////
1604     // Initialize the sound-effects subsystem.
1605     ////////////////////////////////////////////////////////////////////
1606
1607     globals->add_subsystem("fx", new FGFX);
1608     
1609 #endif
1610
1611     globals->add_subsystem("instrumentation", new FGInstrumentMgr);
1612     globals->add_subsystem("systems", new FGSystemMgr);
1613
1614     ////////////////////////////////////////////////////////////////////
1615     // Initialize the radio stack subsystem.
1616     ////////////////////////////////////////////////////////////////////
1617
1618     current_radiostack = new FGRadioStack;
1619     current_radiostack->init();
1620     current_radiostack->bind();
1621
1622
1623     ////////////////////////////////////////////////////////////////////
1624     // Initialize the cockpit subsystem
1625     ////////////////////////////////////////////////////////////////////
1626
1627     if( fgCockpitInit( &current_aircraft )) {
1628         // Cockpit initialized ok.
1629     } else {
1630         SG_LOG( SG_GENERAL, SG_ALERT, "Error in Cockpit initialization!" );
1631         exit(-1);
1632     }
1633
1634
1635     ////////////////////////////////////////////////////////////////////
1636     // Initialize the autopilot subsystem.
1637     ////////////////////////////////////////////////////////////////////
1638
1639     globals->set_autopilot(new FGAutopilot);
1640     globals->get_autopilot()->init();
1641     globals->get_autopilot()->bind();
1642
1643                                 // FIXME: these should go in the
1644                                 // GUI initialization code, not here.
1645     fgAPAdjustInit();
1646     NewTgtAirportInit();
1647     NewHeadingInit();
1648     NewAltitudeInit();
1649
1650     ////////////////////////////////////////////////////////////////////
1651     // Initialize I/O subsystem.
1652     ////////////////////////////////////////////////////////////////////
1653
1654     globals->get_io()->init();
1655     globals->get_io()->bind();
1656
1657
1658     ////////////////////////////////////////////////////////////////////
1659     // Add a new 2D panel.
1660     ////////////////////////////////////////////////////////////////////
1661
1662     string panel_path = fgGetString("/sim/panel/path",
1663                                     "Panels/Default/default.xml");
1664
1665     globals->set_current_panel( fgReadPanel(panel_path) );
1666     if (globals->get_current_panel() == 0) {
1667         SG_LOG( SG_INPUT, SG_ALERT, 
1668                 "Error reading new panel from " << panel_path );
1669     } else {
1670         SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path );
1671         globals->get_current_panel()->init();
1672         globals->get_current_panel()->bind();
1673     }
1674
1675     
1676     ////////////////////////////////////////////////////////////////////
1677     // Initialize the default (kludged) properties.
1678     ////////////////////////////////////////////////////////////////////
1679
1680     fgInitProps();
1681
1682
1683     ////////////////////////////////////////////////////////////////////
1684     // Initialize the controls subsystem.
1685     ////////////////////////////////////////////////////////////////////
1686
1687     globals->get_controls()->init();
1688     globals->get_controls()->bind();
1689
1690
1691     ////////////////////////////////////////////////////////////////////
1692     // Initialize the input subsystem.
1693     ////////////////////////////////////////////////////////////////////
1694
1695     globals->add_subsystem("input", new FGInput);
1696
1697
1698     ////////////////////////////////////////////////////////////////////
1699     // Initialize the replay subsystem
1700     ////////////////////////////////////////////////////////////////////
1701     globals->add_subsystem("replay", new FGReplay);
1702
1703     ////////////////////////////////////////////////////////////////////
1704     // Bind and initialize subsystems.
1705     ////////////////////////////////////////////////////////////////////
1706
1707     globals->get_subsystem_mgr()->bind();
1708     globals->get_subsystem_mgr()->init();
1709
1710
1711 #ifdef FG_MPLAYER_AS
1712     ////////////////////////////////////////////////////////////////////
1713     // Initialize multiplayer subsystem
1714     ////////////////////////////////////////////////////////////////////
1715
1716     globals->set_multiplayer_tx_mgr(new FGMultiplayTxMgr);
1717     globals->get_multiplayer_tx_mgr()->init();
1718
1719     globals->set_multiplayer_rx_mgr(new FGMultiplayRxMgr);
1720     globals->get_multiplayer_rx_mgr()->init();
1721 #endif
1722
1723     ////////////////////////////////////////////////////////////////////////
1724     // End of subsystem initialization.
1725     ////////////////////////////////////////////////////////////////////
1726
1727     SG_LOG( SG_GENERAL, SG_INFO, endl);
1728
1729                                 // Save the initial state for future
1730                                 // reference.
1731     globals->saveInitialState();
1732
1733     return true;
1734 }
1735
1736
1737 void fgReInitSubsystems()
1738 {
1739     // static const SGPropertyNode *longitude
1740     //     = fgGetNode("/sim/presets/longitude-deg");
1741     // static const SGPropertyNode *latitude
1742     //     = fgGetNode("/sim/presets/latitude-deg");
1743     static const SGPropertyNode *altitude
1744         = fgGetNode("/sim/presets/altitude-ft");
1745     static const SGPropertyNode *master_freeze
1746         = fgGetNode("/sim/freeze/master");
1747
1748     SG_LOG( SG_GENERAL, SG_INFO,
1749             "fgReInitSubsystems(): /position/altitude = "
1750             << altitude->getDoubleValue() );
1751
1752     bool freeze = master_freeze->getBoolValue();
1753     if ( !freeze ) {
1754         fgSetBool("/sim/freeze/master", true);
1755     }
1756
1757     // Initialize the FDM
1758     fgInitFDM();
1759     
1760     // allocates structures so must happen before any of the flight
1761     // model or control parameters are set
1762     fgAircraftInit();   // In the future this might not be the case.
1763
1764     // reload offsets from config defaults
1765     globals->get_viewmgr()->reinit();
1766
1767     fgInitView();
1768
1769     globals->get_controls()->reset_all();
1770     globals->get_autopilot()->reset();
1771
1772     fgUpdateSunPos();
1773     fgUpdateMoonPos();
1774     cur_light_params.Update();
1775     fgUpdateLocalTime();
1776
1777     if ( !freeze ) {
1778         fgSetBool("/sim/freeze/master", false);
1779     }
1780 }
1781