6 #include <simgear/debug/logstream.hxx>
7 #include <simgear/math/sg_geodesy.hxx>
8 #include <simgear/misc/sg_path.hxx>
9 #include <simgear/scene/model/placement.hxx>
10 #include <simgear/xml/easyxml.hxx>
12 #include <Main/globals.hxx>
13 #include <Main/fg_props.hxx>
16 #include "Atmosphere.hpp"
18 #include "Airplane.hpp"
20 #include "Integrator.hpp"
24 #include "Launchbar.hpp"
25 #include "FGGround.hpp"
26 #include "PropEngine.hpp"
27 #include "PistonEngine.hpp"
31 using namespace yasim;
33 static const float YASIM_PI = 3.14159265358979323846;
34 static const float RAD2DEG = 180/YASIM_PI;
35 static const float PI2 = YASIM_PI*2;
36 static const float RAD2RPM = 9.54929658551;
37 static const float M2FT = 3.2808399;
38 static const float FT2M = 0.3048;
39 static const float MPS2KTS = 3600.0/1852.0;
40 static const float CM2GALS = 264.172037284; // gallons/cubic meter
41 static const float KG2LBS = 2.20462262185;
42 static const float W2HP = 1.3416e-3;
43 static const float INHG2PA = 3386.389;
44 static const float SLUG2KG = 14.59390;
46 YASim::YASim(double dt) :
54 _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
55 _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
67 Airplane* a = _fdm->getAirplane();
69 float aoa = a->getCruiseAoA() * RAD2DEG;
70 float tail = -1 * a->getTailIncidence() * RAD2DEG;
71 float drag = 1000 * a->getDragCoefficient();
73 SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
74 SG_LOG(SG_FLIGHT,SG_INFO," Iterations: "<<a->getSolutionIterations());
75 SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
76 SG_LOG(SG_FLIGHT,SG_INFO," Lift Ratio: "<<a->getLiftRatio());
77 SG_LOG(SG_FLIGHT,SG_INFO," Cruise AoA: "<< aoa);
78 SG_LOG(SG_FLIGHT,SG_INFO," Tail Incidence: "<< tail);
79 SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
83 a->getModel()->getBody()->getCG(cg);
84 sprintf(buf, " CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
85 SG_LOG(SG_FLIGHT, SG_INFO, buf);
87 if(a->getFailureMsg()) {
88 SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
89 SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
96 // Run the superclass bind to set up a bunch of property ties
99 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
100 // Now UNtie the ones that we are going to set ourselves.
101 // fgUntie("/consumables/fuel/tank[0]/level-gal_us");
102 // fgUntie("/consumables/fuel/tank[1]/level-gal_us");
105 for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
106 sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
107 sprintf(buf, "/engines/engine[%d]/rpm", i); fgUntie(buf);
108 sprintf(buf, "/engines/engine[%d]/mp-osi", i); fgUntie(buf);
109 sprintf(buf, "/engines/engine[%d]/egt-degf", i); fgUntie(buf);
110 sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
114 YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
115 has_brake(gear_root->getNode("has-brake", true)),
116 wow(gear_root->getNode("wow", true)),
117 compression_norm(gear_root->getNode("compression-norm", true)),
118 compression_m(gear_root->getNode("compression-m", true)),
119 caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
120 rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
121 ground_is_solid(gear_root->getNode("ground-is-solid", true)),
122 ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
128 Airplane* airplane = _fdm->getAirplane();
129 Model* model = airplane->getModel();
131 _crashed = fgGetNode("/sim/crashed", true);
132 _pressure_inhg = fgGetNode("/environment/pressure-inhg", true);
133 _temp_degc = fgGetNode("/environment/temperature-degc", true);
134 _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
135 _gear_agl_m = fgGetNode("/position/gear-agl-m", true);
136 _gear_agl_ft = fgGetNode("/position/gear-agl-ft", true);
137 _pilot_g = fgGetNode("/accelerations/pilot-g", true);
138 _speed_setprop = fgGetNode("/sim/presets/speed-set", true);
143 model->setCrashed(false);
144 _crashed->setBoolValue(false);
146 // Figure out the initial speed type
147 string speed_set = _speed_setprop->getStringValue();
148 if ((speed_set == "") || (speed_set == "UVW"))
150 else if (speed_set == "NED")
152 else if (speed_set == "knots")
154 else if (speed_set == "mach")
158 SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
161 // Build a filename and parse it
162 SGPath f(fgGetString("/sim/aircraft-dir"));
163 f.append(fgGetString("/sim/aero"));
166 readXML(f.str(), *_fdm);
167 } catch (const sg_exception &e) {
168 SG_LOG(SG_FLIGHT, SG_ALERT,
169 "Error reading YASim FDM: '" << f.str() << "'" << std::endl
170 << e.getFormattedMessage());
174 // Compile it into a real airplane, and tell the user what they got
180 if (model->getLaunchbar())
182 _catapult_launch_cmd = fgGetNode("/controls/gear/catapult-launch-cmd", true);
183 _launchbar_position_norm = fgGetNode("/gear/launchbar/position-norm", true);
184 _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
185 _launchbar_state = fgGetNode("/gear/launchbar/state", true);
186 _launchbar_strop = fgGetNode("/gear/launchbar/strop", true);
188 if (airplane->getHook())
190 _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
193 // Create some FG{Eng|Gear}Interface objects
194 for(int i=0; i<airplane->numGear(); i++) {
195 Gear* g = airplane->getGear(i);
196 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
199 node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
200 node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
201 node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
203 _gearProps.push_back(GearProps(node));
206 // Are we at ground level? If so, lift the plane up so the gear
208 double runway_altitude = get_Runway_altitude();
209 if(get_Altitude() - runway_altitude < 50) {
210 fgSetBool("/controls/gear/gear-down", false);
211 float minGearZ = 1e18;
212 for(int i=0; i<airplane->numGear(); i++) {
213 Gear* g = airplane->getGear(i);
216 if(pos[2] < minGearZ)
219 _set_Altitude(runway_altitude - minGearZ*M2FT);
220 fgSetBool("/controls/gear/gear-down", true);
223 // Blank the state, and copy in ours
228 _fdm->getExternalInput();
229 _fdm->getAirplane()->initEngines();
234 void YASim::update(double dt)
239 int iterations = _calc_multiloop(dt);
241 // If we're crashed, then we don't care
242 if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
243 if(!_crashed->getBoolValue())
244 _crashed->setBoolValue(true);
245 _fdm->getAirplane()->getModel()->setCrashed(false);
249 // ground. Calculate a cartesian coordinate for the ground under
250 // us, find the (geodetic) up vector normal to the ground, then
251 // use that to find the final (radius) term of the plane equation.
252 float v[3] = { get_uBody(), get_vBody(), get_wBody() };
253 float lat = get_Latitude(); float lon = get_Longitude();
254 float alt = get_Altitude() * FT2M; double xyz[3];
255 sgGeodToCart(lat, lon, alt, xyz);
256 // build the environment cache.
257 float vr = _fdm->getVehicleRadius();
258 vr += 2.0*FT2M*dt*Math::mag3(v);
259 prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
261 // Track time increments.
263 = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
266 for(i=0; i<iterations; i++) {
267 gr->setTimeOffset(_simTime + i*_dt);
273 // Increment the local sim time
275 gr->setTimeOffset(_simTime);
278 void YASim::copyToYASim(bool copyState)
281 double lat = get_Latitude();
282 double lon = get_Longitude();
283 float alt = get_Altitude() * FT2M;
284 float roll = get_Phi();
285 float pitch = get_Theta();
286 float hdg = get_Psi();
290 wind[0] = get_V_north_airmass() * FT2M * -1.0;
291 wind[1] = get_V_east_airmass() * FT2M * -1.0;
292 wind[2] = get_V_down_airmass() * FT2M * -1.0;
294 float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
295 float temp = _temp_degc->getFloatValue() + 273.15;
296 float dens = _density_slugft3->getFloatValue() *
297 SLUG2KG * M2FT*M2FT*M2FT;
300 Model* model = _fdm->getAirplane()->getModel();
303 Glue::xyz2nedMat(lat, lon, xyz2ned);
306 sgGeodToCart(lat, lon, alt, s.pos);
308 // allow setting of /position/[lat|long|alti]tude
309 double * dp = &model->getState()->pos[0];
310 dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
314 Glue::euler2orient(roll, pitch, hdg, s.orient);
315 Math::mmul33(s.orient, xyz2ned, s.orient);
319 bool needCopy = false;
320 switch (_speed_set) {
322 v[0] = get_V_north() * FT2M * -1.0;
323 v[1] = get_V_east() * FT2M * -1.0;
324 v[2] = get_V_down() * FT2M * -1.0;
327 v[0] = get_uBody() * FT2M;
328 v[1] = get_vBody() * FT2M;
329 v[2] = get_wBody() * FT2M;
330 Math::tmul33(s.orient, v, v);
333 v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
337 Math::tmul33(s.orient, v, v);
341 v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
344 Math::tmul33(s.orient, v, v);
354 _speed_set = UVW; // change to this after initial setting
357 if(copyState || needCopy)
361 Math::tmul33(xyz2ned, wind, wind);
362 model->setWind(wind);
365 model->setAir(pressure, temp, dens);
367 // Query a ground plane for each gear/hook/launchbar and
368 // write that value into the corresponding class.
369 _fdm->getAirplane()->getModel()->updateGround(&s);
371 Launchbar* l = model->getLaunchbar();
373 l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
376 // All the settables:
378 // These are set below:
381 // _set_Accels_CG_Body
382 // _set_Accels_Pilot_Body
383 // _set_Accels_CG_Body_N
384 // _set_Velocities_Local
385 // _set_Velocities_Ground
386 // _set_Velocities_Wind_Body
391 // _set_V_ground_speed
393 // _set_V_calibrated_kts
401 // _set_Geodetic_Position
402 // _set_Runway_altitude
404 // Ignoring these, because they're unused:
405 // _set_Geocentric_Position
406 // _set_Geocentric_Rates
409 // _set_Earth_position_angle (WTF?)
410 // _set_Gamma_vert_rad
412 // _set_T_Local_to_Body
414 // _set_Sea_Level_Radius
416 // Externally set via the weather code:
417 // _set_Velocities_Local_Airmass
419 // _set_Static_pressure
420 // _set_Static_temperature
421 void YASim::copyFromYASim()
423 Airplane* airplane = _fdm->getAirplane();
424 Model* model = airplane->getModel();
425 State* s = model->getState();
428 double lat, lon, alt;
429 sgCartToGeod(s->pos, &lat, &lon, &alt);
430 _set_Geodetic_Position(lat, lon, alt*M2FT);
431 double groundlevel_m = get_groundlevel_m(lat, lon, alt);
432 _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
433 _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
435 // the smallest agl of all gears
436 _gear_agl_m->setFloatValue(model->getAGL());
437 _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
440 //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
442 // useful conversion matrix
444 Glue::xyz2nedMat(lat, lon, xyz2ned);
448 Math::vmul33(xyz2ned, s->v, v);
449 _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
450 _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
451 M2FT*v[1]*M2FT*v[1]));
452 _set_Climb_Rate(-M2FT*v[2]);
454 // The HUD uses this, but inverts down (?!)
455 _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
457 // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
461 wind[0] = get_V_north_airmass() * FT2M * -1.0; // Wind in NED
462 wind[1] = get_V_east_airmass() * FT2M * -1.0;
463 wind[2] = get_V_down_airmass() * FT2M * -1.0;
464 Math::tmul33(xyz2ned, wind, wind); // Wind in global
465 Math::sub3(s->v, wind, v); // V - wind in global
466 Math::vmul33(s->orient, v, v); // to body coordinates
467 _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
468 _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
470 float P = _pressure_inhg->getFloatValue() * INHG2PA;
471 float T = _temp_degc->getFloatValue() + 273.15;
472 float D = _density_slugft3->getFloatValue()
473 *SLUG2KG * M2FT*M2FT*M2FT;
474 _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
475 _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
476 _set_Mach_number(Atmosphere::calcMach(v[0], T));
479 Math::vmul33(xyz2ned, s->acc, v);
480 _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
482 Math::vmul33(s->orient, s->acc, v);
483 _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
484 _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
486 _fdm->getAirplane()->getPilotAccel(v);
487 _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
489 // There is no property for pilot G's, but I need it for a panel
490 // instrument. Hack this in here, and REMOVE IT WHEN IT FINDS A
492 _pilot_g->setFloatValue(-v[2]/9.8);
494 // The one appears (!) to want inverted pilot acceleration
495 // numbers, in G's...
496 Math::mul3(1.0/9.8, v, v);
497 _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
501 Glue::calcAlphaBeta(s, wind, &alpha, &beta);
506 Math::trans33(xyz2ned, tmp);
507 Math::mmul33(s->orient, tmp, tmp);
508 float roll, pitch, hdg;
509 Glue::orient2euler(tmp, &roll, &pitch, &hdg);
510 // make heading positive value
511 if(hdg < 0.0) hdg += PI2;
512 _set_Euler_Angles(roll, pitch, hdg);
515 Math::vmul33(s->orient, s->rot, v);
516 _set_Omega_Body(v[0], -v[1], -v[2]);
518 Glue::calcEulerRates(s, &roll, &pitch, &hdg);
519 _set_Euler_Rates(roll, pitch, hdg);
521 // Fill out our engine and gear objects
522 for(int i=0; i<airplane->numGear(); i++) {
523 Gear* g = airplane->getGear(i);
524 GearProps& gearProps = _gearProps[i];
525 gearProps.has_brake->setBoolValue(
527 gearProps.wow->setBoolValue(
528 g->getCompressFraction() != 0);
529 gearProps.compression_norm->setFloatValue(
530 g->getCompressFraction());
531 gearProps.compression_m->setFloatValue(
532 g->getCompressDist());
533 gearProps.caster_angle_deg->setFloatValue(
534 g->getCasterAngle() * RAD2DEG);
535 gearProps.rollspeed_ms->setFloatValue(
537 gearProps.ground_is_solid->setBoolValue(
538 g->getGroundIsSolid()!=0);
539 gearProps.ground_friction_factor->setFloatValue(
540 g->getGroundFrictionFactor());
543 Hook* h = airplane->getHook();
545 _tailhook_position_norm->setFloatValue(h->getCompressFraction());
548 Launchbar* l = airplane->getLaunchbar();
550 _launchbar_position_norm->setFloatValue(l->getCompressFraction());
551 _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
552 _launchbar_state->setStringValue(l->getState());
553 _launchbar_strop->setBoolValue(l->getStrop());
558 * This is only used after a replay session and when the user requested to resume at
559 * a past point of time. In this case the FDM must reload all values from the property
560 * tree (as given by the replay system). */
563 // Process inputs. Use excessive value for dt to make sure all transition effects
564 // have reached their final state (i.e. gear is extended/retracted) - which is vital
565 // for many properties to be complete before the first FDM run (otherwise the gear may
566 // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
567 _fdm->getExternalInput(1000);
569 // get current FDM values from the property tree