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