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->SetVNorthFpsIC( -wind_from_north->getDoubleValue() );
373 fgic->SetVEastFpsIC( -wind_from_east->getDoubleValue() );
374 fgic->SetVDownFpsIC( -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 if (fgGetBool("/sim/presets/running")) {
397 for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) {
398 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
399 node->setBoolValue("running", true);
400 Propulsion->GetEngine(i)->SetRunning(true);
404 FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
409 fdmex->RunIC(); //loop JSBSim once w/o integrating
410 copy_from_JSBsim(); //update the bus
412 SG_LOG( SG_FLIGHT, SG_INFO, " Initialized JSBSim with:" );
414 switch(fgic->GetSpeedSet()) {
416 SG_LOG(SG_FLIGHT,SG_INFO, " Vn,Ve,Vd= "
417 << Propagate->GetVel(FGJSBBase::eNorth) << ", "
418 << Propagate->GetVel(FGJSBBase::eEast) << ", "
419 << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
422 SG_LOG(SG_FLIGHT,SG_INFO, " U,V,W= "
423 << Propagate->GetUVW(1) << ", "
424 << Propagate->GetUVW(2) << ", "
425 << Propagate->GetUVW(3) << " ft/s");
428 SG_LOG(SG_FLIGHT,SG_INFO, " Mach: "
429 << Auxiliary->GetMach() );
433 SG_LOG(SG_FLIGHT,SG_INFO, " Indicated Airspeed: "
434 << Auxiliary->GetVcalibratedKTS() << " knots" );
438 stall_warning->setDoubleValue(0);
440 SG_LOG( SG_FLIGHT, SG_INFO, " Bank Angle: "
441 << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
442 SG_LOG( SG_FLIGHT, SG_INFO, " Pitch Angle: "
443 << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
444 SG_LOG( SG_FLIGHT, SG_INFO, " True Heading: "
445 << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
446 SG_LOG( SG_FLIGHT, SG_INFO, " Latitude: "
447 << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
448 SG_LOG( SG_FLIGHT, SG_INFO, " Longitude: "
449 << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
450 SG_LOG( SG_FLIGHT, SG_INFO, " Altitude: "
451 << Propagate->GetAltitudeASL() << " feet" );
452 SG_LOG( SG_FLIGHT, SG_INFO, " loaded initial conditions" );
454 SG_LOG( SG_FLIGHT, SG_INFO, " set dt" );
456 SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
458 SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
459 globals->get_controls()->get_gear_down() );
462 /******************************************************************************/
464 void FGJSBsim::unbind()
467 FGInterface::unbind();
470 /******************************************************************************/
472 // Run an iteration of the EOM (equations of motion)
474 void FGJSBsim::update( double dt )
477 if(!fgGetBool("/sim/crashed"))
478 fgSetBool("/sim/crashed", true);
485 int multiloop = _calc_multiloop(dt);
489 // Compute the radius of the aircraft. That is the radius of a ball
490 // where all gear units are in. At the moment it is at least 10ft ...
492 int n_gears = GroundReactions->GetNumGearUnits();
493 for (i=0; i<n_gears; ++i) {
494 FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
495 double r = bl.Magnitude();
500 // Compute the potential movement of this aircraft and query for the
501 // ground in this area.
502 double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
503 double alt, slr, lat, lon;
504 FGLocation cart = Auxiliary->GetLocationVRP();
505 if ( needTrim && startup_trim->getBoolValue() ) {
506 alt = fgic->GetAltitudeASLFtIC();
507 slr = fgic->GetSeaLevelRadiusFtIC();
508 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
509 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
510 cart = FGLocation(lon, lat, alt+slr);
512 double cart_pos[3] = { cart(1), cart(2), cart(3) };
513 double t0 = fdmex->GetSimTime();
514 bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
517 SG_LOG(SG_FLIGHT, SG_WARN,
518 "FGInterface is being called without scenery below the aircraft!");
520 alt = fgic->GetAltitudeASLFtIC();
521 SG_LOG(SG_FLIGHT, SG_WARN, "altitude = " << alt);
523 slr = fgic->GetSeaLevelRadiusFtIC();
524 SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = " << slr);
526 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
527 SG_LOG(SG_FLIGHT, SG_WARN, "latitude = " << lat);
529 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
530 SG_LOG(SG_FLIGHT, SG_WARN, "longitude = " << lon);
536 trimmed->setBoolValue(false);
539 if ( startup_trim->getBoolValue() ) {
540 double contact[3], d[3], vel[3], agl;
541 get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
543 double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
544 + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
546 SG_LOG(SG_FLIGHT, SG_INFO,
547 "Ready to trim, terrain elevation is: "
548 << terrain_alt * SG_METER_TO_FEET );
550 if (fgGetBool("/sim/presets/onground")) {
551 FGColumnVector3 gndVelNED = cart.GetTec2l()
552 * FGColumnVector3(vel[0], vel[1], vel[2]);
553 fgic->SetVNorthFpsIC(gndVelNED(1));
554 fgic->SetVEastFpsIC(gndVelNED(2));
555 fgic->SetVDownFpsIC(gndVelNED(3));
557 fgic->SetTerrainElevationFtIC( terrain_alt );
560 fdmex->RunIC(); //apply any changes made through the set_ functions
565 for ( i=0; i < multiloop; i++ ) {
567 update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());
570 FGJSBBase::Message* msg;
571 while ((msg = fdmex->ProcessNextMessage()) != NULL) {
572 // msg = fdmex->ProcessNextMessage();
574 case FGJSBBase::Message::eText:
575 if (msg->text == "Crash Detected: Simulation FREEZE.")
577 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
579 case FGJSBBase::Message::eBool:
580 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
582 case FGJSBBase::Message::eInteger:
583 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
585 case FGJSBBase::Message::eDouble:
586 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
589 SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
594 // translate JSBsim back to FG structure so that the
595 // autopilot (and the rest of the sim can use the updated values
599 /******************************************************************************/
601 void FGJSBsim::suspend()
604 SGSubsystem::suspend();
607 /******************************************************************************/
609 void FGJSBsim::resume()
612 SGSubsystem::resume();
615 /******************************************************************************/
617 // Convert from the FGInterface struct to the JSBsim generic_ struct
619 bool FGJSBsim::copy_to_JSBsim()
623 // copy control positions into the JSBsim structure
625 FCS->SetDaCmd( globals->get_controls()->get_aileron());
626 FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
627 FCS->SetDeCmd( globals->get_controls()->get_elevator());
628 FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
629 FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
630 FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
631 FCS->SetDsCmd( globals->get_controls()->get_rudder() );
632 FCS->SetDfCmd( globals->get_controls()->get_flaps() );
633 FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
634 FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
636 // Parking brake sets minimum braking
638 double parking_brake = globals->get_controls()->get_brake_parking();
639 double left_brake = globals->get_controls()->get_brake_left();
640 double right_brake = globals->get_controls()->get_brake_right();
642 if (ab_brake_engaged->getBoolValue()) {
643 left_brake = ab_brake_left_pct->getDoubleValue();
644 right_brake = ab_brake_right_pct->getDoubleValue();
647 FCS->SetLBrake(FMAX(left_brake, parking_brake));
648 FCS->SetRBrake(FMAX(right_brake, parking_brake));
651 FCS->SetCBrake( 0.0 );
652 // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
654 FCS->SetGearCmd( globals->get_controls()->get_gear_down());
655 for (i = 0; i < Propulsion->GetNumEngines(); i++) {
656 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
658 FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
659 FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
660 FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
661 FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
663 switch (Propulsion->GetEngine(i)->GetType()) {
664 case FGEngine::etPiston:
665 { // FGPiston code block
666 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
667 eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
669 } // end FGPiston code block
670 case FGEngine::etTurbine:
671 { // FGTurbine code block
672 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
673 eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
674 eng->SetReverse( globals->get_controls()->get_reverser(i) );
675 //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
676 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
677 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
679 } // end FGTurbine code block
680 case FGEngine::etRocket:
681 { // FGRocket code block
682 // FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
684 } // end FGRocket code block
685 case FGEngine::etTurboprop:
686 { // FGTurboProp code block
687 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
688 eng->SetReverse( globals->get_controls()->get_reverser(i) );
689 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
690 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
692 eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
693 eng->SetCondition( globals->get_controls()->get_condition(i) );
695 } // end FGTurboProp code block
700 { // FGEngine code block
701 FGEngine* eng = Propulsion->GetEngine(i);
703 eng->SetStarter( globals->get_controls()->get_starter(i) );
704 eng->SetRunning( node->getBoolValue("running") );
705 } // end FGEngine code block
709 Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
711 Atmosphere->SetExTemperature(
712 9.0/5.0*(temperature->getDoubleValue()+273.15) );
713 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
714 Atmosphere->SetExDensity(density->getDoubleValue());
716 Atmosphere->SetTurbType((FGAtmosphere::tType)TURBULENCE_TYPE_NAMES[turbulence_model->getStringValue()]);
717 switch( Atmosphere->GetTurbType() ) {
718 case FGAtmosphere::ttStandard:
719 case FGAtmosphere::ttCulp:
720 case FGAtmosphere::ttBerndt: {
721 double tmp = turbulence_gain->getDoubleValue();
722 Atmosphere->SetTurbGain(tmp * tmp * 100.0);
723 Atmosphere->SetTurbRate(turbulence_rate->getDoubleValue());
726 case FGAtmosphere::ttMilspec:
727 case FGAtmosphere::ttTustin: {
728 // milspec turbulence: 3=light, 4=moderate, 6=severe turbulence
729 // turbulence_gain normalized: 0: none, 1/3: light, 2/3: moderate, 3/3: severe
730 double tmp = turbulence_gain->getDoubleValue();
731 Atmosphere->SetProbabilityOfExceedence(
732 round(TurbulenceSeverityTable.GetValue( tmp ) )
734 Atmosphere->SetWindspeed20ft(ground_wind->getDoubleValue());
742 Atmosphere->SetWindNED( -wind_from_north->getDoubleValue(),
743 -wind_from_east->getDoubleValue(),
744 -wind_from_down->getDoubleValue() );
745 // SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
746 // << get_V_north_airmass() << ", "
747 // << get_V_east_airmass() << ", "
748 // << get_V_down_airmass() );
750 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
751 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
752 FGTank * tank = Propulsion->GetTank(i);
753 double fuelDensity = node->getDoubleValue("density-ppg");
755 if (fuelDensity < 0.1)
756 fuelDensity = 6.0; // Use average fuel value
758 tank->SetDensity(fuelDensity);
759 tank->SetContents(node->getDoubleValue("level-lbs"));
762 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
763 fdmex->SetChild(slaved->getBoolValue());
768 /******************************************************************************/
770 // Convert from the JSBsim generic_ struct to the FGInterface struct
772 bool FGJSBsim::copy_from_JSBsim()
776 _set_Inertias( MassBalance->GetMass(),
777 MassBalance->GetIxx(),
778 MassBalance->GetIyy(),
779 MassBalance->GetIzz(),
780 MassBalance->GetIxz() );
782 _set_CG_Position( MassBalance->GetXYZcg(1),
783 MassBalance->GetXYZcg(2),
784 MassBalance->GetXYZcg(3) );
786 _set_Accels_Body( Aircraft->GetBodyAccel(1),
787 Aircraft->GetBodyAccel(2),
788 Aircraft->GetBodyAccel(3) );
790 _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
792 Aircraft->GetNcg(3) );
794 _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
795 Auxiliary->GetPilotAccel(2),
796 Auxiliary->GetPilotAccel(3) );
798 _set_Nlf( Aircraft->GetNlf() );
802 _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
803 Propagate->GetVel(FGJSBBase::eEast),
804 Propagate->GetVel(FGJSBBase::eDown) );
806 _set_Velocities_Wind_Body( Propagate->GetUVW(1),
807 Propagate->GetUVW(2),
808 Propagate->GetUVW(3) );
810 // Make the HUD work ...
811 _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
812 Propagate->GetVel(FGJSBBase::eEast),
813 -Propagate->GetVel(FGJSBBase::eDown) );
815 _set_V_rel_wind( Auxiliary->GetVt() );
817 _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
819 _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
821 _set_V_ground_speed( Auxiliary->GetVground() );
823 _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
824 Propagate->GetPQR(FGJSBBase::eQ),
825 Propagate->GetPQR(FGJSBBase::eR) );
827 _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
828 Auxiliary->GetEulerRates(FGJSBBase::eTht),
829 Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
831 _set_Mach_number( Auxiliary->GetMach() );
833 // Positions of Visual Reference Point
834 FGLocation l = Auxiliary->GetLocationVRP();
835 _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
836 l.GetRadius() - get_Sea_level_radius() );
838 _set_Altitude_AGL( Propagate->GetDistanceAGL() );
840 double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
841 double contact[3], d[3], sd, t;
842 is_valid_m(&t, d, &sd);
843 get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
845 = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
846 _set_Runway_altitude( rwrad - get_Sea_level_radius() );
849 _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
850 Propagate->GetEuler(FGJSBBase::eTht),
851 Propagate->GetEuler(FGJSBBase::ePsi) );
853 _set_Alpha( Auxiliary->Getalpha() );
854 _set_Beta( Auxiliary->Getbeta() );
857 _set_Gamma_vert_rad( Auxiliary->GetGamma() );
859 _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
861 _set_Climb_Rate( Propagate->Gethdot() );
863 const FGMatrix33& Tl2b = Propagate->GetTl2b();
864 for ( i = 1; i <= 3; i++ ) {
865 for ( j = 1; j <= 3; j++ ) {
866 _set_T_Local_to_Body( i, j, Tl2b(i,j) );
870 // Copy the engine values from JSBSim.
871 for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
872 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
873 SGPropertyNode * tnode = node->getChild("thruster", 0, true);
874 FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
876 switch (Propulsion->GetEngine(i)->GetType()) {
877 case FGEngine::etPiston:
878 { // FGPiston code block
879 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
880 node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
881 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
882 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
883 node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
884 // NOTE: mp-osi is not in ounces per square inch.
885 // This error is left for reasons of backwards compatibility with
886 // existing FlightGear sound and instrument configurations.
887 node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
888 node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
889 node->setDoubleValue("rpm", eng->getRPM());
890 } // end FGPiston code block
892 case FGEngine::etRocket:
893 { // FGRocket code block
894 // FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
895 } // end FGRocket code block
897 case FGEngine::etTurbine:
898 { // FGTurbine code block
899 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
900 node->setDoubleValue("n1", eng->GetN1());
901 node->setDoubleValue("n2", eng->GetN2());
902 node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
903 node->setBoolValue("augmentation", eng->GetAugmentation());
904 node->setBoolValue("water-injection", eng->GetInjection());
905 node->setBoolValue("ignition", eng->GetIgnition() != 0);
906 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
907 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
908 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
909 node->setBoolValue("reversed", eng->GetReversed());
910 node->setBoolValue("cutoff", eng->GetCutoff());
911 node->setDoubleValue("epr", eng->GetEPR());
912 globals->get_controls()->set_reverser(i, eng->GetReversed() );
913 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
914 globals->get_controls()->set_water_injection(i, eng->GetInjection() );
915 globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
916 } // end FGTurbine code block
918 case FGEngine::etTurboprop:
919 { // FGTurboProp code block
920 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
921 node->setDoubleValue("n1", eng->GetN1());
922 //node->setDoubleValue("n2", eng->GetN2());
923 node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
924 node->setBoolValue("ignition", eng->GetIgnition() != 0);
925 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
926 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
927 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
928 node->setBoolValue("reversed", eng->GetReversed());
929 node->setBoolValue("cutoff", eng->GetCutoff());
930 node->setBoolValue("starting", eng->GetEngStarting());
931 node->setBoolValue("generator-power", eng->GetGeneratorPower());
932 node->setBoolValue("damaged", eng->GetCondition() != 0);
933 node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
934 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
935 // node->setBoolValue("onfire", eng->GetFire());
936 globals->get_controls()->set_reverser(i, eng->GetReversed() );
937 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
938 } // end FGTurboProp code block
940 case FGEngine::etElectric:
941 { // FGElectric code block
942 FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
943 node->setDoubleValue("rpm", eng->getRPM());
944 } // end FGElectric code block
946 case FGEngine::etUnknown:
950 { // FGEngine code block
951 FGEngine* eng = Propulsion->GetEngine(i);
952 node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
953 node->setDoubleValue("thrust_lb", thruster->GetThrust());
954 node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
955 node->setBoolValue("running", eng->GetRunning());
956 node->setBoolValue("starter", eng->GetStarter());
957 node->setBoolValue("cranking", eng->GetCranking());
958 globals->get_controls()->set_starter(i, eng->GetStarter() );
959 } // end FGEngine code block
961 switch (thruster->GetType()) {
962 case FGThruster::ttNozzle:
963 { // FGNozzle code block
964 // FGNozzle* noz = (FGNozzle*)thruster;
965 } // end FGNozzle code block
967 case FGThruster::ttPropeller:
968 { // FGPropeller code block
969 FGPropeller* prop = (FGPropeller*)thruster;
970 tnode->setDoubleValue("rpm", thruster->GetRPM());
971 tnode->setDoubleValue("pitch", prop->GetPitch());
972 tnode->setDoubleValue("torque", prop->GetTorque());
973 tnode->setBoolValue("feathered", prop->GetFeather());
974 } // end FGPropeller code block
976 case FGThruster::ttRotor:
977 { // FGRotor code block
978 // FGRotor* rotor = (FGRotor*)thruster;
979 } // end FGRotor code block
981 case FGThruster::ttDirect:
982 { // Direct code block
983 } // end Direct code block
989 // Copy the fuel levels from JSBSim if fuel
990 // freeze not enabled.
991 if ( ! Propulsion->GetFuelFreeze() ) {
992 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
993 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
994 FGTank* tank = Propulsion->GetTank(i);
995 double contents = tank->GetContents();
996 double temp = tank->GetTemperature_degC();
997 double fuelDensity = tank->GetDensity();
999 if (fuelDensity < 0.1)
1000 fuelDensity = 6.0; // Use average fuel value
1002 node->setDoubleValue("density-ppg" , fuelDensity);
1003 node->setDoubleValue("level-lbs", contents);
1004 if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
1010 stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
1012 elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
1013 left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
1014 right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
1015 rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
1016 flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
1017 speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
1018 spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
1019 tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
1020 wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
1022 // force a sim crashed if crashed (altitude AGL < 0)
1023 if (get_Altitude_AGL() < -100.0) {
1024 fdmex->SuspendIntegration();
1032 bool FGJSBsim::ToggleDataLogging(void)
1034 // ToDo: handle this properly
1035 fdmex->DisableOutput();
1040 bool FGJSBsim::ToggleDataLogging(bool state)
1043 fdmex->EnableOutput();
1046 fdmex->DisableOutput();
1053 void FGJSBsim::set_Latitude(double lat)
1055 static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
1057 double sea_level_radius_meters, lat_geoc;
1059 // In case we're not trimming
1060 FGInterface::set_Latitude(lat);
1062 if ( altitude->getDoubleValue() > -9990 ) {
1063 alt = altitude->getDoubleValue();
1069 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1070 SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) = " << alt );
1072 sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1073 &sea_level_radius_meters, &lat_geoc );
1074 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
1075 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
1076 fgic->SetLatitudeRadIC( lat_geoc );
1078 if (!fdmex->Holding())
1083 void FGJSBsim::set_Longitude(double lon)
1085 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1087 // In case we're not trimming
1088 FGInterface::set_Longitude(lon);
1091 fgic->SetLongitudeRadIC( lon );
1093 if (!fdmex->Holding())
1097 // Sets the altitude above sea level.
1098 void FGJSBsim::set_Altitude(double alt)
1100 static SGConstPropertyNode_ptr latitude = fgGetNode("/position/latitude-deg");
1102 double sea_level_radius_meters,lat_geoc;
1104 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1105 SG_LOG(SG_FLIGHT,SG_INFO, " lat (deg) = " << latitude->getDoubleValue() );
1107 // In case we're not trimming
1108 FGInterface::set_Altitude(alt);
1111 sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
1112 &sea_level_radius_meters, &lat_geoc);
1113 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
1114 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
1115 SG_LOG(SG_FLIGHT, SG_INFO,
1116 "Terrain elevation: " << FGInterface::get_Runway_altitude() * SG_METER_TO_FEET );
1117 fgic->SetLatitudeRadIC( lat_geoc );
1118 fgic->SetAltitudeASLFtIC(alt);
1120 if (!fdmex->Holding())
1124 void FGJSBsim::set_V_calibrated_kts(double vc)
1126 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " << vc );
1128 // In case we're not trimming
1129 FGInterface::set_V_calibrated_kts(vc);
1132 fgic->SetVcalibratedKtsIC(vc);
1134 if (!fdmex->Holding())
1138 void FGJSBsim::set_Mach_number(double mach)
1140 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " << mach );
1142 // In case we're not trimming
1143 FGInterface::set_Mach_number(mach);
1146 fgic->SetMachIC(mach);
1148 if (!fdmex->Holding())
1152 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1154 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1155 << north << ", " << east << ", " << down );
1157 // In case we're not trimming
1158 FGInterface::set_Velocities_Local(north, east, down);
1161 fgic->SetVNorthFpsIC(north);
1162 fgic->SetVEastFpsIC(east);
1163 fgic->SetVDownFpsIC(down);
1165 if (!fdmex->Holding())
1169 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1171 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1172 << u << ", " << v << ", " << w );
1174 // In case we're not trimming
1175 FGInterface::set_Velocities_Wind_Body(u, v, w);
1178 fgic->SetUBodyFpsIC(u);
1179 fgic->SetVBodyFpsIC(v);
1180 fgic->SetWBodyFpsIC(w);
1182 if (!fdmex->Holding())
1187 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1189 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1190 << phi << ", " << theta << ", " << psi );
1192 // In case we're not trimming
1193 FGInterface::set_Euler_Angles(phi, theta, psi);
1196 fgic->SetThetaRadIC(theta);
1197 fgic->SetPhiRadIC(phi);
1198 fgic->SetPsiRadIC(psi);
1200 if (!fdmex->Holding())
1205 void FGJSBsim::set_Climb_Rate( double roc)
1207 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1209 // In case we're not trimming
1210 FGInterface::set_Climb_Rate(roc);
1213 //since both climb rate and flight path angle are set in the FG
1214 //startup sequence, something is needed to keep one from cancelling
1216 if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1217 fgic->SetClimbRateFpsIC(roc);
1220 if (!fdmex->Holding())
1224 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1226 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1229 if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1230 fgic->SetFlightPathAngleRadIC(gamma);
1233 if (!fdmex->Holding())
1237 void FGJSBsim::init_gear(void )
1239 FGGroundReactions* gr=fdmex->GetGroundReactions();
1240 int Ngear=GroundReactions->GetNumGearUnits();
1241 for (int i=0;i<Ngear;i++) {
1242 FGLGear *gear = gr->GetGearUnit(i);
1243 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1244 node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1245 node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1246 node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1247 node->setBoolValue("wow", gear->GetWOW());
1248 node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1249 node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1250 node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1251 node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1252 node->setDoubleValue("compression-norm", gear->GetCompLen());
1253 node->setDoubleValue("compression-ft", gear->GetCompLen());
1254 if ( gear->GetSteerable() )
1255 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1259 void FGJSBsim::update_gear(void)
1261 FGGroundReactions* gr=fdmex->GetGroundReactions();
1262 int Ngear=GroundReactions->GetNumGearUnits();
1263 for (int i=0;i<Ngear;i++) {
1264 FGLGear *gear = gr->GetGearUnit(i);
1265 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1266 node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1267 node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1268 node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1269 gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1270 node->setDoubleValue("compression-norm", gear->GetCompLen());
1271 node->setDoubleValue("compression-ft", gear->GetCompLen());
1272 if ( gear->GetSteerable() )
1273 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1277 void FGJSBsim::do_trim(void)
1281 if ( fgGetBool("/sim/presets/onground") )
1283 fgtrim = new FGTrim(fdmex,tGround);
1285 fgtrim = new FGTrim(fdmex,tLongitudinal);
1288 if ( !fgtrim->DoTrim() ) {
1290 fgtrim->TrimStats();
1292 trimmed->setBoolValue(true);
1296 pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1297 throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1298 aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1299 rudder_trim->setDoubleValue( FCS->GetDrCmd() );
1301 globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1302 globals->get_controls()->set_elevator(FCS->GetDeCmd());
1303 for( unsigned i = 0; i < Propulsion->GetNumEngines(); i++ )
1304 globals->get_controls()->set_throttle(i, FCS->GetThrottleCmd(i));
1306 globals->get_controls()->set_aileron(FCS->GetDaCmd());
1307 globals->get_controls()->set_rudder( FCS->GetDrCmd());
1309 SG_LOG( SG_FLIGHT, SG_INFO, " Trim complete" );
1312 void FGJSBsim::update_ic(void)
1315 fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1316 fgic->SetLongitudeRadIC( get_Longitude() );
1317 fgic->SetAltitudeASLFtIC( get_Altitude() );
1318 fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1319 fgic->SetThetaRadIC( get_Theta() );
1320 fgic->SetPhiRadIC( get_Phi() );
1321 fgic->SetPsiRadIC( get_Psi() );
1322 fgic->SetClimbRateFpsIC( get_Climb_Rate() );
1327 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1328 double contact[3], double normal[3], double vel[3],
1329 double angularVel[3], double *agl)
1331 const SGMaterial* material;
1332 simgear::BVHNode::Id id;
1333 if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1334 angularVel, material, id))
1336 SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1337 SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1338 *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1342 inline static double dot3(const FGColumnVector3& a, const FGColumnVector3& b)
1344 return a(1) * b(1) + a(2) * b(2) + a(3) * b(3);
1347 inline static double sqr(double x)
1352 static double angle_diff(double a, double b)
1354 double diff = fabs(a - b);
1355 if (diff > 180) diff = 360 - diff;
1360 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)
1362 FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1363 double dist = dot3(tip, ground_normal_body);
1364 if (fabs(dist + E) < 0.0001) {
1365 sin_fis[*points] = sin_fi_guess;
1366 cos_fis[*points] = cos_fi_guess;
1367 fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1373 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)
1375 if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1376 double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1377 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1378 if (fabs(cos_fi_guess) > SG_EPSILON) {
1379 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1384 void FGJSBsim::update_external_forces(double t_off)
1386 const FGMatrix33& Tb2l = Propagate->GetTb2l();
1387 const FGMatrix33& Tl2b = Propagate->GetTl2b();
1388 const FGLocation& Location = Propagate->GetLocation();
1389 const FGMatrix33& Tec2l = Location.GetTec2l();
1391 double hook_area[4][3];
1393 FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1394 FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l * hook_root_body);
1395 hook_area[1][0] = hook_root(1);
1396 hook_area[1][1] = hook_root(2);
1397 hook_area[1][2] = hook_root(3);
1399 hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1400 double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1401 double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1402 double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1403 double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1404 double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1406 FGColumnVector3 hook_tip_body = hook_root_body;
1407 hook_tip_body(1) -= hook_length * cos_fi;
1408 hook_tip_body(3) += hook_length * sin_fi;
1411 double ground_normal[3];
1412 double ground_vel[3];
1413 double ground_angular_vel[3];
1417 bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1418 ground_vel, ground_angular_vel, &root_agl_ft);
1419 if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1420 FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1421 FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1422 double D = -dot3(contact_body, ground_normal_body);
1424 // check hook tip agl against same ground plane
1425 double hook_tip_agl_ft = dot3(hook_tip_body, ground_normal_body) + D;
1426 if (hook_tip_agl_ft < 0) {
1428 // hook tip: hx - l cos, hy, hz + l sin
1429 // on ground: - n0 l cos + n2 l sin + E = 0
1431 double E = D + dot3(hook_root_body, ground_normal_body);
1433 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1434 // and rearrange to get a quadratic with coeffs:
1435 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1436 double b = 2 * E * ground_normal_body(3) * hook_length;
1437 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);
1439 double disc = sqr(b) - 4 * a * c;
1441 double delta = sqrt(disc) / (2 * a);
1443 // allow 4 solutions for safety, should never happen
1449 double sin_fi_guess = -b / (2 * a) - delta;
1450 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1451 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1454 double diff1 = angle_diff(fi, fis[0]);
1455 double diff2 = angle_diff(fi, fis[1]);
1456 int point = diff1 < diff2 ? 0 : 1;
1458 sin_fi = sin_fis[point];
1459 cos_fi = cos_fis[point];
1460 hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1461 hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1467 FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() * hook_root_body));
1468 double wire_ends_ec[2][3];
1469 double wire_vel_ec[2][3];
1470 get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1471 FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1472 FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1473 FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1474 if (rel_vel.Magnitude() < 3) {
1477 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1479 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;
1480 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;
1481 FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1482 force_plane_normal.Normalize();
1483 cos_fi = dot3(force_plane_normal, FGColumnVector3(0, 0, 1));
1484 if (cos_fi < 0) cos_fi = -cos_fi;
1485 sin_fi = sqrt(1 - sqr(cos_fi));
1486 fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1488 fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1489 fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1490 fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1491 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1495 FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1497 hook_area[0][0] = hook_tip(1);
1498 hook_area[0][1] = hook_tip(2);
1499 hook_area[0][2] = hook_tip(3);
1502 // The previous positions.
1503 hook_area[2][0] = last_hook_root[0];
1504 hook_area[2][1] = last_hook_root[1];
1505 hook_area[2][2] = last_hook_root[2];
1506 hook_area[3][0] = last_hook_tip[0];
1507 hook_area[3][1] = last_hook_tip[1];
1508 hook_area[3][2] = last_hook_tip[2];
1510 // Check if we caught a wire.
1511 // Returns true if we caught one.
1512 if (caught_wire_ft(t_off, hook_area)) {
1517 // save actual position as old position ...
1518 last_hook_tip[0] = hook_area[0][0];
1519 last_hook_tip[1] = hook_area[0][1];
1520 last_hook_tip[2] = hook_area[0][2];
1521 last_hook_root[0] = hook_area[1][0];
1522 last_hook_root[1] = hook_area[1][1];
1523 last_hook_root[2] = hook_area[1][2];
1525 fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);