1 // JSBsim.cxx -- interface to the JSBsim flight model
3 // Written by Curtis Olson, started February 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include <simgear/compiler.h>
30 #include <stdio.h> // size_t
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/structure/commands.hxx>
39 #include <FDM/flight.hxx>
41 #include <Aircraft/controls.hxx>
42 #include <Main/globals.hxx>
43 #include <Main/fg_props.hxx>
46 #include <FDM/JSBSim/FGFDMExec.h>
47 #include <FDM/JSBSim/FGJSBBase.h>
48 #include <FDM/JSBSim/FGState.h>
49 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
50 #include <FDM/JSBSim/initialization/FGTrim.h>
51 #include <FDM/JSBSim/models/FGModel.h>
52 #include <FDM/JSBSim/models/FGAircraft.h>
53 #include <FDM/JSBSim/models/FGFCS.h>
54 #include <FDM/JSBSim/models/FGPropagate.h>
55 #include <FDM/JSBSim/models/FGAuxiliary.h>
56 #include <FDM/JSBSim/models/FGInertial.h>
57 #include <FDM/JSBSim/models/FGAtmosphere.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/propulsion/FGEngine.h>
62 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
63 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
64 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
65 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
66 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
67 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
68 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
69 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
70 #include <FDM/JSBSim/models/propulsion/FGTank.h>
71 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
72 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
74 using namespace JSBSim;
77 FMAX (double a, double b)
82 class FGFSGroundCallback : public FGGroundCallback {
84 FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
85 virtual ~FGFSGroundCallback() {}
87 /** Get the altitude above sea level dependent on the location. */
88 virtual double GetAltitude(const FGLocation& l) const {
89 double pt[3] = { SG_FEET_TO_METER*l(eX),
90 SG_FEET_TO_METER*l(eY),
91 SG_FEET_TO_METER*l(eZ) };
93 sgCartToGeod( pt, &lat, &lon, &alt);
94 return alt * SG_METER_TO_FEET;
97 /** Compute the altitude above ground. */
98 virtual double GetAGLevel(double t, const FGLocation& l,
100 FGColumnVector3& n, FGColumnVector3& v) const {
101 double loc_cart[3] = { l(eX), l(eY), l(eZ) };
102 double contact[3], normal[3], vel[3], agl = 0;
103 mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
105 n = FGColumnVector3( -normal[0], -normal[1], -normal[2] );
106 v = FGColumnVector3( vel[0], vel[1], vel[2] );
107 cont = FGColumnVector3( contact[0], contact[1], contact[2] );
111 FGJSBsim* mInterface;
114 /******************************************************************************/
116 FGJSBsim::FGJSBsim( double dt )
117 : FGInterface(dt), got_wire(false)
120 // Set up the debugging level
121 // FIXME: this will not respond to
124 // if flight is excluded, don't bother
125 if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
127 // do a rough-and-ready mapping to
128 // the levels documented in FGFDMExec.h
129 switch (logbuf::get_log_priority()) {
131 FGJSBBase::debug_lvl = 0x1f;
134 FGJSBBase::debug_lvl = 0x0f;
136 FGJSBBase::debug_lvl = 0x01;
140 FGJSBBase::debug_lvl = 0x00;
145 fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
147 // Register ground callback.
148 fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
150 State = fdmex->GetState();
151 Atmosphere = fdmex->GetAtmosphere();
152 FCS = fdmex->GetFCS();
153 MassBalance = fdmex->GetMassBalance();
154 Propulsion = fdmex->GetPropulsion();
155 Aircraft = fdmex->GetAircraft();
156 Propagate = fdmex->GetPropagate();
157 Auxiliary = fdmex->GetAuxiliary();
158 Inertial = fdmex->GetInertial();
159 Aerodynamics = fdmex->GetAerodynamics();
160 GroundReactions = fdmex->GetGroundReactions();
165 SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
167 SGPath engine_path( fgGetString("/sim/aircraft-dir") );
168 engine_path.append( "Engine" );
170 SGPath systems_path( fgGetString("/sim/aircraft-dir") );
171 systems_path.append( "Systems" );
175 result = fdmex->LoadModel( aircraft_path.str(),
178 fgGetString("/sim/aero"), false );
181 SG_LOG( SG_FLIGHT, SG_INFO, " loaded aero.");
183 SG_LOG( SG_FLIGHT, SG_INFO,
184 " aero does not exist (you may have mis-typed the name).");
188 SG_LOG( SG_FLIGHT, SG_INFO, "" );
189 SG_LOG( SG_FLIGHT, SG_INFO, "" );
190 SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
192 int Neng = Propulsion->GetNumEngines();
193 SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
195 if ( GroundReactions->GetNumGearUnits() <= 0 ) {
196 SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
197 << GroundReactions->GetNumGearUnits() );
198 SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
199 SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
200 SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
206 // Set initial fuel levels if provided.
207 for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
208 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
209 if (node->getChild("level-gal_us", 0, false) != 0) {
210 Propulsion->GetTank(i)->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
212 node->setDoubleValue("level-lbs", Propulsion->GetTank(i)->GetContents());
213 node->setDoubleValue("level-gal_us", Propulsion->GetTank(i)->GetContents() / 6.6);
215 node->setDoubleValue("capacity-gal_us",
216 Propulsion->GetTank(i)->GetCapacity() / 6.6);
218 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
220 fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
221 fgSetDouble("/fdm/trim/throttle", FCS->GetThrottleCmd(0));
222 fgSetDouble("/fdm/trim/aileron", FCS->GetDaCmd());
223 fgSetDouble("/fdm/trim/rudder", FCS->GetDrCmd());
225 startup_trim = fgGetNode("/sim/presets/trim", true);
227 trimmed = fgGetNode("/fdm/trim/trimmed", true);
228 trimmed->setBoolValue(false);
230 pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
231 throttle_trim = fgGetNode("/fdm/trim/throttle", true );
232 aileron_trim = fgGetNode("/fdm/trim/aileron", true );
233 rudder_trim = fgGetNode("/fdm/trim/rudder", true );
235 stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
236 stall_warning->setDoubleValue(0);
239 flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
240 elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
242 =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
243 right_aileron_pos_pct
244 =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
245 rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
247 =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
248 spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
249 tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
250 wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
252 elevator_pos_pct->setDoubleValue(0);
253 left_aileron_pos_pct->setDoubleValue(0);
254 right_aileron_pos_pct->setDoubleValue(0);
255 rudder_pos_pct->setDoubleValue(0);
256 flap_pos_pct->setDoubleValue(0);
257 speedbrake_pos_pct->setDoubleValue(0);
258 spoilers_pos_pct->setDoubleValue(0);
260 temperature = fgGetNode("/environment/temperature-degc",true);
261 pressure = fgGetNode("/environment/pressure-inhg",true);
262 density = fgGetNode("/environment/density-slugft3",true);
263 turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
264 turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
266 wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
267 wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
268 wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
270 slaved = fgGetNode("/sim/slaved/enabled", true);
272 for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
273 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
274 Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
275 Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
278 hook_root_struct = FGColumnVector3(
279 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
280 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
281 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
286 /******************************************************************************/
287 FGJSBsim::~FGJSBsim(void)
292 /******************************************************************************/
294 // Initialize the JSBsim flight model, dt is the time increment for
295 // each subsequent iteration through the EOM
297 void FGJSBsim::init()
301 SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
303 // Explicitly call the superclass's
304 // init method first.
306 if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
307 Atmosphere->UseExternal();
308 Atmosphere->SetExTemperature(
309 9.0/5.0*(temperature->getDoubleValue()+273.15) );
310 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
311 Atmosphere->SetExDensity(density->getDoubleValue());
312 Atmosphere->SetTurbType(FGAtmosphere::ttCulp);
313 Atmosphere->SetTurbGain(turbulence_gain->getDoubleValue());
314 Atmosphere->SetTurbRate(turbulence_rate->getDoubleValue());
317 Atmosphere->UseInternal();
320 fgic->SetVNorthFpsIC( -wind_from_north->getDoubleValue() );
321 fgic->SetVEastFpsIC( -wind_from_east->getDoubleValue() );
322 fgic->SetVDownFpsIC( -wind_from_down->getDoubleValue() );
324 //Atmosphere->SetExTemperature(get_Static_temperature());
325 //Atmosphere->SetExPressure(get_Static_pressure());
326 //Atmosphere->SetExDensity(get_Density());
327 SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
328 << ", " << fdmex->GetAtmosphere()->GetPressure()
329 << ", " << fdmex->GetAtmosphere()->GetDensity() );
331 if (fgGetBool("/sim/presets/running")) {
332 for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) {
333 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
334 node->setBoolValue("running", true);
335 Propulsion->GetEngine(i)->SetRunning(true);
339 FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
344 fdmex->RunIC(); //loop JSBSim once w/o integrating
345 copy_from_JSBsim(); //update the bus
347 SG_LOG( SG_FLIGHT, SG_INFO, " Initialized JSBSim with:" );
349 switch(fgic->GetSpeedSet()) {
351 SG_LOG(SG_FLIGHT,SG_INFO, " Vn,Ve,Vd= "
352 << Propagate->GetVel(FGJSBBase::eNorth) << ", "
353 << Propagate->GetVel(FGJSBBase::eEast) << ", "
354 << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
357 SG_LOG(SG_FLIGHT,SG_INFO, " U,V,W= "
358 << Propagate->GetUVW(1) << ", "
359 << Propagate->GetUVW(2) << ", "
360 << Propagate->GetUVW(3) << " ft/s");
363 SG_LOG(SG_FLIGHT,SG_INFO, " Mach: "
364 << Auxiliary->GetMach() );
368 SG_LOG(SG_FLIGHT,SG_INFO, " Indicated Airspeed: "
369 << Auxiliary->GetVcalibratedKTS() << " knots" );
373 stall_warning->setDoubleValue(0);
375 SG_LOG( SG_FLIGHT, SG_INFO, " Bank Angle: "
376 << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
377 SG_LOG( SG_FLIGHT, SG_INFO, " Pitch Angle: "
378 << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
379 SG_LOG( SG_FLIGHT, SG_INFO, " True Heading: "
380 << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
381 SG_LOG( SG_FLIGHT, SG_INFO, " Latitude: "
382 << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
383 SG_LOG( SG_FLIGHT, SG_INFO, " Longitude: "
384 << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
385 SG_LOG( SG_FLIGHT, SG_INFO, " Altitude: "
386 << Propagate->GetAltitudeASL() << " feet" );
387 SG_LOG( SG_FLIGHT, SG_INFO, " loaded initial conditions" );
389 SG_LOG( SG_FLIGHT, SG_INFO, " set dt" );
391 SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
393 SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
394 globals->get_controls()->get_gear_down() );
397 /******************************************************************************/
399 // Run an iteration of the EOM (equations of motion)
401 void FGJSBsim::update( double dt )
404 if(!fgGetBool("/sim/crashed"))
405 fgSetBool("/sim/crashed", true);
412 int multiloop = _calc_multiloop(dt);
416 // Compute the radius of the aircraft. That is the radius of a ball
417 // where all gear units are in. At the moment it is at least 10ft ...
419 int n_gears = GroundReactions->GetNumGearUnits();
420 for (i=0; i<n_gears; ++i) {
421 FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
422 double r = bl.Magnitude();
427 // Compute the potential movement of this aircraft and query for the
428 // ground in this area.
429 double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
430 double alt, slr, lat, lon;
431 FGColumnVector3 cart = Auxiliary->GetLocationVRP();
432 if ( needTrim && startup_trim->getBoolValue() ) {
433 alt = fgic->GetAltitudeASLFtIC();
434 slr = fgic->GetSeaLevelRadiusFtIC();
435 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
436 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
437 cart = FGLocation(lon, lat, alt+slr);
439 double cart_pos[3] = { cart(1), cart(2), cart(3) };
440 double t0 = State->Getsim_time();
441 bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
444 SG_LOG(SG_FLIGHT, SG_WARN,
445 "FGInterface is being called without scenery below the aircraft!");
447 alt = fgic->GetAltitudeASLFtIC();
448 SG_LOG(SG_FLIGHT, SG_WARN, "altitude = " << alt);
450 slr = fgic->GetSeaLevelRadiusFtIC();
451 SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = " << slr);
453 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
454 SG_LOG(SG_FLIGHT, SG_WARN, "latitude = " << lat);
456 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
457 SG_LOG(SG_FLIGHT, SG_WARN, "longitude = " << lon);
463 trimmed->setBoolValue(false);
466 if ( startup_trim->getBoolValue() ) {
467 double contact[3], d[3], agl;
468 get_agl_ft(State->Getsim_time(), cart_pos, SG_METER_TO_FEET*2, contact,
470 double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
471 + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
473 SG_LOG(SG_FLIGHT, SG_INFO,
474 "Ready to trim, terrain elevation is: "
475 << terrain_alt * SG_METER_TO_FEET );
477 fgic->SetTerrainElevationFtIC( terrain_alt );
480 fdmex->RunIC(); //apply any changes made through the set_ functions
485 for ( i=0; i < multiloop; i++ ) {
487 update_external_forces(State->Getsim_time() + i * State->Getdt());
490 FGJSBBase::Message* msg;
491 while (msg = fdmex->ProcessNextMessage()) {
492 // msg = fdmex->ProcessNextMessage();
494 case FGJSBBase::Message::eText:
495 if (msg->text == "Crash Detected: Simulation FREEZE.")
497 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
499 case FGJSBBase::Message::eBool:
500 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
502 case FGJSBBase::Message::eInteger:
503 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
505 case FGJSBBase::Message::eDouble:
506 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
509 SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
514 // translate JSBsim back to FG structure so that the
515 // autopilot (and the rest of the sim can use the updated values
519 /******************************************************************************/
521 // Convert from the FGInterface struct to the JSBsim generic_ struct
523 bool FGJSBsim::copy_to_JSBsim()
528 // copy control positions into the JSBsim structure
530 FCS->SetDaCmd( globals->get_controls()->get_aileron());
531 FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
532 FCS->SetDeCmd( globals->get_controls()->get_elevator());
533 FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
534 FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
535 FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
536 FCS->SetDsCmd( globals->get_controls()->get_rudder() );
537 FCS->SetDfCmd( globals->get_controls()->get_flaps() );
538 FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
539 FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
541 // Parking brake sets minimum braking
543 double parking_brake = globals->get_controls()->get_brake_parking();
544 double left_brake = globals->get_controls()->get_brake_left();
545 double right_brake = globals->get_controls()->get_brake_right();
546 FCS->SetLBrake(FMAX(left_brake, parking_brake));
547 FCS->SetRBrake(FMAX(right_brake, parking_brake));
550 FCS->SetCBrake( 0.0 );
551 // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
553 FCS->SetGearCmd( globals->get_controls()->get_gear_down());
554 for (i = 0; i < Propulsion->GetNumEngines(); i++) {
555 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
557 FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
558 FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
559 FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
560 FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
562 switch (Propulsion->GetEngine(i)->GetType()) {
563 case FGEngine::etPiston:
564 { // FGPiston code block
565 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
566 eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
568 } // end FGPiston code block
569 case FGEngine::etTurbine:
570 { // FGTurbine code block
571 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
572 eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
573 eng->SetReverse( globals->get_controls()->get_reverser(i) );
574 //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
575 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
576 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
578 } // end FGTurbine code block
579 case FGEngine::etRocket:
580 { // FGRocket code block
581 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
583 } // end FGRocket code block
584 case FGEngine::etTurboprop:
585 { // FGTurboProp code block
586 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
587 eng->SetReverse( globals->get_controls()->get_reverser(i) );
588 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
589 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
591 eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
592 eng->SetCondition( globals->get_controls()->get_condition(i) );
594 } // end FGTurboProp code block
599 { // FGEngine code block
600 FGEngine* eng = Propulsion->GetEngine(i);
602 eng->SetStarter( globals->get_controls()->get_starter(i) );
603 eng->SetRunning( node->getBoolValue("running") );
604 } // end FGEngine code block
608 Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
610 Atmosphere->SetExTemperature(
611 9.0/5.0*(temperature->getDoubleValue()+273.15) );
612 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
613 Atmosphere->SetExDensity(density->getDoubleValue());
615 tmp = turbulence_gain->getDoubleValue();
616 //Atmosphere->SetTurbGain(tmp * tmp * 100.0);
618 tmp = turbulence_rate->getDoubleValue();
619 //Atmosphere->SetTurbRate(tmp);
621 Atmosphere->SetWindNED( -wind_from_north->getDoubleValue(),
622 -wind_from_east->getDoubleValue(),
623 -wind_from_down->getDoubleValue() );
624 // SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
625 // << get_V_north_airmass() << ", "
626 // << get_V_east_airmass() << ", "
627 // << get_V_down_airmass() );
629 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
630 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
631 FGTank * tank = Propulsion->GetTank(i);
632 tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
633 // tank->SetContents(node->getDoubleValue("level-lbs"));
636 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
637 fdmex->SetChild(slaved->getBoolValue());
642 /******************************************************************************/
644 // Convert from the JSBsim generic_ struct to the FGInterface struct
646 bool FGJSBsim::copy_from_JSBsim()
650 _set_Inertias( MassBalance->GetMass(),
651 MassBalance->GetIxx(),
652 MassBalance->GetIyy(),
653 MassBalance->GetIzz(),
654 MassBalance->GetIxz() );
656 _set_CG_Position( MassBalance->GetXYZcg(1),
657 MassBalance->GetXYZcg(2),
658 MassBalance->GetXYZcg(3) );
660 _set_Accels_Body( Aircraft->GetBodyAccel(1),
661 Aircraft->GetBodyAccel(2),
662 Aircraft->GetBodyAccel(3) );
664 _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
666 Aircraft->GetNcg(3) );
668 _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
669 Auxiliary->GetPilotAccel(2),
670 Auxiliary->GetPilotAccel(3) );
672 _set_Nlf( Aircraft->GetNlf() );
676 _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
677 Propagate->GetVel(FGJSBBase::eEast),
678 Propagate->GetVel(FGJSBBase::eDown) );
680 _set_Velocities_Wind_Body( Propagate->GetUVW(1),
681 Propagate->GetUVW(2),
682 Propagate->GetUVW(3) );
684 // Make the HUD work ...
685 _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
686 Propagate->GetVel(FGJSBBase::eEast),
687 -Propagate->GetVel(FGJSBBase::eDown) );
689 _set_V_rel_wind( Auxiliary->GetVt() );
691 _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
693 _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
695 _set_V_ground_speed( Auxiliary->GetVground() );
697 _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
698 Propagate->GetPQR(FGJSBBase::eQ),
699 Propagate->GetPQR(FGJSBBase::eR) );
701 _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
702 Auxiliary->GetEulerRates(FGJSBBase::eTht),
703 Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
705 _set_Mach_number( Auxiliary->GetMach() );
707 // Positions of Visual Reference Point
708 FGLocation l = Auxiliary->GetLocationVRP();
709 _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
710 l.GetRadius() - get_Sea_level_radius() );
712 _set_Altitude_AGL( Propagate->GetDistanceAGL() );
714 double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
715 double contact[3], d[3], sd, t;
716 is_valid_m(&t, d, &sd);
717 get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, &sd);
719 = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
720 _set_Runway_altitude( rwrad - get_Sea_level_radius() );
723 _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
724 Propagate->GetEuler(FGJSBBase::eTht),
725 Propagate->GetEuler(FGJSBBase::ePsi) );
727 _set_Alpha( Auxiliary->Getalpha() );
728 _set_Beta( Auxiliary->Getbeta() );
731 _set_Gamma_vert_rad( Auxiliary->GetGamma() );
733 _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
735 _set_Climb_Rate( Propagate->Gethdot() );
737 const FGMatrix33& Tl2b = Propagate->GetTl2b();
738 for ( i = 1; i <= 3; i++ ) {
739 for ( j = 1; j <= 3; j++ ) {
740 _set_T_Local_to_Body( i, j, Tl2b(i,j) );
744 // Copy the engine values from JSBSim.
745 for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
746 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
747 SGPropertyNode * tnode = node->getChild("thruster", 0, true);
748 FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
750 switch (Propulsion->GetEngine(i)->GetType()) {
751 case FGEngine::etPiston:
752 { // FGPiston code block
753 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
754 node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
755 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
756 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
757 node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
758 // NOTE: mp-osi is not in ounces per square inch.
759 // This error is left for reasons of backwards compatibility with
760 // existing FlightGear sound and instrument configurations.
761 node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
762 node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
763 node->setDoubleValue("rpm", eng->getRPM());
764 } // end FGPiston code block
766 case FGEngine::etRocket:
767 { // FGRocket code block
768 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
769 } // end FGRocket code block
771 case FGEngine::etTurbine:
772 { // FGTurbine code block
773 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
774 node->setDoubleValue("n1", eng->GetN1());
775 node->setDoubleValue("n2", eng->GetN2());
776 node->setDoubleValue("egt_degf", 32 + eng->GetEGT()*9/5);
777 node->setBoolValue("augmentation", eng->GetAugmentation());
778 node->setBoolValue("water-injection", eng->GetInjection());
779 node->setBoolValue("ignition", eng->GetIgnition());
780 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
781 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
782 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
783 node->setBoolValue("reversed", eng->GetReversed());
784 node->setBoolValue("cutoff", eng->GetCutoff());
785 node->setDoubleValue("epr", eng->GetEPR());
786 globals->get_controls()->set_reverser(i, eng->GetReversed() );
787 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
788 globals->get_controls()->set_water_injection(i, eng->GetInjection() );
789 globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
790 } // end FGTurbine code block
792 case FGEngine::etTurboprop:
793 { // FGTurboProp code block
794 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
795 node->setDoubleValue("n1", eng->GetN1());
796 //node->setDoubleValue("n2", eng->GetN2());
797 node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
798 node->setBoolValue("ignition", eng->GetIgnition());
799 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
800 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
801 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
802 node->setBoolValue("reversed", eng->GetReversed());
803 node->setBoolValue("cutoff", eng->GetCutoff());
804 node->setBoolValue("starting", eng->GetEngStarting());
805 node->setBoolValue("generator-power", eng->GetGeneratorPower());
806 node->setBoolValue("damaged", eng->GetCondition());
807 node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
808 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
809 // node->setBoolValue("onfire", eng->GetFire());
810 globals->get_controls()->set_reverser(i, eng->GetReversed() );
811 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
812 } // end FGTurboProp code block
814 case FGEngine::etElectric:
815 { // FGElectric code block
816 FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
817 node->setDoubleValue("rpm", eng->getRPM());
818 } // end FGElectric code block
822 { // FGEngine code block
823 FGEngine* eng = Propulsion->GetEngine(i);
824 node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
825 node->setDoubleValue("thrust_lb", thruster->GetThrust());
826 node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
827 node->setBoolValue("running", eng->GetRunning());
828 node->setBoolValue("starter", eng->GetStarter());
829 node->setBoolValue("cranking", eng->GetCranking());
830 globals->get_controls()->set_starter(i, eng->GetStarter() );
831 } // end FGEngine code block
833 switch (thruster->GetType()) {
834 case FGThruster::ttNozzle:
835 { // FGNozzle code block
836 FGNozzle* noz = (FGNozzle*)thruster;
837 } // end FGNozzle code block
839 case FGThruster::ttPropeller:
840 { // FGPropeller code block
841 FGPropeller* prop = (FGPropeller*)thruster;
842 tnode->setDoubleValue("rpm", thruster->GetRPM());
843 tnode->setDoubleValue("pitch", prop->GetPitch());
844 tnode->setDoubleValue("torque", prop->GetTorque());
845 tnode->setBoolValue("feathered", prop->GetFeather());
846 } // end FGPropeller code block
848 case FGThruster::ttRotor:
849 { // FGRotor code block
850 FGRotor* rotor = (FGRotor*)thruster;
851 } // end FGRotor code block
853 case FGThruster::ttDirect:
854 { // Direct code block
855 } // end Direct code block
861 // Copy the fuel levels from JSBSim if fuel
862 // freeze not enabled.
863 if ( ! Propulsion->GetFuelFreeze() ) {
864 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
865 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
866 FGTank* tank = Propulsion->GetTank(i);
867 double contents = tank->GetContents();
868 double temp = tank->GetTemperature_degC();
869 node->setDoubleValue("level-gal_us", contents/6.6);
870 node->setDoubleValue("level-lbs", contents);
871 if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
877 stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
879 elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
880 left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
881 right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
882 rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
883 flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
884 speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
885 spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
886 tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
887 wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
889 // force a sim crashed if crashed (altitude AGL < 0)
890 if (get_Altitude_AGL() < -100.0) {
891 State->SuspendIntegration();
899 bool FGJSBsim::ToggleDataLogging(void)
901 // ToDo: handle this properly
902 fdmex->DisableOutput();
907 bool FGJSBsim::ToggleDataLogging(bool state)
910 fdmex->EnableOutput();
913 fdmex->DisableOutput();
920 void FGJSBsim::set_Latitude(double lat)
922 static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
924 double sea_level_radius_meters, lat_geoc;
926 // In case we're not trimming
927 FGInterface::set_Latitude(lat);
929 if ( altitude->getDoubleValue() > -9990 ) {
930 alt = altitude->getDoubleValue();
936 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
937 SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) = " << alt );
939 sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
940 &sea_level_radius_meters, &lat_geoc );
941 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
942 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
943 fgic->SetLatitudeRadIC( lat_geoc );
948 void FGJSBsim::set_Longitude(double lon)
950 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
952 // In case we're not trimming
953 FGInterface::set_Longitude(lon);
956 fgic->SetLongitudeRadIC( lon );
960 // Sets the altitude above sea level.
961 void FGJSBsim::set_Altitude(double alt)
963 static SGConstPropertyNode_ptr latitude = fgGetNode("/position/latitude-deg");
965 double sea_level_radius_meters,lat_geoc;
967 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
968 SG_LOG(SG_FLIGHT,SG_INFO, " lat (deg) = " << latitude->getDoubleValue() );
970 // In case we're not trimming
971 FGInterface::set_Altitude(alt);
974 sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
975 &sea_level_radius_meters, &lat_geoc);
976 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
977 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
978 SG_LOG(SG_FLIGHT, SG_INFO,
979 "Terrain elevation: " << FGInterface::get_Runway_altitude() * SG_METER_TO_FEET );
980 fgic->SetLatitudeRadIC( lat_geoc );
981 fgic->SetAltitudeASLFtIC(alt);
985 void FGJSBsim::set_V_calibrated_kts(double vc)
987 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " << vc );
989 // In case we're not trimming
990 FGInterface::set_V_calibrated_kts(vc);
993 fgic->SetVcalibratedKtsIC(vc);
997 void FGJSBsim::set_Mach_number(double mach)
999 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " << mach );
1001 // In case we're not trimming
1002 FGInterface::set_Mach_number(mach);
1005 fgic->SetMachIC(mach);
1009 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1011 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1012 << north << ", " << east << ", " << down );
1014 // In case we're not trimming
1015 FGInterface::set_Velocities_Local(north, east, down);
1018 fgic->SetVNorthFpsIC(north);
1019 fgic->SetVEastFpsIC(east);
1020 fgic->SetVDownFpsIC(down);
1024 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1026 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1027 << u << ", " << v << ", " << w );
1029 // In case we're not trimming
1030 FGInterface::set_Velocities_Wind_Body(u, v, w);
1033 fgic->SetUBodyFpsIC(u);
1034 fgic->SetVBodyFpsIC(v);
1035 fgic->SetWBodyFpsIC(w);
1040 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1042 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1043 << phi << ", " << theta << ", " << psi );
1045 // In case we're not trimming
1046 FGInterface::set_Euler_Angles(phi, theta, psi);
1049 fgic->SetThetaRadIC(theta);
1050 fgic->SetPhiRadIC(phi);
1051 fgic->SetPsiRadIC(psi);
1056 void FGJSBsim::set_Climb_Rate( double roc)
1058 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1060 // In case we're not trimming
1061 FGInterface::set_Climb_Rate(roc);
1064 //since both climb rate and flight path angle are set in the FG
1065 //startup sequence, something is needed to keep one from cancelling
1067 if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1068 fgic->SetClimbRateFpsIC(roc);
1073 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1075 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1078 if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1079 fgic->SetFlightPathAngleRadIC(gamma);
1084 void FGJSBsim::init_gear(void )
1086 FGGroundReactions* gr=fdmex->GetGroundReactions();
1087 int Ngear=GroundReactions->GetNumGearUnits();
1088 for (int i=0;i<Ngear;i++) {
1089 FGLGear *gear = gr->GetGearUnit(i);
1090 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1091 node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1092 node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1093 node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1094 node->setBoolValue("wow", gear->GetWOW());
1095 node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1096 node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1097 node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1098 node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1099 node->setDoubleValue("compression-norm", gear->GetCompLen());
1100 node->setDoubleValue("compression-ft", gear->GetCompLen());
1101 if ( gear->GetSteerable() )
1102 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1106 void FGJSBsim::update_gear(void)
1108 FGGroundReactions* gr=fdmex->GetGroundReactions();
1109 int Ngear=GroundReactions->GetNumGearUnits();
1110 for (int i=0;i<Ngear;i++) {
1111 FGLGear *gear = gr->GetGearUnit(i);
1112 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1113 node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1114 node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1115 node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1116 gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1117 node->setDoubleValue("compression-norm", gear->GetCompLen());
1118 node->setDoubleValue("compression-ft", gear->GetCompLen());
1119 if ( gear->GetSteerable() )
1120 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1124 void FGJSBsim::do_trim(void)
1128 if ( fgGetBool("/sim/presets/onground") )
1130 fgtrim = new FGTrim(fdmex,tGround);
1132 fgtrim = new FGTrim(fdmex,tLongitudinal);
1135 if ( !fgtrim->DoTrim() ) {
1137 fgtrim->TrimStats();
1139 trimmed->setBoolValue(true);
1141 // if (FGJSBBase::debug_lvl > 0)
1142 // State->ReportState();
1146 pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1147 throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1148 aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1149 rudder_trim->setDoubleValue( FCS->GetDrCmd() );
1151 globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1152 globals->get_controls()->set_elevator(FCS->GetDeCmd());
1153 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
1154 FCS->GetThrottleCmd(0));
1156 globals->get_controls()->set_aileron(FCS->GetDaCmd());
1157 globals->get_controls()->set_rudder( FCS->GetDrCmd());
1159 SG_LOG( SG_FLIGHT, SG_INFO, " Trim complete" );
1162 void FGJSBsim::update_ic(void)
1165 fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1166 fgic->SetLongitudeRadIC( get_Longitude() );
1167 fgic->SetAltitudeASLFtIC( get_Altitude() );
1168 fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1169 fgic->SetThetaRadIC( get_Theta() );
1170 fgic->SetPhiRadIC( get_Phi() );
1171 fgic->SetPsiRadIC( get_Psi() );
1172 fgic->SetClimbRateFpsIC( get_Climb_Rate() );
1177 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1178 double contact[3], double normal[3], double vel[3],
1181 double angularVel[3];
1182 const SGMaterial* material;
1183 simgear::BVHNode::Id id;
1184 if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1185 angularVel, material, id))
1187 SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1188 SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1189 *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1193 inline static double dot3(const FGColumnVector3& a, const FGColumnVector3& b)
1195 return a(1) * b(1) + a(2) * b(2) + a(3) * b(3);
1198 inline static double sqr(double x)
1203 static double angle_diff(double a, double b)
1205 double diff = fabs(a - b);
1206 if (diff > 180) diff = 360 - diff;
1211 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)
1213 FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1214 double dist = dot3(tip, ground_normal_body);
1215 if (fabs(dist + E) < 0.0001) {
1216 sin_fis[*points] = sin_fi_guess;
1217 cos_fis[*points] = cos_fi_guess;
1218 fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1224 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)
1226 if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1227 double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1228 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1229 if (fabs(cos_fi_guess) > SG_EPSILON) {
1230 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1235 void FGJSBsim::update_external_forces(double t_off)
1237 const FGMatrix33& Tb2l = Propagate->GetTb2l();
1238 const FGMatrix33& Tl2b = Propagate->GetTl2b();
1239 const FGLocation& Location = Propagate->GetLocation();
1240 const FGMatrix33& Tec2l = Location.GetTec2l();
1242 double hook_area[4][3];
1244 FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1245 FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l * hook_root_body);
1246 hook_area[1][0] = hook_root(1);
1247 hook_area[1][1] = hook_root(2);
1248 hook_area[1][2] = hook_root(3);
1250 hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1251 double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1252 double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1253 double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1254 double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1255 double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1257 FGColumnVector3 hook_tip_body = hook_root_body;
1258 hook_tip_body(1) -= hook_length * cos_fi;
1259 hook_tip_body(3) += hook_length * sin_fi;
1260 bool hook_tip_valid = true;
1263 double ground_normal[3];
1264 double ground_vel[3];
1268 bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal, ground_vel, &root_agl_ft);
1269 if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1270 FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1271 FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1272 double D = -dot3(contact_body, ground_normal_body);
1274 // check hook tip agl against same ground plane
1275 double hook_tip_agl_ft = dot3(hook_tip_body, ground_normal_body) + D;
1276 if (hook_tip_agl_ft < 0) {
1278 // hook tip: hx - l cos, hy, hz + l sin
1279 // on ground: - n0 l cos + n2 l sin + E = 0
1281 double E = D + dot3(hook_root_body, ground_normal_body);
1283 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1284 // and rearrange to get a quadratic with coeffs:
1285 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1286 double b = 2 * E * ground_normal_body(3) * hook_length;
1287 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);
1289 double disc = sqr(b) - 4 * a * c;
1291 double delta = sqrt(disc) / (2 * a);
1293 // allow 4 solutions for safety, should never happen
1299 double sin_fi_guess = -b / (2 * a) - delta;
1300 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1301 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1304 double diff1 = angle_diff(fi, fis[0]);
1305 double diff2 = angle_diff(fi, fis[1]);
1306 int point = diff1 < diff2 ? 0 : 1;
1308 sin_fi = sin_fis[point];
1309 cos_fi = cos_fis[point];
1310 hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1311 hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1317 FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() * hook_root_body));
1318 double wire_ends_ec[2][3];
1319 double wire_vel_ec[2][3];
1320 get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1321 FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1322 FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1323 FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1324 if (rel_vel.Magnitude() < 3) {
1327 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1329 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;
1330 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;
1331 FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1332 force_plane_normal.Normalize();
1333 cos_fi = dot3(force_plane_normal, FGColumnVector3(0, 0, 1));
1334 if (cos_fi < 0) cos_fi = -cos_fi;
1335 sin_fi = sqrt(1 - sqr(cos_fi));
1336 fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1338 fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1339 fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1340 fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1341 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1345 FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1347 hook_area[0][0] = hook_tip(1);
1348 hook_area[0][1] = hook_tip(2);
1349 hook_area[0][2] = hook_tip(3);
1352 // The previous positions.
1353 hook_area[2][0] = last_hook_root[0];
1354 hook_area[2][1] = last_hook_root[1];
1355 hook_area[2][2] = last_hook_root[2];
1356 hook_area[3][0] = last_hook_tip[0];
1357 hook_area[3][1] = last_hook_tip[1];
1358 hook_area[3][2] = last_hook_tip[2];
1360 // Check if we caught a wire.
1361 // Returns true if we caught one.
1362 if (caught_wire_ft(t_off, hook_area)) {
1367 // save actual position as old position ...
1368 last_hook_tip[0] = hook_area[0][0];
1369 last_hook_tip[1] = hook_area[0][1];
1370 last_hook_tip[2] = hook_area[0][2];
1371 last_hook_root[0] = hook_area[1][0];
1372 last_hook_root[1] = hook_area[1][1];
1373 last_hook_root[2] = hook_area[1][2];
1375 fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);