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