]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/FGFDM.cpp
Maik JUSTUS: replace underscore with hyphen in config keywords, to be
[flightgear.git] / src / FDM / YASim / FGFDM.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include <Main/fg_props.hxx>
5
6 #include "Math.hpp"
7 #include "Jet.hpp"
8 #include "SimpleJet.hpp"
9 #include "Gear.hpp"
10 #include "Hook.hpp"
11 #include "Launchbar.hpp"
12 #include "Atmosphere.hpp"
13 #include "PropEngine.hpp"
14 #include "Propeller.hpp"
15 #include "PistonEngine.hpp"
16 #include "TurbineEngine.hpp"
17 #include "Rotor.hpp"
18 #include "Rotorpart.hpp"
19
20 #include "FGFDM.hpp"
21
22 namespace yasim {
23
24 // Some conversion factors
25 static const float KTS2MPS = 0.514444444444;
26 static const float FT2M = 0.3048;
27 static const float DEG2RAD = 0.0174532925199;
28 static const float RPM2RAD = 0.10471975512;
29 static const float LBS2N = 4.44822;
30 static const float LBS2KG = 0.45359237;
31 static const float KG2LBS = 2.2046225;
32 static const float CM2GALS = 264.172037284;
33 static const float HP2W = 745.700;
34 static const float INHG2PA = 3386.389;
35 static const float K2DEGF = 1.8;
36 static const float K2DEGFOFFSET = -459.4;
37 static const float CIN2CM = 1.6387064e-5;
38 static const float YASIM_PI = 3.14159265358979323846;
39
40 static const float NM2FTLB = (1/(LBS2N*FT2M));
41
42 // Stubs, so that this can be compiled without the FlightGear
43 // binary.  What's the best way to handle this?
44
45 //     float fgGetFloat(char* name, float def) { return 0; }
46 //     void fgSetFloat(char* name, float val) {}
47
48 FGFDM::FGFDM()
49 {
50     _vehicle_radius = 0.0f;
51
52     _nextEngine = 0;
53
54     // Map /controls/flight/elevator to the approach elevator control.  This
55     // should probably be settable, but there are very few aircraft
56     // who trim their approaches using things other than elevator.
57     _airplane.setElevatorControl(parseAxis("/controls/flight/elevator-trim"));
58
59     // FIXME: read seed from somewhere?
60     int seed = 0;
61     _turb = new Turbulence(10, seed);
62 }
63
64 FGFDM::~FGFDM()
65 {
66     int i;
67     for(i=0; i<_axes.size(); i++) {
68         AxisRec* a = (AxisRec*)_axes.get(i);
69         delete[] a->name;
70         delete a;
71     }
72     for(i=0; i<_thrusters.size(); i++) {
73         EngRec* er = (EngRec*)_thrusters.get(i);
74         delete[] er->prefix;
75         delete er->eng;
76         delete er;
77     }
78     for(i=0; i<_weights.size(); i++) {
79         WeightRec* wr = (WeightRec*)_weights.get(i);
80         delete[] wr->prop;
81         delete wr;
82     }
83     for(i=0; i<_controlProps.size(); i++)
84         delete (PropOut*)_controlProps.get(i);
85     delete _turb;
86 }
87
88 void FGFDM::iterate(float dt)
89 {
90     getExternalInput(dt);
91     _airplane.iterate(dt);
92
93     // Do fuel stuff (FIXME: should stash SGPropertyNode objects here)
94     char buf[256];
95     for(int i=0; i<_airplane.numThrusters(); i++) {
96         Thruster* t = _airplane.getThruster(i);
97
98         sprintf(buf, "/engines/engine[%d]/out-of-fuel", i);
99         t->setFuelState(!fgGetBool(buf));
100
101         sprintf(buf, "/engines/engine[%d]/fuel-consumed-lbs", i);
102         double consumed = fgGetDouble(buf) + dt * KG2LBS * t->getFuelFlow();
103         fgSetDouble(buf, consumed);
104     }
105     for(int i=0; i<_airplane.numTanks(); i++) {
106         sprintf(buf, "/consumables/fuel/tank[%d]/level-lbs", i);
107         _airplane.setFuel(i, LBS2KG * fgGetFloat(buf));
108     } 
109     _airplane.calcFuelWeights();
110     
111     setOutputProperties(dt);
112 }
113
114 Airplane* FGFDM::getAirplane()
115 {
116     return &_airplane;
117 }
118
119 void FGFDM::init()
120 {
121     // Allows the user to start with something other than full fuel
122     _airplane.setFuelFraction(fgGetFloat("/sim/fuel-fraction", 1));
123
124     // Read out the resulting fuel state
125     char buf[256];
126     for(int i=0; i<_airplane.numTanks(); i++) {
127         sprintf(buf, "/consumables/fuel/tank[%d]/level-lbs", i);
128         fgSetDouble(buf, _airplane.getFuel(i) * KG2LBS);
129
130         double density = _airplane.getFuelDensity(i);
131         sprintf(buf, "/consumables/fuel/tank[%d]/density-ppg", i);
132         fgSetDouble(buf, density * (KG2LBS/CM2GALS));
133
134         sprintf(buf, "/consumables/fuel/tank[%d]/level-gal_us", i);
135         fgSetDouble(buf, _airplane.getFuel(i) * CM2GALS / density);
136
137         sprintf(buf, "/consumables/fuel/tank[%d]/capacity-gal_us", i);
138         fgSetDouble(buf, CM2GALS * _airplane.getTankCapacity(i)/density);
139     }    
140
141     // This has a nasty habit of being false at startup.  That's not
142     // good.
143     fgSetBool("/controls/gear/gear-down", true);
144
145     _airplane.getModel()->setTurbulence(_turb);
146 }
147
148 // Not the worlds safest parser.  But it's short & sweet.
149 void FGFDM::startElement(const char* name, const XMLAttributes &atts)
150 {
151     XMLAttributes* a = (XMLAttributes*)&atts;
152     float v[3];
153     char buf[64];
154
155     if(eq(name, "airplane")) {
156         _airplane.setWeight(attrf(a, "mass") * LBS2KG);
157     } else if(eq(name, "approach")) {
158         float spd = attrf(a, "speed") * KTS2MPS;
159         float alt = attrf(a, "alt", 0) * FT2M;
160         float aoa = attrf(a, "aoa", 0) * DEG2RAD;
161         _airplane.setApproach(spd, alt, aoa, attrf(a, "fuel", 0.2));
162         _cruiseCurr = false;
163     } else if(eq(name, "cruise")) {
164         float spd = attrf(a, "speed") * KTS2MPS;
165         float alt = attrf(a, "alt") * FT2M;
166         _airplane.setCruise(spd, alt, attrf(a, "fuel", 0.5));
167         _cruiseCurr = true;
168     } else if(eq(name, "solve-weight")) {
169         int idx = attri(a, "idx");
170         float wgt = attrf(a, "weight") * LBS2KG;
171         _airplane.addSolutionWeight(!_cruiseCurr, idx, wgt);
172     } else if(eq(name, "cockpit")) {
173         v[0] = attrf(a, "x");
174         v[1] = attrf(a, "y");
175         v[2] = attrf(a, "z");
176         _airplane.setPilotPos(v);
177     } else if(eq(name, "rotor")) {
178         _airplane.getModel()->getRotorgear()->addRotor(parseRotor(a, name));
179     } else if(eq(name, "rotorgear")) {
180         Rotorgear* r = _airplane.getModel()->getRotorgear();
181         _currObj = r;
182         #define p(x) if (a->hasAttribute(#x)) r->setParameter((char *)#x,attrf(a,#x) );
183         #define p2(x,y) if (a->hasAttribute(y)) r->setParameter((char *)#x,attrf(a,y) );
184         p2(max_power_engine,"max-power-engine")
185         p2(engine_prop_factor,"engine-prop-factor")
186         p(yasimdragfactor)
187         p(yasimliftfactor)
188         p2(max_power_rotor_brake,"max-power-rotor-brake")
189         p2(rotorgear_friction,"rotorgear-friction")
190         p2(engine_accel_limit,"engine-accel-limit")
191         #undef p
192         #undef p2
193         r->setInUse();
194     } else if(eq(name, "wing")) {
195         _airplane.setWing(parseWing(a, name));
196     } else if(eq(name, "hstab")) {
197         _airplane.setTail(parseWing(a, name));
198     } else if(eq(name, "vstab") || eq(name, "mstab")) {
199         _airplane.addVStab(parseWing(a, name));
200     } else if(eq(name, "piston-engine")) {
201         parsePistonEngine(a);
202     } else if(eq(name, "turbine-engine")) {
203         parseTurbineEngine(a);
204     } else if(eq(name, "propeller")) {
205         parsePropeller(a);
206     } else if(eq(name, "thruster")) {
207         SimpleJet* j = new SimpleJet();
208         _currObj = j;
209         v[0] = attrf(a, "x"); v[1] = attrf(a, "y"); v[2] = attrf(a, "z");
210         j->setPosition(v);
211         _airplane.addThruster(j, 0, v);
212         v[0] = attrf(a, "vx"); v[1] = attrf(a, "vy"); v[2] = attrf(a, "vz");
213         j->setDirection(v);
214         j->setThrust(attrf(a, "thrust") * LBS2N);
215     } else if(eq(name, "jet")) {
216         Jet* j = new Jet();
217         _currObj = j;
218         v[0] = attrf(a, "x");
219         v[1] = attrf(a, "y");
220         v[2] = attrf(a, "z");
221         float mass = attrf(a, "mass") * LBS2KG;
222         j->setMaxThrust(attrf(a, "thrust") * LBS2N,
223                         attrf(a, "afterburner", 0) * LBS2N);
224         j->setVectorAngle(attrf(a, "rotate", 0) * DEG2RAD);
225         j->setReverseThrust(attrf(a, "reverse", 0.2));
226
227         float n1min = attrf(a, "n1-idle", 55);
228         float n1max = attrf(a, "n1-max", 102);
229         float n2min = attrf(a, "n2-idle", 73);
230         float n2max = attrf(a, "n2-max", 103);
231         j->setRPMs(n1min, n1max, n2min, n2max);
232
233         j->setTSFC(attrf(a, "tsfc", 0.8));
234         if(a->hasAttribute("egt"))  j->setEGT(attrf(a, "egt"));
235         if(a->hasAttribute("epr"))  j->setEPR(attrf(a, "epr"));
236         if(a->hasAttribute("exhaust-speed"))
237             j->setVMax(attrf(a, "exhaust-speed") * KTS2MPS);
238         if(a->hasAttribute("spool-time"))
239             j->setSpooling(attrf(a, "spool-time"));
240         
241         j->setPosition(v);
242         _airplane.addThruster(j, mass, v);
243         sprintf(buf, "/engines/engine[%d]", _nextEngine++);
244         EngRec* er = new EngRec();
245         er->eng = j;
246         er->prefix = dup(buf);
247         _thrusters.add(er);
248     } else if(eq(name, "gear")) {
249         Gear* g = new Gear();
250         _currObj = g;
251         v[0] = attrf(a, "x");
252         v[1] = attrf(a, "y");
253         v[2] = attrf(a, "z");
254         g->setPosition(v);
255         float nrm = Math::mag3(v);
256         if (_vehicle_radius < nrm)
257             _vehicle_radius = nrm;
258         if(a->hasAttribute("upx")) {
259             v[0] = attrf(a, "upx");
260             v[1] = attrf(a, "upy");
261             v[2] = attrf(a, "upz");
262             Math::unit3(v, v);
263         } else {
264             v[0] = 0;
265             v[1] = 0;
266             v[2] = 1;
267         }
268         for(int i=0; i<3; i++)
269             v[i] *= attrf(a, "compression", 1);
270         g->setCompression(v);
271         g->setBrake(attrf(a, "skid", 0));
272         g->setStaticFriction(attrf(a, "sfric", 0.8));
273         g->setDynamicFriction(attrf(a, "dfric", 0.7));
274         g->setSpring(attrf(a, "spring", 1));
275         g->setDamping(attrf(a, "damp", 1));
276         _airplane.addGear(g);
277     } else if(eq(name, "hook")) {
278         Hook* h = new Hook();
279         _currObj = h;
280         v[0] = attrf(a, "x");
281         v[1] = attrf(a, "y");
282         v[2] = attrf(a, "z");
283         h->setPosition(v);
284         float length = attrf(a, "length", 1.0);
285         h->setLength(length);
286         float nrm = length+Math::mag3(v);
287         if (_vehicle_radius < nrm)
288             _vehicle_radius = nrm;
289         h->setDownAngle(attrf(a, "down-angle", 70) * DEG2RAD);
290         h->setUpAngle(attrf(a, "up-angle", 0) * DEG2RAD);
291         _airplane.addHook(h);
292     } else if(eq(name, "launchbar")) {
293         Launchbar* l = new Launchbar();
294         _currObj = l;
295         v[0] = attrf(a, "x");
296         v[1] = attrf(a, "y");
297         v[2] = attrf(a, "z");
298         l->setLaunchbarMount(v);
299         v[0] = attrf(a, "holdback-x", v[0]);
300         v[1] = attrf(a, "holdback-y", v[1]);
301         v[2] = attrf(a, "holdback-z", v[2]);
302         l->setHoldbackMount(v);
303         float length = attrf(a, "length", 1.0);
304         l->setLength(length);
305         l->setDownAngle(attrf(a, "down-angle", 45) * DEG2RAD);
306         l->setUpAngle(attrf(a, "up-angle", -45) * DEG2RAD);
307         l->setHoldbackLength(attrf(a, "holdback-length", 2.0));
308         _airplane.addLaunchbar(l);
309     } else if(eq(name, "fuselage")) {
310         float b[3];
311         v[0] = attrf(a, "ax");
312         v[1] = attrf(a, "ay");
313         v[2] = attrf(a, "az");
314         b[0] = attrf(a, "bx");
315         b[1] = attrf(a, "by");
316         b[2] = attrf(a, "bz");
317         float taper = attrf(a, "taper", 1);
318         float mid = attrf(a, "midpoint", 0.5);
319         _airplane.addFuselage(v, b, attrf(a, "width"), taper, mid);
320     } else if(eq(name, "tank")) {
321         v[0] = attrf(a, "x");
322         v[1] = attrf(a, "y");
323         v[2] = attrf(a, "z");
324         float density = 6.0; // gasoline, in lbs/gal
325         if(a->hasAttribute("jet")) density = 6.72; 
326         density *= LBS2KG*CM2GALS;
327         _airplane.addTank(v, attrf(a, "capacity") * LBS2KG, density);
328     } else if(eq(name, "ballast")) {
329         v[0] = attrf(a, "x");
330         v[1] = attrf(a, "y");
331         v[2] = attrf(a, "z");
332         _airplane.addBallast(v, attrf(a, "mass") * LBS2KG);
333     } else if(eq(name, "weight")) {
334         parseWeight(a);
335     } else if(eq(name, "stall")) {
336         Wing* w = (Wing*)_currObj;
337         w->setStall(attrf(a, "aoa") * DEG2RAD);
338         w->setStallWidth(attrf(a, "width", 2) * DEG2RAD);
339         w->setStallPeak(attrf(a, "peak", 1.5));
340     } else if(eq(name, "flap0")) {
341         ((Wing*)_currObj)->setFlap0(attrf(a, "start"), attrf(a, "end"),
342                                     attrf(a, "lift"), attrf(a, "drag"));
343     } else if(eq(name, "flap1")) {
344         ((Wing*)_currObj)->setFlap1(attrf(a, "start"), attrf(a, "end"),
345                                     attrf(a, "lift"), attrf(a, "drag"));
346     } else if(eq(name, "slat")) {
347         ((Wing*)_currObj)->setSlat(attrf(a, "start"), attrf(a, "end"),
348                                    attrf(a, "aoa"), attrf(a, "drag"));
349     } else if(eq(name, "spoiler")) {
350         ((Wing*)_currObj)->setSpoiler(attrf(a, "start"), attrf(a, "end"),
351                                       attrf(a, "lift"), attrf(a, "drag"));
352     /* } else if(eq(name, "collective")) {
353         ((Rotor*)_currObj)->setcollective(attrf(a, "min"), attrf(a, "max"));
354     } else if(eq(name, "cyclic")) {
355         ((Rotor*)_currObj)->setcyclic(attrf(a, "ail"), attrf(a, "ele"));
356     */                               
357     } else if(eq(name, "actionpt")) {
358         v[0] = attrf(a, "x");
359         v[1] = attrf(a, "y");
360         v[2] = attrf(a, "z");
361         ((Thruster*)_currObj)->setPosition(v);
362     } else if(eq(name, "dir")) {
363         v[0] = attrf(a, "x");
364         v[1] = attrf(a, "y");
365         v[2] = attrf(a, "z");
366         ((Thruster*)_currObj)->setDirection(v);
367     } else if(eq(name, "control-setting")) {
368         // A cruise or approach control setting
369         const char* axis = a->getValue("axis");
370         float value = attrf(a, "value", 0);
371         if(_cruiseCurr)
372             _airplane.addCruiseControl(parseAxis(axis), value);
373         else
374             _airplane.addApproachControl(parseAxis(axis), value);
375     } else if(eq(name, "control-input")) {
376
377         // A mapping of input property to a control
378         int axis = parseAxis(a->getValue("axis"));
379         int control = parseOutput(a->getValue("control"));
380         int opt = 0;
381         opt |= a->hasAttribute("split") ? ControlMap::OPT_SPLIT : 0;
382         opt |= a->hasAttribute("invert") ? ControlMap::OPT_INVERT : 0;
383         opt |= a->hasAttribute("square") ? ControlMap::OPT_SQUARE : 0;
384         
385         ControlMap* cm = _airplane.getControlMap();
386         if(a->hasAttribute("src0")) {
387                            cm->addMapping(axis, control, _currObj, opt,
388                            attrf(a, "src0"), attrf(a, "src1"), 
389                            attrf(a, "dst0"), attrf(a, "dst1"));
390         } else {
391             cm->addMapping(axis, control, _currObj, opt);
392         }
393     } else if(eq(name, "control-output")) {
394         // A property output for a control on the current object
395         ControlMap* cm = _airplane.getControlMap();
396         int type = parseOutput(a->getValue("control"));
397         int handle = cm->getOutputHandle(_currObj, type);
398
399         PropOut* p = new PropOut();
400         p->prop = fgGetNode(a->getValue("prop"), true);
401         p->handle = handle;
402         p->type = type;
403         p->left = !(a->hasAttribute("side") &&
404                         eq("right", a->getValue("side")));
405         p->min = attrf(a, "min", cm->rangeMin(type));
406         p->max = attrf(a, "max", cm->rangeMax(type));
407         _controlProps.add(p);
408
409     } else if(eq(name, "control-speed")) {
410         ControlMap* cm = _airplane.getControlMap();
411         int type = parseOutput(a->getValue("control"));
412         int handle = cm->getOutputHandle(_currObj, type);
413         float time = attrf(a, "transition-time", 0);
414         
415         cm->setTransitionTime(handle, time);
416     } else {
417         SG_LOG(SG_FLIGHT,SG_ALERT,"Unexpected tag '"
418                << name << "' found in YASim aircraft description");
419         exit(1);
420     }
421 }
422
423 void FGFDM::getExternalInput(float dt)
424 {
425     char buf[256];
426
427     _turb->setMagnitude(fgGetFloat("/environment/turbulence/magnitude-norm"));
428     _turb->update(dt, fgGetFloat("/environment/turbulence/rate-hz"));
429
430     // The control axes
431     ControlMap* cm = _airplane.getControlMap();
432     cm->reset();
433     int i;
434     for(i=0; i<_axes.size(); i++) {
435         AxisRec* a = (AxisRec*)_axes.get(i);
436         float val = fgGetFloat(a->name, 0);
437         cm->setInput(a->handle, val);
438     }
439     cm->applyControls(dt);
440
441     // Weights
442     for(i=0; i<_weights.size(); i++) {
443         WeightRec* wr = (WeightRec*)_weights.get(i);
444         _airplane.setWeight(wr->handle, LBS2KG * fgGetFloat(wr->prop));
445     }
446
447     for(i=0; i<_thrusters.size(); i++) {
448         EngRec* er = (EngRec*)_thrusters.get(i);
449         Thruster* t = er->eng;
450
451         if(t->getPropEngine()) {
452             PropEngine* p = t->getPropEngine();
453             sprintf(buf, "%s/rpm", er->prefix);
454             p->setOmega(fgGetFloat(buf, 500) * RPM2RAD);
455         }
456     }
457 }
458
459 // Linearly "seeks" a property by the specified fraction of the way to
460 // the target value.  Used to emulate "slowly changing" output values.
461 static void moveprop(SGPropertyNode* node, const char* prop,
462                     float target, float frac)
463 {
464     float val = node->getFloatValue(prop);
465     if(frac > 1) frac = 1;
466     if(frac < 0) frac = 0;
467     val += (target - val) * frac;
468     node->setFloatValue(prop, val);
469 }
470
471 void FGFDM::setOutputProperties(float dt)
472 {
473     // char buf[256];
474     int i;
475
476     float grossWgt = _airplane.getModel()->getBody()->getTotalMass() * KG2LBS;
477     fgSetFloat("/yasim/gross-weight-lbs", grossWgt);
478
479     ControlMap* cm = _airplane.getControlMap();
480     for(i=0; i<_controlProps.size(); i++) {
481         PropOut* p = (PropOut*)_controlProps.get(i);
482         float val = (p->left
483                      ? cm->getOutput(p->handle)
484                      : cm->getOutputR(p->handle));
485         float rmin = cm->rangeMin(p->type);
486         float rmax = cm->rangeMax(p->type);
487         float frac = (val - rmin) / (rmax - rmin);
488         val = frac*(p->max - p->min) + p->min;
489         p->prop->setFloatValue(val);
490     }
491
492     for(i=0; i<_airplane.getRotorgear()->getNumRotors(); i++) {
493         Rotor*r=(Rotor*)_airplane.getRotorgear()->getRotor(i);
494         int j = 0;
495         float f;
496         char b[256];
497         while((j = r->getValueforFGSet(j, b, &f)))
498             if(b[0]) fgSetFloat(b,f);
499         j=0;
500         while((j = _airplane.getRotorgear()->getValueforFGSet(j, b, &f)))
501             if(b[0]) fgSetFloat(b,f);
502         for(j=0; j < r->numRotorparts(); j+=r->numRotorparts()>>2) {
503             Rotorpart* s = (Rotorpart*)r->getRotorpart(j);
504             char *b;
505             int k;
506             for(k=0; k<2; k++) {
507                 b=s->getAlphaoutput(k);
508                 if(b[0]) fgSetFloat(b, s->getAlpha(k));
509             }
510         }
511     }
512
513     float fuelDensity = _airplane.getFuelDensity(0); // HACK
514     for(i=0; i<_thrusters.size(); i++) {
515         EngRec* er = (EngRec*)_thrusters.get(i);
516         Thruster* t = er->eng;
517         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
518
519         // Set: running, cranking, prop-thrust, max-hp, power-pct
520         node->setBoolValue("running", t->isRunning());
521         node->setBoolValue("cranking", t->isCranking());
522
523         float tmp[3];
524         t->getThrust(tmp);
525         float lbs = Math::mag3(tmp) * (KG2LBS/9.8);
526         node->setFloatValue("prop-thrust", lbs); // Deprecated name
527         node->setFloatValue("thrust-lbs", lbs);
528         node->setFloatValue("fuel-flow-gph",
529                             (t->getFuelFlow()/fuelDensity) * 3600 * CM2GALS);
530
531         if(t->getPropEngine()) {
532             PropEngine* p = t->getPropEngine();
533             node->setFloatValue("rpm", p->getOmega() * (1/RPM2RAD));
534             node->setFloatValue("torque-ftlb",
535                                 p->getEngine()->getTorque() * NM2FTLB);
536         
537             if(p->getEngine()->isPistonEngine()) {
538                 PistonEngine* pe = p->getEngine()->isPistonEngine();
539                 node->setFloatValue("mp-osi", pe->getMP() * (1/INHG2PA));
540                 node->setFloatValue("mp-inhg", pe->getMP() * (1/INHG2PA));
541                 node->setFloatValue("egt-degf",
542                                     pe->getEGT() * K2DEGF + K2DEGFOFFSET);
543                 node->setFloatValue("oil-temperature-degf",
544                                     pe->getOilTemp() * K2DEGF + K2DEGFOFFSET);
545                 node->setFloatValue("boost-gauge-inhg",
546                                     pe->getBoost() * (1/INHG2PA));
547             } else if(p->getEngine()->isTurbineEngine()) {
548                 TurbineEngine* te = p->getEngine()->isTurbineEngine();
549                 node->setFloatValue("n2", te->getN2());
550             }
551         }
552
553         if(t->getJet()) {
554             Jet* j = t->getJet();
555             node->setFloatValue("n1", j->getN1());
556             node->setFloatValue("n2", j->getN2());
557             node->setFloatValue("epr", j->getEPR());
558             node->setFloatValue("egt-degf",
559                                 j->getEGT() * K2DEGF + K2DEGFOFFSET);
560
561             // These are "unmodeled" values that are still needed for
562             // many cockpits.  Tie them all to the N1 speed, but
563             // normalize the numbers to the range [0:1] so the
564             // cockpit code can scale them to the right values.
565             float pnorm = j->getPerfNorm();
566             moveprop(node, "oilp-norm", pnorm, dt/3); // 3s seek time
567             moveprop(node, "oilt-norm", pnorm, dt/30); // 30s 
568             moveprop(node, "itt-norm", pnorm, dt/1); // 1s
569         }
570     }
571 }
572
573 Wing* FGFDM::parseWing(XMLAttributes* a, const char* type)
574 {
575     Wing* w = new Wing();
576
577     float defDihed = 0;
578     if(eq(type, "vstab"))
579         defDihed = 90;
580     else
581         w->setMirror(true);
582
583     float pos[3];
584     pos[0] = attrf(a, "x");
585     pos[1] = attrf(a, "y");
586     pos[2] = attrf(a, "z");
587     w->setBase(pos);
588
589     w->setLength(attrf(a, "length"));
590     w->setChord(attrf(a, "chord"));
591     w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
592     w->setTaper(attrf(a, "taper", 1));
593     w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
594     w->setCamber(attrf(a, "camber", 0));
595
596     // These come in with positive indicating positive AoA, but the
597     // internals expect a rotation about the left-pointing Y axis, so
598     // invert the sign.
599     w->setIncidence(attrf(a, "incidence", 0) * DEG2RAD * -1);
600     w->setTwist(attrf(a, "twist", 0) * DEG2RAD * -1);
601
602     // The 70% is a magic number that sorta kinda seems to match known
603     // throttle settings to approach speed.
604     w->setInducedDrag(0.7*attrf(a, "idrag", 1));
605
606     float effect = attrf(a, "effectiveness", 1);
607     w->setDragScale(w->getDragScale()*effect);
608
609     _currObj = w;
610     return w;
611 }
612
613 Rotor* FGFDM::parseRotor(XMLAttributes* a, const char* type)
614 {
615     Rotor* w = new Rotor();
616
617     // float defDihed = 0;
618
619     float pos[3];
620     pos[0] = attrf(a, "x");
621     pos[1] = attrf(a, "y");
622     pos[2] = attrf(a, "z");
623     w->setBase(pos);
624
625     float normal[3];
626     normal[0] = attrf(a, "nx");
627     normal[1] = attrf(a, "ny");
628     normal[2] = attrf(a, "nz");
629     w->setNormal(normal);
630
631     float forward[3];
632     forward[0] = attrf(a, "fx");
633     forward[1] = attrf(a, "fy");
634     forward[2] = attrf(a, "fz");
635     w->setForward(forward);
636
637     w->setMaxCyclicail(attrf(a, "maxcyclicail", 7.6));
638     w->setMaxCyclicele(attrf(a, "maxcyclicele", 4.94));
639     w->setMinCyclicail(attrf(a, "mincyclicail", -7.6));
640     w->setMinCyclicele(attrf(a, "mincyclicele", -4.94));
641     w->setMaxCollective(attrf(a, "maxcollective", 15.8));
642     w->setMinCollective(attrf(a, "mincollective", -0.2));
643     w->setDiameter(attrf(a, "diameter", 10.2));
644     w->setWeightPerBlade(attrf(a, "weightperblade", 44));
645     w->setNumberOfBlades(attrf(a, "numblades", 4));
646     w->setRelBladeCenter(attrf(a, "relbladecenter", 0.7));
647     w->setDynamic(attrf(a, "dynamic", 0.7));
648     w->setDelta3(attrf(a, "delta3", 0));
649     w->setDelta(attrf(a, "delta", 0));
650     w->setTranslift(attrf(a, "translift", 0.05));
651     w->setC2(attrf(a, "dragfactor", 1));
652     w->setStepspersecond(attrf(a, "stepspersecond", 120));
653     w->setRPM(attrf(a, "rpm", 424));
654     w->setRelLenHinge(attrf(a, "rellenflaphinge", 0.07));
655     w->setAlpha0((attrf(a, "flap0", -5))*YASIM_PI/180);
656     w->setAlphamin((attrf(a, "flapmin", -15))/180*YASIM_PI);
657     w->setAlphamax((attrf(a, "flapmax",  15))*YASIM_PI/180);
658     w->setAlpha0factor(attrf(a, "flap0factor", 1));
659     w->setTeeterdamp(attrf(a,"teeterdamp",.0001));
660     w->setMaxteeterdamp(attrf(a,"maxteeterdamp",1000));
661     w->setRelLenTeeterHinge(attrf(a,"rellenteeterhinge",0.01));
662     void setAlphamin(float f);
663     void setAlphamax(float f);
664     void setAlpha0factor(float f);
665
666     if(attrb(a,"ccw"))
667        w->setCcw(1); 
668     
669     if(a->hasAttribute("name"))
670        w->setName(a->getValue("name") );
671     if(a->hasAttribute("alphaout0"))
672        w->setAlphaoutput(0,a->getValue("alphaout0") );
673     if(a->hasAttribute("alphaout1"))  w->setAlphaoutput(1,a->getValue("alphaout1") );
674     if(a->hasAttribute("alphaout2"))  w->setAlphaoutput(2,a->getValue("alphaout2") );
675     if(a->hasAttribute("alphaout3"))  w->setAlphaoutput(3,a->getValue("alphaout3") );
676     if(a->hasAttribute("coneout"))  w->setAlphaoutput(4,a->getValue("coneout") );
677     if(a->hasAttribute("yawout"))   w->setAlphaoutput(5,a->getValue("yawout") );
678     if(a->hasAttribute("rollout"))  w->setAlphaoutput(6,a->getValue("rollout") );
679
680     w->setPitchA(attrf(a, "pitch-a", 10));
681     w->setPitchB(attrf(a, "pitch-b", 10));
682     w->setForceAtPitchA(attrf(a, "forceatpitch-a", 3000));
683     w->setPowerAtPitch0(attrf(a, "poweratpitch-0", 300));
684     w->setPowerAtPitchB(attrf(a, "poweratpitch-b", 3000));
685     if(attrb(a,"notorque"))
686        w->setNotorque(1); 
687
688 #define p(x) if (a->hasAttribute(#x)) w->setParameter((char *)#x,attrf(a,#x) );
689 #define p2(x,y) if (a->hasAttribute(y)) w->setParameter((char *)#x,attrf(a,y) );
690     p2(translift_ve,"translift-ve")
691     p2(translift_maxfactor,"translift-maxfactor")
692     p2(ground_effect_constant,"ground-effect-constant")
693     p2(vortex_state_lift_factor,"vortex-state-lift-factor")
694     p2(vortex_state_c1,"vortex-state-c1")
695     p2(vortex_state_c2,"vortex-state-c2")
696     p2(vortex_state_c3,"vortex-state_c3")
697     p2(vortex_state_e1,"vortex-state-e1")
698     p2(vortex_state_e2,"vortex-state-e2")
699     p(twist)
700     p2(number_of_segments,"number-of-segments")
701     p2(number_of_parts,"number-of-parts")
702     p2(rel_len_where_incidence_is_measured,"rel-len-where-incidence-is-measured")
703     p(chord)
704     p(taper)
705     p2(airfoil_incidence_no_lift,"airfoil-incidence-no-lift")
706     p2(rel_len_blade_start,"rel-len-blade-start")
707     p2(incidence_stall_zero_speed,"incidence-stall-zero-speed")
708     p2(incidence_stall_half_sonic_speed,"incidence-stall-half-sonic-speed")
709     p2(lift_factor_stall,"lift-factor-stall")
710     p2(stall_change_over,"stall-change-over")
711     p2(drag_factor_stall,"drag-factor-stall")
712     p2(airfoil_lift_coefficient,"airfoil-lift-coefficient")
713     p2(airfoil_drag_coefficient0,"airfoil-drag-coefficient0")
714     p2(airfoil_drag_coefficient1,"airfoil-drag-coefficient1")
715     p2(cyclic_factor,"cyclic-factor")
716     p2(rotor_correction_factor,"rotor-correction-factor")
717 #undef p
718 #undef p2
719     _currObj = w;
720     return w;
721 }
722
723 void FGFDM::parsePistonEngine(XMLAttributes* a)
724 {
725     float engP = attrf(a, "eng-power") * HP2W;
726     float engS = attrf(a, "eng-rpm") * RPM2RAD;
727
728     PistonEngine* eng = new PistonEngine(engP, engS);
729
730     if(a->hasAttribute("displacement"))
731         eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
732
733     if(a->hasAttribute("compression"))
734         eng->setCompression(attrf(a, "compression"));        
735
736     if(a->hasAttribute("turbo-mul")) {
737         float mul = attrf(a, "turbo-mul");
738         float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
739         eng->setTurboParams(mul, mp);
740         eng->setTurboLag(attrf(a, "turbo-lag", 2));
741     }
742
743     if(a->hasAttribute("supercharger"))
744         eng->setSupercharger(attrb(a, "supercharger"));
745
746     ((PropEngine*)_currObj)->setEngine(eng);
747 }
748
749 void FGFDM::parseTurbineEngine(XMLAttributes* a)
750 {
751     float power = attrf(a, "eng-power") * HP2W;
752     float omega = attrf(a, "eng-rpm") * RPM2RAD;
753     float alt = attrf(a, "alt") * FT2M;
754     float flatRating = attrf(a, "flat-rating") * HP2W;
755     TurbineEngine* eng = new TurbineEngine(power, omega, alt, flatRating);
756
757     if(a->hasAttribute("n2-low-idle"))
758         eng->setN2Range(attrf(a, "n2-low-idle"), attrf(a, "n2-high-idle"),
759                         attrf(a, "n2-max"));
760
761     // Nasty units conversion: lbs/hr per hp -> kg/s per watt
762     if(a->hasAttribute("bsfc"))
763         eng->setFuelConsumption(attrf(a, "bsfc") * (LBS2KG/(3600*HP2W)));
764
765     ((PropEngine*)_currObj)->setEngine(eng);
766 }
767
768 void FGFDM::parsePropeller(XMLAttributes* a)
769 {
770     // Legacy Handling for the old engines syntax:
771     PistonEngine* eng = 0;
772     if(a->hasAttribute("eng-power")) {
773         SG_LOG(SG_FLIGHT,SG_ALERT, "WARNING: "
774                << "Legacy engine definition in YASim configuration file.  "
775                << "Please fix.");
776         float engP = attrf(a, "eng-power") * HP2W;
777         float engS = attrf(a, "eng-rpm") * RPM2RAD;
778         eng = new PistonEngine(engP, engS);
779         if(a->hasAttribute("displacement"))
780             eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
781         if(a->hasAttribute("compression"))
782             eng->setCompression(attrf(a, "compression"));        
783         if(a->hasAttribute("turbo-mul")) {
784             float mul = attrf(a, "turbo-mul");
785             float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
786             eng->setTurboParams(mul, mp);
787         }
788     }
789
790     // Now parse the actual propeller definition:
791     float cg[3];
792     cg[0] = attrf(a, "x");
793     cg[1] = attrf(a, "y");
794     cg[2] = attrf(a, "z");
795     float mass = attrf(a, "mass") * LBS2KG;
796     float moment = attrf(a, "moment");
797     float radius = attrf(a, "radius");
798     float speed = attrf(a, "cruise-speed") * KTS2MPS;
799     float omega = attrf(a, "cruise-rpm") * RPM2RAD;
800     float power = attrf(a, "cruise-power") * HP2W;
801     float rho = Atmosphere::getStdDensity(attrf(a, "cruise-alt") * FT2M);
802
803     Propeller* prop = new Propeller(radius, speed, omega, rho, power);
804     PropEngine* thruster = new PropEngine(prop, eng, moment);
805     _airplane.addThruster(thruster, mass, cg);
806
807     // Set the stops (fine = minimum pitch, coarse = maximum pitch)
808     float fine_stop = attrf(a, "fine-stop", 0.25f);
809     float coarse_stop = attrf(a, "coarse-stop", 4.0f);
810     prop->setStops(fine_stop, coarse_stop);
811
812     if(a->hasAttribute("takeoff-power")) {
813         float power0 = attrf(a, "takeoff-power") * HP2W;
814         float omega0 = attrf(a, "takeoff-rpm") * RPM2RAD;
815         prop->setTakeoff(omega0, power0);
816     }
817
818     if(a->hasAttribute("max-rpm")) {
819         float max = attrf(a, "max-rpm") * RPM2RAD;
820         float min = attrf(a, "min-rpm") * RPM2RAD;
821         thruster->setVariableProp(min, max);
822     }
823
824     if(attrb(a, "contra"))
825         thruster->setContraPair(true);
826
827     if(a->hasAttribute("manual-pitch")) {
828         prop->setManualPitch();
829     }
830
831     thruster->setGearRatio(attrf(a, "gear-ratio", 1));
832
833     char buf[64];
834     sprintf(buf, "/engines/engine[%d]", _nextEngine++);
835     EngRec* er = new EngRec();
836     er->eng = thruster;
837     er->prefix = dup(buf);
838     _thrusters.add(er);
839
840     _currObj = thruster;
841 }
842
843 // Turns a string axis name into an integer for use by the
844 // ControlMap.  Creates a new axis if this one hasn't been defined
845 // yet.
846 int FGFDM::parseAxis(const char* name)
847 {
848     int i;
849     for(i=0; i<_axes.size(); i++) {
850         AxisRec* a = (AxisRec*)_axes.get(i);
851         if(eq(a->name, name))
852             return a->handle;
853     }
854
855     // Not there, make a new one.
856     AxisRec* a = new AxisRec();
857     a->name = dup(name);
858     fgGetNode( a->name, true ); // make sure the property name exists
859     a->handle = _airplane.getControlMap()->newInput();
860     _axes.add(a);
861     return a->handle;
862 }
863
864 int FGFDM::parseOutput(const char* name)
865 {
866     if(eq(name, "THROTTLE"))  return ControlMap::THROTTLE;
867     if(eq(name, "MIXTURE"))   return ControlMap::MIXTURE;
868     if(eq(name, "CONDLEVER")) return ControlMap::CONDLEVER;
869     if(eq(name, "STARTER"))   return ControlMap::STARTER;
870     if(eq(name, "MAGNETOS"))  return ControlMap::MAGNETOS;
871     if(eq(name, "ADVANCE"))   return ControlMap::ADVANCE;
872     if(eq(name, "REHEAT"))    return ControlMap::REHEAT;
873     if(eq(name, "BOOST"))     return ControlMap::BOOST;
874     if(eq(name, "VECTOR"))    return ControlMap::VECTOR;
875     if(eq(name, "PROP"))      return ControlMap::PROP;
876     if(eq(name, "BRAKE"))     return ControlMap::BRAKE;
877     if(eq(name, "STEER"))     return ControlMap::STEER;
878     if(eq(name, "EXTEND"))    return ControlMap::EXTEND;
879     if(eq(name, "HEXTEND"))   return ControlMap::HEXTEND;
880     if(eq(name, "LEXTEND"))   return ControlMap::LEXTEND;
881     if(eq(name, "INCIDENCE")) return ControlMap::INCIDENCE;
882     if(eq(name, "FLAP0"))     return ControlMap::FLAP0;
883     if(eq(name, "FLAP1"))     return ControlMap::FLAP1;
884     if(eq(name, "SLAT"))      return ControlMap::SLAT;
885     if(eq(name, "SPOILER"))   return ControlMap::SPOILER;
886     if(eq(name, "CASTERING")) return ControlMap::CASTERING;
887     if(eq(name, "PROPPITCH")) return ControlMap::PROPPITCH;
888     if(eq(name, "PROPFEATHER")) return ControlMap::PROPFEATHER;
889     if(eq(name, "COLLECTIVE")) return ControlMap::COLLECTIVE;
890     if(eq(name, "CYCLICAIL")) return ControlMap::CYCLICAIL;
891     if(eq(name, "CYCLICELE")) return ControlMap::CYCLICELE;
892     if(eq(name, "ROTORGEARENGINEON")) return ControlMap::ROTORENGINEON;
893     if(eq(name, "ROTORBRAKE")) return ControlMap::ROTORBRAKE;
894     if(eq(name, "REVERSE_THRUST")) return ControlMap::REVERSE_THRUST;
895     if(eq(name, "WASTEGATE")) return ControlMap::WASTEGATE;
896     SG_LOG(SG_FLIGHT,SG_ALERT,"Unrecognized control type '"
897            << name << "' in YASim aircraft description.");
898     exit(1);
899
900 }
901
902 void FGFDM::parseWeight(XMLAttributes* a)
903 {
904     WeightRec* wr = new WeightRec();
905
906     float v[3];
907     v[0] = attrf(a, "x");
908     v[1] = attrf(a, "y");
909     v[2] = attrf(a, "z");
910
911     wr->prop = dup(a->getValue("mass-prop"));
912     wr->size = attrf(a, "size", 0);
913     wr->handle = _airplane.addWeight(v, wr->size);
914
915     _weights.add(wr);
916 }
917
918 bool FGFDM::eq(const char* a, const char* b)
919 {
920     // Figure it out for yourself. :)
921     while(*a && *b && *a == *b) { a++; b++; }
922     return !(*a || *b);
923 }
924
925 char* FGFDM::dup(const char* s)
926 {
927     int len=0;
928     while(s[len++]);
929     char* s2 = new char[len+1];
930     char* p = s2;
931     while((*p++ = *s++));
932     s2[len] = 0;
933     return s2;
934 }
935
936 int FGFDM::attri(XMLAttributes* atts, char* attr)
937 {
938     if(!atts->hasAttribute(attr)) {
939         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
940                "' in YASim aircraft description");
941         exit(1);
942     }
943     return attri(atts, attr, 0);
944 }
945
946 int FGFDM::attri(XMLAttributes* atts, char* attr, int def)
947 {
948     const char* val = atts->getValue(attr);
949     if(val == 0) return def;
950     else         return atol(val);
951 }
952
953 float FGFDM::attrf(XMLAttributes* atts, char* attr)
954 {
955     if(!atts->hasAttribute(attr)) {
956         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
957                "' in YASim aircraft description");
958         exit(1);
959     }
960     return attrf(atts, attr, 0);
961 }
962
963 float FGFDM::attrf(XMLAttributes* atts, char* attr, float def)
964 {
965     const char* val = atts->getValue(attr);
966     if(val == 0) return def;
967     else         return (float)atof(val);    
968 }
969
970 // ACK: the dreaded ambiguous string boolean.  Remind me to shoot Maik
971 // when I have a chance. :).  Unless you have a parser that can check
972 // symbol constants (we don't), this kind of coding is just a Bad
973 // Idea.  This implementation, for example, silently returns a boolean
974 // falsehood for values of "1", "yes", "True", and "TRUE".  Which is
975 // especially annoying preexisting boolean attributes in the same
976 // parser want to see "1" and will choke on a "true"...
977 //
978 // Unfortunately, this usage creeped into existing configuration files
979 // while I wasn't active, and it's going to be hard to remove.  Issue
980 // a warning to nag people into changing their ways for now...
981 bool FGFDM::attrb(XMLAttributes* atts, char* attr)
982 {
983     const char* val = atts->getValue(attr);
984     if(val == 0) return false;
985
986     if(eq(val,"true")) {
987         SG_LOG(SG_FLIGHT, SG_ALERT, "Warning: " <<
988                "deprecated 'true' boolean in YASim configuration file.  " <<
989                "Use numeric booleans (attribute=\"1\") instead");
990         return true;
991     }
992     return attri(atts, attr, 0) ? true : false;
993 }
994
995 }; // namespace yasim