]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
Tentative to fix JSBSim bug SF #115 : don't compute cl-squared when qbar is too low...
[flightgear.git] / src / FDM / JSBSim / JSBSim.cxx
1 // JSBsim.cxx -- interface to the JSBsim flight model
2 //
3 // Written by Curtis Olson, started February 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Lesser 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 // Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id: FlightGear.cxx,v 1.15 2014/01/28 09:42:20 ehofman Exp $
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/sg_inlines.h>
30
31 #include <cstdlib>    //    size_t
32 #include <string>
33
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/structure/commands.hxx>
39 #include <simgear/bvh/BVHMaterial.hxx>
40
41 #include <FDM/flight.hxx>
42
43 #include <Aircraft/controls.hxx>
44 #include <Main/globals.hxx>
45 #include <Main/fg_props.hxx>
46
47 #include "JSBSim.hxx"
48 #include <FDM/JSBSim/FGFDMExec.h>
49 #include <FDM/JSBSim/FGJSBBase.h>
50 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
51 #include <FDM/JSBSim/initialization/FGTrim.h>
52 #include <FDM/JSBSim/models/FGModel.h>
53 #include <FDM/JSBSim/models/FGAircraft.h>
54 #include <FDM/JSBSim/models/FGFCS.h>
55 #include <FDM/JSBSim/models/FGPropagate.h>
56 #include <FDM/JSBSim/models/FGAuxiliary.h>
57 #include <FDM/JSBSim/models/FGInertial.h>
58 #include <FDM/JSBSim/models/FGAtmosphere.h>
59 #include <FDM/JSBSim/models/FGMassBalance.h>
60 #include <FDM/JSBSim/models/FGAerodynamics.h>
61 #include <FDM/JSBSim/models/FGLGear.h>
62 #include <FDM/JSBSim/models/FGGroundReactions.h>
63 #include <FDM/JSBSim/models/FGPropulsion.h>
64 #include <FDM/JSBSim/models/FGAccelerations.h>
65 #include <FDM/JSBSim/models/atmosphere/FGWinds.h>
66 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
67 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
68 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
69 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
70 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
71 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
72 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
73 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
74 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
75 #include <FDM/JSBSim/models/propulsion/FGTank.h>
76 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
77 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
78
79 using namespace JSBSim;
80
81 static inline double
82 FMAX (double a, double b)
83 {
84   return a > b ? a : b;
85 }
86
87 class FGFSGroundCallback : public FGGroundCallback {
88 public:
89   FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
90   virtual ~FGFSGroundCallback() {}
91
92   /** Get the altitude above sea level dependent on the location. */
93   virtual double GetAltitude(const FGLocation& l) const {
94     double pt[3] = { SG_FEET_TO_METER*l(FGJSBBase::eX),
95                      SG_FEET_TO_METER*l(FGJSBBase::eY),
96                      SG_FEET_TO_METER*l(FGJSBBase::eZ) };
97     double lat, lon, alt;
98     sgCartToGeod( pt, &lat, &lon, &alt);
99     return alt * SG_METER_TO_FEET;
100   }
101
102   /** Compute the altitude above ground. */
103   virtual double GetAGLevel(double t, const FGLocation& l,
104                             FGLocation& cont, FGColumnVector3& n,
105                             FGColumnVector3& v, FGColumnVector3& w) const {
106     double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
107     double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
108     mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
109                            vel, angularVel, &agl);
110     n = FGColumnVector3( normal[0], normal[1], normal[2] );
111     v = FGColumnVector3( vel[0], vel[1], vel[2] );
112     w = FGColumnVector3( angularVel[0], angularVel[1], angularVel[2] );
113     cont = FGColumnVector3( contact[0], contact[1], contact[2] );
114     return agl;
115   }
116
117   virtual double GetTerrainGeoCentRadius(double t, const FGLocation& l) const {
118     double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
119     double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
120     mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
121                            vel, angularVel, &agl);
122     return sqrt(contact[0]*contact[0]+contact[1]*contact[1]+contact[2]*contact[2]);
123   }
124
125   virtual double GetSeaLevelRadius(const FGLocation& l) const {
126     double seaLevelRadius, latGeoc;
127
128     sgGeodToGeoc(l.GetGeodLatitudeRad(), l.GetGeodAltitude(),
129                  &seaLevelRadius, &latGeoc);
130
131     return seaLevelRadius * SG_METER_TO_FEET;
132   }
133
134   virtual void SetTerrainGeoCentRadius(double radius) {}
135   virtual void SetSeaLevelRadius(double radius) {}
136 private:
137   FGJSBsim* mInterface;
138 };
139
140 // FG uses a squared normalized magnitude for turbulence
141 // this lookup table maps fg's severity levels 
142 // none(0), light(1/3), moderate(2/3) and severe(3/3)
143 // to the POE table indexes 0, 3, 4 and 7
144 class FGTurbulenceSeverityTable : public FGTable {
145 public:
146   FGTurbulenceSeverityTable() : FGTable(4) {
147     *this << (0.0/9.0) << 0.0;
148     *this << (1.0/9.0) << 3.0;
149     *this << (4.0/9.0) << 4.0;
150     *this << (9.0/9.0) << 7.0;
151   }
152 };
153
154 /******************************************************************************/
155 std::map<std::string,int> FGJSBsim::TURBULENCE_TYPE_NAMES;
156
157 static FGTurbulenceSeverityTable TurbulenceSeverityTable;
158
159 FGJSBsim::FGJSBsim( double dt )
160   : FGInterface(dt), got_wire(false)
161 {
162     bool result;
163     if( TURBULENCE_TYPE_NAMES.empty() ) {
164         TURBULENCE_TYPE_NAMES["ttNone"]     = FGWinds::ttNone;
165         TURBULENCE_TYPE_NAMES["ttStandard"] = FGWinds::ttStandard;
166         TURBULENCE_TYPE_NAMES["ttCulp"]     = FGWinds::ttCulp;
167         TURBULENCE_TYPE_NAMES["ttMilspec"]  = FGWinds::ttMilspec;
168         TURBULENCE_TYPE_NAMES["ttTustin"]   = FGWinds::ttTustin;
169     }
170
171     // Set up the debugging level
172     // FIXME: this will not respond to
173     // runtime changes
174
175     if ((sglog().get_log_classes() & SG_FLIGHT) != 0) {
176
177                                 // do a rough-and-ready mapping to
178                                 // the levels documented in FGFDMExec.h
179         switch (sglog().get_log_priority()) {
180         case SG_BULK:
181             FGJSBBase::debug_lvl = 0x1f;
182             break;
183         case SG_DEBUG:
184             FGJSBBase::debug_lvl = 0x1f;
185         case SG_INFO:
186         case SG_WARN:
187         case SG_ALERT:
188             FGJSBBase::debug_lvl = 0x00;
189             break;
190         }
191     } else {
192                                 // if flight is excluded, don't bother
193             FGJSBBase::debug_lvl = 0x00;
194     }
195
196     PropertyManager = new FGPropertyManager( (FGPropertyNode*)globals->get_props() );
197     fdmex = new FGFDMExec( PropertyManager );
198
199     // Register ground callback.
200     fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
201
202     Atmosphere      = fdmex->GetAtmosphere();
203     Winds           = fdmex->GetWinds();
204     FCS             = fdmex->GetFCS();
205     MassBalance     = fdmex->GetMassBalance();
206     Propulsion      = fdmex->GetPropulsion();
207     Aircraft        = fdmex->GetAircraft();
208     Propagate       = fdmex->GetPropagate();
209     Auxiliary       = fdmex->GetAuxiliary();
210     Inertial        = fdmex->GetInertial();
211     Aerodynamics    = fdmex->GetAerodynamics();
212     GroundReactions = fdmex->GetGroundReactions();
213     Accelerations   = fdmex->GetAccelerations();
214
215     fgic=fdmex->GetIC();
216     needTrim=true;
217
218     SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
219
220     SGPath engine_path( fgGetString("/sim/fg-root") );
221     engine_path.append( "Aircraft/Generic/JSBSim/Engines" );
222
223     SGPath systems_path( fgGetString("/sim/fg-root") );
224     systems_path.append( "Aircraft/Generic/JSBSim/Systems" );
225
226 // deprecate sim-time-sec for simulation/sim-time-sec
227 // remove alias with increased configuration file version number (2.1 or later)
228     SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec");
229     fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node );
230 // end of sim-time-sec deprecation patch
231
232     terrain = fgGetNode("/sim/fdm/surface", true);
233
234     fdmex->Setdt( dt );
235
236     result = fdmex->LoadModel( aircraft_path.str(),
237                                engine_path.str(),
238                                systems_path.str(),
239                                fgGetString("/sim/aero"), false );
240
241     if (result) {
242       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
243     } else {
244       SG_LOG( SG_FLIGHT, SG_INFO,
245               "  aero does not exist (you may have mis-typed the name).");
246       throw(-1);
247     }
248
249     SG_LOG( SG_FLIGHT, SG_INFO, "" );
250     SG_LOG( SG_FLIGHT, SG_INFO, "" );
251     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
252
253     int Neng = Propulsion->GetNumEngines();
254     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
255
256     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
257         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
258                 << GroundReactions->GetNumGearUnits() );
259         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
260         SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
261         SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
262         exit(-1);
263     }
264
265     init_gear();
266
267     // Set initial fuel levels if provided.
268     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
269       double d;
270       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
271       FGTank* tank = Propulsion->GetTank(i);
272
273       d = node->getNode( "density-ppg", true )->getDoubleValue();
274       if( d > 0.0 ) {
275         tank->SetDensity( d );
276       } else {
277         node->getNode( "density-ppg", true )->setDoubleValue( SG_MAX2<double>(tank->GetDensity(), 0.1) );
278       }
279
280       d = node->getNode( "level-lbs", true )->getDoubleValue();
281       if( d > 0.0 ) {
282         tank->SetContents( d );
283       } else {
284         node->getNode( "level-lbs", true )->setDoubleValue( tank->GetContents() );
285       }
286       /* Capacity is read-only in FGTank and can't be overwritten from FlightGear */
287       node->getNode("capacity-gal_us", true )->setDoubleValue( tank->GetCapacityGallons() );
288     }
289     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
290
291     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
292     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
293     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
294     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
295
296     startup_trim = fgGetNode("/sim/presets/trim", true);
297
298     trimmed = fgGetNode("/fdm/trim/trimmed", true);
299     trimmed->setBoolValue(false);
300
301     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
302     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
303     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
304     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
305
306     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
307     stall_warning->setDoubleValue(0);
308
309
310     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
311     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
312     left_aileron_pos_pct
313         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
314     right_aileron_pos_pct
315         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
316     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
317     speedbrake_pos_pct
318         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
319     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
320     tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
321     wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
322
323     elevator_pos_pct->setDoubleValue(0);
324     left_aileron_pos_pct->setDoubleValue(0);
325     right_aileron_pos_pct->setDoubleValue(0);
326     rudder_pos_pct->setDoubleValue(0);
327     flap_pos_pct->setDoubleValue(0);
328     speedbrake_pos_pct->setDoubleValue(0);
329     spoilers_pos_pct->setDoubleValue(0);
330
331     ab_brake_engaged = fgGetNode("/autopilot/autobrake/engaged", true);
332     ab_brake_left_pct = fgGetNode("/autopilot/autobrake/brake-left-output", true);
333     ab_brake_right_pct = fgGetNode("/autopilot/autobrake/brake-right-output", true);
334     
335     altitude = fgGetNode("/position/altitude-ft");
336     temperature = fgGetNode("/environment/temperature-degc",true);
337     pressure = fgGetNode("/environment/pressure-inhg",true);
338     pressureSL = fgGetNode("/environment/pressure-sea-level-inhg",true);
339     ground_wind = fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt",true);
340     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
341     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
342     turbulence_model = fgGetNode("/environment/params/jsbsim-turbulence-model",true);
343
344     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
345     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
346     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
347
348     slaved = fgGetNode("/sim/slaved/enabled", true);
349
350     for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
351       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
352       Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
353                      Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
354     }
355
356     hook_root_struct = FGColumnVector3(
357         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
358         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
359         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
360     last_hook_tip[0] = 0; last_hook_tip[1] = 0; last_hook_tip[2] = 0;
361     last_hook_root[0] = 0; last_hook_root[1] = 0; last_hook_root[2] = 0;
362
363     crashed = false;
364 }
365
366 /******************************************************************************/
367 FGJSBsim::~FGJSBsim(void)
368 {
369   delete fdmex;
370   delete PropertyManager;
371 }
372
373 /******************************************************************************/
374
375 // Initialize the JSBsim flight model, dt is the time increment for
376 // each subsequent iteration through the EOM
377
378 void FGJSBsim::init()
379 {
380     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
381
382     // Explicitly call the superclass's
383     // init method first.
384
385     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
386       Atmosphere->SetTemperature(temperature->getDoubleValue(), get_Altitude(), FGAtmosphere::eCelsius);
387       Atmosphere->SetPressureSL(FGAtmosphere::eInchesHg, pressureSL->getDoubleValue());
388       // initialize to no turbulence, these values get set in the update loop
389       Winds->SetTurbType(FGWinds::ttNone);
390       Winds->SetTurbGain(0.0);
391       Winds->SetTurbRate(0.0);
392       Winds->SetWindspeed20ft(0.0);
393       Winds->SetProbabilityOfExceedence(0.0);
394     }
395
396     fgic->SetWindNEDFpsIC(0.0, 0.0, 0.0);
397
398     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << Atmosphere->GetTemperature()
399      << ", " << Atmosphere->GetPressure()
400      << ", " << Atmosphere->GetDensity() );
401
402     FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
403
404     needTrim = startup_trim->getBoolValue();
405     common_init();
406
407     copy_to_JSBsim();
408     fdmex->RunIC();     //loop JSBSim once w/o integrating
409     if (fgGetBool("/sim/presets/running")) {
410       Propulsion->InitRunning(-1);
411       for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
412         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
413         globals->get_controls()->set_magnetos(i, eng->GetMagnetos());
414         globals->get_controls()->set_mixture(i, FCS->GetMixtureCmd(i));
415       }
416     }
417
418     if ( needTrim ) {
419       const FGLocation& cart = fgic->GetPosition();
420       double cart_pos[3], contact[3], d[3], vel[3], agl;
421       update_ground_cache(cart, cart_pos, 0.01);
422
423       get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
424                  d, vel, d, &agl);
425       double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
426                                 + contact[2]*contact[2]) - cart.GetSeaLevelRadius();
427
428       SG_LOG(SG_FLIGHT, SG_INFO, "Ready to trim, terrain elevation is: "
429                                  << terrain_alt );
430
431       if (fgGetBool("/sim/presets/onground")) {
432         FGColumnVector3 gndVelNED = cart.GetTec2l()
433                                   * FGColumnVector3(vel[0], vel[1], vel[2]);
434         fgic->SetVNorthFpsIC(gndVelNED(1));
435         fgic->SetVEastFpsIC(gndVelNED(2));
436         fgic->SetVDownFpsIC(gndVelNED(3));
437       }
438       do_trim();
439       needTrim = false;
440     }
441
442     copy_from_JSBsim(); //update the bus
443
444     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
445
446     switch(fgic->GetSpeedSet()) {
447     case setned:
448         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
449                << Propagate->GetVel(FGJSBBase::eNorth) << ", "
450                << Propagate->GetVel(FGJSBBase::eEast) << ", "
451                << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
452     break;
453     case setuvw:
454         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
455                << Propagate->GetUVW(1) << ", "
456                << Propagate->GetUVW(2) << ", "
457                << Propagate->GetUVW(3) << " ft/s");
458     break;
459     case setmach:
460         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
461                << Auxiliary->GetMach() );
462     break;
463     case setvc:
464     default:
465         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
466                << Auxiliary->GetVcalibratedKTS() << " knots" );
467     break;
468     }
469
470     stall_warning->setDoubleValue(0);
471
472     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
473             << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
474     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
475             << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
476     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
477             << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
478     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
479             << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
480     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
481             << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
482     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
483             << Propagate->GetAltitudeASL() << " feet" );
484     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
485
486     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
487
488     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
489
490     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
491                                   globals->get_controls()->get_gear_down() );
492 }
493
494 /******************************************************************************/
495
496 void FGJSBsim::unbind()
497 {
498   fdmex->Unbind();
499   FGInterface::unbind();
500 }
501
502 /******************************************************************************/
503
504 // Run an iteration of the EOM (equations of motion)
505
506 void FGJSBsim::update( double dt )
507 {
508     if(crashed) {
509       if(!fgGetBool("/sim/crashed"))
510         fgSetBool("/sim/crashed", true);
511       return;
512     }
513
514     if (is_suspended())
515       return;
516
517     int multiloop = _calc_multiloop(dt);
518     FGLocation cart = Auxiliary->GetLocationVRP();
519     double cart_pos[3];
520
521     update_ground_cache(cart, cart_pos, dt);
522
523     copy_to_JSBsim();
524
525     trimmed->setBoolValue(false);
526
527     for ( int i=0; i < multiloop; i++ ) {
528       if (!fdmex->Run()) {
529         // The property fdm/jsbsim/simulation/terminate has been set to true
530         // by the user. The sim is considered crashed.
531         crashed = true;
532         break;
533       }
534       update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());
535     }
536
537     FGJSBBase::Message* msg;
538     while ((msg = fdmex->ProcessNextMessage()) != NULL) {
539 //      msg = fdmex->ProcessNextMessage();
540       switch (msg->type) {
541       case FGJSBBase::Message::eText:
542         if (msg->text == "Crash Detected: Simulation FREEZE.")
543           crashed = true;
544         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
545         break;
546       case FGJSBBase::Message::eBool:
547         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
548         break;
549       case FGJSBBase::Message::eInteger:
550         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
551         break;
552       case FGJSBBase::Message::eDouble:
553         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
554         break;
555       default:
556         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
557         break;
558       }
559     }
560
561     // translate JSBsim back to FG structure so that the
562     // autopilot (and the rest of the sim can use the updated values
563     copy_from_JSBsim();
564 }
565
566 /******************************************************************************/
567
568 void FGJSBsim::suspend()
569 {
570   fdmex->Hold();
571   SGSubsystem::suspend();
572 }
573
574 /******************************************************************************/
575
576 void FGJSBsim::resume()
577 {
578   fdmex->Resume();
579   SGSubsystem::resume();
580 }
581
582 /******************************************************************************/
583
584 // Convert from the FGInterface struct to the JSBsim generic_ struct
585
586 bool FGJSBsim::copy_to_JSBsim()
587 {
588     unsigned int i;
589
590     // copy control positions into the JSBsim structure
591
592     FCS->SetDaCmd( globals->get_controls()->get_aileron());
593     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
594     FCS->SetDeCmd( globals->get_controls()->get_elevator());
595     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
596     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
597     FCS->SetDsCmd( globals->get_controls()->get_rudder() );
598     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
599     FCS->SetDfCmd( globals->get_controls()->get_flaps() );
600     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
601     FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
602
603         // Parking brake sets minimum braking
604         // level for mains.
605     double parking_brake = globals->get_controls()->get_brake_parking();
606     double left_brake = globals->get_controls()->get_brake_left();
607     double right_brake = globals->get_controls()->get_brake_right();
608     
609     if (ab_brake_engaged->getBoolValue()) {
610       left_brake = ab_brake_left_pct->getDoubleValue();
611       right_brake = ab_brake_right_pct->getDoubleValue(); 
612     }
613     
614     FCS->SetLBrake(FMAX(left_brake, parking_brake));
615     FCS->SetRBrake(FMAX(right_brake, parking_brake));
616     
617     
618     FCS->SetCBrake( 0.0 );
619     // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
620
621     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
622     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
623       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
624
625       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
626       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
627       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
628       FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
629
630       switch (Propulsion->GetEngine(i)->GetType()) {
631       case FGEngine::etPiston:
632         { // FGPiston code block
633         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
634         eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
635         break;
636         } // end FGPiston code block
637       case FGEngine::etTurbine:
638         { // FGTurbine code block
639         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
640         eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
641         eng->SetReverse( globals->get_controls()->get_reverser(i) );
642         //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
643         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
644         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
645         break;
646         } // end FGTurbine code block
647       case FGEngine::etRocket:
648         { // FGRocket code block
649 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
650         break;
651         } // end FGRocket code block
652       case FGEngine::etTurboprop:
653         { // FGTurboProp code block
654         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
655         eng->SetReverse( globals->get_controls()->get_reverser(i) );
656         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
657         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
658
659         eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
660         eng->SetCondition( globals->get_controls()->get_condition(i) );
661         break;
662         } // end FGTurboProp code block
663       default:
664         break;
665       }
666
667       { // FGEngine code block
668       FGEngine* eng = Propulsion->GetEngine(i);
669
670       eng->SetStarter( globals->get_controls()->get_starter(i) );
671       eng->SetRunning( node->getBoolValue("running") );
672       } // end FGEngine code block
673     }
674
675     Atmosphere->SetTemperature(temperature->getDoubleValue(), get_Altitude(), FGAtmosphere::eCelsius);
676     Atmosphere->SetPressureSL(FGAtmosphere::eInchesHg, pressureSL->getDoubleValue());
677
678     Winds->SetTurbType((FGWinds::tType)TURBULENCE_TYPE_NAMES[turbulence_model->getStringValue()]);
679     switch( Winds->GetTurbType() ) {
680         case FGWinds::ttStandard:
681         case FGWinds::ttCulp: {
682             double tmp = turbulence_gain->getDoubleValue();
683             Winds->SetTurbGain(tmp * tmp * 100.0);
684             Winds->SetTurbRate(turbulence_rate->getDoubleValue());
685             break;
686         }
687         case FGWinds::ttMilspec:
688         case FGWinds::ttTustin: {
689             // milspec turbulence: 3=light, 4=moderate, 6=severe turbulence
690             // turbulence_gain normalized: 0: none, 1/3: light, 2/3: moderate, 3/3: severe
691             double tmp = turbulence_gain->getDoubleValue();
692             Winds->SetProbabilityOfExceedence(
693               SGMiscd::roundToInt(TurbulenceSeverityTable.GetValue( tmp ) )
694             );
695             Winds->SetWindspeed20ft(ground_wind->getDoubleValue());
696             break;
697         }
698
699         default:
700             break;
701     }
702
703     Winds->SetWindNED( -wind_from_north->getDoubleValue(),
704                        -wind_from_east->getDoubleValue(),
705                        -wind_from_down->getDoubleValue() );
706 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
707 //                  << get_V_north_airmass() << ", "
708 //                  << get_V_east_airmass()  << ", "
709 //                  << get_V_down_airmass() );
710
711     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
712       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
713       FGTank * tank = Propulsion->GetTank(i);
714       double fuelDensity = node->getDoubleValue("density-ppg");
715
716       if (fuelDensity < 0.1)
717         fuelDensity = 6.0; // Use average fuel value
718
719       tank->SetDensity(fuelDensity);
720       tank->SetContents(node->getDoubleValue("level-lbs"));
721     }
722
723     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
724     fdmex->SetChild(slaved->getBoolValue());
725
726     return true;
727 }
728
729 /******************************************************************************/
730
731 // Convert from the JSBsim generic_ struct to the FGInterface struct
732
733 bool FGJSBsim::copy_from_JSBsim()
734 {
735     unsigned int i, j;
736 /*
737     _set_Inertias( MassBalance->GetMass(),
738                    MassBalance->GetIxx(),
739                    MassBalance->GetIyy(),
740                    MassBalance->GetIzz(),
741                    MassBalance->GetIxz() );
742 */
743     _set_CG_Position( MassBalance->GetXYZcg(1),
744                       MassBalance->GetXYZcg(2),
745                       MassBalance->GetXYZcg(3) );
746
747     _set_Accels_Body( Accelerations->GetBodyAccel(1),
748                       Accelerations->GetBodyAccel(2),
749                       Accelerations->GetBodyAccel(3) );
750
751     _set_Accels_CG_Body_N ( Auxiliary->GetNcg(1),
752                             Auxiliary->GetNcg(2),
753                             Auxiliary->GetNcg(3) );
754
755     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
756                             Auxiliary->GetPilotAccel(2),
757                             Auxiliary->GetPilotAccel(3) );
758
759     _set_Nlf( Auxiliary->GetNlf() );
760
761     // Velocities
762
763     _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
764                            Propagate->GetVel(FGJSBBase::eEast),
765                            Propagate->GetVel(FGJSBBase::eDown) );
766
767     _set_Velocities_Body( Propagate->GetUVW(1),
768                           Propagate->GetUVW(2),
769                           Propagate->GetUVW(3) );
770
771     // Make the HUD work ...
772     _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
773                             Propagate->GetVel(FGJSBBase::eEast),
774                             -Propagate->GetVel(FGJSBBase::eDown) );
775
776     _set_V_rel_wind( Auxiliary->GetVt() );
777
778     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
779
780     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
781
782     _set_V_ground_speed( Auxiliary->GetVground() );
783
784     _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
785                      Propagate->GetPQR(FGJSBBase::eQ),
786                      Propagate->GetPQR(FGJSBBase::eR) );
787
788     _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
789                       Auxiliary->GetEulerRates(FGJSBBase::eTht),
790                       Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
791
792     _set_Mach_number( Auxiliary->GetMach() );
793
794     // Positions of Visual Reference Point
795     FGLocation l = Auxiliary->GetLocationVRP();
796     _updatePosition(SGGeoc::fromRadFt( l.GetLongitude(), l.GetLatitude(),
797                                        l.GetRadius() ));
798
799     _set_Altitude_AGL( Propagate->GetDistanceAGL() );
800     {
801       double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
802       double contact[3], d[3], sd, t;
803       is_valid_m(&t, d, &sd);
804       get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
805       double rwrad
806         = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
807       _set_Runway_altitude( rwrad - get_Sea_level_radius() );
808     }
809
810     _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
811                        Propagate->GetEuler(FGJSBBase::eTht),
812                        Propagate->GetEuler(FGJSBBase::ePsi) );
813
814     _set_Alpha( Auxiliary->Getalpha() );
815     _set_Beta( Auxiliary->Getbeta() );
816
817
818     _set_Gamma_vert_rad( Auxiliary->GetGamma() );
819
820     _set_Earth_position_angle( Propagate->GetEarthPositionAngle() );
821
822     _set_Climb_Rate( Propagate->Gethdot() );
823
824     const FGMatrix33& Tl2b = Propagate->GetTl2b();
825     for ( i = 1; i <= 3; i++ ) {
826         for ( j = 1; j <= 3; j++ ) {
827             _set_T_Local_to_Body( i, j, Tl2b(i,j) );
828         }
829     }
830
831     // Copy the engine values from JSBSim.
832     for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
833       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
834       SGPropertyNode * tnode = node->getChild("thruster", 0, true);
835       FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
836
837       switch (Propulsion->GetEngine(i)->GetType()) {
838       case FGEngine::etPiston:
839         { // FGPiston code block
840         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
841         node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
842         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
843         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
844         node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
845         // NOTE: mp-osi is not in ounces per square inch.
846         // This error is left for reasons of backwards compatibility with
847         // existing FlightGear sound and instrument configurations.
848         node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
849         node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
850         node->setDoubleValue("rpm", eng->getRPM());
851         } // end FGPiston code block
852         break;
853       case FGEngine::etRocket:
854         { // FGRocket code block
855 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
856         } // end FGRocket code block
857         break;
858       case FGEngine::etTurbine:
859         { // FGTurbine code block
860         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
861         node->setDoubleValue("n1", eng->GetN1());
862         node->setDoubleValue("n2", eng->GetN2());
863         node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
864         node->setBoolValue("augmentation", eng->GetAugmentation());
865         node->setBoolValue("water-injection", eng->GetInjection());
866         node->setBoolValue("ignition", eng->GetIgnition() != 0);
867         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
868         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
869         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
870         node->setBoolValue("reversed", eng->GetReversed());
871         node->setBoolValue("cutoff", eng->GetCutoff());
872         node->setDoubleValue("epr", eng->GetEPR());
873         globals->get_controls()->set_reverser(i, eng->GetReversed() );
874         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
875         globals->get_controls()->set_water_injection(i, eng->GetInjection() );
876         globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
877         } // end FGTurbine code block
878         break;
879       case FGEngine::etTurboprop:
880         { // FGTurboProp code block
881         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
882         node->setDoubleValue("n1", eng->GetN1());
883         //node->setDoubleValue("n2", eng->GetN2());
884         node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
885         node->setBoolValue("ignition", eng->GetIgnition() != 0);
886         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
887         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
888         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
889         node->setBoolValue("reversed", eng->GetReversed());
890         node->setBoolValue("cutoff", eng->GetCutoff());
891         node->setBoolValue("starting", eng->GetEngStarting());
892         node->setBoolValue("generator-power", eng->GetGeneratorPower());
893         node->setBoolValue("damaged", eng->GetCondition() != 0);
894         node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
895         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
896 //        node->setBoolValue("onfire", eng->GetFire());
897         globals->get_controls()->set_reverser(i, eng->GetReversed() );
898         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
899         } // end FGTurboProp code block
900         break;
901       case FGEngine::etElectric:
902         { // FGElectric code block
903         FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
904         node->setDoubleValue("rpm", eng->getRPM());
905         } // end FGElectric code block
906         break;
907       case FGEngine::etUnknown:
908         break;
909       }
910
911       { // FGEngine code block
912       FGEngine* eng = Propulsion->GetEngine(i);
913       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
914       node->setDoubleValue("thrust_lb", thruster->GetThrust());
915       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
916       node->setBoolValue("running", eng->GetRunning());
917       node->setBoolValue("starter", eng->GetStarter());
918       node->setBoolValue("cranking", eng->GetCranking());
919       globals->get_controls()->set_starter(i, eng->GetStarter() );
920       } // end FGEngine code block
921
922       switch (thruster->GetType()) {
923       case FGThruster::ttNozzle:
924         { // FGNozzle code block
925 //        FGNozzle* noz = (FGNozzle*)thruster;
926         } // end FGNozzle code block
927         break;
928       case FGThruster::ttPropeller:
929         { // FGPropeller code block
930         FGPropeller* prop = (FGPropeller*)thruster;
931         tnode->setDoubleValue("rpm", thruster->GetRPM());
932         tnode->setDoubleValue("pitch", prop->GetPitch());
933         tnode->setDoubleValue("torque", prop->GetTorque());
934         tnode->setBoolValue("feathered", prop->GetFeather());
935         } // end FGPropeller code block
936         break;
937       case FGThruster::ttRotor:
938         { // FGRotor code block
939 //        FGRotor* rotor = (FGRotor*)thruster;
940         } // end FGRotor code block
941         break;
942       case FGThruster::ttDirect:
943         { // Direct code block
944         } // end Direct code block
945         break;
946       }
947
948     }
949
950     // Copy the fuel levels from JSBSim if fuel
951     // freeze not enabled.
952     if ( ! Propulsion->GetFuelFreeze() ) {
953       for (i = 0; i < Propulsion->GetNumTanks(); i++) {
954         SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
955         FGTank* tank = Propulsion->GetTank(i);
956         double contents = tank->GetContents();
957         double temp = tank->GetTemperature_degC();
958         double fuelDensity = tank->GetDensity();
959
960         if (fuelDensity < 0.1)
961           fuelDensity = 6.0; // Use average fuel value
962
963         node->setDoubleValue("density-ppg" , fuelDensity);
964         node->setDoubleValue("level-lbs", contents);
965         if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
966
967         node->setDoubleValue("arm-in", tank->GetXYZ(FGJSBBase::eX ) );
968       }
969     }
970
971     update_gear();
972
973     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
974
975     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
976     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
977     right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
978     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
979     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
980     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
981     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
982     tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
983     wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
984
985     // force a sim crashed if crashed (altitude AGL < 0)
986     if (get_Altitude_AGL() < -100.0) {
987          fdmex->SuspendIntegration();
988          crashed = true;
989     }
990
991     return true;
992 }
993
994
995 bool FGJSBsim::ToggleDataLogging(void)
996 {
997   // ToDo: handle this properly
998   fdmex->DisableOutput();
999   return false;
1000 }
1001
1002
1003 bool FGJSBsim::ToggleDataLogging(bool state)
1004 {
1005     if (state) {
1006       fdmex->EnableOutput();
1007       return true;
1008     } else {
1009       fdmex->DisableOutput();
1010       return false;
1011     }
1012 }
1013
1014
1015 //Positions
1016 void FGJSBsim::set_Latitude(double lat)
1017 {
1018   double alt = altitude->getDoubleValue();
1019   double sea_level_radius_meters, lat_geoc;
1020
1021   if ( alt < -9990 ) alt = 0.0;
1022
1023   SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1024   SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
1025
1026   sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1027                     &sea_level_radius_meters, &lat_geoc );
1028
1029   double sea_level_radius_ft = sea_level_radius_meters * SG_METER_TO_FEET;
1030   _set_Sea_level_radius( sea_level_radius_ft );
1031
1032   if (needTrim)
1033     fgic->SetLatitudeRadIC( lat_geoc );
1034   else
1035     Propagate->SetLatitude(lat_geoc);
1036
1037   FGInterface::set_Latitude(lat);
1038 }
1039
1040
1041 void FGJSBsim::set_Longitude(double lon)
1042 {
1043   SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1044
1045   if (needTrim)
1046     fgic->SetLongitudeRadIC(lon);
1047   else
1048     Propagate->SetLongitude(lon);
1049
1050   FGInterface::set_Longitude(lon);
1051 }
1052
1053 // Sets the altitude above sea level.
1054 void FGJSBsim::set_Altitude(double alt)
1055 {
1056   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1057
1058   if (needTrim) {
1059     FGLocation position = fgic->GetPosition();
1060
1061     position.SetPositionGeodetic(0.0, position.GetGeodLatitudeRad(), alt);
1062     fgic->SetAltitudeASLFtIC(position.GetAltitudeASL());
1063     fgic->SetLatitudeRadIC(position.GetLatitude());
1064   }
1065   else
1066     Propagate->SetAltitudeASL(alt);
1067
1068   FGInterface::set_Altitude(alt);
1069 }
1070
1071 void FGJSBsim::set_V_calibrated_kts(double vc)
1072 {
1073     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
1074
1075   if (needTrim)
1076     fgic->SetVcalibratedKtsIC(vc);
1077   else {
1078     double p=pressure->getDoubleValue();
1079     double psl=fdmex->GetAtmosphere()->GetPressureSL();
1080     double rhosl=fdmex->GetAtmosphere()->GetDensitySL();
1081     double mach = FGJSBBase::MachFromVcalibrated(vc, p, psl, rhosl);
1082     double temp = 1.8*(temperature->getDoubleValue()+273.15);
1083     double soundSpeed = sqrt(1.4*1716.0*temp);
1084     FGColumnVector3 vUVW = Propagate->GetUVW();
1085     vUVW.Normalize();
1086     vUVW *= mach * soundSpeed;
1087     Propagate->SetUVW(1, vUVW(1));
1088     Propagate->SetUVW(2, vUVW(2));
1089     Propagate->SetUVW(3, vUVW(3));
1090   }
1091
1092   FGInterface::set_V_calibrated_kts(vc);
1093 }
1094
1095 void FGJSBsim::set_Mach_number(double mach)
1096 {
1097   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
1098
1099   if (needTrim)
1100     fgic->SetMachIC(mach);
1101   else {
1102     double temp = 1.8*(temperature->getDoubleValue()+273.15);
1103     double soundSpeed = sqrt(1.4*1716.0*temp);
1104     FGColumnVector3 vUVW = Propagate->GetUVW();
1105     vUVW.Normalize();
1106     vUVW *= mach * soundSpeed;
1107     Propagate->SetUVW(1, vUVW(1));
1108     Propagate->SetUVW(2, vUVW(2));
1109     Propagate->SetUVW(3, vUVW(3));
1110   }
1111
1112   FGInterface::set_Mach_number(mach);
1113 }
1114
1115 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1116 {
1117   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1118      << north << ", " <<  east << ", " << down );
1119
1120   if (needTrim) {
1121     fgic->SetVNorthFpsIC(north);
1122     fgic->SetVEastFpsIC(east);
1123     fgic->SetVDownFpsIC(down);
1124   }
1125   else {
1126     FGColumnVector3 vNED(north, east, down);
1127     FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1128     Propagate->SetUVW(1, vUVW(1));
1129     Propagate->SetUVW(2, vUVW(2));
1130     Propagate->SetUVW(3, vUVW(3));
1131   }
1132
1133   FGInterface::set_Velocities_Local(north, east, down);
1134 }
1135
1136 void FGJSBsim::set_Velocities_Body( double u, double v, double w)
1137 {
1138   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Body: "
1139      << u << ", " <<  v << ", " <<  w );
1140
1141   if (needTrim) {
1142     fgic->SetUBodyFpsIC(u);
1143     fgic->SetVBodyFpsIC(v);
1144     fgic->SetWBodyFpsIC(w);
1145   }
1146   else {
1147     Propagate->SetUVW(1, u);
1148     Propagate->SetUVW(2, v);
1149     Propagate->SetUVW(3, w);
1150   }
1151
1152   FGInterface::set_Velocities_Body(u, v, w);
1153 }
1154
1155 //Euler angles
1156 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1157 {
1158   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1159      << phi << ", " << theta << ", " << psi );
1160
1161   if (needTrim) {
1162     fgic->SetThetaRadIC(theta);
1163     fgic->SetPhiRadIC(phi);
1164     fgic->SetPsiRadIC(psi);
1165   }
1166   else {
1167     FGQuaternion quat(phi, theta, psi);
1168     FGMatrix33 Tl2b = quat.GetT();
1169     FGMatrix33 Ti2b = Tl2b*Propagate->GetTi2l();
1170     FGQuaternion Qi = Ti2b.GetQuaternion();
1171     Propagate->SetInertialOrientation(Qi);
1172   }
1173
1174   FGInterface::set_Euler_Angles(phi, theta, psi);
1175 }
1176
1177 //Flight Path
1178 void FGJSBsim::set_Climb_Rate( double roc)
1179 {
1180   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1181
1182   //since both climb rate and flight path angle are set in the FG
1183   //startup sequence, something is needed to keep one from cancelling
1184   //out the other.
1185   if( fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01 ) {
1186     if (needTrim)
1187       fgic->SetClimbRateFpsIC(roc);
1188     else {
1189       FGColumnVector3 vNED = Propagate->GetVel();
1190       vNED(FGJSBBase::eDown) = -roc;
1191       FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1192       Propagate->SetUVW(1, vUVW(1));
1193       Propagate->SetUVW(2, vUVW(2));
1194       Propagate->SetUVW(3, vUVW(3));
1195     }
1196
1197     FGInterface::set_Climb_Rate(roc);
1198   }
1199 }
1200
1201 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1202 {
1203   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1204
1205   if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1206     if (needTrim)
1207       fgic->SetFlightPathAngleRadIC(gamma);
1208     else {
1209       FGColumnVector3 vNED = Propagate->GetVel();
1210       double vt = vNED.Magnitude();
1211       vNED(FGJSBBase::eDown) = -vt * sin(gamma);
1212       FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1213       Propagate->SetUVW(1, vUVW(1));
1214       Propagate->SetUVW(2, vUVW(2));
1215       Propagate->SetUVW(3, vUVW(3));
1216     }
1217
1218     FGInterface::set_Gamma_vert_rad(gamma);
1219   }
1220 }
1221
1222 void FGJSBsim::init_gear(void )
1223 {
1224     FGGroundReactions* gr=fdmex->GetGroundReactions();
1225     int Ngear=GroundReactions->GetNumGearUnits();
1226     for (int i=0;i<Ngear;i++) {
1227       FGLGear *gear = gr->GetGearUnit(i);
1228       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1229       node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1) * 12);
1230       node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2) * 12);
1231       node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3) * 12);
1232       node->setBoolValue("wow", gear->GetWOW());
1233       node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1234       node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1235       node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1236 //    node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1237       node->setDoubleValue("compression-norm", gear->GetCompLen());
1238       node->setDoubleValue("compression-ft", gear->GetCompLen());
1239       if ( gear->GetSteerable() )
1240         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1241     }
1242 }
1243
1244 void FGJSBsim::update_gear(void)
1245 {
1246     FGGroundReactions* gr=fdmex->GetGroundReactions();
1247     int Ngear=GroundReactions->GetNumGearUnits();
1248     for (int i=0;i<Ngear;i++) {
1249       FGLGear *gear = gr->GetGearUnit(i);
1250       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1251       node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1252       node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1253       node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1254 //    gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1255       node->setDoubleValue("compression-norm", gear->GetCompLen());
1256       node->setDoubleValue("compression-ft", gear->GetCompLen());
1257       if ( gear->GetSteerable() )
1258         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1259     }
1260 }
1261
1262 void FGJSBsim::do_trim(void)
1263 {
1264   FGTrim *fgtrim;
1265
1266   if ( fgGetBool("/sim/presets/onground") )
1267   {
1268     fgtrim = new FGTrim(fdmex,tGround);
1269   } else {
1270     fgtrim = new FGTrim(fdmex,tFull);
1271   }
1272
1273   if ( !fgtrim->DoTrim() ) {
1274     fgtrim->Report();
1275     fgtrim->TrimStats();
1276   } else {
1277     trimmed->setBoolValue(true);
1278   }
1279   delete fgtrim;
1280
1281   pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1282   throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1283   aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1284   rudder_trim->setDoubleValue( -FCS->GetDrCmd() );
1285
1286   globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1287   globals->get_controls()->set_elevator(FCS->GetDeCmd());
1288   for( unsigned i = 0; i < Propulsion->GetNumEngines(); i++ )
1289     globals->get_controls()->set_throttle(i, FCS->GetThrottleCmd(i));
1290
1291   globals->get_controls()->set_aileron(FCS->GetDaCmd());
1292   globals->get_controls()->set_rudder( -FCS->GetDrCmd());
1293
1294   SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
1295 }
1296
1297 bool FGJSBsim::update_ground_cache(const FGLocation& cart, double* cart_pos,
1298                                    double dt)
1299 {
1300   // Compute the radius of the aircraft. That is the radius of a ball
1301   // where all gear units are in. At the moment it is at least 10ft ...
1302   double acrad = 10.0;
1303   int n_gears = GroundReactions->GetNumGearUnits();
1304   for (int i=0; i<n_gears; ++i) {
1305     FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
1306     double r = bl.Magnitude();
1307     if (acrad < r)
1308       acrad = r;
1309   }
1310
1311   // Compute the potential movement of this aircraft and query for the
1312   // ground in this area.
1313   double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
1314   cart_pos[0] = cart(1);
1315   cart_pos[1] = cart(2);
1316   cart_pos[2] = cart(3);
1317   double t0 = fdmex->GetSimTime();
1318   bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
1319                                            groundCacheRadius );
1320   if (!cache_ok) {
1321     SG_LOG(SG_FLIGHT, SG_WARN,
1322            "FGInterface is being called without scenery below the aircraft!");
1323
1324     SG_LOG(SG_FLIGHT, SG_WARN, "altitude         = "
1325                       << fgic->GetAltitudeASLFtIC());
1326
1327     SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = "
1328                       << get_Sea_level_radius());
1329
1330     SG_LOG(SG_FLIGHT, SG_WARN, "latitude         = "
1331                       << fgic->GetLatitudeRadIC());
1332
1333     SG_LOG(SG_FLIGHT, SG_WARN, "longitude        = "
1334                       << fgic->GetLongitudeRadIC());
1335   }
1336
1337   return cache_ok;
1338 }
1339
1340 bool
1341 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1342                      double contact[3], double normal[3], double vel[3],
1343                      double angularVel[3], double *agl)
1344 {
1345   const simgear::BVHMaterial* material;
1346   simgear::BVHNode::Id id;
1347
1348   // don't check the return value and continue above scenery discontinuity
1349   // see http://osdir.com/ml/flightgear-sim/2014-04/msg00145.html
1350   FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1351                                angularVel, material, id);
1352
1353   SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1354   SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1355   *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1356
1357 #ifdef JSBSIM_USE_GROUNDREACTIONS
1358   bool terrain_active = (terrain->getIntValue("override-level", -1) > 0) ? false : true;
1359   terrain->setBoolValue("active", terrain_active);
1360   terrain->setBoolValue("valid", (material && terrain_active) ? true : false);
1361   if (terrain_active)
1362   {
1363     static bool material_valid = false;
1364     if (material) {
1365       GroundReactions->SetStaticFFactor((*material).get_friction_factor());
1366       GroundReactions->SetRollingFFactor((*material).get_rolling_friction()/0.02);
1367       // 1 Pascal = 0.00014503773800721815 lbs/in^2
1368       double pressure = (*material).get_load_resistance(); // N/m^2 (or Pascal)
1369       GroundReactions->SetMaximumForce(pressure*0.00014503773800721815);
1370
1371       GroundReactions->SetBumpiness((*material).get_bumpiness());
1372       GroundReactions->SetSolid((*material).get_solid());
1373       GroundReactions->SetPosition(pt);
1374       material_valid = true;
1375     } else {
1376        if (material_valid) {
1377          GroundReactions->resetValues();
1378          material_valid = false;
1379       }
1380     }
1381   }
1382 #else
1383   terrain->setBoolValue("valid", false);
1384 #endif
1385   return true;
1386 }
1387
1388 inline static double sqr(double x)
1389 {
1390     return x * x;
1391 }
1392
1393 static double angle_diff(double a, double b)
1394 {
1395     double diff = fabs(a - b);
1396     if (diff > 180) diff = 360 - diff;
1397     
1398     return diff;
1399 }
1400
1401 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double cos_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1402 {
1403     FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1404     double dist = DotProduct(tip, ground_normal_body);
1405     if (fabs(dist + E) < 0.0001) {
1406         sin_fis[*points] = sin_fi_guess;
1407         cos_fis[*points] = cos_fi_guess;
1408         fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1409         (*points)++;
1410     } 
1411 }
1412
1413
1414 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1415 {
1416     if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1417         double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1418         check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1419         if (fabs(cos_fi_guess) > SG_EPSILON) {
1420             check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1421         }
1422     }
1423 }
1424
1425 void FGJSBsim::update_external_forces(double t_off)
1426 {
1427     const FGMatrix33& Tb2l = Propagate->GetTb2l();
1428     const FGMatrix33& Tl2b = Propagate->GetTl2b();
1429     const FGLocation& Location = Propagate->GetLocation();
1430     const FGMatrix33& Tec2l = Location.GetTec2l();
1431         
1432     double hook_area[4][3];
1433     
1434     FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1435     FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l *   hook_root_body);
1436     hook_area[1][0] = hook_root(1);
1437     hook_area[1][1] = hook_root(2);
1438     hook_area[1][2] = hook_root(3);
1439     
1440     hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1441     double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1442     double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1443     double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1444     double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1445     double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1446
1447     FGColumnVector3 hook_tip_body = hook_root_body;
1448     hook_tip_body(1) -= hook_length * cos_fi;
1449     hook_tip_body(3) += hook_length * sin_fi;    
1450     
1451     double contact[3];
1452     double ground_normal[3];
1453     double ground_vel[3];
1454     double ground_angular_vel[3];
1455     double root_agl_ft;
1456
1457     if (!got_wire) {
1458         bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1459                               ground_vel, ground_angular_vel, &root_agl_ft);
1460         if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1461             FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1462             FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1463             double D = -DotProduct(contact_body, ground_normal_body);
1464
1465             // check hook tip agl against same ground plane
1466             double hook_tip_agl_ft = DotProduct(hook_tip_body, ground_normal_body) + D;
1467             if (hook_tip_agl_ft < 0) {
1468
1469                 // hook tip: hx - l cos, hy, hz + l sin
1470                 // on ground:  - n0 l cos + n2 l sin + E = 0
1471
1472                 double E = D + DotProduct(hook_root_body, ground_normal_body);
1473
1474                 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1475                 // and rearrange to get a quadratic with coeffs:
1476                 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1477                 double b = 2 * E * ground_normal_body(3) * hook_length;
1478                 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);   
1479
1480                 double disc = sqr(b) - 4 * a * c;
1481                 if (disc >= 0) {
1482                     double delta = sqrt(disc) / (2 * a);
1483                 
1484                     // allow 4 solutions for safety, should never happen
1485                     double sin_fis[4];
1486                     double cos_fis[4];
1487                     double fis[4];
1488                     int points = 0;
1489                 
1490                     double sin_fi_guess = -b / (2 * a) - delta;
1491                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1492                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1493                 
1494                     if (points == 2) {
1495                         double diff1 = angle_diff(fi, fis[0]);
1496                         double diff2 = angle_diff(fi, fis[1]);
1497                         int point = diff1 < diff2 ? 0 : 1;
1498                         fi = fis[point];
1499                         sin_fi = sin_fis[point];
1500                         cos_fi = cos_fis[point];
1501                         hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1502                         hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1503                     }
1504                 }
1505             }
1506         }
1507     } else {
1508         FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() *  hook_root_body));
1509         double wire_ends_ec[2][3];
1510         double wire_vel_ec[2][3];
1511         get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1512         FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1513         FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1514         FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1515         if (rel_vel.Magnitude() < 3) {
1516             got_wire = false;
1517             release_wire();
1518             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1519         } else {
1520             FGColumnVector3 wire_end1_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[0][0], wire_ends_ec[0][1], wire_ends_ec[0][2])) - hook_root_body;
1521             FGColumnVector3 wire_end2_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[1][0], wire_ends_ec[1][1], wire_ends_ec[1][2])) - hook_root_body;
1522             FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1523             force_plane_normal.Normalize();
1524             cos_fi = DotProduct(force_plane_normal, FGColumnVector3(0, 0, 1));
1525             if (cos_fi < 0) cos_fi = -cos_fi;
1526             sin_fi = sqrt(1 - sqr(cos_fi));
1527             fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1528         
1529             fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1530             fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1531             fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1532             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1533         }
1534     }
1535
1536     FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1537
1538     hook_area[0][0] = hook_tip(1);
1539     hook_area[0][1] = hook_tip(2);
1540     hook_area[0][2] = hook_tip(3);
1541
1542     if (!got_wire) {
1543         // The previous positions.
1544         hook_area[2][0] = last_hook_root[0];
1545         hook_area[2][1] = last_hook_root[1];
1546         hook_area[2][2] = last_hook_root[2];
1547         hook_area[3][0] = last_hook_tip[0];
1548         hook_area[3][1] = last_hook_tip[1];
1549         hook_area[3][2] = last_hook_tip[2];
1550
1551         // Check if we caught a wire.
1552         // Returns true if we caught one.
1553         if (caught_wire_ft(t_off, hook_area)) {
1554                 got_wire = true;
1555         }
1556     }
1557     
1558     // save actual position as old position ...
1559     last_hook_tip[0] = hook_area[0][0];
1560     last_hook_tip[1] = hook_area[0][1];
1561     last_hook_tip[2] = hook_area[0][2];
1562     last_hook_root[0] = hook_area[1][0];
1563     last_hook_root[1] = hook_area[1][1];
1564     last_hook_root[2] = hook_area[1][2];
1565     
1566     fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);
1567 }
1568