9 #include <simgear/debug/logstream.hxx>
10 #include <simgear/math/sg_geodesy.hxx>
11 #include <simgear/misc/sg_path.hxx>
12 #include <simgear/scene/model/placement.hxx>
13 #include <simgear/xml/easyxml.hxx>
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
19 #include "Atmosphere.hpp"
21 #include "Airplane.hpp"
23 #include "Integrator.hpp"
27 #include "Launchbar.hpp"
28 #include "FGGround.hpp"
29 #include "PropEngine.hpp"
30 #include "PistonEngine.hpp"
34 using namespace yasim;
36 static const float YASIM_PI = 3.14159265358979323846;
37 static const float RAD2DEG = 180/YASIM_PI;
38 static const float PI2 = YASIM_PI*2;
39 static const float RAD2RPM = 9.54929658551;
40 static const float M2FT = 3.2808399;
41 static const float FT2M = 0.3048;
42 static const float MPS2KTS = 3600.0/1852.0;
43 static const float CM2GALS = 264.172037284; // gallons/cubic meter
44 static const float KG2LBS = 2.20462262185;
45 static const float W2HP = 1.3416e-3;
46 static const float INHG2PA = 3386.389;
47 static const float SLUG2KG = 14.59390;
49 YASim::YASim(double dt) :
57 _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
58 _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
70 Airplane* a = _fdm->getAirplane();
72 float aoa = a->getCruiseAoA() * RAD2DEG;
73 float tail = -1 * a->getTailIncidence() * RAD2DEG;
74 float drag = 1000 * a->getDragCoefficient();
76 SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
77 SG_LOG(SG_FLIGHT,SG_INFO," Iterations: "<<a->getSolutionIterations());
78 SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
79 SG_LOG(SG_FLIGHT,SG_INFO," Lift Ratio: "<<a->getLiftRatio());
80 SG_LOG(SG_FLIGHT,SG_INFO," Cruise AoA: "<< aoa);
81 SG_LOG(SG_FLIGHT,SG_INFO," Tail Incidence: "<< tail);
82 SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
86 a->getModel()->getBody()->getCG(cg);
87 sprintf(buf, " CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
88 SG_LOG(SG_FLIGHT, SG_INFO, buf);
90 if(a->getFailureMsg()) {
91 SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
92 SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
99 // Run the superclass bind to set up a bunch of property ties
102 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
103 // Now UNtie the ones that we are going to set ourselves.
104 // fgUntie("/consumables/fuel/tank[0]/level-gal_us");
105 // fgUntie("/consumables/fuel/tank[1]/level-gal_us");
108 for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
109 sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
110 sprintf(buf, "/engines/engine[%d]/rpm", i); fgUntie(buf);
111 sprintf(buf, "/engines/engine[%d]/mp-osi", i); fgUntie(buf);
112 sprintf(buf, "/engines/engine[%d]/egt-degf", i); fgUntie(buf);
113 sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
117 YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
118 has_brake(gear_root->getNode("has-brake", true)),
119 wow(gear_root->getNode("wow", true)),
120 compression_norm(gear_root->getNode("compression-norm", true)),
121 compression_m(gear_root->getNode("compression-m", true)),
122 caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
123 rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
124 ground_is_solid(gear_root->getNode("ground-is-solid", true)),
125 ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
131 Airplane* airplane = _fdm->getAirplane();
132 Model* model = airplane->getModel();
134 _crashed = fgGetNode("/sim/crashed", true);
135 _pressure_inhg = fgGetNode("/environment/pressure-inhg", true);
136 _temp_degc = fgGetNode("/environment/temperature-degc", true);
137 _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
138 _gear_agl_m = fgGetNode("/position/gear-agl-m", true);
139 _gear_agl_ft = fgGetNode("/position/gear-agl-ft", true);
140 _pilot_g = fgGetNode("/accelerations/pilot-g", true);
141 _speed_setprop = fgGetNode("/sim/presets/speed-set", true);
146 model->setCrashed(false);
147 _crashed->setBoolValue(false);
149 // Figure out the initial speed type
150 string speed_set = _speed_setprop->getStringValue();
151 if ((speed_set == "") || (speed_set == "UVW"))
153 else if (speed_set == "NED")
155 else if (speed_set == "knots")
157 else if (speed_set == "mach")
161 SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
164 // Build a filename and parse it
165 SGPath f(fgGetString("/sim/aircraft-dir"));
166 f.append(fgGetString("/sim/aero"));
169 readXML(f.str(), *_fdm);
170 } catch (const sg_exception &e) {
171 SG_LOG(SG_FLIGHT, SG_ALERT,
172 "Error reading YASim FDM: '" << f.str() << "'" << std::endl
173 << e.getFormattedMessage());
177 // Compile it into a real airplane, and tell the user what they got
183 if (model->getLaunchbar())
185 _catapult_launch_cmd = fgGetNode("/controls/gear/catapult-launch-cmd", true);
186 _launchbar_position_norm = fgGetNode("/gear/launchbar/position-norm", true);
187 _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
188 _launchbar_state = fgGetNode("/gear/launchbar/state", true);
189 _launchbar_strop = fgGetNode("/gear/launchbar/strop", true);
191 if (airplane->getHook())
193 _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
196 // Create some FG{Eng|Gear}Interface objects
197 for(int i=0; i<airplane->numGear(); i++) {
198 Gear* g = airplane->getGear(i);
199 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
202 node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
203 node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
204 node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
206 _gearProps.push_back(GearProps(node));
209 // Are we at ground level? If so, lift the plane up so the gear
211 double runway_altitude = get_Runway_altitude();
212 if(get_Altitude() - runway_altitude < 50) {
213 fgSetBool("/controls/gear/gear-down", false);
214 float minGearZ = 1e18;
215 for(int i=0; i<airplane->numGear(); i++) {
216 Gear* g = airplane->getGear(i);
219 if(pos[2] < minGearZ)
222 _set_Altitude(runway_altitude - minGearZ*M2FT);
223 // ground start-up: gear down
224 fgSetBool("/controls/gear/gear-down", true);
228 // airborne start-up: gear up
229 fgSetBool("/controls/gear/gear-down", false);
232 // Blank the state, and copy in ours
237 _fdm->getExternalInput();
238 _fdm->getAirplane()->initEngines();
243 void YASim::update(double dt)
248 int iterations = _calc_multiloop(dt);
250 // If we're crashed, then we don't care
251 if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
252 if(!_crashed->getBoolValue())
253 _crashed->setBoolValue(true);
254 _fdm->getAirplane()->getModel()->setCrashed(false);
258 // ground. Calculate a cartesian coordinate for the ground under
259 // us, find the (geodetic) up vector normal to the ground, then
260 // use that to find the final (radius) term of the plane equation.
261 float v[3] = { get_uBody(), get_vBody(), get_wBody() };
262 float lat = get_Latitude(); float lon = get_Longitude();
263 float alt = get_Altitude() * FT2M; double xyz[3];
264 sgGeodToCart(lat, lon, alt, xyz);
265 // build the environment cache.
266 float vr = _fdm->getVehicleRadius();
267 vr += 2.0*FT2M*dt*Math::mag3(v);
268 prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
270 // Track time increments.
272 = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
275 for(i=0; i<iterations; i++) {
276 gr->setTimeOffset(_simTime + i*_dt);
282 // Increment the local sim time
284 gr->setTimeOffset(_simTime);
287 void YASim::copyToYASim(bool copyState)
290 double lat = get_Latitude();
291 double lon = get_Longitude();
292 float alt = get_Altitude() * FT2M;
293 float roll = get_Phi();
294 float pitch = get_Theta();
295 float hdg = get_Psi();
299 wind[0] = get_V_north_airmass() * FT2M * -1.0;
300 wind[1] = get_V_east_airmass() * FT2M * -1.0;
301 wind[2] = get_V_down_airmass() * FT2M * -1.0;
303 float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
304 float temp = _temp_degc->getFloatValue() + 273.15;
305 float dens = _density_slugft3->getFloatValue() *
306 SLUG2KG * M2FT*M2FT*M2FT;
309 Model* model = _fdm->getAirplane()->getModel();
312 Glue::xyz2nedMat(lat, lon, xyz2ned);
315 sgGeodToCart(lat, lon, alt, s.pos);
317 // allow setting of /position/[lat|long|alti]tude
318 double * dp = &model->getState()->pos[0];
319 dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
323 Glue::euler2orient(roll, pitch, hdg, s.orient);
324 Math::mmul33(s.orient, xyz2ned, s.orient);
328 bool needCopy = false;
329 switch (_speed_set) {
331 v[0] = get_V_north() * FT2M * -1.0;
332 v[1] = get_V_east() * FT2M * -1.0;
333 v[2] = get_V_down() * FT2M * -1.0;
336 v[0] = get_uBody() * FT2M;
337 v[1] = get_vBody() * FT2M;
338 v[2] = get_wBody() * FT2M;
339 Math::tmul33(s.orient, v, v);
342 v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
346 Math::tmul33(s.orient, v, v);
350 v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
353 Math::tmul33(s.orient, v, v);
363 _speed_set = UVW; // change to this after initial setting
366 if(copyState || needCopy)
370 Math::tmul33(xyz2ned, wind, wind);
371 model->setWind(wind);
374 model->setAir(pressure, temp, dens);
376 // Query a ground plane for each gear/hook/launchbar and
377 // write that value into the corresponding class.
378 _fdm->getAirplane()->getModel()->updateGround(&s);
380 Launchbar* l = model->getLaunchbar();
382 l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
385 // All the settables:
387 // These are set below:
390 // _set_Accels_CG_Body
391 // _set_Accels_Pilot_Body
392 // _set_Accels_CG_Body_N
393 // _set_Velocities_Local
394 // _set_Velocities_Ground
395 // _set_Velocities_Wind_Body
400 // _set_V_ground_speed
402 // _set_V_calibrated_kts
410 // _set_Geodetic_Position
411 // _set_Runway_altitude
413 // Ignoring these, because they're unused:
414 // _set_Geocentric_Position
415 // _set_Geocentric_Rates
418 // _set_Earth_position_angle (WTF?)
419 // _set_Gamma_vert_rad
421 // _set_T_Local_to_Body
423 // _set_Sea_Level_Radius
425 // Externally set via the weather code:
426 // _set_Velocities_Local_Airmass
428 // _set_Static_pressure
429 // _set_Static_temperature
430 void YASim::copyFromYASim()
432 Airplane* airplane = _fdm->getAirplane();
433 Model* model = airplane->getModel();
434 State* s = model->getState();
437 double lat, lon, alt;
438 sgCartToGeod(s->pos, &lat, &lon, &alt);
439 _set_Geodetic_Position(lat, lon, alt*M2FT);
440 double groundlevel_m = get_groundlevel_m(lat, lon, alt);
441 _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
442 _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
444 // the smallest agl of all gears
445 _gear_agl_m->setFloatValue(model->getAGL());
446 _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
449 //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
451 // useful conversion matrix
453 Glue::xyz2nedMat(lat, lon, xyz2ned);
457 Math::vmul33(xyz2ned, s->v, v);
458 _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
459 _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
460 M2FT*v[1]*M2FT*v[1]));
461 _set_Climb_Rate(-M2FT*v[2]);
463 // The HUD uses this, but inverts down (?!)
464 _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
466 // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
470 wind[0] = get_V_north_airmass() * FT2M * -1.0; // Wind in NED
471 wind[1] = get_V_east_airmass() * FT2M * -1.0;
472 wind[2] = get_V_down_airmass() * FT2M * -1.0;
473 Math::tmul33(xyz2ned, wind, wind); // Wind in global
474 Math::sub3(s->v, wind, v); // V - wind in global
475 Math::vmul33(s->orient, v, v); // to body coordinates
476 _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
477 _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
479 float P = _pressure_inhg->getFloatValue() * INHG2PA;
480 float T = _temp_degc->getFloatValue() + 273.15;
481 float D = _density_slugft3->getFloatValue()
482 *SLUG2KG * M2FT*M2FT*M2FT;
483 _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
484 _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
485 _set_Mach_number(Atmosphere::calcMach(v[0], T));
488 Math::vmul33(xyz2ned, s->acc, v);
489 _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
491 Math::vmul33(s->orient, s->acc, v);
492 _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
493 _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
495 _fdm->getAirplane()->getPilotAccel(v);
496 _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
498 // There is no property for pilot G's, but I need it for a panel
499 // instrument. Hack this in here, and REMOVE IT WHEN IT FINDS A
501 _pilot_g->setFloatValue(-v[2]/9.8);
503 // The one appears (!) to want inverted pilot acceleration
504 // numbers, in G's...
505 Math::mul3(1.0/9.8, v, v);
506 _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
510 Glue::calcAlphaBeta(s, wind, &alpha, &beta);
515 Math::trans33(xyz2ned, tmp);
516 Math::mmul33(s->orient, tmp, tmp);
517 float roll, pitch, hdg;
518 Glue::orient2euler(tmp, &roll, &pitch, &hdg);
519 // make heading positive value
520 if(hdg < 0.0) hdg += PI2;
521 _set_Euler_Angles(roll, pitch, hdg);
524 Math::vmul33(s->orient, s->rot, v);
525 _set_Omega_Body(v[0], -v[1], -v[2]);
527 Glue::calcEulerRates(s, &roll, &pitch, &hdg);
528 _set_Euler_Rates(roll, pitch, hdg);
530 // Fill out our engine and gear objects
531 for(int i=0; i<airplane->numGear(); i++) {
532 Gear* g = airplane->getGear(i);
533 GearProps& gearProps = _gearProps[i];
534 gearProps.has_brake->setBoolValue(
536 gearProps.wow->setBoolValue(
537 g->getCompressFraction() != 0);
538 gearProps.compression_norm->setFloatValue(
539 g->getCompressFraction());
540 gearProps.compression_m->setFloatValue(
541 g->getCompressDist());
542 gearProps.caster_angle_deg->setFloatValue(
543 g->getCasterAngle() * RAD2DEG);
544 gearProps.rollspeed_ms->setFloatValue(
546 gearProps.ground_is_solid->setBoolValue(
547 g->getGroundIsSolid()!=0);
548 gearProps.ground_friction_factor->setFloatValue(
549 g->getGroundFrictionFactor());
552 Hook* h = airplane->getHook();
554 _tailhook_position_norm->setFloatValue(h->getCompressFraction());
557 Launchbar* l = airplane->getLaunchbar();
559 _launchbar_position_norm->setFloatValue(l->getCompressFraction());
560 _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
561 _launchbar_state->setStringValue(l->getState());
562 _launchbar_strop->setBoolValue(l->getStrop());
567 * This is only used after a replay session and when the user requested to resume at
568 * a past point of time. In this case the FDM must reload all values from the property
569 * tree (as given by the replay system). */
572 // Process inputs. Use excessive value for dt to make sure all transition effects
573 // have reached their final state (i.e. gear is extended/retracted) - which is vital
574 // for many properties to be complete before the first FDM run (otherwise the gear may
575 // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
576 _fdm->getExternalInput(1000);
578 // get current FDM values from the property tree