]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
David Megginson writes:
[flightgear.git] / src / FDM / YASim / YASim.cxx
1 #include <stdio.h>
2
3 #include <simgear/misc/sg_path.hxx>
4 #include <simgear/debug/logstream.hxx>
5 #include <simgear/easyxml.hxx>
6 #include <Main/globals.hxx>
7 #include <Main/fg_props.hxx>
8 #include <Scenery/scenery.hxx>
9
10 #include "FGFDM.hpp"
11 #include "Atmosphere.hpp"
12 #include "Math.hpp"
13 #include "Airplane.hpp"
14 #include "Model.hpp"
15 #include "Integrator.hpp"
16 #include "Glue.hpp"
17 #include "Gear.hpp"
18 #include "PropEngine.hpp"
19 #include "PistonEngine.hpp"
20
21 #include "YASim.hxx"
22
23 using namespace yasim;
24
25 static const float RAD2DEG = 180/3.14159265358979323846;
26 static const float RAD2RPM = 9.54929658551;
27 static const float M2FT = 3.2808399;
28 static const float FT2M = 0.3048;
29 static const float MPS2KTS = 3600.0/1852.0;
30 static const float CM2GALS = 264.172037284; // gallons/cubic meter
31 static const float KG2LBS = 2.20462262185;
32 static const float W2HP = 1.3416e-3;
33
34 void YASim::printDEBUG()
35 {
36     static int debugCount = 0;
37     
38     debugCount++;
39     if(debugCount >= 3) {
40         debugCount = 0;
41
42 //      printf("RPM %.1f FF %.1f\n",
43 //             fgGetFloat("/engines/engine[0]/rpm"),
44 //             fgGetFloat("/engines/engine[0]/fuel-flow-gph"));
45
46 //      printf("gear: %f\n", fgGetFloat("/controls/gear-down"));
47
48 //      printf("alpha %5.1f beta %5.1f\n", get_Alpha()*57.3, get_Beta()*57.3);
49
50 //      printf("pilot: %f %f %f\n",
51 //             fgGetDouble("/sim/view/pilot/x-offset-m"),
52 //             fgGetDouble("/sim/view/pilot/y-offset-m"),
53 //             fgGetDouble("/sim/view/pilot/z-offset-m"));
54     }
55 }
56
57 YASim::YASim(double dt)
58 {
59     set_delta_t(dt);
60     _fdm = new FGFDM();
61
62     // Because the integration method is via fourth-order Runge-Kutta,
63     // we only get an "output" state for every 4 times the internal
64     // forces are calculated.  So divide dt by four to account for
65     // this, and only run an iteration every fourth time through
66     // update.
67     _dt = dt * 4;
68     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
69     _updateCount = 0;
70 }
71
72 void YASim::report()
73 {
74     Airplane* a = _fdm->getAirplane();
75
76     float aoa = a->getCruiseAoA() * RAD2DEG;
77     float tail = -1 * a->getTailIncidence() * RAD2DEG;
78     float drag = 1000 * a->getDragCoefficient();
79
80     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
81     SG_LOG(SG_FLIGHT,SG_INFO,"      Iterations: "<<a->getSolutionIterations());
82     SG_LOG(SG_FLIGHT,SG_INFO,"Drag Coefficient: "<< drag);
83     SG_LOG(SG_FLIGHT,SG_INFO,"      Lift Ratio: "<<a->getLiftRatio());
84     SG_LOG(SG_FLIGHT,SG_INFO,"      Cruise AoA: "<< aoa);
85     SG_LOG(SG_FLIGHT,SG_INFO,"  Tail Incidence: "<< tail);
86
87     float cg[3];
88     char buf[256];
89     a->getModel()->getBody()->getCG(cg);
90     sprintf(buf, "            CG: %.1f, %.1f, %.1f", cg[0], cg[1], cg[2]);
91     SG_LOG(SG_FLIGHT, SG_INFO, buf);
92
93     if(a->getFailureMsg()) {
94         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
95         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
96         exit(1);
97     }
98 }
99
100 void YASim::init()
101 {
102     Airplane* a = _fdm->getAirplane();
103     Model* m = a->getModel();
104
105     // Superclass hook
106     common_init();
107
108     // Build a filename and parse it
109     SGPath f(globals->get_fg_root());
110     f.append("Aircraft-yasim");
111     f.append(fgGetString("/sim/aero"));
112     f.concat(".xml");
113     readXML(f.str(), *_fdm);
114
115     // Compile it into a real airplane, and tell the user what they got
116     a->compile();
117     report();
118
119     _fdm->init();
120
121     // Create some FG{Eng|Gear}Interface objects
122     int i;
123     for(i=0; i<a->numGear(); i++) {
124         Gear* g = a->getGear(i);
125         FGGearInterface fgg;
126         float pos[3];
127         g->getPosition(pos);
128         fgg.SetX(pos[0]); fgg.SetY(-pos[1]); fgg.SetZ(-pos[2]);
129         add_gear_unit(fgg);
130     }
131     for(i=0; i<m->numThrusters(); i++) {
132         FGEngInterface fge;
133         add_engine(fge);
134
135         // Sanify the initial input conditions
136         char buf[64];
137         sprintf(buf, "/controls/throttle[%d]", i);        fgSetFloat(buf, 0);
138         sprintf(buf, "/controls/mixture[%d]", i);         fgSetFloat(buf, 1);
139         sprintf(buf, "/controls/propeller-pitch[%d]", i); fgSetFloat(buf, 1);
140         sprintf(buf, "/controls/afterburner[%d]", i);     fgSetFloat(buf, 0);
141     }
142     
143
144     // Lift the plane up so the gear clear the ground
145     float minGearZ = 1e18;
146     for(i=0; i<a->numGear(); i++) {
147         Gear* g = a->getGear(i);
148         float pos[3];
149         g->getPosition(pos);
150         if(pos[2] < minGearZ)
151             minGearZ = pos[2];
152     }
153     _set_Altitude(get_Altitude() - minGearZ*M2FT);
154
155     // The pilot's eyepoint
156     float pilot[3];
157     a->getPilotPos(pilot);
158     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
159     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
160     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
161
162     // Blank the state, and copy in ours
163     State s;
164     m->setState(&s);
165
166     copyToYASim(true);
167     set_inited(true);
168 }
169
170 bool YASim::update(int iterations)
171 {
172     int i;
173     for(i=0; i<iterations; i++) {
174         // Remember, update only every 4th call
175         _updateCount++;
176         if(_updateCount >= 4) {
177
178             copyToYASim(false);
179             _fdm->iterate(_dt);
180             copyFromYASim();
181
182             printDEBUG();
183
184             _updateCount = 0;
185         }
186     }
187
188     return true; // what does this mean?
189 }
190
191 void YASim::copyToYASim(bool copyState)
192 {
193     // Physical state
194     float lat = get_Latitude();
195     float lon = get_Longitude();
196     float alt = get_Altitude() * FT2M;
197     float roll = get_Phi();
198     float pitch = get_Theta();
199     float hdg = get_Psi();
200
201     // Environment
202     float wind[3];
203     wind[0] = get_V_north_airmass() * FT2M;
204     wind[1] = get_V_east_airmass() * FT2M;
205     wind[2] = get_V_down_airmass() * FT2M;
206     double ground = get_Runway_altitude() * FT2M;
207
208     // You'd this this would work, but it doesn't.  These values are
209     // always zero.  Use a "standard" pressure intstead.
210     //
211     // float pressure = get_Static_pressure();
212     // float temp = get_Static_temperature();
213     float pressure = Atmosphere::getStdPressure(alt);
214     float temp = Atmosphere::getStdTemperature(alt);
215
216     // Convert and set:
217     Model* model = _fdm->getAirplane()->getModel();
218     State s;
219     float xyz2ned[9];
220     Glue::xyz2nedMat(lat, lon, xyz2ned);
221
222     // position
223     Glue::geod2xyz(lat, lon, alt, s.pos);
224
225     // orientation
226     Glue::euler2orient(roll, pitch, hdg, s.orient);
227     Math::mmul33(s.orient, xyz2ned, s.orient);
228
229     // Copy in the existing velocity for now...
230     Math::set3(model->getState()->v, s.v);
231
232     if(copyState)
233         model->setState(&s);
234
235     // wind
236     Math::tmul33(xyz2ned, wind, wind);
237     model->setWind(wind);
238
239     // ground.  Calculate a cartesian coordinate for the ground under
240     // us, find the (geodetic) up vector normal to the ground, then
241     // use that to find the final (radius) term of the plane equation.
242     double xyz[3], gplane[3]; float up[3];
243     Glue::geod2xyz(lat, lon, ground, xyz);
244     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
245     int i;
246     for(i=0; i<3; i++) gplane[i] = up[i];
247     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
248     model->setGroundPlane(gplane, rad);
249
250     // air
251     model->setAir(pressure, temp);
252 }
253
254 // All the settables:
255 //
256 // These are set below:
257 // _set_Accels_Local
258 // _set_Accels_Body
259 // _set_Accels_CG_Body 
260 // _set_Accels_Pilot_Body
261 // _set_Accels_CG_Body_N 
262 // _set_Velocities_Local
263 // _set_Velocities_Ground
264 // _set_Velocities_Wind_Body
265 // _set_Omega_Body
266 // _set_Euler_Rates
267 // _set_Euler_Angles
268 // _set_V_rel_wind
269 // _set_V_ground_speed
270 // _set_V_equiv_kts
271 // _set_V_calibrated_kts
272 // _set_Alpha
273 // _set_Beta
274 // _set_Mach_number
275 // _set_Climb_Rate
276 // _set_Tank1Fuel
277 // _set_Tank2Fuel
278 // _set_Altitude_AGL
279 // _set_Geodetic_Position
280 // _set_Runway_altitude
281
282 // Ignoring these, because they're unused:
283 // _set_Geocentric_Position
284 // _set_Geocentric_Rates
285 // _set_Cos_phi
286 // _set_Cos_theta
287 // _set_Earth_position_angle (WTF?)
288 // _set_Gamma_vert_rad
289 // _set_Inertias
290 // _set_T_Local_to_Body
291 // _set_CG_Position
292 // _set_Sea_Level_Radius
293
294 // Externally set via the weather code:
295 // _set_Velocities_Local_Airmass
296 // _set_Density
297 // _set_Static_pressure
298 // _set_Static_temperature
299 void YASim::copyFromYASim()
300 {
301     Airplane* airplane = _fdm->getAirplane();
302     Model* model = airplane->getModel();
303     State* s = model->getState();
304
305     // position
306     double lat, lon, alt;
307     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
308     _set_Geodetic_Position(lat, lon, alt*M2FT);
309
310     // UNUSED
311     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
312
313     // FIXME: there's a normal vector available too, use it.
314     float groundMSL = scenery.get_cur_elev();
315     _set_Runway_altitude(groundMSL*M2FT);
316     _set_Altitude_AGL((alt - groundMSL)*M2FT);
317
318     // useful conversion matrix
319     float xyz2ned[9];
320     Glue::xyz2nedMat(lat, lon, xyz2ned);
321
322     // velocity
323     float v[3];
324     Math::vmul33(xyz2ned, s->v, v);
325     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
326     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
327                                    M2FT*v[1]*M2FT*v[1]));
328     _set_Climb_Rate(-M2FT*v[2]);
329
330     // The HUD uses this, but inverts down (?!)
331     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
332
333     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
334
335     Math::vmul33(s->orient, s->v, v);
336     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
337     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
338
339     // These don't work, use a dummy based on altitude
340     // float P = get_Static_pressure();
341     // float T = get_Static_temperature();
342     float P = Atmosphere::getStdPressure(alt);
343     float T = Atmosphere::getStdTemperature(alt);
344     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
345     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
346     _set_Mach_number(Atmosphere::calcMach(v[0], T));
347
348     // acceleration
349     Math::vmul33(xyz2ned, s->acc, v);
350     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
351
352     Math::vmul33(s->orient, s->acc, v);
353     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
354     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
355
356     _fdm->getAirplane()->getPilotAccel(v);
357     _set_Accels_Pilot_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
358
359     // The one appears (!) to want inverted pilot acceleration
360     // numbers, in G's...
361     Math::mul3(1.0/9.8, v, v);
362     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
363
364     // orientation
365     float alpha, beta;
366     Glue::calcAlphaBeta(s, &alpha, &beta);
367     _set_Alpha(alpha);
368     _set_Beta(beta);
369
370     float tmp[9];
371     Math::trans33(xyz2ned, tmp);
372     Math::mmul33(s->orient, tmp, tmp);
373     float roll, pitch, hdg;
374     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
375     _set_Euler_Angles(roll, pitch, hdg);
376
377     // rotation
378     Math::vmul33(s->orient, s->rot, v);
379     _set_Omega_Body(v[0], -v[1], -v[2]);
380
381     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
382     _set_Euler_Rates(roll, pitch, hdg);
383
384     // Fill out our engine and gear objects
385     int i;
386     for(i=0; i<get_num_gear(); i++) {
387         FGGearInterface* fgg = get_gear_unit(i);
388         Gear* g = airplane->getGear(i);
389         if(g->getBrake() != 0)
390             fgg->SetBrake(true);
391         if(g->getCompressFraction() != 0)
392             fgg->SetWoW(true);
393         fgg->SetPosition(g->getExtension());
394     }
395
396     for(i=0; i<get_num_engines(); i++) {
397         FGEngInterface* fge = get_engine(i);
398         Thruster* t = model->getThruster(i);
399
400         fge->set_Running_Flag(true);
401
402         // Note: assumes all tanks have the same fuel density!
403         fge->set_Fuel_Flow(CM2GALS * t->getFuelFlow()
404                            / airplane->getFuelDensity(0));
405
406         float tmp[3];
407         t->getThrust(tmp);
408         fge->set_prop_thrust(Math::mag3(tmp) * KG2LBS / 9.8);
409
410         PropEngine* pe = t->getPropEngine();
411         if(pe) {
412             fge->set_RPM(pe->getOmega() * RAD2RPM);
413
414             pe->getTorque(tmp);
415             float power = Math::mag3(tmp) * pe->getOmega();
416             float maxPower = pe->getPistonEngine()->getPower();
417
418             fge->set_MaxHP(maxPower * W2HP);
419             fge->set_Percentage_Power(100 * power/maxPower);
420         }
421     }
422 }