]> git.mxchange.org Git - flightgear.git/blob - src/FDM/flight.cxx
Remove confusing reference to SDL/GLUT
[flightgear.git] / src / FDM / flight.cxx
1 // flight.cxx -- a general interface to the various flight models
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include "flight.hxx"
28
29 #include <simgear/constants.h>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/timing/timestamp.hxx>
32 #include <simgear/scene/material/mat.hxx>
33 #include <simgear/io/iochannel.hxx>
34
35 #include <Scenery/scenery.hxx>
36 #include <Main/globals.hxx>
37 #include <Main/fg_props.hxx>
38 #include <FDM/groundcache.hxx>
39
40
41 static inline void assign(double* ptr, const SGVec3d& vec)
42 {
43   ptr[0] = vec[0];
44   ptr[1] = vec[1];
45   ptr[2] = vec[2];
46 }
47
48 // Constructor
49 FGInterface::FGInterface()
50 {
51     _setup();
52 }
53
54 FGInterface::FGInterface( double dt )
55 {
56     _setup();
57 }
58
59 // Destructor
60 FGInterface::~FGInterface() {
61     // unbind();                   // FIXME: should be called explicitly
62 }
63
64 int
65 FGInterface::_calc_multiloop (double dt)
66 {
67   // Since some time the simulation time increments we get here are
68   // already a multiple of the basic update frequency.
69   // So, there is no need to do our own multiloop rounding with all bad
70   // roundoff problems when we already have nearly accurate values.
71   // Only the speedup thing must be still handled here
72   int hz = fgGetInt("/sim/model-hz");
73   double speedup = fgGetDouble("/sim/speed-up");
74   double loops = dt * hz * speedup + delta_loops;
75   int iloops = SGMiscd::roundToInt(loops);
76   delta_loops = loops-iloops; // delta_loops required for speed-ups < 1 (to do one iteration every n-th step)
77   return iloops;
78 }
79
80
81 /**
82  * Set default values for the state of the FDM.
83  *
84  * This method is invoked by the constructors.
85  */
86 void
87 FGInterface::_setup ()
88 {
89     inited = false;
90     bound = false;
91
92     _state.d_cg_rp_body_v = SGVec3d::zeros();
93     _state.v_dot_local_v = SGVec3d::zeros();
94     _state.v_dot_body_v = SGVec3d::zeros();
95     _state.a_cg_body_v = SGVec3d::zeros();
96     _state.a_pilot_body_v = SGVec3d::zeros();
97     _state.n_cg_body_v = SGVec3d::zeros();
98     _state.v_local_v = SGVec3d::zeros();
99     _state.v_local_rel_ground_v = SGVec3d::zeros();
100     _state.v_local_airmass_v = SGVec3d::zeros();
101     _state.v_wind_body_v = SGVec3d::zeros();
102     _state.omega_body_v = SGVec3d::zeros();
103     _state.euler_rates_v = SGVec3d::zeros();
104     _state.geocentric_rates_v = SGVec3d::zeros();
105     _state.geodetic_position_v = SGGeod::fromRadM(0, 0, 0);
106     _state.cartesian_position_v = SGVec3d::fromGeod(_state.geodetic_position_v);
107     _state.geocentric_position_v = SGGeoc::fromCart(_state.cartesian_position_v);
108     _state.euler_angles_v = SGVec3d::zeros();
109     
110     _state.nlf=0;
111     _state.v_rel_wind=_state.v_true_kts=0;
112     _state.v_ground_speed=_state.v_equiv_kts=0;
113     _state.v_calibrated_kts=0;
114     _state.alpha=_state.beta=0;
115     _state.gamma_vert_rad=0;
116     _state.density=_state.mach_number=0;
117     _state.static_pressure=_state.total_pressure=0;
118     _state.dynamic_pressure=0;
119     _state.static_temperature=_state.total_temperature=0;
120     _state.sea_level_radius=_state.earth_position_angle=0;
121     _state.runway_altitude=0;
122     _state.climb_rate=0;
123     _state.altitude_agl=0;
124     _state.track=0;
125     
126     delta_loops = 0.0;
127 }
128
129 void
130 FGInterface::init () {}
131
132 /**
133  * Initialize the state of the FDM.
134  *
135  * Subclasses of FGInterface may do their own, additional initialization,
136  * but there is some that is common to all.  Normally, they should call
137  * this before they begin their own init to make sure the basic structures
138  * are set up properly.
139  */
140 void
141 FGInterface::common_init ()
142 {
143     SG_LOG( SG_FLIGHT, SG_INFO, "Start common FDM init" );
144
145     set_inited( true );
146
147     ground_cache.set_cache_time_offset(globals->get_sim_time_sec());
148
149     // Set initial position
150     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing position..." );
151     double lon = fgGetDouble("/sim/presets/longitude-deg")
152       * SGD_DEGREES_TO_RADIANS;
153     double lat = fgGetDouble("/sim/presets/latitude-deg")
154       * SGD_DEGREES_TO_RADIANS;
155     double alt_ft = fgGetDouble("/sim/presets/altitude-ft");
156     double alt_m = alt_ft * SG_FEET_TO_METER;
157     set_Longitude( lon );
158     set_Latitude( lat );
159     SG_LOG( SG_FLIGHT, SG_INFO, "Checking for lon = "
160             << lon*SGD_RADIANS_TO_DEGREES << "deg, lat = "
161             << lat*SGD_RADIANS_TO_DEGREES << "deg, alt = "
162             << alt_ft << "ft");
163
164     double ground_elev_m = get_groundlevel_m(lat, lon, alt_m);
165     double ground_elev_ft = ground_elev_m * SG_METER_TO_FEET;
166     _set_Runway_altitude ( ground_elev_ft );
167
168     // Set aircraft altitude
169     if ( fgGetBool("/sim/presets/onground") || alt_ft < ground_elev_ft ) {
170         fgSetDouble("/position/altitude-ft", ground_elev_ft + 0.1);
171         set_Altitude( ground_elev_ft + 0.1);
172     } else {
173         set_Altitude( alt_ft );
174     }
175
176     // Set ground elevation
177     SG_LOG( SG_FLIGHT, SG_INFO,
178             "...initializing ground elevation to " << ground_elev_ft
179             << "ft..." );
180
181     // Set sea-level radius
182     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing sea-level radius..." );
183     SG_LOG( SG_FLIGHT, SG_INFO, " lat = "
184             << fgGetDouble("/sim/presets/latitude-deg")
185             << " alt = " << get_Altitude() );
186     double slr = SGGeodesy::SGGeodToSeaLevelRadius(_state.geodetic_position_v);
187     _set_Sea_level_radius( slr * SG_METER_TO_FEET );
188
189     // Set initial Euler angles
190     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing Euler angles..." );
191     set_Euler_Angles( fgGetDouble("/sim/presets/roll-deg")
192                         * SGD_DEGREES_TO_RADIANS,
193                       fgGetDouble("/sim/presets/pitch-deg")
194                         * SGD_DEGREES_TO_RADIANS,
195                       fgGetDouble("/sim/presets/heading-deg")
196                         * SGD_DEGREES_TO_RADIANS );
197
198     // Set initial velocities
199     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing velocities..." );
200     if ( !fgHasNode("/sim/presets/speed-set") ) {
201         set_V_calibrated_kts(0.0);
202     } else {
203         const std::string speedset = fgGetString("/sim/presets/speed-set");
204         if ( speedset == "knots" || speedset == "KNOTS" ) {
205             set_V_calibrated_kts( fgGetDouble("/sim/presets/airspeed-kt") );
206         } else if ( speedset == "mach" || speedset == "MACH" ) {
207             set_Mach_number( fgGetDouble("/sim/presets/mach") );
208         } else if ( speedset == "UVW" || speedset == "uvw" ) {
209             set_Velocities_Wind_Body(
210                                      fgGetDouble("/sim/presets/uBody-fps"),
211                                      fgGetDouble("/sim/presets/vBody-fps"),
212                                      fgGetDouble("/sim/presets/wBody-fps") );
213         } else if ( speedset == "NED" || speedset == "ned" ) {
214             set_Velocities_Local(
215                                  fgGetDouble("/sim/presets/speed-north-fps"),
216                                  fgGetDouble("/sim/presets/speed-east-fps"),
217                                  fgGetDouble("/sim/presets/speed-down-fps") );
218         } else {
219             SG_LOG( SG_FLIGHT, SG_ALERT,
220                     "Unrecognized value for /sim/presets/speed-set: "
221                     << speedset);
222             set_V_calibrated_kts( 0.0 );
223         }
224     }
225
226     if ( fgHasNode("/sim/presets/glideslope-deg") )
227         set_Gamma_vert_rad( fgGetDouble("/sim/presets/glideslope-deg")
228                               * SGD_DEGREES_TO_RADIANS );
229     else if ( fgHasNode("/sim/presets/speed-set") &&
230               fgHasNode( "/sim/presets/vertical-speed-fps") )
231     {
232         set_Climb_Rate( fgGetDouble("/sim/presets/vertical-speed-fps") );
233     }
234
235     SG_LOG( SG_FLIGHT, SG_INFO, "End common FDM init" );
236 }
237
238
239 /**
240  * Bind getters and setters to properties.
241  *
242  * The bind() method will be invoked after init().  Note that unlike
243  * the usual implementations of FGSubsystem::bind(), this method does
244  * not automatically pick up existing values for the properties at
245  * bind time; instead, all values are set explicitly in the init()
246  * method.
247  */
248 void
249 FGInterface::bind ()
250 {
251   bound = true;
252
253   _tiedProperties.setRoot(globals->get_props());
254   // Aircraft position
255   _tiedProperties.Tie("/position/latitude-deg", this,
256                       &FGInterface::get_Latitude_deg,
257                       &FGInterface::set_Latitude_deg,
258                       false);
259   fgSetArchivable("/position/latitude-deg");
260   _tiedProperties.Tie("/position/longitude-deg", this,
261                       &FGInterface::get_Longitude_deg,
262                       &FGInterface::set_Longitude_deg,
263                       false);
264   fgSetArchivable("/position/longitude-deg");
265   _tiedProperties.Tie("/position/altitude-ft", this,
266                       &FGInterface::get_Altitude,
267                       &FGInterface::set_Altitude,
268                       false);
269   fgSetArchivable("/position/altitude-ft");
270   _tiedProperties.Tie("/position/altitude-agl-ft", this,
271                       &FGInterface::get_Altitude_AGL, &FGInterface::set_AltitudeAGL, false);
272   fgSetArchivable("/position/ground-elev-ft");
273   _tiedProperties.Tie("/position/ground-elev-ft", this,
274                       &FGInterface::get_Runway_altitude); // read-only
275   fgSetArchivable("/position/ground-elev-m");
276   _tiedProperties.Tie("/position/ground-elev-m", this,
277                       &FGInterface::get_Runway_altitude_m); // read-only
278   _tiedProperties.Tie("/environment/ground-elevation-m", this,
279                       &FGInterface::get_Runway_altitude_m); // read-only
280   fgSetArchivable("/position/sea-level-radius-ft");
281   _tiedProperties.Tie("/position/sea-level-radius-ft", this,
282                       &FGInterface::get_Sea_level_radius,
283                       &FGInterface::_set_Sea_level_radius, false);
284
285   // Orientation
286   _tiedProperties.Tie("/orientation/roll-deg", this,
287                       &FGInterface::get_Phi_deg,
288                       &FGInterface::set_Phi_deg, false);
289   fgSetArchivable("/orientation/roll-deg");
290   _tiedProperties.Tie("/orientation/pitch-deg", this,
291                       &FGInterface::get_Theta_deg,
292                       &FGInterface::set_Theta_deg, false);
293   fgSetArchivable("/orientation/pitch-deg");
294   _tiedProperties.Tie("/orientation/heading-deg", this,
295                       &FGInterface::get_Psi_deg,
296                       &FGInterface::set_Psi_deg, false);
297   fgSetArchivable("/orientation/heading-deg");
298   _tiedProperties.Tie("/orientation/track-deg", this,
299                       &FGInterface::get_Track); // read-only
300
301   // Body-axis "euler rates" (rotation speed, but in a funny
302   // representation).
303   _tiedProperties.Tie("/orientation/roll-rate-degps", this,
304                       &FGInterface::get_Phi_dot_degps,
305                       &FGInterface::set_Phi_dot_degps, false);
306   _tiedProperties.Tie("/orientation/pitch-rate-degps", this,
307                       &FGInterface::get_Theta_dot_degps,
308                       &FGInterface::set_Theta_dot_degps, false);
309   _tiedProperties.Tie("/orientation/yaw-rate-degps", this,
310                       &FGInterface::get_Psi_dot_degps,
311                       &FGInterface::set_Psi_dot_degps, false);
312
313   _tiedProperties.Tie("/orientation/p-body", this, &FGInterface::get_P_body); // read-only
314   _tiedProperties.Tie("/orientation/q-body", this, &FGInterface::get_Q_body); // read-only
315   _tiedProperties.Tie("/orientation/r-body", this, &FGInterface::get_R_body); // read-only
316
317   // Ground speed knots
318   _tiedProperties.Tie("/velocities/groundspeed-kt", this,
319                       &FGInterface::get_V_ground_speed_kt,
320                       &FGInterface::set_V_ground_speed_kt); // read-only
321
322   // Calibrated airspeed
323   _tiedProperties.Tie("/velocities/airspeed-kt", this,
324                       &FGInterface::get_V_calibrated_kts,
325                       &FGInterface::set_V_calibrated_kts,
326                       false);
327
328   _tiedProperties.Tie("/velocities/equivalent-kt", this,
329                       &FGInterface::get_V_equiv_kts); // read-only
330
331   // Mach number
332   _tiedProperties.Tie("/velocities/mach", this,
333                       &FGInterface::get_Mach_number,
334                       &FGInterface::set_Mach_number,
335                       false);
336
337   // Local velocities
338 //   _tiedProperties.Tie("/velocities/speed-north-fps", this,
339 //                       &FGInterface::get_V_north,
340 //                       &FGInterface::set_V_north);
341 //   fgSetArchivable("/velocities/speed-north-fps");
342 //   _tiedProperties.Tie("/velocities/speed-east-fps", this,
343 //                       &FGInterface::get_V_east,
344 //                       &FGInterface::set_V_east);
345 //   fgSetArchivable("/velocities/speed-east-fps");
346 //   _tiedProperties.Tie("/velocities/speed-down-fps", this,
347 //                       &FGInterface::get_V_down,
348 //                       &FGInterface::set_V_down);
349 //   fgSetArchivable("/velocities/speed-down-fps");
350
351   // FIXME: Temporarily read-only, until the
352   // incompatibilities between JSBSim and
353   // LaRCSim are fixed (LaRCSim adds the
354   // earth's rotation to the east velocity).
355   _tiedProperties.Tie("/velocities/speed-north-fps", this,
356                       &FGInterface::get_V_north, &FGInterface::set_V_north, false);
357   _tiedProperties.Tie("/velocities/speed-east-fps", this,
358                       &FGInterface::get_V_east, &FGInterface::set_V_east, false);
359   _tiedProperties.Tie("/velocities/speed-down-fps", this,
360                       &FGInterface::get_V_down, &FGInterface::set_V_down, false);
361
362   _tiedProperties.Tie("/velocities/north-relground-fps", this,
363                       &FGInterface::get_V_north_rel_ground); // read-only
364   _tiedProperties.Tie("/velocities/east-relground-fps", this,
365                       &FGInterface::get_V_east_rel_ground); // read-only
366   _tiedProperties.Tie("/velocities/down-relground-fps", this,
367                       &FGInterface::get_V_down_rel_ground); // read-only
368
369   // Relative wind
370   // FIXME: temporarily archivable, until the NED problem is fixed.
371   _tiedProperties.Tie("/velocities/uBody-fps", this,
372                       &FGInterface::get_uBody,
373                       &FGInterface::set_uBody,
374                       false);
375   fgSetArchivable("/velocities/uBody-fps");
376   _tiedProperties.Tie("/velocities/vBody-fps", this,
377                       &FGInterface::get_vBody,
378                       &FGInterface::set_vBody,
379                       false);
380   fgSetArchivable("/velocities/vBody-fps");
381   _tiedProperties.Tie("/velocities/wBody-fps", this,
382                       &FGInterface::get_wBody,
383                       &FGInterface::set_wBody,
384                       false);
385   fgSetArchivable("/velocities/wBody-fps");
386
387   // Climb and slip (read-only)
388   _tiedProperties.Tie("/velocities/vertical-speed-fps", this,
389                       &FGInterface::get_Climb_Rate,
390                       &FGInterface::set_Climb_Rate, false );
391   _tiedProperties.Tie("/velocities/glideslope", this,
392                       &FGInterface::get_Gamma_vert_rad,
393                       &FGInterface::set_Gamma_vert_rad, false );
394   _tiedProperties.Tie("/orientation/side-slip-rad", this,
395                       &FGInterface::get_Beta, &FGInterface::_set_Beta, false);
396   _tiedProperties.Tie("/orientation/side-slip-deg", this,
397                       &FGInterface::get_Beta_deg); // read-only
398   _tiedProperties.Tie("/orientation/alpha-deg", this,
399                       &FGInterface::get_Alpha_deg, &FGInterface::set_Alpha_deg, false);
400   _tiedProperties.Tie("/accelerations/nlf", this,
401                       &FGInterface::get_Nlf); // read-only
402
403   // NED accelerations
404   _tiedProperties.Tie("/accelerations/ned/north-accel-fps_sec",
405                       this, &FGInterface::get_V_dot_north); // read-only
406   _tiedProperties.Tie("/accelerations/ned/east-accel-fps_sec",
407                       this, &FGInterface::get_V_dot_east); // read-only
408   _tiedProperties.Tie("/accelerations/ned/down-accel-fps_sec",
409                       this, &FGInterface::get_V_dot_down); // read-only
410
411   // Pilot accelerations
412   _tiedProperties.Tie("/accelerations/pilot/x-accel-fps_sec",
413                       this, &FGInterface::get_A_X_pilot, &FGInterface::set_A_X_pilot, false);
414   _tiedProperties.Tie("/accelerations/pilot/y-accel-fps_sec",
415                       this, &FGInterface::get_A_Y_pilot, &FGInterface::set_A_Y_pilot, false);
416   _tiedProperties.Tie("/accelerations/pilot/z-accel-fps_sec",
417                       this, &FGInterface::get_A_Z_pilot, &FGInterface::set_A_Z_pilot, false);
418
419   _tiedProperties.Tie("/accelerations/n-z-cg-fps_sec",
420                       this, &FGInterface::get_N_Z_cg); // read-only
421 }
422
423
424 /**
425  * Unbind any properties bound to this FDM.
426  *
427  * This method allows the FDM to release properties so that a new
428  * FDM can bind them instead.
429  */
430 void
431 FGInterface::unbind ()
432 {
433   _tiedProperties.Untie();
434   bound = false;
435 }
436
437 /**
438  * Update the state of the FDM (i.e. run the equations of motion).
439  */
440 void
441 FGInterface::update (double dt)
442 {
443     SG_LOG(SG_FLIGHT, SG_ALERT, "dummy update() ... SHOULDN'T BE CALLED!");
444 }
445
446 bool FGInterface::readState(SGIOChannel* io)
447 {
448     FlightState buf;
449     int length = sizeof(FlightState);
450     
451     if ( io->get_type() == sgFileType ) {
452             if ( io->read( (char *)(& buf), length ) == length ) {
453             SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
454             } else {
455             return false;
456         }
457         } else {
458             while ( io->read( (char *)(& buf), length ) == length ) {
459             SG_LOG( SG_IO, SG_DEBUG, "Success reading data." );
460             }
461         }
462     
463     _state = buf; // copy the read state over
464     return true;
465 }
466
467 bool FGInterface::writeState(SGIOChannel* io)
468 {
469     if (!bound || !inited) {
470         return false;
471     }
472     
473     int length = sizeof(FlightState);
474     if ( ! io->write( (char *)(& _state), length ) ) {
475             SG_LOG( SG_IO, SG_ALERT, "Error writing data." );
476             return false;
477         }
478     
479     return true;
480 }
481
482 void FGInterface::_updatePositionM(const SGVec3d& cartPos)
483 {
484     TrackComputer tracker( _state.track, _state.geodetic_position_v );
485     _state.cartesian_position_v = cartPos;
486     _state.geodetic_position_v = SGGeod::fromCart(_state.cartesian_position_v);
487     _state.geocentric_position_v = SGGeoc::fromCart(_state.cartesian_position_v);
488     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(_state.geodetic_position_v)*SG_METER_TO_FEET );
489     _update_ground_elev_at_pos();
490 }
491
492
493 void FGInterface::_updatePosition(const SGGeod& geod)
494 {
495     TrackComputer tracker( _state.track, _state.geodetic_position_v );
496     _state.geodetic_position_v = geod;
497     _state.cartesian_position_v = SGVec3d::fromGeod(_state.geodetic_position_v);
498     _state.geocentric_position_v = SGGeoc::fromCart(_state.cartesian_position_v);
499
500     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(_state.geodetic_position_v)*SG_METER_TO_FEET );
501     _update_ground_elev_at_pos();
502 }
503
504
505 void FGInterface::_updatePosition(const SGGeoc& geoc)
506 {
507     TrackComputer tracker( _state.track, _state.geodetic_position_v );
508     _state.geocentric_position_v = geoc;
509     _state.cartesian_position_v = SGVec3d::fromGeoc(_state.geocentric_position_v);
510     _state.geodetic_position_v = SGGeod::fromCart(_state.cartesian_position_v);
511
512     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(_state.geodetic_position_v)*SG_METER_TO_FEET );
513     _update_ground_elev_at_pos();
514 }
515
516
517 void FGInterface::_updateGeodeticPosition( double lat, double lon, double alt )
518 {
519     _updatePosition(SGGeod::fromRadFt(lon, lat, alt));
520 }
521
522
523 void FGInterface::_updateGeocentricPosition( double lat, double lon,
524                                              double alt )
525 {
526     _updatePosition(SGGeoc::fromRadFt(lon, lat, get_Sea_level_radius() + alt));
527 }
528
529 void FGInterface::_update_ground_elev_at_pos( void ) {
530     double groundlevel_m = get_groundlevel_m(_state.geodetic_position_v);
531     _set_Runway_altitude( groundlevel_m * SG_METER_TO_FEET );
532 }
533
534 // Positions
535 void FGInterface::set_Latitude(double lat) {
536     _state.geodetic_position_v.setLatitudeRad(lat);
537 }
538
539 void FGInterface::set_Longitude(double lon) {
540     _state.geodetic_position_v.setLongitudeRad(lon);
541 }
542
543 void FGInterface::set_Altitude(double alt) {
544     _state.geodetic_position_v.setElevationFt(alt);
545 }
546
547 void FGInterface::set_AltitudeAGL(double altagl) {
548     _state.altitude_agl=altagl;
549 }
550
551 // Velocities
552 void FGInterface::set_V_calibrated_kts(double vc) {
553     _state.v_calibrated_kts = vc;
554 }
555
556 void FGInterface::set_Mach_number(double mach) {
557     _state.mach_number = mach;
558 }
559
560 void FGInterface::set_Velocities_Local( double north, 
561                                         double east,
562                                         double down ){
563     _state.v_local_v[0] = north;
564     _state.v_local_v[1] = east;
565     _state.v_local_v[2] = down;
566 }
567
568 void FGInterface::set_Velocities_Wind_Body( double u, 
569                                             double v,
570                                             double w){
571     _state.v_wind_body_v[0] = u;
572     _state.v_wind_body_v[1] = v;
573     _state.v_wind_body_v[2] = w;
574 }
575
576 // Euler angles 
577 void FGInterface::set_Euler_Angles( double phi, 
578                                     double theta,
579                                     double psi ) {
580     _state.euler_angles_v[0] = phi;
581     _state.euler_angles_v[1] = theta;
582     _state.euler_angles_v[2] = psi;
583 }  
584
585 // Flight Path
586 void FGInterface::set_Climb_Rate( double roc) {
587     _state.climb_rate = roc;
588 }
589
590 void FGInterface::set_Gamma_vert_rad( double gamma) {
591     _state.gamma_vert_rad = gamma;
592 }
593
594 void FGInterface::set_Static_pressure(double p) { _state.static_pressure = p; }
595 void FGInterface::set_Static_temperature(double T) { _state.static_temperature = T; }
596 void FGInterface::set_Density(double rho) { _state.density = rho; }
597
598 void FGInterface::set_Velocities_Local_Airmass (double wnorth, 
599                                                 double weast,
600                                                 double wdown ) {
601     _state.v_local_airmass_v[0] = wnorth;
602     _state.v_local_airmass_v[1] = weast;
603     _state.v_local_airmass_v[2] = wdown;
604 }
605
606
607 void FGInterface::_busdump(void)
608 {
609     SG_LOG(SG_FLIGHT,SG_INFO,"d_cg_rp_body_v: " << _state.d_cg_rp_body_v);
610     SG_LOG(SG_FLIGHT,SG_INFO,"v_dot_local_v: " << _state.v_dot_local_v);
611     SG_LOG(SG_FLIGHT,SG_INFO,"v_dot_body_v: " << _state.v_dot_body_v);
612     SG_LOG(SG_FLIGHT,SG_INFO,"a_cg_body_v: " << _state.a_cg_body_v);
613     SG_LOG(SG_FLIGHT,SG_INFO,"a_pilot_body_v: " << _state.a_pilot_body_v);
614     SG_LOG(SG_FLIGHT,SG_INFO,"n_cg_body_v: " << _state.n_cg_body_v);
615     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_v: " << _state.v_local_v);
616     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_rel_ground_v: " << _state.v_local_rel_ground_v);
617     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_airmass_v: " << _state.v_local_airmass_v);
618     SG_LOG(SG_FLIGHT,SG_INFO,"v_wind_body_v: " << _state.v_wind_body_v);
619     SG_LOG(SG_FLIGHT,SG_INFO,"omega_body_v: " << _state.omega_body_v);
620     SG_LOG(SG_FLIGHT,SG_INFO,"euler_rates_v: " << _state.euler_rates_v);
621     SG_LOG(SG_FLIGHT,SG_INFO,"geocentric_rates_v: " << _state.geocentric_rates_v);
622     SG_LOG(SG_FLIGHT,SG_INFO,"geocentric_position_v: " << _state.geocentric_position_v);
623     SG_LOG(SG_FLIGHT,SG_INFO,"geodetic_position_v: " << _state.geodetic_position_v);
624     SG_LOG(SG_FLIGHT,SG_INFO,"euler_angles_v: " << _state.euler_angles_v);
625
626     SG_LOG(SG_FLIGHT,SG_INFO,"nlf: " << _state.nlf );
627     SG_LOG(SG_FLIGHT,SG_INFO,"v_rel_wind: " << _state.v_rel_wind );
628     SG_LOG(SG_FLIGHT,SG_INFO,"v_true_kts: " << _state.v_true_kts );
629     SG_LOG(SG_FLIGHT,SG_INFO,"v_ground_speed: " << _state.v_ground_speed );
630     SG_LOG(SG_FLIGHT,SG_INFO,"v_equiv_kts: " << _state.v_equiv_kts );
631     SG_LOG(SG_FLIGHT,SG_INFO,"v_calibrated_kts: " << _state.v_calibrated_kts );
632     SG_LOG(SG_FLIGHT,SG_INFO,"alpha: " << _state.alpha );
633     SG_LOG(SG_FLIGHT,SG_INFO,"beta: " << _state.beta );
634     SG_LOG(SG_FLIGHT,SG_INFO,"gamma_vert_rad: " << _state.gamma_vert_rad );
635     SG_LOG(SG_FLIGHT,SG_INFO,"density: " << _state.density );
636     SG_LOG(SG_FLIGHT,SG_INFO,"mach_number: " << _state.mach_number );
637     SG_LOG(SG_FLIGHT,SG_INFO,"static_pressure: " << _state.static_pressure );
638     SG_LOG(SG_FLIGHT,SG_INFO,"total_pressure: " << _state.total_pressure );
639     SG_LOG(SG_FLIGHT,SG_INFO,"dynamic_pressure: " << _state.dynamic_pressure );
640     SG_LOG(SG_FLIGHT,SG_INFO,"static_temperature: " << _state.static_temperature );
641     SG_LOG(SG_FLIGHT,SG_INFO,"total_temperature: " << _state.total_temperature );
642     SG_LOG(SG_FLIGHT,SG_INFO,"sea_level_radius: " << _state.sea_level_radius );
643     SG_LOG(SG_FLIGHT,SG_INFO,"earth_position_angle: " << _state.earth_position_angle );
644     SG_LOG(SG_FLIGHT,SG_INFO,"runway_altitude: " << _state.runway_altitude );
645     SG_LOG(SG_FLIGHT,SG_INFO,"climb_rate: " << _state.climb_rate );
646     SG_LOG(SG_FLIGHT,SG_INFO,"altitude_agl: " << _state.altitude_agl );
647 }
648
649 bool
650 FGInterface::prepare_ground_cache_m(double startSimTime, double endSimTime,
651                                     const double pt[3], double rad)
652 {
653   return ground_cache.prepare_ground_cache(startSimTime, endSimTime,
654                                            SGVec3d(pt), rad);
655 }
656
657 bool
658 FGInterface::prepare_ground_cache_ft(double startSimTime, double endSimTime,
659                                      const double pt[3], double rad)
660 {
661   // Convert units and do the real work.
662   SGVec3d pt_ft = SG_FEET_TO_METER*SGVec3d(pt);
663   return ground_cache.prepare_ground_cache(startSimTime, endSimTime,
664                                            pt_ft, rad*SG_FEET_TO_METER);
665 }
666
667 bool
668 FGInterface::is_valid_m(double *ref_time, double pt[3], double *rad)
669 {
670   SGVec3d _pt;
671   bool valid = ground_cache.is_valid(*ref_time, _pt, *rad);
672   assign(pt, _pt);
673   return valid;
674 }
675
676 bool FGInterface::is_valid_ft(double *ref_time, double pt[3], double *rad)
677 {
678   // Convert units and do the real work.
679   SGVec3d _pt;
680   bool found_ground = ground_cache.is_valid(*ref_time, _pt, *rad);
681   assign(pt, SG_METER_TO_FEET*_pt);
682   *rad *= SG_METER_TO_FEET;
683   return found_ground;
684 }
685
686 double
687 FGInterface::get_cat_m(double t, const double pt[3],
688                        double end[2][3], double vel[2][3])
689 {
690   SGVec3d _end[2], _vel[2];
691   double dist = ground_cache.get_cat(t, SGVec3d(pt), _end, _vel);
692   for (int k=0; k<2; ++k) {
693     assign( end[k], _end[k] );
694     assign( vel[k], _vel[k] );
695   }
696   return dist;
697 }
698
699 double
700 FGInterface::get_cat_ft(double t, const double pt[3],
701                         double end[2][3], double vel[2][3])
702 {
703   // Convert units and do the real work.
704   SGVec3d pt_m = SG_FEET_TO_METER*SGVec3d(pt);
705   SGVec3d _end[2], _vel[2];
706   double dist = ground_cache.get_cat(t, pt_m, _end, _vel);
707   for (int k=0; k<2; ++k) {
708     assign( end[k], SG_METER_TO_FEET*_end[k] );
709     assign( vel[k], SG_METER_TO_FEET*_vel[k] );
710   }
711   return dist*SG_METER_TO_FEET;
712 }
713
714 bool
715 FGInterface::get_body_m(double t, simgear::BVHNode::Id id,
716                         double bodyToWorld[16], double linearVel[3],
717                         double angularVel[3])
718 {
719   SGMatrixd _bodyToWorld;
720   SGVec3d _linearVel, _angularVel;
721   if (!ground_cache.get_body(t, _bodyToWorld, _linearVel, _angularVel, id))
722     return false;
723
724   assign(linearVel, _linearVel);
725   assign(angularVel, _angularVel);
726   for (unsigned i = 0; i < 16; ++i)
727       bodyToWorld[i] = _bodyToWorld.data()[i];
728
729   return true;
730 }
731
732 bool
733 FGInterface::get_agl_m(double t, const double pt[3], double max_altoff,
734                        double contact[3], double normal[3],
735                        double linearVel[3], double angularVel[3],
736                        simgear::BVHMaterial const*& material, simgear::BVHNode::Id& id)
737 {
738   SGVec3d pt_m = SGVec3d(pt) - max_altoff*ground_cache.get_down();
739   SGVec3d _contact, _normal, _linearVel, _angularVel;
740   material = 0;
741   bool ret = ground_cache.get_agl(t, pt_m, _contact, _normal, _linearVel,
742                                   _angularVel, id, material);
743   // correct the linear velocity, since the line intersector delivers
744   // values for the start point and the get_agl function should
745   // traditionally deliver for the contact point
746   _linearVel += cross(_angularVel, _contact - pt_m);
747
748   assign(contact, _contact);
749   assign(normal, _normal);
750   assign(linearVel, _linearVel);
751   assign(angularVel, _angularVel);
752   return ret;
753 }
754
755 bool
756 FGInterface::get_agl_ft(double t, const double pt[3], double max_altoff,
757                         double contact[3], double normal[3],
758                         double linearVel[3], double angularVel[3],
759                         simgear::BVHMaterial const*& material, simgear::BVHNode::Id& id)
760 {
761   // Convert units and do the real work.
762   SGVec3d pt_m = SGVec3d(pt) - max_altoff*ground_cache.get_down();
763   pt_m *= SG_FEET_TO_METER;
764   SGVec3d _contact, _normal, _linearVel, _angularVel;
765   material = 0;
766   bool ret = ground_cache.get_agl(t, pt_m, _contact, _normal, _linearVel,
767                                   _angularVel, id, material);
768   // correct the linear velocity, since the line intersector delivers
769   // values for the start point and the get_agl function should
770   // traditionally deliver for the contact point
771   _linearVel += cross(_angularVel, _contact - pt_m);
772
773   // Convert units back ...
774   assign( contact, SG_METER_TO_FEET*_contact );
775   assign( normal, _normal );
776   assign( linearVel, SG_METER_TO_FEET*_linearVel );
777   assign( angularVel, _angularVel );
778   return ret;
779 }
780
781 bool
782 FGInterface::get_nearest_m(double t, const double pt[3], double maxDist,
783                            double contact[3], double normal[3],
784                            double linearVel[3], double angularVel[3],
785                            simgear::BVHMaterial const*& material,
786                            simgear::BVHNode::Id& id)
787 {
788   SGVec3d _contact, _linearVel, _angularVel;
789   material = 0;
790   if (!ground_cache.get_nearest(t, SGVec3d(pt), maxDist, _contact, _linearVel,
791                                 _angularVel, id, material))
792       return false;
793
794   assign(contact, _contact);
795   assign(linearVel, _linearVel);
796   assign(angularVel, _angularVel);
797   return true;
798 }
799
800 bool
801 FGInterface::get_nearest_ft(double t, const double pt[3], double maxDist,
802                             double contact[3], double normal[3],
803                             double linearVel[3], double angularVel[3],
804                             simgear::BVHMaterial const*& material,
805                             simgear::BVHNode::Id& id)
806 {
807   SGVec3d _contact, _linearVel, _angularVel;
808   material = 0;
809   if (!ground_cache.get_nearest(t, SG_FEET_TO_METER*SGVec3d(pt),
810                                 SG_FEET_TO_METER*maxDist, _contact, _linearVel,
811                                 _angularVel, id, material))
812       return false;
813
814   assign(contact, SG_METER_TO_FEET*_contact);
815   assign(linearVel, SG_METER_TO_FEET*_linearVel);
816   assign(angularVel, _angularVel);
817   return true;
818 }
819
820 double
821 FGInterface::get_groundlevel_m(double lat, double lon, double alt)
822 {
823   return get_groundlevel_m(SGGeod::fromRadM(lon, lat, alt));
824 }
825
826 double
827 FGInterface::get_groundlevel_m(const SGGeod& geod)
828 {
829   // Compute the cartesian position of the given lat/lon/alt.
830   SGVec3d pos = SGVec3d::fromGeod(geod);
831
832   // FIXME: how to handle t - ref_time differences ???
833   SGVec3d cpos;
834   double ref_time = 0, radius;
835   // Prepare the ground cache for that position.
836   if (!is_valid_m(&ref_time, cpos.data(), &radius)) {
837     double startTime = ref_time;
838     double endTime = startTime + 1;
839     bool ok = prepare_ground_cache_m(startTime, endTime, pos.data(), 10);
840     /// This is most likely the case when the given altitude is
841     /// too low, try with a new altitude of 10000m, that should be
842     /// sufficient to find a ground level below everywhere on our planet
843     if (!ok) {
844       pos = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, 10000));
845       /// If there is still no ground, return sea level radius
846       if (!prepare_ground_cache_m(startTime, endTime, pos.data(), 10))
847         return 0;
848     }
849   } else if (radius*radius <= distSqr(pos, cpos)) {
850     double startTime = ref_time;
851     double endTime = startTime + 1;
852
853     /// We reuse the old radius value, but only if it is at least 10 Meters ..
854     if (!(10 < radius)) // Well this strange compare is nan safe
855       radius = 10;
856
857     bool ok = prepare_ground_cache_m(startTime, endTime, pos.data(), radius);
858     /// This is most likely the case when the given altitude is
859     /// too low, try with a new altitude of 10000m, that should be
860     /// sufficient to find a ground level below everywhere on our planet
861     if (!ok) {
862       pos = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, 10000));
863       /// If there is still no ground, return sea level radius
864       if (!prepare_ground_cache_m(startTime, endTime, pos.data(), radius))
865         return 0;
866     }
867   }
868   
869   double contact[3], normal[3], vel[3], angvel[3];
870   const simgear::BVHMaterial* material;
871   simgear::BVHNode::Id id;
872   // Ignore the return value here, since it just tells us if
873   // the returns stem from the groundcache or from the coarse
874   // computations below the groundcache. The contact point is still something
875   // valid, the normals and the other returns just contain some defaults.
876   get_agl_m(ref_time, pos.data(), 2.0, contact, normal, vel, angvel,
877             material, id);
878   return SGGeod::fromCart(SGVec3d(contact)).getElevationM();
879 }
880   
881 bool
882 FGInterface::caught_wire_m(double t, const double pt[4][3])
883 {
884   SGVec3d pt_m[4];
885   for (int i=0; i<4; ++i)
886     pt_m[i] = SGVec3d(pt[i]);
887   
888   return ground_cache.caught_wire(t, pt_m);
889 }
890
891 bool
892 FGInterface::caught_wire_ft(double t, const double pt[4][3])
893 {
894   // Convert units and do the real work.
895   SGVec3d pt_m[4];
896   for (int i=0; i<4; ++i)
897     pt_m[i] = SG_FEET_TO_METER*SGVec3d(pt[i]);
898     
899   return ground_cache.caught_wire(t, pt_m);
900 }
901   
902 bool
903 FGInterface::get_wire_ends_m(double t, double end[2][3], double vel[2][3])
904 {
905   SGVec3d _end[2], _vel[2];
906   bool ret = ground_cache.get_wire_ends(t, _end, _vel);
907   for (int k=0; k<2; ++k) {
908     assign( end[k], _end[k] );
909     assign( vel[k], _vel[k] );
910   }
911   return ret;
912 }
913
914 bool
915 FGInterface::get_wire_ends_ft(double t, double end[2][3], double vel[2][3])
916 {
917   // Convert units and do the real work.
918   SGVec3d _end[2], _vel[2];
919   bool ret = ground_cache.get_wire_ends(t, _end, _vel);
920   for (int k=0; k<2; ++k) {
921     assign( end[k], SG_METER_TO_FEET*_end[k] );
922     assign( vel[k], SG_METER_TO_FEET*_vel[k] );
923   }
924   return ret;
925 }
926
927 void
928 FGInterface::release_wire(void)
929 {
930   ground_cache.release_wire();
931 }
932