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