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