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