]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
considering u,v,wbody-fps are the ECEF velocity expressed in body axis, change in...
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <cstdlib>
7 #include <cstdio>
8
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>
14
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
17
18 #include "FGFDM.hpp"
19 #include "Atmosphere.hpp"
20 #include "Math.hpp"
21 #include "Airplane.hpp"
22 #include "Model.hpp"
23 #include "Integrator.hpp"
24 #include "Glue.hpp"
25 #include "Gear.hpp"
26 #include "Hook.hpp"
27 #include "Launchbar.hpp"
28 #include "FGGround.hpp"
29 #include "PropEngine.hpp"
30 #include "PistonEngine.hpp"
31
32 #include "YASim.hxx"
33
34 using namespace yasim;
35
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;
48
49 YASim::YASim(double dt) :
50     _simTime(0)
51 {
52 //     set_delta_t(dt);
53     _fdm = new FGFDM();
54
55     _dt = dt;
56
57     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
58     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
59 }
60
61 YASim::~YASim()
62 {
63     delete _fdm;
64
65     _gearProps.clear();
66 }
67
68 void YASim::report()
69 {
70     Airplane* a = _fdm->getAirplane();
71
72     float aoa = a->getCruiseAoA() * RAD2DEG;
73     float tail = -1 * a->getTailIncidence() * RAD2DEG;
74     float drag = 1000 * a->getDragCoefficient();
75
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());
83
84     float cg[3];
85     char buf[256];
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);
89
90     if(a->getFailureMsg()) {
91         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
92         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
93         exit(1);
94     }
95 }
96
97 void YASim::bind()
98 {
99     // Run the superclass bind to set up a bunch of property ties
100     FGInterface::bind();
101
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");
106
107     char buf[256];
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);
114     }
115 }
116
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))
126 {
127 }
128
129 void YASim::init()
130 {
131     Airplane* airplane = _fdm->getAirplane();
132     Model* model = airplane->getModel();
133
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);
142
143     // Superclass hook
144     common_init();
145
146     model->setCrashed(false);
147     _crashed->setBoolValue(false);
148
149     // Figure out the initial speed type
150     string speed_set = _speed_setprop->getStringValue();
151     if ((speed_set == "") || (speed_set == "UVW"))
152         _speed_set = UVW;
153     else if (speed_set == "NED")
154         _speed_set = NED;
155     else if (speed_set == "knots")
156         _speed_set = KNOTS;
157     else if (speed_set == "mach")
158         _speed_set = MACH;
159     else {
160         _speed_set = UVW;
161         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
162     }
163
164     // Build a filename and parse it
165     SGPath f(fgGetString("/sim/aircraft-dir"));
166     f.append(fgGetString("/sim/aero"));
167     f.concat(".xml");
168     try {
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());
174         throw e;
175     }
176
177     // Compile it into a real airplane, and tell the user what they got
178     airplane->compile();
179     report();
180
181     _fdm->init();
182
183     if (model->getLaunchbar())
184     {
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);
190     }
191     if (airplane->getHook())
192     {
193         _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
194     }
195
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);
200         float pos[3];
201         g->getPosition(pos);
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);
205
206         _gearProps.push_back(GearProps(node));
207     }
208
209     // Are we at ground level?  If so, lift the plane up so the gear
210     // clear the ground.
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);
217             float pos[3];
218             g->getPosition(pos);
219             if(pos[2] < minGearZ)
220                 minGearZ = pos[2];
221         }
222         _set_Altitude(runway_altitude - minGearZ*M2FT);
223         // ground start-up: gear down
224         fgSetBool("/controls/gear/gear-down", true);
225     }
226     else
227     {
228         // airborne start-up: gear up
229         fgSetBool("/controls/gear/gear-down", false);
230     }
231
232     // Blank the state, and copy in ours
233     State s;
234     model->setState(&s);
235     copyToYASim(true);
236
237     _fdm->getExternalInput();
238     _fdm->getAirplane()->initEngines();
239
240     set_inited(true);
241 }
242
243 void YASim::update(double dt)
244 {
245     if (is_suspended())
246         return;
247
248     int iterations = _calc_multiloop(dt);
249
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);
255         return;
256     }
257
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] = {
262       static_cast<float>(get_uBody()),
263       static_cast<float>(get_vBody()),
264       static_cast<float>(get_wBody())
265     };
266     float lat = get_Latitude(); float lon = get_Longitude();
267     float alt = get_Altitude() * FT2M; double xyz[3];
268     sgGeodToCart(lat, lon, alt, xyz);
269     // build the environment cache.
270     float vr = _fdm->getVehicleRadius();
271     vr += 2.0*FT2M*dt*Math::mag3(v);
272     prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
273
274     // Track time increments.
275     FGGround* gr
276       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
277
278     int i;
279     for(i=0; i<iterations; i++) {
280         gr->setTimeOffset(_simTime + i*_dt);
281         copyToYASim(false);
282         _fdm->iterate(_dt);
283         copyFromYASim();
284     }
285
286     // Increment the local sim time
287     _simTime += dt;
288     gr->setTimeOffset(_simTime);
289 }
290
291 void YASim::copyToYASim(bool copyState)
292 {
293     // Physical state
294     double lat = get_Latitude();
295     double lon = get_Longitude();
296     float alt = get_Altitude() * FT2M;
297     float roll = get_Phi();
298     float pitch = get_Theta();
299     float hdg = get_Psi();
300
301     // Environment
302     float wind[3];
303     wind[0] = get_V_north_airmass() * FT2M * -1.0;
304     wind[1] = get_V_east_airmass() * FT2M * -1.0;
305     wind[2] = get_V_down_airmass() * FT2M * -1.0;
306
307     float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
308     float temp     = _temp_degc->getFloatValue() + 273.15;
309     float dens     = _density_slugft3->getFloatValue() *
310                             SLUG2KG * M2FT*M2FT*M2FT;
311
312     // Convert and set:
313     Model* model = _fdm->getAirplane()->getModel();
314     State s;
315     float xyz2ned[9];
316     Glue::xyz2nedMat(lat, lon, xyz2ned);
317
318     // position
319     sgGeodToCart(lat, lon, alt, s.pos);
320     {
321       // allow setting of /position/[lat|long|alti]tude
322       double * dp = &model->getState()->pos[0];
323       dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
324     }
325
326     // orientation
327     Glue::euler2orient(roll, pitch, hdg, s.orient);
328     Math::mmul33(s.orient, xyz2ned, s.orient);
329
330     // Velocity
331     float v[3];
332     bool needCopy = false;
333     switch (_speed_set) {
334     case NED:
335         v[0] = get_V_north() * FT2M * -1.0;
336         v[1] = get_V_east() * FT2M * -1.0;
337         v[2] = get_V_down() * FT2M * -1.0;
338         break;
339     case UVW:
340         v[0] = get_uBody() * FT2M;
341         v[1] = get_vBody() * FT2M;
342         v[2] = get_wBody() * FT2M;
343         Math::tmul33(s.orient, v, v);
344         break;
345     case KNOTS:
346         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
347                                        pressure, temp);
348         v[1] = 0;
349         v[2] = 0;
350         Math::tmul33(s.orient, v, v);
351         needCopy = true;
352         break;
353     case MACH:
354         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
355         v[1] = 0;
356         v[2] = 0;
357         Math::tmul33(s.orient, v, v);
358         needCopy = true;
359         break;
360     default:
361         v[0] = 0;
362         v[1] = 0;
363         v[2] = 0;
364         break;
365     }
366     if (!copyState)
367         _speed_set = UVW;       // change to this after initial setting
368     Math::set3(v, s.v);
369
370     if(copyState || needCopy)
371         model->setState(&s);
372
373     // wind
374     Math::tmul33(xyz2ned, wind, wind);
375     model->setWind(wind);
376
377     // air
378     model->setAir(pressure, temp, dens);
379
380     // Query a ground plane for each gear/hook/launchbar and
381     // write that value into the corresponding class.
382     _fdm->getAirplane()->getModel()->updateGround(&s);
383
384     Launchbar* l = model->getLaunchbar();
385     if (l)
386         l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
387 }
388
389 // All the settables:
390 //
391 // These are set below:
392 // _set_Accels_Local
393 // _set_Accels_Body
394 // _set_Accels_CG_Body 
395 // _set_Accels_Pilot_Body
396 // _set_Accels_CG_Body_N 
397 // _set_Velocities_Local
398 // _set_Velocities_Ground
399 // _set_Velocities_Body
400 // _set_Omega_Body
401 // _set_Euler_Rates
402 // _set_Euler_Angles
403 // _set_V_rel_wind
404 // _set_V_ground_speed
405 // _set_V_equiv_kts
406 // _set_V_calibrated_kts
407 // _set_Alpha
408 // _set_Beta
409 // _set_Mach_number
410 // _set_Climb_Rate
411 // _set_Tank1Fuel
412 // _set_Tank2Fuel
413 // _set_Altitude_AGL
414 // _set_Geodetic_Position
415 // _set_Runway_altitude
416
417 // Ignoring these, because they're unused:
418 // _set_Geocentric_Position
419 // _set_Geocentric_Rates
420 // _set_Cos_phi
421 // _set_Cos_theta
422 // _set_Earth_position_angle (WTF?)
423 // _set_Gamma_vert_rad
424 // _set_Inertias
425 // _set_T_Local_to_Body
426 // _set_CG_Position
427 // _set_Sea_Level_Radius
428
429 // Externally set via the weather code:
430 // _set_Velocities_Local_Airmass
431 // _set_Density
432 // _set_Static_pressure
433 // _set_Static_temperature
434 void YASim::copyFromYASim()
435 {
436     Airplane* airplane = _fdm->getAirplane();
437     Model* model = airplane->getModel();
438     State* s = model->getState();
439
440     // position
441     double lat, lon, alt;
442     sgCartToGeod(s->pos, &lat, &lon, &alt);
443     _set_Geodetic_Position(lat, lon, alt*M2FT);
444     double groundlevel_m = get_groundlevel_m(lat, lon, alt);
445     _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
446     _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
447
448     // the smallest agl of all gears
449     _gear_agl_m->setFloatValue(model->getAGL());
450     _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
451
452     // UNUSED
453     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
454
455     // useful conversion matrix
456     float xyz2ned[9];
457     Glue::xyz2nedMat(lat, lon, xyz2ned);
458
459     // velocity
460     float v[3];
461     Math::vmul33(xyz2ned, s->v, v);
462     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
463     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
464                                    M2FT*v[1]*M2FT*v[1]));
465     _set_Climb_Rate(-M2FT*v[2]);
466
467     // The HUD uses this, but inverts down (?!)
468     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
469
470     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
471
472     // ecef speed in body axis
473     Math::vmul33(s->orient, s->v, v);
474     _set_Velocities_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
475
476     // Airflow velocity.
477     float wind[3];
478     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
479     wind[1] = get_V_east_airmass() * FT2M * -1.0;
480     wind[2] = get_V_down_airmass() * FT2M * -1.0;
481     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
482     Math::sub3(s->v, wind, v);                      // V - wind in global
483     Math::vmul33(s->orient, v, v);               // to body coordinates
484     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
485
486     float P = _pressure_inhg->getFloatValue() * INHG2PA;
487     float T = _temp_degc->getFloatValue() + 273.15;
488     float D = _density_slugft3->getFloatValue()
489         *SLUG2KG * M2FT*M2FT*M2FT;
490     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
491     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
492     _set_Mach_number(Atmosphere::calcMach(v[0], T));
493
494     // acceleration
495     Math::vmul33(xyz2ned, s->acc, v);
496     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
497
498     Math::vmul33(s->orient, s->acc, v);
499     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
500     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
501
502     _fdm->getAirplane()->getPilotAccel(v);
503     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
504
505     // There is no property for pilot G's, but I need it for a panel
506     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
507     // REAL HOME!
508     _pilot_g->setFloatValue(-v[2]/9.8);
509
510     // The one appears (!) to want inverted pilot acceleration
511     // numbers, in G's...
512     Math::mul3(1.0/9.8, v, v);
513     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
514
515     // orientation
516     float alpha, beta;
517     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
518     _set_Alpha(alpha);
519     _set_Beta(-beta);
520
521     float tmp[9];
522     Math::trans33(xyz2ned, tmp);
523     Math::mmul33(s->orient, tmp, tmp);
524     float roll, pitch, hdg;
525     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
526     // make heading positive value
527     if(hdg < 0.0) hdg += PI2;
528     _set_Euler_Angles(roll, pitch, hdg);
529
530     // rotation
531     Math::vmul33(s->orient, s->rot, v);
532     _set_Omega_Body(v[0], -v[1], -v[2]);
533
534     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
535     _set_Euler_Rates(roll, pitch, hdg);
536
537     // Fill out our engine and gear objects
538     for(int i=0; i<airplane->numGear(); i++) {
539         Gear* g = airplane->getGear(i);
540         GearProps& gearProps = _gearProps[i];
541         gearProps.has_brake->setBoolValue(
542                 g->getBrake() != 0);
543         gearProps.wow->setBoolValue(
544                 g->getCompressFraction() != 0);
545         gearProps.compression_norm->setFloatValue(
546                 g->getCompressFraction());
547         gearProps.compression_m->setFloatValue(
548                 g->getCompressDist());
549         gearProps.caster_angle_deg->setFloatValue(
550                 g->getCasterAngle() * RAD2DEG);
551         gearProps.rollspeed_ms->setFloatValue(
552                 g->getRollSpeed());
553         gearProps.ground_is_solid->setBoolValue(
554                 g->getGroundIsSolid()!=0);
555         gearProps.ground_friction_factor->setFloatValue(
556                 g->getGroundFrictionFactor());
557     }
558
559     Hook* h = airplane->getHook();
560     if(h) {
561         _tailhook_position_norm->setFloatValue(h->getCompressFraction());
562     }
563
564     Launchbar* l = airplane->getLaunchbar();
565     if(l) {
566         _launchbar_position_norm->setFloatValue(l->getCompressFraction());
567         _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
568         _launchbar_state->setStringValue(l->getState());
569         _launchbar_strop->setBoolValue(l->getStrop());
570     }
571 }
572
573 /** Reinit the FDM.
574  * This is only used after a replay session and when the user requested to resume at
575  * a past point of time. In this case the FDM must reload all values from the property
576  * tree (as given by the replay system). */
577 void YASim::reinit()
578 {
579     // Process inputs. Use excessive value for dt to make sure all transition effects
580     // have reached their final state (i.e. gear is extended/retracted) - which is vital
581     // for many properties to be complete before the first FDM run (otherwise the gear may
582     // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
583     _fdm->getExternalInput(1000);
584
585     // get current FDM values from the property tree
586     copyToYASim(true);
587 }