]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Merge branch 'next' into comm-subsystem
[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
63 void YASim::report()
64 {
65     Airplane* a = _fdm->getAirplane();
66
67     float aoa = a->getCruiseAoA() * RAD2DEG;
68     float tail = -1 * a->getTailIncidence() * RAD2DEG;
69     float drag = 1000 * a->getDragCoefficient();
70
71     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
72     SG_LOG(SG_FLIGHT,SG_INFO,"       Iterations: "<<a->getSolutionIterations());
73     SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
74     SG_LOG(SG_FLIGHT,SG_INFO,"       Lift Ratio: "<<a->getLiftRatio());
75     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
76     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
77     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
78     
79
80     float cg[3];
81     char buf[256];
82     a->getModel()->getBody()->getCG(cg);
83     sprintf(buf, "            CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
84     SG_LOG(SG_FLIGHT, SG_INFO, buf);
85
86     if(a->getFailureMsg()) {
87         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
88         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
89         exit(1);
90     }
91 }
92
93 void YASim::bind()
94 {
95     // Run the superclass bind to set up a bunch of property ties
96     FGInterface::bind();
97
98 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
99     // Now UNtie the ones that we are going to set ourselves.
100 //    fgUntie("/consumables/fuel/tank[0]/level-gal_us");
101 //    fgUntie("/consumables/fuel/tank[1]/level-gal_us");
102
103     char buf[256];
104     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
105         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i);        fgUntie(buf);
106         sprintf(buf, "/engines/engine[%d]/rpm", i);                  fgUntie(buf);
107         sprintf(buf, "/engines/engine[%d]/mp-osi", i);               fgUntie(buf);
108         sprintf(buf, "/engines/engine[%d]/egt-degf", i);             fgUntie(buf);
109         sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
110     }
111 }
112
113 void YASim::init()
114 {
115     Airplane* a = _fdm->getAirplane();
116     Model* m = a->getModel();
117
118     // Superclass hook
119     common_init();
120
121     m->setCrashed(false);
122
123     // Figure out the initial speed type
124     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
125     if (speed_set == "NED")
126         _speed_set = NED;
127     else if (speed_set == "UVW")
128         _speed_set = UVW;
129     else if (speed_set == "knots")
130         _speed_set = KNOTS;
131     else if (speed_set == "mach")
132         _speed_set = MACH;
133     else {
134         _speed_set = UVW;
135         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
136     }
137
138     // Build a filename and parse it
139     SGPath f(fgGetString("/sim/aircraft-dir"));
140     f.append(fgGetString("/sim/aero"));
141     f.concat(".xml");
142     try {
143         readXML(f.str(), *_fdm);
144     } catch (const sg_exception &e) {
145         SG_LOG(SG_GENERAL, SG_ALERT,
146                "Error reading YASim FDM: '" << f.str() << "'" << std::endl
147                << e.getFormattedMessage());
148         throw e;
149     }
150
151     // Compile it into a real airplane, and tell the user what they got
152     a->compile();
153     report();
154
155     _fdm->init();
156
157     // Create some FG{Eng|Gear}Interface objects
158     int i;
159     for(i=0; i<a->numGear(); i++) {
160         Gear* g = a->getGear(i);
161         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
162         float pos[3];
163         g->getPosition(pos);
164         node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
165         node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
166         node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
167     }
168
169     // Are we at ground level?  If so, lift the plane up so the gear
170     // clear the ground.
171     double runway_altitude = get_Runway_altitude();
172     if(get_Altitude() - runway_altitude < 50) {
173         fgSetBool("/controls/gear/gear-down", false);
174         float minGearZ = 1e18;
175         for(i=0; i<a->numGear(); i++) {
176             Gear* g = a->getGear(i);
177             float pos[3];
178             g->getPosition(pos);
179             if(pos[2] < minGearZ)
180                 minGearZ = pos[2];
181         }
182         _set_Altitude(runway_altitude - minGearZ*M2FT);
183         fgSetBool("/controls/gear/gear-down", true);
184     }
185
186     // Blank the state, and copy in ours
187     State s;
188     m->setState(&s);
189     copyToYASim(true);
190
191     _fdm->getExternalInput();
192     _fdm->getAirplane()->initEngines();
193
194     set_inited(true);
195 }
196
197 void YASim::update(double dt)
198 {
199     if (is_suspended())
200         return;
201
202     int iterations = _calc_multiloop(dt);
203
204     // If we're crashed, then we don't care
205     if(fgGetBool("/sim/crashed") || _fdm->getAirplane()->getModel()->isCrashed()) {
206         if(!fgGetBool("/sim/crashed"))
207             fgSetBool("/sim/crashed", true);
208         _fdm->getAirplane()->getModel()->setCrashed(false);
209         return;
210     }
211
212     // ground.  Calculate a cartesian coordinate for the ground under
213     // us, find the (geodetic) up vector normal to the ground, then
214     // use that to find the final (radius) term of the plane equation.
215     float v[3] = { get_uBody(), get_vBody(), get_wBody() };
216     float lat = get_Latitude(); float lon = get_Longitude();
217     float alt = get_Altitude() * FT2M; double xyz[3];
218     sgGeodToCart(lat, lon, alt, xyz);
219     // build the environment cache.
220     float vr = _fdm->getVehicleRadius();
221     vr += 2.0*FT2M*dt*Math::mag3(v);
222     prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
223
224     // Track time increments.
225     FGGround* gr
226       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
227
228     int i;
229     for(i=0; i<iterations; i++) {
230         gr->setTimeOffset(_simTime + i*_dt);
231         copyToYASim(false);
232         _fdm->iterate(_dt);
233         copyFromYASim();
234     }
235
236     // Increment the local sim time
237     _simTime += dt;
238     gr->setTimeOffset(_simTime);
239 }
240
241 void YASim::copyToYASim(bool copyState)
242 {
243     // Physical state
244     double lat = get_Latitude();
245     double lon = get_Longitude();
246     float alt = get_Altitude() * FT2M;
247     float roll = get_Phi();
248     float pitch = get_Theta();
249     float hdg = get_Psi();
250
251     // Environment
252     float wind[3];
253     wind[0] = get_V_north_airmass() * FT2M * -1.0;
254     wind[1] = get_V_east_airmass() * FT2M * -1.0;
255     wind[2] = get_V_down_airmass() * FT2M * -1.0;
256
257     float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
258     float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
259     float dens = fgGetFloat("/environment/density-slugft3") 
260         * SLUG2KG * M2FT*M2FT*M2FT;
261
262     // Convert and set:
263     Model* model = _fdm->getAirplane()->getModel();
264     State s;
265     float xyz2ned[9];
266     Glue::xyz2nedMat(lat, lon, xyz2ned);
267
268     // position
269     sgGeodToCart(lat, lon, alt, s.pos);
270     {
271       // allow setting of /position/[lat|long|alti]tude
272       double * dp = &model->getState()->pos[0];
273       dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
274     }
275
276     // orientation
277     Glue::euler2orient(roll, pitch, hdg, s.orient);
278     Math::mmul33(s.orient, xyz2ned, s.orient);
279
280     // Velocity
281     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
282     float v[3];
283     bool needCopy = false;
284     switch (_speed_set) {
285     case NED:
286         v[0] = get_V_north() * FT2M * -1.0;
287         v[1] = get_V_east() * FT2M * -1.0;
288         v[2] = get_V_down() * FT2M * -1.0;
289         break;
290     case UVW:
291         v[0] = get_uBody() * FT2M;
292         v[1] = get_vBody() * FT2M;
293         v[2] = get_wBody() * FT2M;
294         Math::tmul33(s.orient, v, v);
295         break;
296     case KNOTS:
297         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
298                                        pressure, temp);
299         v[1] = 0;
300         v[2] = 0;
301         Math::tmul33(s.orient, v, v);
302         needCopy = true;
303         break;
304     case MACH:
305         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
306         v[1] = 0;
307         v[2] = 0;
308         Math::tmul33(s.orient, v, v);
309         needCopy = true;
310         break;
311     default:
312         v[0] = 0;
313         v[1] = 0;
314         v[2] = 0;
315         break;
316     }
317     if (!copyState)
318         _speed_set = UVW;       // change to this after initial setting
319     Math::set3(v, s.v);
320
321     if(copyState || needCopy)
322         model->setState(&s);
323
324     // wind
325     Math::tmul33(xyz2ned, wind, wind);
326     model->setWind(wind);
327
328     // air
329     model->setAir(pressure, temp, dens);
330
331     // Query a ground plane for each gear/hook/launchbar and
332     // write that value into the corresponding class.
333     _fdm->getAirplane()->getModel()->updateGround(&s);
334
335     Launchbar* l = model->getLaunchbar();
336     if (l)
337         l->setLaunchCmd(0.0<fgGetFloat("/controls/gear/catapult-launch-cmd"));
338 }
339
340 // All the settables:
341 //
342 // These are set below:
343 // _set_Accels_Local
344 // _set_Accels_Body
345 // _set_Accels_CG_Body 
346 // _set_Accels_Pilot_Body
347 // _set_Accels_CG_Body_N 
348 // _set_Velocities_Local
349 // _set_Velocities_Ground
350 // _set_Velocities_Wind_Body
351 // _set_Omega_Body
352 // _set_Euler_Rates
353 // _set_Euler_Angles
354 // _set_V_rel_wind
355 // _set_V_ground_speed
356 // _set_V_equiv_kts
357 // _set_V_calibrated_kts
358 // _set_Alpha
359 // _set_Beta
360 // _set_Mach_number
361 // _set_Climb_Rate
362 // _set_Tank1Fuel
363 // _set_Tank2Fuel
364 // _set_Altitude_AGL
365 // _set_Geodetic_Position
366 // _set_Runway_altitude
367
368 // Ignoring these, because they're unused:
369 // _set_Geocentric_Position
370 // _set_Geocentric_Rates
371 // _set_Cos_phi
372 // _set_Cos_theta
373 // _set_Earth_position_angle (WTF?)
374 // _set_Gamma_vert_rad
375 // _set_Inertias
376 // _set_T_Local_to_Body
377 // _set_CG_Position
378 // _set_Sea_Level_Radius
379
380 // Externally set via the weather code:
381 // _set_Velocities_Local_Airmass
382 // _set_Density
383 // _set_Static_pressure
384 // _set_Static_temperature
385 void YASim::copyFromYASim()
386 {
387     Airplane* airplane = _fdm->getAirplane();
388     Model* model = airplane->getModel();
389     State* s = model->getState();
390
391     // position
392     double lat, lon, alt;
393     sgCartToGeod(s->pos, &lat, &lon, &alt);
394     _set_Geodetic_Position(lat, lon, alt*M2FT);
395     double groundlevel_m = get_groundlevel_m(lat, lon, alt);
396     _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
397     _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
398
399     // the smallest agl of all gears
400     fgSetFloat("/position/gear-agl-m", model->getAGL());
401     fgSetFloat("/position/gear-agl-ft", model->getAGL()*M2FT);
402
403     // UNUSED
404     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
405
406     // useful conversion matrix
407     float xyz2ned[9];
408     Glue::xyz2nedMat(lat, lon, xyz2ned);
409
410     // velocity
411     float v[3];
412     Math::vmul33(xyz2ned, s->v, v);
413     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
414     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
415                                    M2FT*v[1]*M2FT*v[1]));
416     _set_Climb_Rate(-M2FT*v[2]);
417
418     // The HUD uses this, but inverts down (?!)
419     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
420
421     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
422
423     // Airflow velocity.
424     float wind[3];
425     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
426     wind[1] = get_V_east_airmass() * FT2M * -1.0;
427     wind[2] = get_V_down_airmass() * FT2M * -1.0;
428     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
429     Math::sub3(s->v, wind, v);                      // V - wind in global
430     Math::vmul33(s->orient, v, v);               // to body coordinates
431     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
432     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
433
434     float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
435     float T = fgGetDouble("/environment/temperature-degc") + 273.15;
436     float D = fgGetFloat("/environment/density-slugft3")
437         *SLUG2KG * M2FT*M2FT*M2FT;
438     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
439     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
440     _set_Mach_number(Atmosphere::calcMach(v[0], T));
441
442     // acceleration
443     Math::vmul33(xyz2ned, s->acc, v);
444     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
445
446     Math::vmul33(s->orient, s->acc, v);
447     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
448     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
449
450     _fdm->getAirplane()->getPilotAccel(v);
451     _set_Accels_Pilot_Body(-M2FT*v[0], M2FT*v[1], M2FT*v[2]);
452
453     // There is no property for pilot G's, but I need it for a panel
454     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
455     // REAL HOME!
456     fgSetFloat("/accelerations/pilot-g", -v[2]/9.8);
457
458     // The one appears (!) to want inverted pilot acceleration
459     // numbers, in G's...
460     Math::mul3(1.0/9.8, v, v);
461     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
462
463     // orientation
464     float alpha, beta;
465     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
466     _set_Alpha(alpha);
467     _set_Beta(beta);
468
469     float tmp[9];
470     Math::trans33(xyz2ned, tmp);
471     Math::mmul33(s->orient, tmp, tmp);
472     float roll, pitch, hdg;
473     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
474     // make heading positive value
475     if(hdg < 0.0) hdg += PI2;
476     _set_Euler_Angles(roll, pitch, hdg);
477
478     // rotation
479     Math::vmul33(s->orient, s->rot, v);
480     _set_Omega_Body(v[0], -v[1], -v[2]);
481
482     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
483     _set_Euler_Rates(roll, pitch, hdg);
484
485     // Fill out our engine and gear objects
486     int i;
487     for(i=0; i<airplane->numGear(); i++) {
488         Gear* g = airplane->getGear(i);
489         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
490         node->setBoolValue("has-brake", g->getBrake() != 0);
491         node->setBoolValue("wow", g->getCompressFraction() != 0);
492         node->setFloatValue("compression-norm", g->getCompressFraction());
493         node->setFloatValue("compression-m", g->getCompressDist());
494         node->setFloatValue("caster-angle-deg", g->getCasterAngle() * RAD2DEG);
495         node->setFloatValue("rollspeed-ms", g->getRollSpeed());
496         node->setBoolValue("ground-is-solid", g->getGroundIsSolid()!=0);
497         node->setFloatValue("ground-friction-factor", g->getGroundFrictionFactor());
498     }
499
500     Hook* h = airplane->getHook();
501     if(h) {
502         SGPropertyNode * node = fgGetNode("gear/tailhook", 0, true);
503         node->setFloatValue("position-norm", h->getCompressFraction());
504     }
505
506     Launchbar* l = airplane->getLaunchbar();
507     if(l) {
508         SGPropertyNode * node = fgGetNode("gear/launchbar", 0, true);
509         node->setFloatValue("position-norm", l->getCompressFraction());
510         node->setFloatValue("holdback-position-norm", l->getHoldbackCompressFraction());
511         node->setStringValue("state", l->getState());
512         node->setBoolValue("strop", l->getStrop());
513     }
514
515 }
516
517 /** Reinit the FDM.
518  * This is only used after a replay session and when the user requested to resume at
519  * a past point of time. In thise case the FDM must reload all values from the property
520  * tree (as given by the replay system). */
521 void YASim::reinit()
522 {
523     // Process inputs. Use excessive value for dt to make sure all transition effects
524     // have reached their final state (i.e. gear is extended/retracted) - which is vital
525     // for many properties to be complete before the first FDM run (otherwise the gear may
526     // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
527     _fdm->getExternalInput(1000);
528
529     // get current FDM values from the property tree
530     copyToYASim(true);
531 }