8 #include <simgear/debug/logstream.hxx>
9 #include <simgear/math/sg_geodesy.hxx>
10 #include <simgear/misc/sg_path.hxx>
11 #include <simgear/scene/model/placement.hxx>
12 #include <simgear/xml/easyxml.hxx>
14 #include <Main/globals.hxx>
15 #include <Main/fg_props.hxx>
18 #include "Atmosphere.hpp"
20 #include "Airplane.hpp"
22 #include "Integrator.hpp"
26 #include "Launchbar.hpp"
27 #include "FGGround.hpp"
28 #include "PropEngine.hpp"
29 #include "PistonEngine.hpp"
33 using namespace yasim;
35 static const float YASIM_PI = 3.14159265358979323846;
36 static const float RAD2DEG = 180/YASIM_PI;
37 static const float PI2 = YASIM_PI*2;
38 static const float RAD2RPM = 9.54929658551;
39 static const float M2FT = 3.2808399;
40 static const float FT2M = 0.3048;
41 static const float MPS2KTS = 3600.0/1852.0;
42 static const float CM2GALS = 264.172037284; // gallons/cubic meter
43 static const float KG2LBS = 2.20462262185;
44 static const float W2HP = 1.3416e-3;
45 static const float INHG2PA = 3386.389;
46 static const float SLUG2KG = 14.59390;
48 YASim::YASim(double dt) :
56 _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
57 _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
69 Airplane* a = _fdm->getAirplane();
71 float aoa = a->getCruiseAoA() * RAD2DEG;
72 float tail = -1 * a->getTailIncidence() * RAD2DEG;
73 float drag = 1000 * a->getDragCoefficient();
75 SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
76 SG_LOG(SG_FLIGHT,SG_INFO," Iterations: "<<a->getSolutionIterations());
77 SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
78 SG_LOG(SG_FLIGHT,SG_INFO," Lift Ratio: "<<a->getLiftRatio());
79 SG_LOG(SG_FLIGHT,SG_INFO," Cruise AoA: "<< aoa);
80 SG_LOG(SG_FLIGHT,SG_INFO," Tail Incidence: "<< tail);
81 SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
85 a->getModel()->getBody()->getCG(cg);
86 sprintf(buf, " CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
87 SG_LOG(SG_FLIGHT, SG_INFO, buf);
89 if(a->getFailureMsg()) {
90 SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
91 SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
98 // Run the superclass bind to set up a bunch of property ties
101 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
102 // Now UNtie the ones that we are going to set ourselves.
103 // fgUntie("/consumables/fuel/tank[0]/level-gal_us");
104 // fgUntie("/consumables/fuel/tank[1]/level-gal_us");
107 for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
108 sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
109 sprintf(buf, "/engines/engine[%d]/rpm", i); fgUntie(buf);
110 sprintf(buf, "/engines/engine[%d]/mp-osi", i); fgUntie(buf);
111 sprintf(buf, "/engines/engine[%d]/egt-degf", i); fgUntie(buf);
112 sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
116 YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
117 has_brake(gear_root->getNode("has-brake", true)),
118 wow(gear_root->getNode("wow", true)),
119 compression_norm(gear_root->getNode("compression-norm", true)),
120 compression_m(gear_root->getNode("compression-m", true)),
121 caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
122 rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
123 ground_is_solid(gear_root->getNode("ground-is-solid", true)),
124 ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
130 Airplane* airplane = _fdm->getAirplane();
131 Model* model = airplane->getModel();
133 _crashed = fgGetNode("/sim/crashed", true);
134 _pressure_inhg = fgGetNode("/environment/pressure-inhg", true);
135 _temp_degc = fgGetNode("/environment/temperature-degc", true);
136 _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
137 _gear_agl_m = fgGetNode("/position/gear-agl-m", true);
138 _gear_agl_ft = fgGetNode("/position/gear-agl-ft", true);
139 _pilot_g = fgGetNode("/accelerations/pilot-g", true);
140 _speed_setprop = fgGetNode("/sim/presets/speed-set", true);
145 model->setCrashed(false);
146 _crashed->setBoolValue(false);
148 // Figure out the initial speed type
149 string speed_set = _speed_setprop->getStringValue();
150 if ((speed_set == "") || (speed_set == "UVW"))
152 else if (speed_set == "NED")
154 else if (speed_set == "knots")
156 else if (speed_set == "mach")
160 SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
163 // Build a filename and parse it
164 SGPath f(fgGetString("/sim/aircraft-dir"));
165 f.append(fgGetString("/sim/aero"));
168 readXML(f.str(), *_fdm);
169 } catch (const sg_exception &e) {
170 SG_LOG(SG_FLIGHT, SG_ALERT,
171 "Error reading YASim FDM: '" << f.str() << "'" << std::endl
172 << e.getFormattedMessage());
176 // Compile it into a real airplane, and tell the user what they got
182 if (model->getLaunchbar())
184 _catapult_launch_cmd = fgGetNode("/controls/gear/catapult-launch-cmd", true);
185 _launchbar_position_norm = fgGetNode("/gear/launchbar/position-norm", true);
186 _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
187 _launchbar_state = fgGetNode("/gear/launchbar/state", true);
188 _launchbar_strop = fgGetNode("/gear/launchbar/strop", true);
190 if (airplane->getHook())
192 _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
195 // Create some FG{Eng|Gear}Interface objects
196 for(int i=0; i<airplane->numGear(); i++) {
197 Gear* g = airplane->getGear(i);
198 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
201 node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
202 node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
203 node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
205 _gearProps.push_back(GearProps(node));
208 // Are we at ground level? If so, lift the plane up so the gear
210 double runway_altitude = get_Runway_altitude();
211 if(get_Altitude() - runway_altitude < 50) {
212 fgSetBool("/controls/gear/gear-down", false);
213 float minGearZ = 1e18;
214 for(int i=0; i<airplane->numGear(); i++) {
215 Gear* g = airplane->getGear(i);
218 if(pos[2] < minGearZ)
221 _set_Altitude(runway_altitude - minGearZ*M2FT);
222 fgSetBool("/controls/gear/gear-down", true);
225 // Blank the state, and copy in ours
230 _fdm->getExternalInput();
231 _fdm->getAirplane()->initEngines();
236 void YASim::update(double dt)
241 int iterations = _calc_multiloop(dt);
243 // If we're crashed, then we don't care
244 if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
245 if(!_crashed->getBoolValue())
246 _crashed->setBoolValue(true);
247 _fdm->getAirplane()->getModel()->setCrashed(false);
251 // ground. Calculate a cartesian coordinate for the ground under
252 // us, find the (geodetic) up vector normal to the ground, then
253 // use that to find the final (radius) term of the plane equation.
254 float v[3] = { get_uBody(), get_vBody(), get_wBody() };
255 float lat = get_Latitude(); float lon = get_Longitude();
256 float alt = get_Altitude() * FT2M; double xyz[3];
257 sgGeodToCart(lat, lon, alt, xyz);
258 // build the environment cache.
259 float vr = _fdm->getVehicleRadius();
260 vr += 2.0*FT2M*dt*Math::mag3(v);
261 prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
263 // Track time increments.
265 = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
268 for(i=0; i<iterations; i++) {
269 gr->setTimeOffset(_simTime + i*_dt);
275 // Increment the local sim time
277 gr->setTimeOffset(_simTime);
280 void YASim::copyToYASim(bool copyState)
283 double lat = get_Latitude();
284 double lon = get_Longitude();
285 float alt = get_Altitude() * FT2M;
286 float roll = get_Phi();
287 float pitch = get_Theta();
288 float hdg = get_Psi();
292 wind[0] = get_V_north_airmass() * FT2M * -1.0;
293 wind[1] = get_V_east_airmass() * FT2M * -1.0;
294 wind[2] = get_V_down_airmass() * FT2M * -1.0;
296 float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
297 float temp = _temp_degc->getFloatValue() + 273.15;
298 float dens = _density_slugft3->getFloatValue() *
299 SLUG2KG * M2FT*M2FT*M2FT;
302 Model* model = _fdm->getAirplane()->getModel();
305 Glue::xyz2nedMat(lat, lon, xyz2ned);
308 sgGeodToCart(lat, lon, alt, s.pos);
310 // allow setting of /position/[lat|long|alti]tude
311 double * dp = &model->getState()->pos[0];
312 dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
316 Glue::euler2orient(roll, pitch, hdg, s.orient);
317 Math::mmul33(s.orient, xyz2ned, s.orient);
321 bool needCopy = false;
322 switch (_speed_set) {
324 v[0] = get_V_north() * FT2M * -1.0;
325 v[1] = get_V_east() * FT2M * -1.0;
326 v[2] = get_V_down() * FT2M * -1.0;
329 v[0] = get_uBody() * FT2M;
330 v[1] = get_vBody() * FT2M;
331 v[2] = get_wBody() * FT2M;
332 Math::tmul33(s.orient, v, v);
335 v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
339 Math::tmul33(s.orient, v, v);
343 v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
346 Math::tmul33(s.orient, v, v);
356 _speed_set = UVW; // change to this after initial setting
359 if(copyState || needCopy)
363 Math::tmul33(xyz2ned, wind, wind);
364 model->setWind(wind);
367 model->setAir(pressure, temp, dens);
369 // Query a ground plane for each gear/hook/launchbar and
370 // write that value into the corresponding class.
371 _fdm->getAirplane()->getModel()->updateGround(&s);
373 Launchbar* l = model->getLaunchbar();
375 l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
378 // All the settables:
380 // These are set below:
383 // _set_Accels_CG_Body
384 // _set_Accels_Pilot_Body
385 // _set_Accels_CG_Body_N
386 // _set_Velocities_Local
387 // _set_Velocities_Ground
388 // _set_Velocities_Wind_Body
393 // _set_V_ground_speed
395 // _set_V_calibrated_kts
403 // _set_Geodetic_Position
404 // _set_Runway_altitude
406 // Ignoring these, because they're unused:
407 // _set_Geocentric_Position
408 // _set_Geocentric_Rates
411 // _set_Earth_position_angle (WTF?)
412 // _set_Gamma_vert_rad
414 // _set_T_Local_to_Body
416 // _set_Sea_Level_Radius
418 // Externally set via the weather code:
419 // _set_Velocities_Local_Airmass
421 // _set_Static_pressure
422 // _set_Static_temperature
423 void YASim::copyFromYASim()
425 Airplane* airplane = _fdm->getAirplane();
426 Model* model = airplane->getModel();
427 State* s = model->getState();
430 double lat, lon, alt;
431 sgCartToGeod(s->pos, &lat, &lon, &alt);
432 _set_Geodetic_Position(lat, lon, alt*M2FT);
433 double groundlevel_m = get_groundlevel_m(lat, lon, alt);
434 _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
435 _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
437 // the smallest agl of all gears
438 _gear_agl_m->setFloatValue(model->getAGL());
439 _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
442 //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
444 // useful conversion matrix
446 Glue::xyz2nedMat(lat, lon, xyz2ned);
450 Math::vmul33(xyz2ned, s->v, v);
451 _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
452 _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
453 M2FT*v[1]*M2FT*v[1]));
454 _set_Climb_Rate(-M2FT*v[2]);
456 // The HUD uses this, but inverts down (?!)
457 _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
459 // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
463 wind[0] = get_V_north_airmass() * FT2M * -1.0; // Wind in NED
464 wind[1] = get_V_east_airmass() * FT2M * -1.0;
465 wind[2] = get_V_down_airmass() * FT2M * -1.0;
466 Math::tmul33(xyz2ned, wind, wind); // Wind in global
467 Math::sub3(s->v, wind, v); // V - wind in global
468 Math::vmul33(s->orient, v, v); // to body coordinates
469 _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
470 _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
472 float P = _pressure_inhg->getFloatValue() * INHG2PA;
473 float T = _temp_degc->getFloatValue() + 273.15;
474 float D = _density_slugft3->getFloatValue()
475 *SLUG2KG * M2FT*M2FT*M2FT;
476 _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
477 _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
478 _set_Mach_number(Atmosphere::calcMach(v[0], T));
481 Math::vmul33(xyz2ned, s->acc, v);
482 _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
484 Math::vmul33(s->orient, s->acc, v);
485 _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
486 _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
488 _fdm->getAirplane()->getPilotAccel(v);
489 _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
491 // There is no property for pilot G's, but I need it for a panel
492 // instrument. Hack this in here, and REMOVE IT WHEN IT FINDS A
494 _pilot_g->setFloatValue(-v[2]/9.8);
496 // The one appears (!) to want inverted pilot acceleration
497 // numbers, in G's...
498 Math::mul3(1.0/9.8, v, v);
499 _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
503 Glue::calcAlphaBeta(s, wind, &alpha, &beta);
508 Math::trans33(xyz2ned, tmp);
509 Math::mmul33(s->orient, tmp, tmp);
510 float roll, pitch, hdg;
511 Glue::orient2euler(tmp, &roll, &pitch, &hdg);
512 // make heading positive value
513 if(hdg < 0.0) hdg += PI2;
514 _set_Euler_Angles(roll, pitch, hdg);
517 Math::vmul33(s->orient, s->rot, v);
518 _set_Omega_Body(v[0], -v[1], -v[2]);
520 Glue::calcEulerRates(s, &roll, &pitch, &hdg);
521 _set_Euler_Rates(roll, pitch, hdg);
523 // Fill out our engine and gear objects
524 for(int i=0; i<airplane->numGear(); i++) {
525 Gear* g = airplane->getGear(i);
526 GearProps& gearProps = _gearProps[i];
527 gearProps.has_brake->setBoolValue(
529 gearProps.wow->setBoolValue(
530 g->getCompressFraction() != 0);
531 gearProps.compression_norm->setFloatValue(
532 g->getCompressFraction());
533 gearProps.compression_m->setFloatValue(
534 g->getCompressDist());
535 gearProps.caster_angle_deg->setFloatValue(
536 g->getCasterAngle() * RAD2DEG);
537 gearProps.rollspeed_ms->setFloatValue(
539 gearProps.ground_is_solid->setBoolValue(
540 g->getGroundIsSolid()!=0);
541 gearProps.ground_friction_factor->setFloatValue(
542 g->getGroundFrictionFactor());
545 Hook* h = airplane->getHook();
547 _tailhook_position_norm->setFloatValue(h->getCompressFraction());
550 Launchbar* l = airplane->getLaunchbar();
552 _launchbar_position_norm->setFloatValue(l->getCompressFraction());
553 _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
554 _launchbar_state->setStringValue(l->getState());
555 _launchbar_strop->setBoolValue(l->getStrop());
560 * This is only used after a replay session and when the user requested to resume at
561 * a past point of time. In this case the FDM must reload all values from the property
562 * tree (as given by the replay system). */
565 // Process inputs. Use excessive value for dt to make sure all transition effects
566 // have reached their final state (i.e. gear is extended/retracted) - which is vital
567 // for many properties to be complete before the first FDM run (otherwise the gear may
568 // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
569 _fdm->getExternalInput(1000);
571 // get current FDM values from the property tree