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