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