]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
YASim performance optimization
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
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>
11
12 #include <Main/globals.hxx>
13 #include <Main/fg_props.hxx>
14
15 #include "FGFDM.hpp"
16 #include "Atmosphere.hpp"
17 #include "Math.hpp"
18 #include "Airplane.hpp"
19 #include "Model.hpp"
20 #include "Integrator.hpp"
21 #include "Glue.hpp"
22 #include "Gear.hpp"
23 #include "Hook.hpp"
24 #include "Launchbar.hpp"
25 #include "FGGround.hpp"
26 #include "PropEngine.hpp"
27 #include "PistonEngine.hpp"
28
29 #include "YASim.hxx"
30
31 using namespace yasim;
32
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;
45
46 YASim::YASim(double dt) :
47     _simTime(0)
48 {
49 //     set_delta_t(dt);
50     _fdm = new FGFDM();
51
52     _dt = dt;
53
54     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
55     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
56 }
57
58 YASim::~YASim()
59 {
60     delete _fdm;
61
62     _gearProps.clear();
63 }
64
65 void YASim::report()
66 {
67     Airplane* a = _fdm->getAirplane();
68
69     float aoa = a->getCruiseAoA() * RAD2DEG;
70     float tail = -1 * a->getTailIncidence() * RAD2DEG;
71     float drag = 1000 * a->getDragCoefficient();
72
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());
80
81     float cg[3];
82     char buf[256];
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);
86
87     if(a->getFailureMsg()) {
88         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
89         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
90         exit(1);
91     }
92 }
93
94 void YASim::bind()
95 {
96     // Run the superclass bind to set up a bunch of property ties
97     FGInterface::bind();
98
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");
103
104     char buf[256];
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);
111     }
112 }
113
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))
123 {
124 }
125
126 void YASim::init()
127 {
128     Airplane* airplane = _fdm->getAirplane();
129     Model* model = airplane->getModel();
130
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);
139
140     // Superclass hook
141     common_init();
142
143     model->setCrashed(false);
144     _crashed->setBoolValue(false);
145
146     // Figure out the initial speed type
147     string speed_set = _speed_setprop->getStringValue();
148     if ((speed_set == "") || (speed_set == "UVW"))
149         _speed_set = UVW;
150     else if (speed_set == "NED")
151         _speed_set = NED;
152     else if (speed_set == "knots")
153         _speed_set = KNOTS;
154     else if (speed_set == "mach")
155         _speed_set = MACH;
156     else {
157         _speed_set = UVW;
158         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
159     }
160
161     // Build a filename and parse it
162     SGPath f(fgGetString("/sim/aircraft-dir"));
163     f.append(fgGetString("/sim/aero"));
164     f.concat(".xml");
165     try {
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());
171         throw e;
172     }
173
174     // Compile it into a real airplane, and tell the user what they got
175     airplane->compile();
176     report();
177
178     _fdm->init();
179
180     if (model->getLaunchbar())
181     {
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);
187     }
188     if (airplane->getHook())
189     {
190         _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
191     }
192
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);
197         float pos[3];
198         g->getPosition(pos);
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);
202
203         _gearProps.push_back(GearProps(node));
204     }
205
206     // Are we at ground level?  If so, lift the plane up so the gear
207     // clear the ground.
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);
214             float pos[3];
215             g->getPosition(pos);
216             if(pos[2] < minGearZ)
217                 minGearZ = pos[2];
218         }
219         _set_Altitude(runway_altitude - minGearZ*M2FT);
220         fgSetBool("/controls/gear/gear-down", true);
221     }
222
223     // Blank the state, and copy in ours
224     State s;
225     model->setState(&s);
226     copyToYASim(true);
227
228     _fdm->getExternalInput();
229     _fdm->getAirplane()->initEngines();
230
231     set_inited(true);
232 }
233
234 void YASim::update(double dt)
235 {
236     if (is_suspended())
237         return;
238
239     int iterations = _calc_multiloop(dt);
240
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);
246         return;
247     }
248
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 );
260
261     // Track time increments.
262     FGGround* gr
263       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
264
265     int i;
266     for(i=0; i<iterations; i++) {
267         gr->setTimeOffset(_simTime + i*_dt);
268         copyToYASim(false);
269         _fdm->iterate(_dt);
270         copyFromYASim();
271     }
272
273     // Increment the local sim time
274     _simTime += dt;
275     gr->setTimeOffset(_simTime);
276 }
277
278 void YASim::copyToYASim(bool copyState)
279 {
280     // Physical state
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();
287
288     // Environment
289     float wind[3];
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;
293
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;
298
299     // Convert and set:
300     Model* model = _fdm->getAirplane()->getModel();
301     State s;
302     float xyz2ned[9];
303     Glue::xyz2nedMat(lat, lon, xyz2ned);
304
305     // position
306     sgGeodToCart(lat, lon, alt, s.pos);
307     {
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];
311     }
312
313     // orientation
314     Glue::euler2orient(roll, pitch, hdg, s.orient);
315     Math::mmul33(s.orient, xyz2ned, s.orient);
316
317     // Velocity
318     float v[3];
319     bool needCopy = false;
320     switch (_speed_set) {
321     case NED:
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;
325         break;
326     case UVW:
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);
331         break;
332     case KNOTS:
333         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
334                                        pressure, temp);
335         v[1] = 0;
336         v[2] = 0;
337         Math::tmul33(s.orient, v, v);
338         needCopy = true;
339         break;
340     case MACH:
341         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
342         v[1] = 0;
343         v[2] = 0;
344         Math::tmul33(s.orient, v, v);
345         needCopy = true;
346         break;
347     default:
348         v[0] = 0;
349         v[1] = 0;
350         v[2] = 0;
351         break;
352     }
353     if (!copyState)
354         _speed_set = UVW;       // change to this after initial setting
355     Math::set3(v, s.v);
356
357     if(copyState || needCopy)
358         model->setState(&s);
359
360     // wind
361     Math::tmul33(xyz2ned, wind, wind);
362     model->setWind(wind);
363
364     // air
365     model->setAir(pressure, temp, dens);
366
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);
370
371     Launchbar* l = model->getLaunchbar();
372     if (l)
373         l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
374 }
375
376 // All the settables:
377 //
378 // These are set below:
379 // _set_Accels_Local
380 // _set_Accels_Body
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
387 // _set_Omega_Body
388 // _set_Euler_Rates
389 // _set_Euler_Angles
390 // _set_V_rel_wind
391 // _set_V_ground_speed
392 // _set_V_equiv_kts
393 // _set_V_calibrated_kts
394 // _set_Alpha
395 // _set_Beta
396 // _set_Mach_number
397 // _set_Climb_Rate
398 // _set_Tank1Fuel
399 // _set_Tank2Fuel
400 // _set_Altitude_AGL
401 // _set_Geodetic_Position
402 // _set_Runway_altitude
403
404 // Ignoring these, because they're unused:
405 // _set_Geocentric_Position
406 // _set_Geocentric_Rates
407 // _set_Cos_phi
408 // _set_Cos_theta
409 // _set_Earth_position_angle (WTF?)
410 // _set_Gamma_vert_rad
411 // _set_Inertias
412 // _set_T_Local_to_Body
413 // _set_CG_Position
414 // _set_Sea_Level_Radius
415
416 // Externally set via the weather code:
417 // _set_Velocities_Local_Airmass
418 // _set_Density
419 // _set_Static_pressure
420 // _set_Static_temperature
421 void YASim::copyFromYASim()
422 {
423     Airplane* airplane = _fdm->getAirplane();
424     Model* model = airplane->getModel();
425     State* s = model->getState();
426
427     // position
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);
434
435     // the smallest agl of all gears
436     _gear_agl_m->setFloatValue(model->getAGL());
437     _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
438
439     // UNUSED
440     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
441
442     // useful conversion matrix
443     float xyz2ned[9];
444     Glue::xyz2nedMat(lat, lon, xyz2ned);
445
446     // velocity
447     float v[3];
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]);
453
454     // The HUD uses this, but inverts down (?!)
455     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
456
457     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
458
459     // Airflow velocity.
460     float wind[3];
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?
469
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));
477
478     // acceleration
479     Math::vmul33(xyz2ned, s->acc, v);
480     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
481
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]);
485
486     _fdm->getAirplane()->getPilotAccel(v);
487     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
488
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
491     // REAL HOME!
492     _pilot_g->setFloatValue(-v[2]/9.8);
493
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]);
498
499     // orientation
500     float alpha, beta;
501     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
502     _set_Alpha(alpha);
503     _set_Beta(beta);
504
505     float tmp[9];
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);
513
514     // rotation
515     Math::vmul33(s->orient, s->rot, v);
516     _set_Omega_Body(v[0], -v[1], -v[2]);
517
518     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
519     _set_Euler_Rates(roll, pitch, hdg);
520
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(
526                 g->getBrake() != 0);
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(
536                 g->getRollSpeed());
537         gearProps.ground_is_solid->setBoolValue(
538                 g->getGroundIsSolid()!=0);
539         gearProps.ground_friction_factor->setFloatValue(
540                 g->getGroundFrictionFactor());
541     }
542
543     Hook* h = airplane->getHook();
544     if(h) {
545         _tailhook_position_norm->setFloatValue(h->getCompressFraction());
546     }
547
548     Launchbar* l = airplane->getLaunchbar();
549     if(l) {
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());
554     }
555 }
556
557 /** Reinit the FDM.
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). */
561 void YASim::reinit()
562 {
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);
568
569     // get current FDM values from the property tree
570     copyToYASim(true);
571 }