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