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