1 // JSBsim.cxx -- interface to the JSBsim flight model
3 // Written by Curtis Olson, started February 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include <simgear/compiler.h>
30 #include <stdio.h> // size_t
31 #ifdef SG_MATH_EXCEPTION_CLASH
37 #include <simgear/constants.h>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/math/sg_geodesy.hxx>
40 #include <simgear/misc/sg_path.hxx>
41 #include <simgear/structure/commands.hxx>
43 #include <FDM/flight.hxx>
45 #include <Aircraft/aircraft.hxx>
46 #include <Aircraft/controls.hxx>
47 #include <Main/globals.hxx>
48 #include <Main/fg_props.hxx>
51 #include <FDM/JSBSim/FGFDMExec.h>
52 #include <FDM/JSBSim/FGJSBBase.h>
53 #include <FDM/JSBSim/FGState.h>
54 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
55 #include <FDM/JSBSim/initialization/FGTrim.h>
56 #include <FDM/JSBSim/models/FGModel.h>
57 #include <FDM/JSBSim/models/FGAircraft.h>
58 #include <FDM/JSBSim/models/FGFCS.h>
59 #include <FDM/JSBSim/models/FGPropagate.h>
60 #include <FDM/JSBSim/models/FGAuxiliary.h>
61 #include <FDM/JSBSim/models/FGAtmosphere.h>
62 #include <FDM/JSBSim/models/FGMassBalance.h>
63 #include <FDM/JSBSim/models/FGAerodynamics.h>
64 #include <FDM/JSBSim/models/FGLGear.h>
65 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
66 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
67 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
68 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
69 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
70 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
71 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
72 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
73 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
74 #include <FDM/JSBSim/models/propulsion/FGTank.h>
75 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
76 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
78 using namespace JSBSim;
81 FMAX (double a, double b)
86 class FGFSGroundCallback : public FGGroundCallback {
88 FGFSGroundCallback(FGInterface* ifc) : mInterface(ifc) {}
89 virtual ~FGFSGroundCallback() {}
91 /** Get the altitude above sea level depenent on the location. */
92 virtual double GetAltitude(const FGLocation& l) const {
93 double pt[3] = { SG_FEET_TO_METER*l(eX),
94 SG_FEET_TO_METER*l(eY),
95 SG_FEET_TO_METER*l(eZ) };
97 sgCartToGeod( pt, &lat, &lon, &alt);
98 return alt * SG_METER_TO_FEET;
101 /** Compute the altitude above ground. */
102 virtual double GetAGLevel(double t, const FGLocation& l,
104 FGColumnVector3& n, FGColumnVector3& v) const {
105 double loc_cart[3] = { l(eX), l(eY), l(eZ) };
106 double contact[3], normal[3], vel[3], lc, ff, agl;
108 mInterface->get_agl_ft(t, loc_cart, contact, normal, vel,
109 &groundtype, &lc, &ff, &agl);
110 n = l.GetTec2l()*FGColumnVector3( normal[0], normal[1], normal[2] );
111 v = l.GetTec2l()*FGColumnVector3( vel[0], vel[1], vel[2] );
112 cont = FGColumnVector3( contact[0], contact[1], contact[2] );
116 FGInterface* mInterface;
119 /******************************************************************************/
121 FGJSBsim::FGJSBsim( double dt )
125 // Set up the debugging level
126 // FIXME: this will not respond to
129 // if flight is excluded, don't bother
130 if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
132 // do a rough-and-ready mapping to
133 // the levels documented in FGFDMExec.h
134 switch (logbuf::get_log_priority()) {
136 FGJSBBase::debug_lvl = 0x1f;
139 FGJSBBase::debug_lvl = 0x0f;
141 FGJSBBase::debug_lvl = 0x01;
145 FGJSBBase::debug_lvl = 0x00;
150 fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
152 // Register ground callback.
153 fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
155 State = fdmex->GetState();
156 Atmosphere = fdmex->GetAtmosphere();
157 FCS = fdmex->GetFCS();
158 MassBalance = fdmex->GetMassBalance();
159 Propulsion = fdmex->GetPropulsion();
160 Aircraft = fdmex->GetAircraft();
161 Propagate = fdmex->GetPropagate();
162 Auxiliary = fdmex->GetAuxiliary();
163 Aerodynamics = fdmex->GetAerodynamics();
164 GroundReactions = fdmex->GetGroundReactions();
169 SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
171 SGPath engine_path( fgGetString("/sim/aircraft-dir") );
172 engine_path.append( "Engine" );
175 result = fdmex->LoadModel( aircraft_path.str(),
177 fgGetString("/sim/aero"), false );
180 SG_LOG( SG_FLIGHT, SG_INFO, " loaded aero.");
182 SG_LOG( SG_FLIGHT, SG_INFO,
183 " aero does not exist (you may have mis-typed the name).");
187 SG_LOG( SG_FLIGHT, SG_INFO, "" );
188 SG_LOG( SG_FLIGHT, SG_INFO, "" );
189 SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
191 int Neng = Propulsion->GetNumEngines();
192 SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
194 if ( GroundReactions->GetNumGearUnits() <= 0 ) {
195 SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
196 << GroundReactions->GetNumGearUnits() );
197 SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
198 SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
199 SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
205 // Set initial fuel levels if provided.
206 for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
207 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
208 if (node->getChild("level-gal_us", 0, false) != 0) {
209 Propulsion->GetTank(i)->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
211 node->setDoubleValue("level-lb", Propulsion->GetTank(i)->GetContents());
212 node->setDoubleValue("level-gal_us", Propulsion->GetTank(i)->GetContents() / 6.6);
215 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
217 fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
218 fgSetDouble("/fdm/trim/throttle", FCS->GetThrottleCmd(0));
219 fgSetDouble("/fdm/trim/aileron", FCS->GetDaCmd());
220 fgSetDouble("/fdm/trim/rudder", FCS->GetDrCmd());
222 startup_trim = fgGetNode("/sim/presets/trim", true);
224 trimmed = fgGetNode("/fdm/trim/trimmed", true);
225 trimmed->setBoolValue(false);
227 pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
228 throttle_trim = fgGetNode("/fdm/trim/throttle", true );
229 aileron_trim = fgGetNode("/fdm/trim/aileron", true );
230 rudder_trim = fgGetNode("/fdm/trim/rudder", true );
232 stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
233 stall_warning->setDoubleValue(0);
236 flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
237 elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
239 =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
240 right_aileron_pos_pct
241 =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
242 rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
244 =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
245 spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
247 elevator_pos_pct->setDoubleValue(0);
248 left_aileron_pos_pct->setDoubleValue(0);
249 right_aileron_pos_pct->setDoubleValue(0);
250 rudder_pos_pct->setDoubleValue(0);
251 flap_pos_pct->setDoubleValue(0);
252 speedbrake_pos_pct->setDoubleValue(0);
253 spoilers_pos_pct->setDoubleValue(0);
255 temperature = fgGetNode("/environment/temperature-degc",true);
256 pressure = fgGetNode("/environment/pressure-inhg",true);
257 density = fgGetNode("/environment/density-slugft3",true);
258 turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
259 turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
261 wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
262 wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
263 wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
265 slaved = fgGetNode("/sim/slaved/enabled", true);
267 for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
268 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
269 Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
270 Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
274 /******************************************************************************/
275 FGJSBsim::~FGJSBsim(void)
280 /******************************************************************************/
282 // Initialize the JSBsim flight model, dt is the time increment for
283 // each subsequent iteration through the EOM
285 void FGJSBsim::init()
289 SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
291 // Explicitly call the superclass's
292 // init method first.
294 if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
295 Atmosphere->UseExternal();
296 Atmosphere->SetExTemperature(
297 9.0/5.0*(temperature->getDoubleValue()+273.15) );
298 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
299 Atmosphere->SetExDensity(density->getDoubleValue());
301 tmp = turbulence_gain->getDoubleValue();
302 Atmosphere->SetTurbGain(tmp * tmp * 100.0);
304 tmp = turbulence_rate->getDoubleValue();
305 Atmosphere->SetTurbRate(tmp);
308 Atmosphere->UseInternal();
311 fgic->SetVnorthFpsIC( wind_from_north->getDoubleValue() );
312 fgic->SetVeastFpsIC( wind_from_east->getDoubleValue() );
313 fgic->SetVdownFpsIC( wind_from_down->getDoubleValue() );
315 //Atmosphere->SetExTemperature(get_Static_temperature());
316 //Atmosphere->SetExPressure(get_Static_pressure());
317 //Atmosphere->SetExDensity(get_Density());
318 SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
319 << ", " << fdmex->GetAtmosphere()->GetPressure()
320 << ", " << fdmex->GetAtmosphere()->GetDensity() );
322 if (fgGetBool("/sim/presets/running")) {
323 for (int i=0; i < Propulsion->GetNumEngines(); i++) {
324 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
325 node->setBoolValue("running", true);
326 Propulsion->GetEngine(i)->SetRunning(true);
333 fdmex->RunIC(); //loop JSBSim once w/o integrating
334 copy_from_JSBsim(); //update the bus
336 SG_LOG( SG_FLIGHT, SG_INFO, " Initialized JSBSim with:" );
338 switch(fgic->GetSpeedSet()) {
340 SG_LOG(SG_FLIGHT,SG_INFO, " Vn,Ve,Vd= "
341 << Propagate->GetVel(FGJSBBase::eNorth) << ", "
342 << Propagate->GetVel(FGJSBBase::eEast) << ", "
343 << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
346 SG_LOG(SG_FLIGHT,SG_INFO, " U,V,W= "
347 << Propagate->GetUVW(1) << ", "
348 << Propagate->GetUVW(2) << ", "
349 << Propagate->GetUVW(3) << " ft/s");
352 SG_LOG(SG_FLIGHT,SG_INFO, " Mach: "
353 << Auxiliary->GetMach() );
357 SG_LOG(SG_FLIGHT,SG_INFO, " Indicated Airspeed: "
358 << Auxiliary->GetVcalibratedKTS() << " knots" );
362 stall_warning->setDoubleValue(0);
364 SG_LOG( SG_FLIGHT, SG_INFO, " Bank Angle: "
365 << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
366 SG_LOG( SG_FLIGHT, SG_INFO, " Pitch Angle: "
367 << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
368 SG_LOG( SG_FLIGHT, SG_INFO, " True Heading: "
369 << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
370 SG_LOG( SG_FLIGHT, SG_INFO, " Latitude: "
371 << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
372 SG_LOG( SG_FLIGHT, SG_INFO, " Longitude: "
373 << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
374 SG_LOG( SG_FLIGHT, SG_INFO, " Altitude: "
375 << Propagate->Geth() << " feet" );
376 SG_LOG( SG_FLIGHT, SG_INFO, " loaded initial conditions" );
378 SG_LOG( SG_FLIGHT, SG_INFO, " set dt" );
380 SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
382 SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
383 globals->get_controls()->get_gear_down() );
386 /******************************************************************************/
388 // Run an iteration of the EOM (equations of motion)
390 void FGJSBsim::update( double dt )
395 int multiloop = _calc_multiloop(dt);
399 // Compute the radius of the aircraft. That is the radius of a ball
400 // where all gear units are in. At the moment it is at least 10ft ...
402 int n_gears = GroundReactions->GetNumGearUnits();
403 for (i=0; i<n_gears; ++i) {
404 FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
405 double r = bl.Magnitude();
410 // Compute the potential movement of this aircraft and query for the
411 // ground in this area.
412 double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
413 double alt, slr, lat, lon;
414 FGColumnVector3 cart = Auxiliary->GetLocationVRP();
415 if ( needTrim && startup_trim->getBoolValue() ) {
416 alt = fgic->GetAltitudeFtIC();
417 slr = fgic->GetSeaLevelRadiusFtIC();
418 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
419 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
420 cart = FGLocation(lon, lat, alt+slr);
422 double cart_pos[3] = { cart(1), cart(2), cart(3) };
423 bool cache_ok = prepare_ground_cache_ft( State->Getsim_time(), cart_pos,
426 SG_LOG(SG_FLIGHT, SG_WARN,
427 "FGInterface is being called without scenery below the aircraft!");
428 cout << "altitude = " << alt << endl;
429 cout << "sea level radius = " << slr << endl;
430 cout << "latitude = " << lat << endl;
431 cout << "longitude = " << lon << endl;
437 trimmed->setBoolValue(false);
440 if ( startup_trim->getBoolValue() ) {
441 double contact[3], dummy[3], lc, ff, agl;
443 get_agl_ft(State->Getsim_time(), cart_pos, contact,
444 dummy, dummy, &groundtype, &lc, &ff, &agl);
445 double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
446 + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
448 SG_LOG(SG_FLIGHT, SG_INFO,
449 "Ready to trim, terrain altitude is: "
450 << terrain_alt * SG_METER_TO_FEET );
452 fgic->SetTerrainAltitudeFtIC( terrain_alt );
455 fdmex->RunIC(); //apply any changes made through the set_ functions
460 for ( i=0; i < multiloop; i++ ) {
464 FGJSBBase::Message* msg;
465 while (fdmex->ReadMessage()) {
466 msg = fdmex->ProcessMessage();
468 case FGJSBBase::Message::eText:
469 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
471 case FGJSBBase::Message::eBool:
472 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
474 case FGJSBBase::Message::eInteger:
475 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
477 case FGJSBBase::Message::eDouble:
478 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
481 SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
486 // translate JSBsim back to FG structure so that the
487 // autopilot (and the rest of the sim can use the updated values
491 /******************************************************************************/
493 // Convert from the FGInterface struct to the JSBsim generic_ struct
495 bool FGJSBsim::copy_to_JSBsim()
500 // copy control positions into the JSBsim structure
502 FCS->SetDaCmd( globals->get_controls()->get_aileron());
503 FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
504 FCS->SetDeCmd( globals->get_controls()->get_elevator());
505 FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
506 FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
507 FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
508 // FIXME: make that get_steering work
509 // FCS->SetDsCmd( globals->get_controls()->get_steering()/80.0 );
510 FCS->SetDsCmd( globals->get_controls()->get_rudder() );
511 FCS->SetDfCmd( globals->get_controls()->get_flaps() );
512 FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
513 FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
515 // Parking brake sets minimum braking
517 double parking_brake = globals->get_controls()->get_brake_parking();
518 FCS->SetLBrake(FMAX(globals->get_controls()->get_brake_left(), parking_brake));
519 FCS->SetRBrake(FMAX(globals->get_controls()->get_brake_right(), parking_brake));
520 FCS->SetCBrake( 0.0 );
521 // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
523 FCS->SetGearCmd( globals->get_controls()->get_gear_down());
524 for (i = 0; i < Propulsion->GetNumEngines(); i++) {
525 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
527 FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
528 FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
529 FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
530 FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
532 switch (Propulsion->GetEngine(i)->GetType()) {
533 case FGEngine::etPiston:
534 { // FGPiston code block
535 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
536 eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
538 } // end FGPiston code block
539 case FGEngine::etTurbine:
540 { // FGTurbine code block
541 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
542 eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
543 eng->SetReverse( globals->get_controls()->get_reverser(i) );
544 eng->SetInjection( globals->get_controls()->get_water_injection(i) );
545 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
546 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
548 } // end FGTurbine code block
549 case FGEngine::etRocket:
550 { // FGRocket code block
551 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
553 } // end FGRocket code block
554 case FGEngine::etTurboprop:
555 { // FGTurboProp code block
556 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
557 eng->SetReverse( globals->get_controls()->get_reverser(i) );
558 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
559 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
561 eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
562 eng->SetCondition( globals->get_controls()->get_condition(i) );
564 } // end FGTurboProp code block
567 { // FGEngine code block
568 FGEngine* eng = Propulsion->GetEngine(i);
570 eng->SetStarter( globals->get_controls()->get_starter(i) );
571 eng->SetRunning( node->getBoolValue("running") );
572 } // end FGEngine code block
576 Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
578 Atmosphere->SetExTemperature(
579 9.0/5.0*(temperature->getDoubleValue()+273.15) );
580 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
581 Atmosphere->SetExDensity(density->getDoubleValue());
583 tmp = turbulence_gain->getDoubleValue();
584 Atmosphere->SetTurbGain(tmp * tmp * 100.0);
586 tmp = turbulence_rate->getDoubleValue();
587 Atmosphere->SetTurbRate(tmp);
589 Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
590 wind_from_east->getDoubleValue(),
591 wind_from_down->getDoubleValue() );
592 // SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
593 // << get_V_north_airmass() << ", "
594 // << get_V_east_airmass() << ", "
595 // << get_V_down_airmass() );
597 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
598 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
599 FGTank * tank = Propulsion->GetTank(i);
600 tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
601 // tank->SetContents(node->getDoubleValue("level-lb"));
603 SGPropertyNode* node = fgGetNode("/systems/refuel", true);
604 Propulsion->SetRefuel(node->getDoubleValue("contact"));
605 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
606 fdmex->SetSlave(slaved->getBoolValue());
611 /******************************************************************************/
613 // Convert from the JSBsim generic_ struct to the FGInterface struct
615 bool FGJSBsim::copy_from_JSBsim()
619 _set_Inertias( MassBalance->GetMass(),
620 MassBalance->GetIxx(),
621 MassBalance->GetIyy(),
622 MassBalance->GetIzz(),
623 MassBalance->GetIxz() );
625 _set_CG_Position( MassBalance->GetXYZcg(1),
626 MassBalance->GetXYZcg(2),
627 MassBalance->GetXYZcg(3) );
629 _set_Accels_Body( Aircraft->GetBodyAccel(1),
630 Aircraft->GetBodyAccel(2),
631 Aircraft->GetBodyAccel(3) );
633 _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
635 Aircraft->GetNcg(3) );
637 _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
638 Auxiliary->GetPilotAccel(2),
639 Auxiliary->GetPilotAccel(3) );
641 _set_Nlf( Aircraft->GetNlf() );
645 _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
646 Propagate->GetVel(FGJSBBase::eEast),
647 Propagate->GetVel(FGJSBBase::eDown) );
649 _set_Velocities_Wind_Body( Propagate->GetUVW(1),
650 Propagate->GetUVW(2),
651 Propagate->GetUVW(3) );
653 // Make the HUD work ...
654 _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
655 Propagate->GetVel(FGJSBBase::eEast),
656 -Propagate->GetVel(FGJSBBase::eDown) );
658 _set_V_rel_wind( Auxiliary->GetVt() );
660 _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
662 _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
664 _set_V_ground_speed( Auxiliary->GetVground() );
666 _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
667 Propagate->GetPQR(FGJSBBase::eQ),
668 Propagate->GetPQR(FGJSBBase::eR) );
670 _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
671 Auxiliary->GetEulerRates(FGJSBBase::eTht),
672 Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
674 _set_Mach_number( Auxiliary->GetMach() );
676 // Positions of Visual Reference Point
677 FGLocation l = Auxiliary->GetLocationVRP();
678 _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
679 l.GetRadius() - get_Sea_level_radius() );
681 _set_Altitude_AGL( Propagate->GetDistanceAGL() );
683 double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
684 double contact[3], d[3], sd, t;
686 is_valid_m(&t, d, &sd);
687 get_agl_ft(t, loc_cart, contact, d, d, &id, &sd, &sd, &sd);
689 = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
690 _set_Runway_altitude( rwrad - get_Sea_level_radius() );
693 _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
694 Propagate->GetEuler(FGJSBBase::eTht),
695 Propagate->GetEuler(FGJSBBase::ePsi) );
697 _set_Alpha( Auxiliary->Getalpha() );
698 _set_Beta( Auxiliary->Getbeta() );
701 _set_Gamma_vert_rad( Auxiliary->GetGamma() );
703 _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
705 _set_Climb_Rate( Propagate->Gethdot() );
707 const FGMatrix33& Tl2b = Propagate->GetTl2b();
708 for ( i = 1; i <= 3; i++ ) {
709 for ( j = 1; j <= 3; j++ ) {
710 _set_T_Local_to_Body( i, j, Tl2b(i,j) );
714 // Copy the engine values from JSBSim.
715 for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
716 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
718 sprintf(buf, "engines/engine[%d]/thruster", i);
719 SGPropertyNode * tnode = fgGetNode(buf, true);
720 FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
722 switch (Propulsion->GetEngine(i)->GetType()) {
723 case FGEngine::etPiston:
724 { // FGPiston code block
725 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
726 node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
727 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
728 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
729 node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
730 node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
731 node->setDoubleValue("rpm", eng->getRPM());
732 } // end FGPiston code block
734 case FGEngine::etRocket:
735 { // FGRocket code block
736 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
737 } // end FGRocket code block
739 case FGEngine::etTurbine:
740 { // FGTurbine code block
741 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
742 node->setDoubleValue("n1", eng->GetN1());
743 node->setDoubleValue("n2", eng->GetN2());
744 node->setDoubleValue("egt_degf", 32 + eng->GetEGT()*9/5);
745 node->setBoolValue("augmentation", eng->GetAugmentation());
746 node->setBoolValue("water-injection", eng->GetInjection());
747 node->setBoolValue("ignition", eng->GetIgnition());
748 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
749 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
750 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
751 node->setBoolValue("reversed", eng->GetReversed());
752 node->setBoolValue("cutoff", eng->GetCutoff());
753 node->setDoubleValue("epr", eng->GetEPR());
754 globals->get_controls()->set_reverser(i, eng->GetReversed() );
755 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
756 globals->get_controls()->set_water_injection(i, eng->GetInjection() );
757 globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
758 } // end FGTurbine code block
760 case FGEngine::etTurboprop:
761 { // FGTurboProp code block
762 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
763 node->setDoubleValue("n1", eng->GetN1());
764 //node->setDoubleValue("n2", eng->GetN2());
765 node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
766 node->setBoolValue("ignition", eng->GetIgnition());
767 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
768 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
769 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
770 node->setBoolValue("reversed", eng->GetReversed());
771 node->setBoolValue("cutoff", eng->GetCutoff());
772 node->setBoolValue("starting", eng->GetEngStarting());
773 node->setBoolValue("generator-power", eng->GetGeneratorPower());
774 node->setBoolValue("damaged", eng->GetCondition());
775 node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
776 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
777 // node->setBoolValue("onfire", eng->GetFire());
778 globals->get_controls()->set_reverser(i, eng->GetReversed() );
779 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
780 } // end FGTurboProp code block
782 case FGEngine::etElectric:
783 { // FGElectric code block
784 FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
785 node->setDoubleValue("rpm", eng->getRPM());
786 } // end FGElectric code block
790 { // FGEngine code block
791 FGEngine* eng = Propulsion->GetEngine(i);
792 node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
793 node->setDoubleValue("thrust_lb", thruster->GetThrust());
794 node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
795 node->setBoolValue("running", eng->GetRunning());
796 node->setBoolValue("starter", eng->GetStarter());
797 node->setBoolValue("cranking", eng->GetCranking());
798 globals->get_controls()->set_starter(i, eng->GetStarter() );
799 } // end FGEngine code block
801 switch (thruster->GetType()) {
802 case FGThruster::ttNozzle:
803 { // FGNozzle code block
804 FGNozzle* noz = (FGNozzle*)thruster;
805 } // end FGNozzle code block
807 case FGThruster::ttPropeller:
808 { // FGPropeller code block
809 FGPropeller* prop = (FGPropeller*)thruster;
810 tnode->setDoubleValue("rpm", thruster->GetRPM());
811 tnode->setDoubleValue("pitch", prop->GetPitch());
812 tnode->setDoubleValue("torque", prop->GetTorque());
813 tnode->setBoolValue("feathered", prop->GetFeather());
814 } // end FGPropeller code block
816 case FGThruster::ttRotor:
817 { // FGRotor code block
818 FGRotor* rotor = (FGRotor*)thruster;
819 } // end FGRotor code block
821 case FGThruster::ttDirect:
822 { // Direct code block
823 } // end Direct code block
829 // Copy the fuel levels from JSBSim if fuel
830 // freeze not enabled.
831 if ( ! Propulsion->GetFuelFreeze() ) {
832 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
833 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
834 FGTank* tank = Propulsion->GetTank(i);
835 double contents = tank->GetContents();
836 double temp = tank->GetTemperature_degC();
837 node->setDoubleValue("level-gal_us", contents/6.6);
838 node->setDoubleValue("level-lb", contents);
839 if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
845 stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
847 elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
848 left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
849 right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
850 rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
851 flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
852 speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
853 spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
855 // force a sim reset if crashed (altitude AGL < 0)
856 if (get_Altitude_AGL() < -100.0) {
857 fgSetBool("/sim/crashed", true);
858 SGPropertyNode* node = fgGetNode("/sim/presets", true);
859 globals->get_commands()->execute("old-reinit-dialog", node);
866 bool FGJSBsim::ToggleDataLogging(void)
868 // ToDo: handle this properly
869 fdmex->DisableOutput();
874 bool FGJSBsim::ToggleDataLogging(bool state)
877 fdmex->EnableOutput();
880 fdmex->DisableOutput();
887 void FGJSBsim::set_Latitude(double lat)
889 static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
891 double sea_level_radius_meters, lat_geoc;
893 // In case we're not trimming
894 FGInterface::set_Latitude(lat);
896 if ( altitude->getDoubleValue() > -9990 ) {
897 alt = altitude->getDoubleValue();
903 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
904 SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) = " << alt );
906 sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
907 &sea_level_radius_meters, &lat_geoc );
908 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
909 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
910 fgic->SetLatitudeRadIC( lat_geoc );
915 void FGJSBsim::set_Longitude(double lon)
917 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
919 // In case we're not trimming
920 FGInterface::set_Longitude(lon);
923 fgic->SetLongitudeRadIC( lon );
927 void FGJSBsim::set_Altitude(double alt)
929 static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
931 double sea_level_radius_meters,lat_geoc;
933 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
934 SG_LOG(SG_FLIGHT,SG_INFO, " lat (deg) = " << latitude->getDoubleValue() );
936 // In case we're not trimming
937 FGInterface::set_Altitude(alt);
940 sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
941 &sea_level_radius_meters, &lat_geoc);
942 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
943 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
944 SG_LOG(SG_FLIGHT, SG_INFO,
945 "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
946 fgic->SetLatitudeRadIC( lat_geoc );
947 fgic->SetAltitudeFtIC(alt);
951 void FGJSBsim::set_V_calibrated_kts(double vc)
953 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " << vc );
955 // In case we're not trimming
956 FGInterface::set_V_calibrated_kts(vc);
959 fgic->SetVcalibratedKtsIC(vc);
963 void FGJSBsim::set_Mach_number(double mach)
965 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " << mach );
967 // In case we're not trimming
968 FGInterface::set_Mach_number(mach);
971 fgic->SetMachIC(mach);
975 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
977 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
978 << north << ", " << east << ", " << down );
980 // In case we're not trimming
981 FGInterface::set_Velocities_Local(north, east, down);
984 fgic->SetVnorthFpsIC(north);
985 fgic->SetVeastFpsIC(east);
986 fgic->SetVdownFpsIC(down);
990 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
992 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
993 << u << ", " << v << ", " << w );
995 // In case we're not trimming
996 FGInterface::set_Velocities_Wind_Body(u, v, w);
999 fgic->SetUBodyFpsIC(u);
1000 fgic->SetVBodyFpsIC(v);
1001 fgic->SetWBodyFpsIC(w);
1006 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1008 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1009 << phi << ", " << theta << ", " << psi );
1011 // In case we're not trimming
1012 FGInterface::set_Euler_Angles(phi, theta, psi);
1015 fgic->SetThetaRadIC(theta);
1016 fgic->SetPhiRadIC(phi);
1017 fgic->SetPsiRadIC(psi);
1022 void FGJSBsim::set_Climb_Rate( double roc)
1024 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1026 // In case we're not trimming
1027 FGInterface::set_Climb_Rate(roc);
1030 //since both climb rate and flight path angle are set in the FG
1031 //startup sequence, something is needed to keep one from cancelling
1033 if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1034 fgic->SetClimbRateFpsIC(roc);
1039 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1041 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1044 if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1045 fgic->SetFlightPathAngleRadIC(gamma);
1050 void FGJSBsim::init_gear(void )
1052 FGGroundReactions* gr=fdmex->GetGroundReactions();
1053 int Ngear=GroundReactions->GetNumGearUnits();
1054 for (int i=0;i<Ngear;i++) {
1055 FGLGear *gear = gr->GetGearUnit(i);
1056 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1057 node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1058 node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1059 node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1060 node->setBoolValue("wow", gear->GetWOW());
1061 node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1062 node->setDoubleValue("position-norm", FCS->GetGearPos());
1063 node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1064 node->setDoubleValue("compression-norm", gear->GetCompLen());
1065 if ( gear->GetSteerable() )
1066 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1070 void FGJSBsim::update_gear(void)
1072 FGGroundReactions* gr=fdmex->GetGroundReactions();
1073 int Ngear=GroundReactions->GetNumGearUnits();
1074 for (int i=0;i<Ngear;i++) {
1075 FGLGear *gear = gr->GetGearUnit(i);
1076 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1077 node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1078 node->getChild("position-norm", 0, true)->setDoubleValue(FCS->GetGearPos());
1079 gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1080 node->setDoubleValue("compression-norm", gear->GetCompLen());
1081 if ( gear->GetSteerable() )
1082 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1086 void FGJSBsim::do_trim(void)
1090 if ( fgGetBool("/sim/presets/onground") )
1092 fgic->SetVcalibratedKtsIC(0.0);
1093 fgtrim = new FGTrim(fdmex,tGround);
1095 fgtrim = new FGTrim(fdmex,tLongitudinal);
1098 if ( !fgtrim->DoTrim() ) {
1100 fgtrim->TrimStats();
1102 trimmed->setBoolValue(true);
1104 if (FGJSBBase::debug_lvl > 0)
1105 State->ReportState();
1109 pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1110 throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1111 aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1112 rudder_trim->setDoubleValue( FCS->GetDrCmd() );
1114 globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1115 globals->get_controls()->set_elevator(FCS->GetDeCmd());
1116 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
1117 FCS->GetThrottleCmd(0));
1119 globals->get_controls()->set_aileron(FCS->GetDaCmd());
1120 globals->get_controls()->set_rudder( FCS->GetDrCmd());
1122 SG_LOG( SG_FLIGHT, SG_INFO, " Trim complete" );
1125 void FGJSBsim::update_ic(void)
1128 fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1129 fgic->SetLongitudeRadIC( get_Longitude() );
1130 fgic->SetAltitudeFtIC( get_Altitude() );
1131 fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1132 fgic->SetThetaRadIC( get_Theta() );
1133 fgic->SetPhiRadIC( get_Phi() );
1134 fgic->SetPsiRadIC( get_Psi() );
1135 fgic->SetClimbRateFpsIC( get_Climb_Rate() );