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 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.
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
21 // $Id: JSBSim.cxx,v 1.64 2010/10/31 04:49:25 jberndt Exp $
28 #include <simgear/compiler.h>
29 #include <simgear/sg_inlines.h>
31 #include <stdio.h> // size_t
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>
40 #include <FDM/flight.hxx>
42 #include <Aircraft/controls.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
47 #include <FDM/JSBSim/FGFDMExec.h>
48 #include <FDM/JSBSim/FGJSBBase.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/FGGroundReactions.h>
62 #include <FDM/JSBSim/models/FGPropulsion.h>
63 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
64 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
65 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
66 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
67 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
68 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
69 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
70 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
71 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
72 #include <FDM/JSBSim/models/propulsion/FGTank.h>
73 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
74 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
76 using namespace JSBSim;
79 FMAX (double a, double b)
84 class FGFSGroundCallback : public FGGroundCallback {
86 FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
87 virtual ~FGFSGroundCallback() {}
89 /** Get the altitude above sea level dependent on the location. */
90 virtual double GetAltitude(const FGLocation& l) const {
91 double pt[3] = { SG_FEET_TO_METER*l(eX),
92 SG_FEET_TO_METER*l(eY),
93 SG_FEET_TO_METER*l(eZ) };
95 sgCartToGeod( pt, &lat, &lon, &alt);
96 return alt * SG_METER_TO_FEET;
99 /** Compute the altitude above ground. */
100 virtual double GetAGLevel(double t, const FGLocation& l,
101 FGLocation& cont, FGColumnVector3& n,
102 FGColumnVector3& v, FGColumnVector3& w) const {
103 double loc_cart[3] = { l(eX), l(eY), l(eZ) };
104 double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
105 mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
106 vel, angularVel, &agl);
107 n = FGColumnVector3( normal[0], normal[1], normal[2] );
108 v = FGColumnVector3( vel[0], vel[1], vel[2] );
109 w = FGColumnVector3( angularVel[0], angularVel[1], angularVel[2] );
110 cont = FGColumnVector3( contact[0], contact[1], contact[2] );
114 FGJSBsim* mInterface;
117 // FG uses a squared normalized magnitude for turbulence
118 // this lookup table maps fg's severity levels
119 // none(0), light(1/3), moderate(2/3) and severe(3/3)
120 // to the POE table indexes 0, 3, 4 and 7
121 class FGTurbulenceSeverityTable : public FGTable {
123 FGTurbulenceSeverityTable() : FGTable(4) {
124 *this << (0.0/9.0) << 0.0;
125 *this << (1.0/9.0) << 3.0;
126 *this << (4.0/9.0) << 4.0;
127 *this << (9.0/9.0) << 7.0;
131 /******************************************************************************/
132 std::map<std::string,int> FGJSBsim::TURBULENCE_TYPE_NAMES;
134 static FGTurbulenceSeverityTable TurbulenceSeverityTable;
136 FGJSBsim::FGJSBsim( double dt )
137 : FGInterface(dt), got_wire(false)
140 if( TURBULENCE_TYPE_NAMES.empty() ) {
141 TURBULENCE_TYPE_NAMES["ttNone"] = FGAtmosphere::ttNone;
142 TURBULENCE_TYPE_NAMES["ttStandard"] = FGAtmosphere::ttStandard;
143 // TURBULENCE_TYPE_NAMES["ttBerndt"] = FGAtmosphere::ttBerndt;
144 TURBULENCE_TYPE_NAMES["ttCulp"] = FGAtmosphere::ttCulp;
145 TURBULENCE_TYPE_NAMES["ttMilspec"] = FGAtmosphere::ttMilspec;
146 TURBULENCE_TYPE_NAMES["ttTustin"] = FGAtmosphere::ttTustin;
149 // Set up the debugging level
150 // FIXME: this will not respond to
153 // if flight is excluded, don't bother
154 if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
156 // do a rough-and-ready mapping to
157 // the levels documented in FGFDMExec.h
158 switch (logbuf::get_log_priority()) {
160 FGJSBBase::debug_lvl = 0x1f;
163 FGJSBBase::debug_lvl = 0x0f;
165 FGJSBBase::debug_lvl = 0x01;
169 FGJSBBase::debug_lvl = 0x00;
174 fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
176 // Register ground callback.
177 fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
179 Atmosphere = fdmex->GetAtmosphere();
180 FCS = fdmex->GetFCS();
181 MassBalance = fdmex->GetMassBalance();
182 Propulsion = fdmex->GetPropulsion();
183 Aircraft = fdmex->GetAircraft();
184 Propagate = fdmex->GetPropagate();
185 Auxiliary = fdmex->GetAuxiliary();
186 Inertial = fdmex->GetInertial();
187 Aerodynamics = fdmex->GetAerodynamics();
188 GroundReactions = fdmex->GetGroundReactions();
193 SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
195 SGPath engine_path( fgGetString("/sim/aircraft-dir") );
196 engine_path.append( "Engine" );
198 SGPath systems_path( fgGetString("/sim/aircraft-dir") );
199 systems_path.append( "Systems" );
201 // deprecate sim-time-sec for simulation/sim-time-sec
202 // remove alias with increased configuration file version number (2.1 or later)
203 SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec");
204 fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node );
205 // end of sim-time-sec deprecation patch
209 result = fdmex->LoadModel( aircraft_path.str(),
212 fgGetString("/sim/aero"), false );
215 SG_LOG( SG_FLIGHT, SG_INFO, " loaded aero.");
217 SG_LOG( SG_FLIGHT, SG_INFO,
218 " aero does not exist (you may have mis-typed the name).");
222 SG_LOG( SG_FLIGHT, SG_INFO, "" );
223 SG_LOG( SG_FLIGHT, SG_INFO, "" );
224 SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
226 int Neng = Propulsion->GetNumEngines();
227 SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
229 if ( GroundReactions->GetNumGearUnits() <= 0 ) {
230 SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
231 << GroundReactions->GetNumGearUnits() );
232 SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
233 SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
234 SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
240 // Set initial fuel levels if provided.
241 for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
243 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
244 FGTank* tank = Propulsion->GetTank(i);
246 d = node->getNode( "density-ppg", true )->getDoubleValue();
248 tank->SetDensity( d );
250 node->getNode( "density-ppg", true )->setDoubleValue( SG_MAX2<double>(tank->GetDensity(), 0.1) );
253 d = node->getNode( "level-lbs", true )->getDoubleValue();
255 tank->SetContents( d );
257 node->getNode( "level-lbs", true )->setDoubleValue( tank->GetContents() );
259 /* Capacity is read-only in FGTank and can't be overwritten from FlightGear */
260 node->getNode("capacity-gal_us", true )->setDoubleValue( tank->GetCapacityGallons() );
262 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
264 fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
265 fgSetDouble("/fdm/trim/throttle", FCS->GetThrottleCmd(0));
266 fgSetDouble("/fdm/trim/aileron", FCS->GetDaCmd());
267 fgSetDouble("/fdm/trim/rudder", FCS->GetDrCmd());
269 startup_trim = fgGetNode("/sim/presets/trim", true);
271 trimmed = fgGetNode("/fdm/trim/trimmed", true);
272 trimmed->setBoolValue(false);
274 pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
275 throttle_trim = fgGetNode("/fdm/trim/throttle", true );
276 aileron_trim = fgGetNode("/fdm/trim/aileron", true );
277 rudder_trim = fgGetNode("/fdm/trim/rudder", true );
279 stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
280 stall_warning->setDoubleValue(0);
283 flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
284 elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
286 =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
287 right_aileron_pos_pct
288 =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
289 rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
291 =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
292 spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
293 tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
294 wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
296 elevator_pos_pct->setDoubleValue(0);
297 left_aileron_pos_pct->setDoubleValue(0);
298 right_aileron_pos_pct->setDoubleValue(0);
299 rudder_pos_pct->setDoubleValue(0);
300 flap_pos_pct->setDoubleValue(0);
301 speedbrake_pos_pct->setDoubleValue(0);
302 spoilers_pos_pct->setDoubleValue(0);
304 ab_brake_engaged = fgGetNode("/autopilot/autobrake/engaged", true);
305 ab_brake_left_pct = fgGetNode("/autopilot/autobrake/brake-left-output", true);
306 ab_brake_right_pct = fgGetNode("/autopilot/autobrake/brake-right-output", true);
308 temperature = fgGetNode("/environment/temperature-degc",true);
309 pressure = fgGetNode("/environment/pressure-inhg",true);
310 density = fgGetNode("/environment/density-slugft3",true);
311 ground_wind = fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt",true);
312 turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
313 turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
314 turbulence_model = fgGetNode("/environment/params/jsbsim-turbulence-model",true);
316 wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
317 wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
318 wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
320 slaved = fgGetNode("/sim/slaved/enabled", true);
322 for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
323 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
324 Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
325 Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
328 hook_root_struct = FGColumnVector3(
329 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
330 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
331 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
332 last_hook_tip[0] = 0; last_hook_tip[1] = 0; last_hook_tip[2] = 0;
333 last_hook_root[0] = 0; last_hook_root[1] = 0; last_hook_root[2] = 0;
338 /******************************************************************************/
339 FGJSBsim::~FGJSBsim(void)
344 /******************************************************************************/
346 // Initialize the JSBsim flight model, dt is the time increment for
347 // each subsequent iteration through the EOM
349 void FGJSBsim::init()
351 SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
353 // Explicitly call the superclass's
354 // init method first.
356 if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
357 Atmosphere->UseExternal();
358 Atmosphere->SetExTemperature(
359 9.0/5.0*(temperature->getDoubleValue()+273.15) );
360 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
361 Atmosphere->SetExDensity(density->getDoubleValue());
362 // initialize to no turbulence, these values get set in the update loop
363 Atmosphere->SetTurbType(FGAtmosphere::ttNone);
364 Atmosphere->SetTurbGain(0.0);
365 Atmosphere->SetTurbRate(0.0);
366 Atmosphere->SetWindspeed20ft(0.0);
367 Atmosphere->SetProbabilityOfExceedence(0.0);
369 Atmosphere->UseInternal();
372 fgic->SetWindNEDFpsIC( -wind_from_north->getDoubleValue(),
373 -wind_from_east->getDoubleValue(),
374 -wind_from_down->getDoubleValue() );
376 //Atmosphere->SetExTemperature(get_Static_temperature());
377 //Atmosphere->SetExPressure(get_Static_pressure());
378 //Atmosphere->SetExDensity(get_Density());
379 SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
380 << ", " << fdmex->GetAtmosphere()->GetPressure()
381 << ", " << fdmex->GetAtmosphere()->GetDensity() );
383 // deprecate egt_degf for egt-degf to have consistent naming
384 // TODO: remove this by end of 2011
385 for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) {
386 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
387 SGPropertyNode * egtn = node->getNode( "egt_degf" );
389 SG_LOG(SG_FLIGHT,SG_ALERT,
390 "Aircraft uses deprecated node egt_degf. Please upgrade to egt-degf");
391 node->getNode("egt-degf", true)->alias( egtn );
394 // end of egt_degf deprecation patch
396 FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
401 fdmex->RunIC(); //loop JSBSim once w/o integrating
402 if (fgGetBool("/sim/presets/running")) {
403 Propulsion->InitRunning(-1);
404 for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
405 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
406 globals->get_controls()->set_magnetos(i, eng->GetMagnetos());
407 globals->get_controls()->set_mixture(i, FCS->GetMixtureCmd(i));
411 if ( startup_trim->getBoolValue() ) {
412 FGLocation cart(fgic->GetLongitudeRadIC(), fgic->GetLatitudeRadIC(),
413 fgic->GetSeaLevelRadiusFtIC() + fgic->GetAltitudeASLFtIC());
414 double cart_pos[3], contact[3], d[3], vel[3], agl;
415 update_ground_cache(cart, cart_pos, 0.01);
417 get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
419 double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
420 + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
422 SG_LOG(SG_FLIGHT, SG_INFO, "Ready to trim, terrain elevation is: "
423 << terrain_alt * SG_METER_TO_FEET );
425 if (fgGetBool("/sim/presets/onground")) {
426 FGColumnVector3 gndVelNED = cart.GetTec2l()
427 * FGColumnVector3(vel[0], vel[1], vel[2]);
428 fgic->SetVNorthFpsIC(gndVelNED(1));
429 fgic->SetVEastFpsIC(gndVelNED(2));
430 fgic->SetVDownFpsIC(gndVelNED(3));
432 fgic->SetTerrainElevationFtIC( terrain_alt );
437 copy_from_JSBsim(); //update the bus
439 SG_LOG( SG_FLIGHT, SG_INFO, " Initialized JSBSim with:" );
441 switch(fgic->GetSpeedSet()) {
443 SG_LOG(SG_FLIGHT,SG_INFO, " Vn,Ve,Vd= "
444 << Propagate->GetVel(FGJSBBase::eNorth) << ", "
445 << Propagate->GetVel(FGJSBBase::eEast) << ", "
446 << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
449 SG_LOG(SG_FLIGHT,SG_INFO, " U,V,W= "
450 << Propagate->GetUVW(1) << ", "
451 << Propagate->GetUVW(2) << ", "
452 << Propagate->GetUVW(3) << " ft/s");
455 SG_LOG(SG_FLIGHT,SG_INFO, " Mach: "
456 << Auxiliary->GetMach() );
460 SG_LOG(SG_FLIGHT,SG_INFO, " Indicated Airspeed: "
461 << Auxiliary->GetVcalibratedKTS() << " knots" );
465 stall_warning->setDoubleValue(0);
467 SG_LOG( SG_FLIGHT, SG_INFO, " Bank Angle: "
468 << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
469 SG_LOG( SG_FLIGHT, SG_INFO, " Pitch Angle: "
470 << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
471 SG_LOG( SG_FLIGHT, SG_INFO, " True Heading: "
472 << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
473 SG_LOG( SG_FLIGHT, SG_INFO, " Latitude: "
474 << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
475 SG_LOG( SG_FLIGHT, SG_INFO, " Longitude: "
476 << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
477 SG_LOG( SG_FLIGHT, SG_INFO, " Altitude: "
478 << Propagate->GetAltitudeASL() << " feet" );
479 SG_LOG( SG_FLIGHT, SG_INFO, " loaded initial conditions" );
481 SG_LOG( SG_FLIGHT, SG_INFO, " set dt" );
483 SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
485 SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
486 globals->get_controls()->get_gear_down() );
489 /******************************************************************************/
491 void FGJSBsim::unbind()
494 FGInterface::unbind();
497 /******************************************************************************/
499 // Run an iteration of the EOM (equations of motion)
501 void FGJSBsim::update( double dt )
504 if(!fgGetBool("/sim/crashed"))
505 fgSetBool("/sim/crashed", true);
512 int multiloop = _calc_multiloop(dt);
513 FGLocation cart = Auxiliary->GetLocationVRP();
516 update_ground_cache(cart, cart_pos, dt);
520 trimmed->setBoolValue(false);
522 for ( int i=0; i < multiloop; i++ ) {
524 update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());
527 FGJSBBase::Message* msg;
528 while ((msg = fdmex->ProcessNextMessage()) != NULL) {
529 // msg = fdmex->ProcessNextMessage();
531 case FGJSBBase::Message::eText:
532 if (msg->text == "Crash Detected: Simulation FREEZE.")
534 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
536 case FGJSBBase::Message::eBool:
537 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
539 case FGJSBBase::Message::eInteger:
540 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
542 case FGJSBBase::Message::eDouble:
543 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
546 SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
551 // translate JSBsim back to FG structure so that the
552 // autopilot (and the rest of the sim can use the updated values
556 /******************************************************************************/
558 void FGJSBsim::suspend()
561 SGSubsystem::suspend();
564 /******************************************************************************/
566 void FGJSBsim::resume()
569 SGSubsystem::resume();
572 /******************************************************************************/
574 // Convert from the FGInterface struct to the JSBsim generic_ struct
576 bool FGJSBsim::copy_to_JSBsim()
580 // copy control positions into the JSBsim structure
582 FCS->SetDaCmd( globals->get_controls()->get_aileron());
583 FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
584 FCS->SetDeCmd( globals->get_controls()->get_elevator());
585 FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
586 FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
587 FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
588 FCS->SetDsCmd( globals->get_controls()->get_rudder() );
589 FCS->SetDfCmd( globals->get_controls()->get_flaps() );
590 FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
591 FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
593 // Parking brake sets minimum braking
595 double parking_brake = globals->get_controls()->get_brake_parking();
596 double left_brake = globals->get_controls()->get_brake_left();
597 double right_brake = globals->get_controls()->get_brake_right();
599 if (ab_brake_engaged->getBoolValue()) {
600 left_brake = ab_brake_left_pct->getDoubleValue();
601 right_brake = ab_brake_right_pct->getDoubleValue();
604 FCS->SetLBrake(FMAX(left_brake, parking_brake));
605 FCS->SetRBrake(FMAX(right_brake, parking_brake));
608 FCS->SetCBrake( 0.0 );
609 // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
611 FCS->SetGearCmd( globals->get_controls()->get_gear_down());
612 for (i = 0; i < Propulsion->GetNumEngines(); i++) {
613 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
615 FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
616 FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
617 FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
618 FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
620 switch (Propulsion->GetEngine(i)->GetType()) {
621 case FGEngine::etPiston:
622 { // FGPiston code block
623 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
624 eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
626 } // end FGPiston code block
627 case FGEngine::etTurbine:
628 { // FGTurbine code block
629 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
630 eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
631 eng->SetReverse( globals->get_controls()->get_reverser(i) );
632 //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
633 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
634 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
636 } // end FGTurbine code block
637 case FGEngine::etRocket:
638 { // FGRocket code block
639 // FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
641 } // end FGRocket code block
642 case FGEngine::etTurboprop:
643 { // FGTurboProp code block
644 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
645 eng->SetReverse( globals->get_controls()->get_reverser(i) );
646 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
647 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
649 eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
650 eng->SetCondition( globals->get_controls()->get_condition(i) );
652 } // end FGTurboProp code block
657 { // FGEngine code block
658 FGEngine* eng = Propulsion->GetEngine(i);
660 eng->SetStarter( globals->get_controls()->get_starter(i) );
661 eng->SetRunning( node->getBoolValue("running") );
662 } // end FGEngine code block
666 Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
668 Atmosphere->SetExTemperature(
669 9.0/5.0*(temperature->getDoubleValue()+273.15) );
670 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
671 Atmosphere->SetExDensity(density->getDoubleValue());
673 Atmosphere->SetTurbType((FGAtmosphere::tType)TURBULENCE_TYPE_NAMES[turbulence_model->getStringValue()]);
674 switch( Atmosphere->GetTurbType() ) {
675 // case FGAtmosphere::ttBerndt:
676 case FGAtmosphere::ttStandard:
677 case FGAtmosphere::ttCulp: {
678 double tmp = turbulence_gain->getDoubleValue();
679 Atmosphere->SetTurbGain(tmp * tmp * 100.0);
680 Atmosphere->SetTurbRate(turbulence_rate->getDoubleValue());
683 case FGAtmosphere::ttMilspec:
684 case FGAtmosphere::ttTustin: {
685 // milspec turbulence: 3=light, 4=moderate, 6=severe turbulence
686 // turbulence_gain normalized: 0: none, 1/3: light, 2/3: moderate, 3/3: severe
687 double tmp = turbulence_gain->getDoubleValue();
688 Atmosphere->SetProbabilityOfExceedence(
689 SGMiscd::roundToInt(TurbulenceSeverityTable.GetValue( tmp ) )
691 Atmosphere->SetWindspeed20ft(ground_wind->getDoubleValue());
699 Atmosphere->SetWindNED( -wind_from_north->getDoubleValue(),
700 -wind_from_east->getDoubleValue(),
701 -wind_from_down->getDoubleValue() );
702 // SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
703 // << get_V_north_airmass() << ", "
704 // << get_V_east_airmass() << ", "
705 // << get_V_down_airmass() );
707 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
708 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
709 FGTank * tank = Propulsion->GetTank(i);
710 double fuelDensity = node->getDoubleValue("density-ppg");
712 if (fuelDensity < 0.1)
713 fuelDensity = 6.0; // Use average fuel value
715 tank->SetDensity(fuelDensity);
716 tank->SetContents(node->getDoubleValue("level-lbs"));
719 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
720 fdmex->SetChild(slaved->getBoolValue());
725 /******************************************************************************/
727 // Convert from the JSBsim generic_ struct to the FGInterface struct
729 bool FGJSBsim::copy_from_JSBsim()
733 _set_Inertias( MassBalance->GetMass(),
734 MassBalance->GetIxx(),
735 MassBalance->GetIyy(),
736 MassBalance->GetIzz(),
737 MassBalance->GetIxz() );
739 _set_CG_Position( MassBalance->GetXYZcg(1),
740 MassBalance->GetXYZcg(2),
741 MassBalance->GetXYZcg(3) );
743 _set_Accels_Body( Aircraft->GetBodyAccel(1),
744 Aircraft->GetBodyAccel(2),
745 Aircraft->GetBodyAccel(3) );
747 _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
749 Aircraft->GetNcg(3) );
751 _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
752 Auxiliary->GetPilotAccel(2),
753 Auxiliary->GetPilotAccel(3) );
755 _set_Nlf( Aircraft->GetNlf() );
759 _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
760 Propagate->GetVel(FGJSBBase::eEast),
761 Propagate->GetVel(FGJSBBase::eDown) );
763 _set_Velocities_Wind_Body( Propagate->GetUVW(1),
764 Propagate->GetUVW(2),
765 Propagate->GetUVW(3) );
767 // Make the HUD work ...
768 _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
769 Propagate->GetVel(FGJSBBase::eEast),
770 -Propagate->GetVel(FGJSBBase::eDown) );
772 _set_V_rel_wind( Auxiliary->GetVt() );
774 _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
776 _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
778 _set_V_ground_speed( Auxiliary->GetVground() );
780 _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
781 Propagate->GetPQR(FGJSBBase::eQ),
782 Propagate->GetPQR(FGJSBBase::eR) );
784 _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
785 Auxiliary->GetEulerRates(FGJSBBase::eTht),
786 Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
788 _set_Mach_number( Auxiliary->GetMach() );
790 // Positions of Visual Reference Point
791 FGLocation l = Auxiliary->GetLocationVRP();
792 _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
793 l.GetRadius() - get_Sea_level_radius() );
795 _set_Altitude_AGL( Propagate->GetDistanceAGL() );
797 double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
798 double contact[3], d[3], sd, t;
799 is_valid_m(&t, d, &sd);
800 get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
802 = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
803 _set_Runway_altitude( rwrad - get_Sea_level_radius() );
806 _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
807 Propagate->GetEuler(FGJSBBase::eTht),
808 Propagate->GetEuler(FGJSBBase::ePsi) );
810 _set_Alpha( Auxiliary->Getalpha() );
811 _set_Beta( Auxiliary->Getbeta() );
814 _set_Gamma_vert_rad( Auxiliary->GetGamma() );
816 _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
818 _set_Climb_Rate( Propagate->Gethdot() );
820 const FGMatrix33& Tl2b = Propagate->GetTl2b();
821 for ( i = 1; i <= 3; i++ ) {
822 for ( j = 1; j <= 3; j++ ) {
823 _set_T_Local_to_Body( i, j, Tl2b(i,j) );
827 // Copy the engine values from JSBSim.
828 for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
829 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
830 SGPropertyNode * tnode = node->getChild("thruster", 0, true);
831 FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
833 switch (Propulsion->GetEngine(i)->GetType()) {
834 case FGEngine::etPiston:
835 { // FGPiston code block
836 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
837 node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
838 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
839 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
840 node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
841 // NOTE: mp-osi is not in ounces per square inch.
842 // This error is left for reasons of backwards compatibility with
843 // existing FlightGear sound and instrument configurations.
844 node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
845 node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
846 node->setDoubleValue("rpm", eng->getRPM());
847 } // end FGPiston code block
849 case FGEngine::etRocket:
850 { // FGRocket code block
851 // FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
852 } // end FGRocket code block
854 case FGEngine::etTurbine:
855 { // FGTurbine code block
856 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
857 node->setDoubleValue("n1", eng->GetN1());
858 node->setDoubleValue("n2", eng->GetN2());
859 node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
860 node->setBoolValue("augmentation", eng->GetAugmentation());
861 node->setBoolValue("water-injection", eng->GetInjection());
862 node->setBoolValue("ignition", eng->GetIgnition() != 0);
863 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
864 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
865 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
866 node->setBoolValue("reversed", eng->GetReversed());
867 node->setBoolValue("cutoff", eng->GetCutoff());
868 node->setDoubleValue("epr", eng->GetEPR());
869 globals->get_controls()->set_reverser(i, eng->GetReversed() );
870 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
871 globals->get_controls()->set_water_injection(i, eng->GetInjection() );
872 globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
873 } // end FGTurbine code block
875 case FGEngine::etTurboprop:
876 { // FGTurboProp code block
877 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
878 node->setDoubleValue("n1", eng->GetN1());
879 //node->setDoubleValue("n2", eng->GetN2());
880 node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
881 node->setBoolValue("ignition", eng->GetIgnition() != 0);
882 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
883 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
884 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
885 node->setBoolValue("reversed", eng->GetReversed());
886 node->setBoolValue("cutoff", eng->GetCutoff());
887 node->setBoolValue("starting", eng->GetEngStarting());
888 node->setBoolValue("generator-power", eng->GetGeneratorPower());
889 node->setBoolValue("damaged", eng->GetCondition() != 0);
890 node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
891 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
892 // node->setBoolValue("onfire", eng->GetFire());
893 globals->get_controls()->set_reverser(i, eng->GetReversed() );
894 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
895 } // end FGTurboProp code block
897 case FGEngine::etElectric:
898 { // FGElectric code block
899 FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
900 node->setDoubleValue("rpm", eng->getRPM());
901 } // end FGElectric code block
903 case FGEngine::etUnknown:
907 { // FGEngine code block
908 FGEngine* eng = Propulsion->GetEngine(i);
909 node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
910 node->setDoubleValue("thrust_lb", thruster->GetThrust());
911 node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
912 node->setBoolValue("running", eng->GetRunning());
913 node->setBoolValue("starter", eng->GetStarter());
914 node->setBoolValue("cranking", eng->GetCranking());
915 globals->get_controls()->set_starter(i, eng->GetStarter() );
916 } // end FGEngine code block
918 switch (thruster->GetType()) {
919 case FGThruster::ttNozzle:
920 { // FGNozzle code block
921 // FGNozzle* noz = (FGNozzle*)thruster;
922 } // end FGNozzle code block
924 case FGThruster::ttPropeller:
925 { // FGPropeller code block
926 FGPropeller* prop = (FGPropeller*)thruster;
927 tnode->setDoubleValue("rpm", thruster->GetRPM());
928 tnode->setDoubleValue("pitch", prop->GetPitch());
929 tnode->setDoubleValue("torque", prop->GetTorque());
930 tnode->setBoolValue("feathered", prop->GetFeather());
931 } // end FGPropeller code block
933 case FGThruster::ttRotor:
934 { // FGRotor code block
935 // FGRotor* rotor = (FGRotor*)thruster;
936 } // end FGRotor code block
938 case FGThruster::ttDirect:
939 { // Direct code block
940 } // end Direct code block
946 // Copy the fuel levels from JSBSim if fuel
947 // freeze not enabled.
948 if ( ! Propulsion->GetFuelFreeze() ) {
949 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
950 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
951 FGTank* tank = Propulsion->GetTank(i);
952 double contents = tank->GetContents();
953 double temp = tank->GetTemperature_degC();
954 double fuelDensity = tank->GetDensity();
956 if (fuelDensity < 0.1)
957 fuelDensity = 6.0; // Use average fuel value
959 node->setDoubleValue("density-ppg" , fuelDensity);
960 node->setDoubleValue("level-lbs", contents);
961 if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
967 stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
969 elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
970 left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
971 right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
972 rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
973 flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
974 speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
975 spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
976 tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
977 wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
979 // force a sim crashed if crashed (altitude AGL < 0)
980 if (get_Altitude_AGL() < -100.0) {
981 fdmex->SuspendIntegration();
989 bool FGJSBsim::ToggleDataLogging(void)
991 // ToDo: handle this properly
992 fdmex->DisableOutput();
997 bool FGJSBsim::ToggleDataLogging(bool state)
1000 fdmex->EnableOutput();
1003 fdmex->DisableOutput();
1010 void FGJSBsim::set_Latitude(double lat)
1012 static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
1014 double sea_level_radius_meters, lat_geoc;
1016 if ( altitude->getDoubleValue() > -9990 )
1017 alt = altitude->getDoubleValue();
1021 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1022 SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) = " << alt );
1024 sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1025 &sea_level_radius_meters, &lat_geoc );
1026 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
1029 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
1030 fgic->SetLatitudeRadIC( lat_geoc );
1033 Propagate->SetLatitude(lat_geoc);
1034 FGInterface::set_Latitude(lat);
1039 void FGJSBsim::set_Longitude(double lon)
1041 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1044 fgic->SetLongitudeRadIC(lon);
1046 Propagate->SetLongitude(lon);
1047 FGInterface::set_Longitude(lon);
1051 // Sets the altitude above sea level.
1052 void FGJSBsim::set_Altitude(double alt)
1054 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1057 fgic->SetAltitudeASLFtIC(alt);
1059 Propagate->SetAltitudeASL(alt);
1060 FGInterface::set_Altitude(alt);
1064 void FGJSBsim::set_V_calibrated_kts(double vc)
1066 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " << vc );
1069 fgic->SetVcalibratedKtsIC(vc);
1071 double mach = getMachFromVcas(vc);
1072 double temp = 1.8*(temperature->getDoubleValue()+273.15);
1073 double soundSpeed = sqrt(1.4*1716.0*temp);
1074 FGColumnVector3 vUVW = Propagate->GetUVW();
1076 vUVW *= mach * soundSpeed;
1077 Propagate->SetUVW(1, vUVW(1));
1078 Propagate->SetUVW(2, vUVW(2));
1079 Propagate->SetUVW(3, vUVW(3));
1081 FGInterface::set_V_calibrated_kts(vc);
1085 void FGJSBsim::set_Mach_number(double mach)
1087 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " << mach );
1090 fgic->SetMachIC(mach);
1092 double temp = 1.8*(temperature->getDoubleValue()+273.15);
1093 double soundSpeed = sqrt(1.4*1716.0*temp);
1094 FGColumnVector3 vUVW = Propagate->GetUVW();
1096 vUVW *= mach * soundSpeed;
1097 Propagate->SetUVW(1, vUVW(1));
1098 Propagate->SetUVW(2, vUVW(2));
1099 Propagate->SetUVW(3, vUVW(3));
1101 FGInterface::set_Mach_number(mach);
1105 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1107 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1108 << north << ", " << east << ", " << down );
1111 fgic->SetVNorthFpsIC(north);
1112 fgic->SetVEastFpsIC(east);
1113 fgic->SetVDownFpsIC(down);
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));
1122 FGInterface::set_Velocities_Local(north, east, down);
1126 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1128 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1129 << u << ", " << v << ", " << w );
1132 fgic->SetUBodyFpsIC(u);
1133 fgic->SetVBodyFpsIC(v);
1134 fgic->SetWBodyFpsIC(w);
1137 Propagate->SetUVW(1, u);
1138 Propagate->SetUVW(2, v);
1139 Propagate->SetUVW(3, w);
1141 FGInterface::set_Velocities_Wind_Body(u, v, w);
1146 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1148 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1149 << phi << ", " << theta << ", " << psi );
1152 fgic->SetThetaRadIC(theta);
1153 fgic->SetPhiRadIC(phi);
1154 fgic->SetPsiRadIC(psi);
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);
1163 FGInterface::set_Euler_Angles(phi, theta, psi);
1168 void FGJSBsim::set_Climb_Rate( double roc)
1170 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
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
1175 if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1177 fgic->SetClimbRateFpsIC(roc);
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));
1186 FGInterface::set_Climb_Rate(roc);
1191 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1193 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1195 if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1197 fgic->SetFlightPathAngleRadIC(gamma);
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));
1207 FGInterface::set_Gamma_vert_rad(gamma);
1211 // Reverse the VCAS formula to obtain the corresponding Mach number. For subsonic
1212 // speeds, the reversed formula has a closed form. For supersonic speeds, the
1213 // formula is reversed by the Newton-Raphson algorithm.
1215 double FGJSBsim::getMachFromVcas(double vcas)
1217 double p=pressure->getDoubleValue();
1218 double psl=fdmex->GetAtmosphere()->GetPressureSL();
1219 double rhosl=fdmex->GetAtmosphere()->GetDensitySL();
1221 double pt = p + psl*(pow(1+vcas*vcas*rhosl/(7.0*psl),3.5)-1);
1224 return sqrt(5.0*(pow(pt/p, 0.2857143) -1)); // Mach < 1
1227 double mach = sqrt(0.77666*pt/p); // Initial guess is based on a quadratic approximation of the Rayleigh formula
1229 double target = pt/(166.92158*p);
1232 // Find the root with Newton-Raphson. Since the differential is never zero,
1233 // the function is monotonic and has only one root with a multiplicity of one.
1234 // Convergence is certain.
1235 while (delta > 1E-5 && iter < 10) {
1236 double m2 = mach*mach; // Mach^2
1237 double m6 = m2*m2*m2; // Mach^6
1238 delta = mach*m6/pow(7.0*m2-1.0,2.5) - target;
1239 double diff = 7.0*m6*(2.0*m2-1)/pow(7.0*m2-1.0,3.5); // Never zero when Mach >= 1
1248 void FGJSBsim::init_gear(void )
1250 FGGroundReactions* gr=fdmex->GetGroundReactions();
1251 int Ngear=GroundReactions->GetNumGearUnits();
1252 for (int i=0;i<Ngear;i++) {
1253 FGLGear *gear = gr->GetGearUnit(i);
1254 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1255 node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1256 node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1257 node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1258 node->setBoolValue("wow", gear->GetWOW());
1259 node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1260 node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1261 node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1262 node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1263 node->setDoubleValue("compression-norm", gear->GetCompLen());
1264 node->setDoubleValue("compression-ft", gear->GetCompLen());
1265 if ( gear->GetSteerable() )
1266 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1270 void FGJSBsim::update_gear(void)
1272 FGGroundReactions* gr=fdmex->GetGroundReactions();
1273 int Ngear=GroundReactions->GetNumGearUnits();
1274 for (int i=0;i<Ngear;i++) {
1275 FGLGear *gear = gr->GetGearUnit(i);
1276 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1277 node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1278 node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1279 node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1280 gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1281 node->setDoubleValue("compression-norm", gear->GetCompLen());
1282 node->setDoubleValue("compression-ft", gear->GetCompLen());
1283 if ( gear->GetSteerable() )
1284 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1288 void FGJSBsim::do_trim(void)
1292 if ( fgGetBool("/sim/presets/onground") )
1294 fgtrim = new FGTrim(fdmex,tGround);
1296 fgtrim = new FGTrim(fdmex,tFull);
1299 if ( !fgtrim->DoTrim() ) {
1301 fgtrim->TrimStats();
1303 trimmed->setBoolValue(true);
1307 pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1308 throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1309 aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1310 rudder_trim->setDoubleValue( -FCS->GetDrCmd() );
1312 globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1313 globals->get_controls()->set_elevator(FCS->GetDeCmd());
1314 for( unsigned i = 0; i < Propulsion->GetNumEngines(); i++ )
1315 globals->get_controls()->set_throttle(i, FCS->GetThrottleCmd(i));
1317 globals->get_controls()->set_aileron(FCS->GetDaCmd());
1318 globals->get_controls()->set_rudder( -FCS->GetDrCmd());
1320 SG_LOG( SG_FLIGHT, SG_INFO, " Trim complete" );
1323 bool FGJSBsim::update_ground_cache(FGLocation cart, double* cart_pos, double dt)
1325 // Compute the radius of the aircraft. That is the radius of a ball
1326 // where all gear units are in. At the moment it is at least 10ft ...
1327 double acrad = 10.0;
1328 int n_gears = GroundReactions->GetNumGearUnits();
1329 for (int i=0; i<n_gears; ++i) {
1330 FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
1331 double r = bl.Magnitude();
1336 // Compute the potential movement of this aircraft and query for the
1337 // ground in this area.
1338 double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
1339 cart_pos[0] = cart(1);
1340 cart_pos[1] = cart(2);
1341 cart_pos[2] = cart(3);
1342 double t0 = fdmex->GetSimTime();
1343 bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
1344 groundCacheRadius );
1346 SG_LOG(SG_FLIGHT, SG_WARN,
1347 "FGInterface is being called without scenery below the aircraft!");
1349 SG_LOG(SG_FLIGHT, SG_WARN, "altitude = "
1350 << fgic->GetAltitudeASLFtIC());
1352 SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = "
1353 << fgic->GetSeaLevelRadiusFtIC());
1355 SG_LOG(SG_FLIGHT, SG_WARN, "latitude = "
1356 << fgic->GetLatitudeRadIC());
1358 SG_LOG(SG_FLIGHT, SG_WARN, "longitude = "
1359 << fgic->GetLongitudeRadIC());
1366 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1367 double contact[3], double normal[3], double vel[3],
1368 double angularVel[3], double *agl)
1370 const SGMaterial* material;
1371 simgear::BVHNode::Id id;
1372 if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1373 angularVel, material, id))
1375 SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1376 SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1377 *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1381 inline static double sqr(double x)
1386 static double angle_diff(double a, double b)
1388 double diff = fabs(a - b);
1389 if (diff > 180) diff = 360 - diff;
1394 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)
1396 FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1397 double dist = DotProduct(tip, ground_normal_body);
1398 if (fabs(dist + E) < 0.0001) {
1399 sin_fis[*points] = sin_fi_guess;
1400 cos_fis[*points] = cos_fi_guess;
1401 fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1407 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)
1409 if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1410 double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1411 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1412 if (fabs(cos_fi_guess) > SG_EPSILON) {
1413 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1418 void FGJSBsim::update_external_forces(double t_off)
1420 const FGMatrix33& Tb2l = Propagate->GetTb2l();
1421 const FGMatrix33& Tl2b = Propagate->GetTl2b();
1422 const FGLocation& Location = Propagate->GetLocation();
1423 const FGMatrix33& Tec2l = Location.GetTec2l();
1425 double hook_area[4][3];
1427 FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1428 FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l * hook_root_body);
1429 hook_area[1][0] = hook_root(1);
1430 hook_area[1][1] = hook_root(2);
1431 hook_area[1][2] = hook_root(3);
1433 hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1434 double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1435 double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1436 double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1437 double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1438 double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1440 FGColumnVector3 hook_tip_body = hook_root_body;
1441 hook_tip_body(1) -= hook_length * cos_fi;
1442 hook_tip_body(3) += hook_length * sin_fi;
1445 double ground_normal[3];
1446 double ground_vel[3];
1447 double ground_angular_vel[3];
1451 bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1452 ground_vel, ground_angular_vel, &root_agl_ft);
1453 if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1454 FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1455 FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1456 double D = -DotProduct(contact_body, ground_normal_body);
1458 // check hook tip agl against same ground plane
1459 double hook_tip_agl_ft = DotProduct(hook_tip_body, ground_normal_body) + D;
1460 if (hook_tip_agl_ft < 0) {
1462 // hook tip: hx - l cos, hy, hz + l sin
1463 // on ground: - n0 l cos + n2 l sin + E = 0
1465 double E = D + DotProduct(hook_root_body, ground_normal_body);
1467 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1468 // and rearrange to get a quadratic with coeffs:
1469 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1470 double b = 2 * E * ground_normal_body(3) * hook_length;
1471 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);
1473 double disc = sqr(b) - 4 * a * c;
1475 double delta = sqrt(disc) / (2 * a);
1477 // allow 4 solutions for safety, should never happen
1483 double sin_fi_guess = -b / (2 * a) - delta;
1484 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1485 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1488 double diff1 = angle_diff(fi, fis[0]);
1489 double diff2 = angle_diff(fi, fis[1]);
1490 int point = diff1 < diff2 ? 0 : 1;
1492 sin_fi = sin_fis[point];
1493 cos_fi = cos_fis[point];
1494 hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1495 hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1501 FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() * hook_root_body));
1502 double wire_ends_ec[2][3];
1503 double wire_vel_ec[2][3];
1504 get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1505 FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1506 FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1507 FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1508 if (rel_vel.Magnitude() < 3) {
1511 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1513 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;
1514 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;
1515 FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1516 force_plane_normal.Normalize();
1517 cos_fi = DotProduct(force_plane_normal, FGColumnVector3(0, 0, 1));
1518 if (cos_fi < 0) cos_fi = -cos_fi;
1519 sin_fi = sqrt(1 - sqr(cos_fi));
1520 fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1522 fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1523 fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1524 fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1525 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1529 FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1531 hook_area[0][0] = hook_tip(1);
1532 hook_area[0][1] = hook_tip(2);
1533 hook_area[0][2] = hook_tip(3);
1536 // The previous positions.
1537 hook_area[2][0] = last_hook_root[0];
1538 hook_area[2][1] = last_hook_root[1];
1539 hook_area[2][2] = last_hook_root[2];
1540 hook_area[3][0] = last_hook_tip[0];
1541 hook_area[3][1] = last_hook_tip[1];
1542 hook_area[3][2] = last_hook_tip[2];
1544 // Check if we caught a wire.
1545 // Returns true if we caught one.
1546 if (caught_wire_ft(t_off, hook_area)) {
1551 // save actual position as old position ...
1552 last_hook_tip[0] = hook_area[0][0];
1553 last_hook_tip[1] = hook_area[0][1];
1554 last_hook_tip[2] = hook_area[0][2];
1555 last_hook_root[0] = hook_area[1][0];
1556 last_hook_root[1] = hook_area[1][1];
1557 last_hook_root[2] = hook_area[1][2];
1559 fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);