]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
2c87d1baf497a5f083181ca7d259e8d1d7d57718
[flightgear.git] / src / FDM / YASim / YASim.cxx
1 #include <simgear/misc/sg_path.hxx>
2 #include <simgear/debug/logstream.hxx>
3 #include <simgear/xml/easyxml.hxx>
4 #include <Main/globals.hxx>
5 #include <Main/fg_props.hxx>
6 #include <Scenery/scenery.hxx>
7
8 #include "FGFDM.hpp"
9 #include "Atmosphere.hpp"
10 #include "Math.hpp"
11 #include "Airplane.hpp"
12 #include "Model.hpp"
13 #include "Integrator.hpp"
14 #include "Glue.hpp"
15 #include "Gear.hpp"
16 #include "PropEngine.hpp"
17 #include "PistonEngine.hpp"
18
19 #include "YASim.hxx"
20
21 using namespace yasim;
22
23 static const float RAD2DEG = 180/3.14159265358979323846;
24 static const float RAD2RPM = 9.54929658551;
25 static const float M2FT = 3.2808399;
26 static const float FT2M = 0.3048;
27 static const float MPS2KTS = 3600.0/1852.0;
28 static const float CM2GALS = 264.172037284; // gallons/cubic meter
29 static const float KG2LBS = 2.20462262185;
30 static const float W2HP = 1.3416e-3;
31 static const float INHG2PA = 3386.389;
32
33 void YASim::printDEBUG()
34 {
35     static int debugCount = 0;
36     
37     debugCount++;
38     if(debugCount >= 3) {
39         debugCount = 0;
40
41 //      printf("N1 %5.1f N2 %5.1f FF %7.1f EPR %4.2f EGT %6.1f\n",
42 //             fgGetFloat("/engines/engine[0]/n1"),
43 //             fgGetFloat("/engines/engine[0]/n2"),
44 //             fgGetFloat("/engines/engine[0]/fuel-flow-gph"),
45 //             fgGetFloat("/engines/engine[0]/epr"),
46 //             fgGetFloat("/engines/engine[0]/egt"));
47
48 //      printf("gear: %f\n", fgGetFloat("/controls/gear-down"));
49
50 //      printf("alpha %5.1f beta %5.1f\n", get_Alpha()*57.3, get_Beta()*57.3);
51
52 //      printf("pilot: %f %f %f\n",
53 //             fgGetDouble("/sim/view/pilot/x-offset-m"),
54 //             fgGetDouble("/sim/view/pilot/y-offset-m"),
55 //             fgGetDouble("/sim/view/pilot/z-offset-m"));
56     }
57 }
58
59 YASim::YASim(double dt)
60 {
61 //     set_delta_t(dt);
62     _fdm = new FGFDM();
63
64     _dt = dt;
65
66     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
67 }
68
69 void YASim::report()
70 {
71     Airplane* a = _fdm->getAirplane();
72
73     float aoa = a->getCruiseAoA() * RAD2DEG;
74     float tail = -1 * a->getTailIncidence() * RAD2DEG;
75     float drag = 1000 * a->getDragCoefficient();
76
77     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
78     SG_LOG(SG_FLIGHT,SG_INFO,"      Iterations: "<<a->getSolutionIterations());
79     SG_LOG(SG_FLIGHT,SG_INFO,"Drag Coefficient: "<< drag);
80     SG_LOG(SG_FLIGHT,SG_INFO,"      Lift Ratio: "<<a->getLiftRatio());
81     SG_LOG(SG_FLIGHT,SG_INFO,"      Cruise AoA: "<< aoa);
82     SG_LOG(SG_FLIGHT,SG_INFO,"  Tail Incidence: "<< tail);
83
84     float cg[3];
85     char buf[256];
86     a->getModel()->getBody()->getCG(cg);
87     sprintf(buf, "            CG: %.1f, %.1f, %.1f", 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     // 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");
105
106     char buf[256];
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     }
113
114 }
115
116 void YASim::init()
117 {
118     Airplane* a = _fdm->getAirplane();
119     Model* m = a->getModel();
120
121     // Superclass hook
122     common_init();
123
124     m->setCrashed(false);
125
126     // Build a filename and parse it
127     SGPath f(globals->get_fg_root());
128     f.append("Aircraft-yasim");
129     f.append(fgGetString("/sim/aero"));
130     f.concat(".xml");
131     readXML(f.str(), *_fdm);
132
133     // Compile it into a real airplane, and tell the user what they got
134     a->compile();
135     report();
136
137     _fdm->init();
138
139     // Create some FG{Eng|Gear}Interface objects
140     int i;
141     for(i=0; i<a->numGear(); i++) {
142         Gear* g = a->getGear(i);
143         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
144         float pos[3];
145         g->getPosition(pos);
146         node->setDoubleValue("xoffset-in", pos[0]);
147         node->setDoubleValue("yoffset-in", pos[1]);
148         node->setDoubleValue("zoffset-in", pos[2]);
149     }
150     for(i=0; i<m->numThrusters(); i++) {
151         // Sanify the initial input conditions
152         char buf[64];
153         sprintf(buf, "/controls/throttle[%d]", i);        fgSetFloat(buf, 0);
154         sprintf(buf, "/controls/mixture[%d]", i);         fgSetFloat(buf, 1);
155         sprintf(buf, "/controls/propeller-pitch[%d]", i); fgSetFloat(buf, 1);
156         sprintf(buf, "/controls/afterburner[%d]", i);     fgSetFloat(buf, 0);
157     }
158
159     fgSetFloat("/controls/slats", 0);
160     fgSetFloat("/controls/spoilers", 0);
161
162     // Are we at ground level?  If so, lift the plane up so the gear
163     // clear the ground.
164     double runway_altitude =
165       fgGetDouble("/environment/ground-elevation-m") * SG_METER_TO_FEET;
166     fgSetBool("/controls/gear-down", false);
167     if(get_Altitude() - runway_altitude < 50) {
168         float minGearZ = 1e18;
169         for(i=0; i<a->numGear(); i++) {
170             Gear* g = a->getGear(i);
171             float pos[3];
172             g->getPosition(pos);
173             if(pos[2] < minGearZ)
174                 minGearZ = pos[2];
175         }
176         _set_Altitude(runway_altitude - minGearZ*M2FT);
177         fgSetBool("/controls/gear-down", true);
178     }
179
180     // The pilot's eyepoint
181     float pilot[3];
182     a->getPilotPos(pilot);
183 //     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
184 //     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
185 //     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
186
187     // Blank the state, and copy in ours
188     State s;
189     m->setState(&s);
190     copyToYASim(true);
191
192     _fdm->getExternalInput();
193     _fdm->getAirplane()->initEngines();
194
195     set_inited(true);
196 }
197
198 void YASim::update(double dt)
199 {
200     if (is_suspended())
201       return;
202
203     int iterations = _calc_multiloop(dt);
204
205     // If we're crashed, then we don't care
206     if(_fdm->getAirplane()->getModel()->isCrashed())
207       return;
208
209     int i;
210     for(i=0; i<iterations; i++) {
211             copyToYASim(false);
212             _fdm->iterate(_dt);
213             copyFromYASim();
214
215             printDEBUG();
216     }
217 }
218
219 void YASim::copyToYASim(bool copyState)
220 {
221     // Physical state
222     float lat = get_Latitude();
223     float lon = get_Longitude();
224     float alt = get_Altitude() * FT2M;
225     float roll = get_Phi();
226     float pitch = get_Theta();
227     float hdg = get_Psi();
228
229     // Environment
230     float wind[3];
231     wind[0] = get_V_north_airmass() * FT2M * -1.0;
232     wind[1] = get_V_east_airmass() * FT2M * -1.0;
233     wind[2] = get_V_down_airmass() * FT2M * -1.0;
234
235     // The ground elevation doesn't come from FGInterface; query it
236     // from the scenery and set it for others to find.
237     double ground = globals->get_scenery()->get_cur_elev();
238     _set_Runway_altitude(ground * FT2M);
239
240     float pressure = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
241     float temp = fgGetDouble("/environment/temperature-degC") + 273.15;
242
243     // Convert and set:
244     Model* model = _fdm->getAirplane()->getModel();
245     State s;
246     float xyz2ned[9];
247     Glue::xyz2nedMat(lat, lon, xyz2ned);
248
249     // position
250     Glue::geod2xyz(lat, lon, alt, s.pos);
251
252     // orientation
253     Glue::euler2orient(roll, pitch, hdg, s.orient);
254     Math::mmul33(s.orient, xyz2ned, s.orient);
255
256     // Copy in the existing velocity for now...
257     Math::set3(model->getState()->v, s.v);
258
259     if(copyState)
260         model->setState(&s);
261
262     // wind
263     Math::tmul33(xyz2ned, wind, wind);
264     model->setWind(wind);
265
266     // ground.  Calculate a cartesian coordinate for the ground under
267     // us, find the (geodetic) up vector normal to the ground, then
268     // use that to find the final (radius) term of the plane equation.
269     double xyz[3], gplane[3]; float up[3];
270     Glue::geod2xyz(lat, lon, ground, xyz);
271     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
272     int i;
273     for(i=0; i<3; i++) gplane[i] = up[i];
274     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
275     model->setGroundPlane(gplane, rad);
276
277     // air
278     model->setAir(pressure, temp);
279 }
280
281 // All the settables:
282 //
283 // These are set below:
284 // _set_Accels_Local
285 // _set_Accels_Body
286 // _set_Accels_CG_Body 
287 // _set_Accels_Pilot_Body
288 // _set_Accels_CG_Body_N 
289 // _set_Velocities_Local
290 // _set_Velocities_Ground
291 // _set_Velocities_Wind_Body
292 // _set_Omega_Body
293 // _set_Euler_Rates
294 // _set_Euler_Angles
295 // _set_V_rel_wind
296 // _set_V_ground_speed
297 // _set_V_equiv_kts
298 // _set_V_calibrated_kts
299 // _set_Alpha
300 // _set_Beta
301 // _set_Mach_number
302 // _set_Climb_Rate
303 // _set_Tank1Fuel
304 // _set_Tank2Fuel
305 // _set_Altitude_AGL
306 // _set_Geodetic_Position
307 // _set_Runway_altitude
308
309 // Ignoring these, because they're unused:
310 // _set_Geocentric_Position
311 // _set_Geocentric_Rates
312 // _set_Cos_phi
313 // _set_Cos_theta
314 // _set_Earth_position_angle (WTF?)
315 // _set_Gamma_vert_rad
316 // _set_Inertias
317 // _set_T_Local_to_Body
318 // _set_CG_Position
319 // _set_Sea_Level_Radius
320
321 // Externally set via the weather code:
322 // _set_Velocities_Local_Airmass
323 // _set_Density
324 // _set_Static_pressure
325 // _set_Static_temperature
326 void YASim::copyFromYASim()
327 {
328     Airplane* airplane = _fdm->getAirplane();
329     Model* model = airplane->getModel();
330     State* s = model->getState();
331
332     // position
333     double lat, lon, alt;
334     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
335     _set_Geodetic_Position(lat, lon, alt*M2FT);
336
337     // UNUSED
338     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
339
340     _set_Altitude_AGL(model->getAGL() * M2FT);
341
342     // useful conversion matrix
343     float xyz2ned[9];
344     Glue::xyz2nedMat(lat, lon, xyz2ned);
345
346     // velocity
347     float v[3];
348     Math::vmul33(xyz2ned, s->v, v);
349     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
350     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
351                                    M2FT*v[1]*M2FT*v[1]));
352     _set_Climb_Rate(-M2FT*v[2]);
353
354     // The HUD uses this, but inverts down (?!)
355     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
356
357     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
358
359     // Airflow velocity.
360     float wind[3];
361     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
362     wind[1] = get_V_east_airmass() * FT2M * -1.0;
363     wind[2] = get_V_down_airmass() * FT2M * -1.0;
364     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
365     Math::sub3(s->v, wind, v);                      // V - wind in global
366     Math::vmul33(s->orient, s->v, v);               // to body coordinates
367     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
368     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
369
370
371     float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
372     float T = fgGetDouble("/environment/temperature-degC") + 273.15;
373     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
374     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
375     _set_Mach_number(Atmosphere::calcMach(v[0], T));
376
377     // acceleration
378     Math::vmul33(xyz2ned, s->acc, v);
379     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
380
381     Math::vmul33(s->orient, s->acc, v);
382     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
383     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
384
385     _fdm->getAirplane()->getPilotAccel(v);
386     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
387
388     // The one appears (!) to want inverted pilot acceleration
389     // numbers, in G's...
390     Math::mul3(1.0/9.8, v, v);
391     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
392
393     // orientation
394     float alpha, beta;
395     Glue::calcAlphaBeta(s, &alpha, &beta);
396     _set_Alpha(alpha);
397     _set_Beta(beta);
398
399     float tmp[9];
400     Math::trans33(xyz2ned, tmp);
401     Math::mmul33(s->orient, tmp, tmp);
402     float roll, pitch, hdg;
403     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
404     _set_Euler_Angles(roll, pitch, hdg);
405
406     // rotation
407     Math::vmul33(s->orient, s->rot, v);
408     _set_Omega_Body(v[0], -v[1], -v[2]);
409
410     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
411     _set_Euler_Rates(roll, pitch, hdg);
412
413     // Fill out our engine and gear objects
414     int i;
415     for(i=0; i<airplane->numGear(); i++) {
416         Gear* g = airplane->getGear(i);
417         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
418         node->setBoolValue("has-brake", g->getBrake() != 0);
419         node->setBoolValue("wow", g->getCompressFraction() != 0);
420         node->setFloatValue("compression-norm", g->getCompressFraction());
421     }
422
423     for(i=0; i<model->numThrusters(); i++) {
424         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
425         Thruster* t = model->getThruster(i);
426
427         node->setBoolValue("running", t->isRunning());
428         node->setBoolValue("cranking", t->isCranking());
429
430         // Note: assumes all tanks have the same fuel density!
431         node->setDoubleValue("fuel-flow-gph", CM2GALS * t->getFuelFlow()
432                              / airplane->getFuelDensity(0));
433
434         float tmp[3];
435         t->getThrust(tmp);
436         node->setDoubleValue("prop-thrust", Math::mag3(tmp) * KG2LBS / 9.8);
437
438         PropEngine* pe = t->getPropEngine();
439         if(pe) {
440             node->setDoubleValue("rpm", pe->getOmega() * RAD2RPM);
441
442             pe->getTorque(tmp);
443             float power = Math::mag3(tmp) * pe->getOmega();
444             float maxPower = pe->getPistonEngine()->getMaxPower();
445
446             node->setDoubleValue("max-hp", maxPower * W2HP);
447             node->setDoubleValue("power-pct", 100 * power/maxPower);
448         }
449     }
450 }