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