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