]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/FGFDM.cpp
Patch from Maik adds user-settable scaling constants for per-axis fuselage drag and...
[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         float cx = attrf(a, "cx", 1);
320         float cy = attrf(a, "cy", 1);
321         float cz = attrf(a, "cz", 1);
322         float idrag = attrf(a, "idrag", 1);
323         _airplane.addFuselage(v, b, attrf(a, "width"), taper, mid, 
324             cx, cy, cz, idrag);
325     } else if(eq(name, "tank")) {
326         v[0] = attrf(a, "x");
327         v[1] = attrf(a, "y");
328         v[2] = attrf(a, "z");
329         float density = 6.0; // gasoline, in lbs/gal
330         if(a->hasAttribute("jet")) density = 6.72; 
331         density *= LBS2KG*CM2GALS;
332         _airplane.addTank(v, attrf(a, "capacity") * LBS2KG, density);
333     } else if(eq(name, "ballast")) {
334         v[0] = attrf(a, "x");
335         v[1] = attrf(a, "y");
336         v[2] = attrf(a, "z");
337         _airplane.addBallast(v, attrf(a, "mass") * LBS2KG);
338     } else if(eq(name, "weight")) {
339         parseWeight(a);
340     } else if(eq(name, "stall")) {
341         Wing* w = (Wing*)_currObj;
342         w->setStall(attrf(a, "aoa") * DEG2RAD);
343         w->setStallWidth(attrf(a, "width", 2) * DEG2RAD);
344         w->setStallPeak(attrf(a, "peak", 1.5));
345     } else if(eq(name, "flap0")) {
346         ((Wing*)_currObj)->setFlap0(attrf(a, "start"), attrf(a, "end"),
347                                     attrf(a, "lift"), attrf(a, "drag"));
348     } else if(eq(name, "flap1")) {
349         ((Wing*)_currObj)->setFlap1(attrf(a, "start"), attrf(a, "end"),
350                                     attrf(a, "lift"), attrf(a, "drag"));
351     } else if(eq(name, "slat")) {
352         ((Wing*)_currObj)->setSlat(attrf(a, "start"), attrf(a, "end"),
353                                    attrf(a, "aoa"), attrf(a, "drag"));
354     } else if(eq(name, "spoiler")) {
355         ((Wing*)_currObj)->setSpoiler(attrf(a, "start"), attrf(a, "end"),
356                                       attrf(a, "lift"), attrf(a, "drag"));
357     /* } else if(eq(name, "collective")) {
358         ((Rotor*)_currObj)->setcollective(attrf(a, "min"), attrf(a, "max"));
359     } else if(eq(name, "cyclic")) {
360         ((Rotor*)_currObj)->setcyclic(attrf(a, "ail"), attrf(a, "ele"));
361     */                               
362     } else if(eq(name, "actionpt")) {
363         v[0] = attrf(a, "x");
364         v[1] = attrf(a, "y");
365         v[2] = attrf(a, "z");
366         ((Thruster*)_currObj)->setPosition(v);
367     } else if(eq(name, "dir")) {
368         v[0] = attrf(a, "x");
369         v[1] = attrf(a, "y");
370         v[2] = attrf(a, "z");
371         ((Thruster*)_currObj)->setDirection(v);
372     } else if(eq(name, "control-setting")) {
373         // A cruise or approach control setting
374         const char* axis = a->getValue("axis");
375         float value = attrf(a, "value", 0);
376         if(_cruiseCurr)
377             _airplane.addCruiseControl(parseAxis(axis), value);
378         else
379             _airplane.addApproachControl(parseAxis(axis), value);
380     } else if(eq(name, "control-input")) {
381
382         // A mapping of input property to a control
383         int axis = parseAxis(a->getValue("axis"));
384         int control = parseOutput(a->getValue("control"));
385         int opt = 0;
386         opt |= a->hasAttribute("split") ? ControlMap::OPT_SPLIT : 0;
387         opt |= a->hasAttribute("invert") ? ControlMap::OPT_INVERT : 0;
388         opt |= a->hasAttribute("square") ? ControlMap::OPT_SQUARE : 0;
389         
390         ControlMap* cm = _airplane.getControlMap();
391         if(a->hasAttribute("src0")) {
392                            cm->addMapping(axis, control, _currObj, opt,
393                            attrf(a, "src0"), attrf(a, "src1"), 
394                            attrf(a, "dst0"), attrf(a, "dst1"));
395         } else {
396             cm->addMapping(axis, control, _currObj, opt);
397         }
398     } else if(eq(name, "control-output")) {
399         // A property output for a control on the current object
400         ControlMap* cm = _airplane.getControlMap();
401         int type = parseOutput(a->getValue("control"));
402         int handle = cm->getOutputHandle(_currObj, type);
403
404         PropOut* p = new PropOut();
405         p->prop = fgGetNode(a->getValue("prop"), true);
406         p->handle = handle;
407         p->type = type;
408         p->left = !(a->hasAttribute("side") &&
409                         eq("right", a->getValue("side")));
410         p->min = attrf(a, "min", cm->rangeMin(type));
411         p->max = attrf(a, "max", cm->rangeMax(type));
412         _controlProps.add(p);
413
414     } else if(eq(name, "control-speed")) {
415         ControlMap* cm = _airplane.getControlMap();
416         int type = parseOutput(a->getValue("control"));
417         int handle = cm->getOutputHandle(_currObj, type);
418         float time = attrf(a, "transition-time", 0);
419         
420         cm->setTransitionTime(handle, time);
421     } else {
422         SG_LOG(SG_FLIGHT,SG_ALERT,"Unexpected tag '"
423                << name << "' found in YASim aircraft description");
424         exit(1);
425     }
426 }
427
428 void FGFDM::getExternalInput(float dt)
429 {
430     char buf[256];
431
432     _turb->setMagnitude(fgGetFloat("/environment/turbulence/magnitude-norm"));
433     _turb->update(dt, fgGetFloat("/environment/turbulence/rate-hz"));
434
435     // The control axes
436     ControlMap* cm = _airplane.getControlMap();
437     cm->reset();
438     int i;
439     for(i=0; i<_axes.size(); i++) {
440         AxisRec* a = (AxisRec*)_axes.get(i);
441         float val = fgGetFloat(a->name, 0);
442         cm->setInput(a->handle, val);
443     }
444     cm->applyControls(dt);
445
446     // Weights
447     for(i=0; i<_weights.size(); i++) {
448         WeightRec* wr = (WeightRec*)_weights.get(i);
449         _airplane.setWeight(wr->handle, LBS2KG * fgGetFloat(wr->prop));
450     }
451
452     for(i=0; i<_thrusters.size(); i++) {
453         EngRec* er = (EngRec*)_thrusters.get(i);
454         Thruster* t = er->eng;
455
456         if(t->getPropEngine()) {
457             PropEngine* p = t->getPropEngine();
458             sprintf(buf, "%s/rpm", er->prefix);
459             p->setOmega(fgGetFloat(buf, 500) * RPM2RAD);
460         }
461     }
462 }
463
464 // Linearly "seeks" a property by the specified fraction of the way to
465 // the target value.  Used to emulate "slowly changing" output values.
466 static void moveprop(SGPropertyNode* node, const char* prop,
467                     float target, float frac)
468 {
469     float val = node->getFloatValue(prop);
470     if(frac > 1) frac = 1;
471     if(frac < 0) frac = 0;
472     val += (target - val) * frac;
473     node->setFloatValue(prop, val);
474 }
475
476 void FGFDM::setOutputProperties(float dt)
477 {
478     // char buf[256];
479     int i;
480
481     float grossWgt = _airplane.getModel()->getBody()->getTotalMass() * KG2LBS;
482     fgSetFloat("/yasim/gross-weight-lbs", grossWgt);
483
484     ControlMap* cm = _airplane.getControlMap();
485     for(i=0; i<_controlProps.size(); i++) {
486         PropOut* p = (PropOut*)_controlProps.get(i);
487         float val = (p->left
488                      ? cm->getOutput(p->handle)
489                      : cm->getOutputR(p->handle));
490         float rmin = cm->rangeMin(p->type);
491         float rmax = cm->rangeMax(p->type);
492         float frac = (val - rmin) / (rmax - rmin);
493         val = frac*(p->max - p->min) + p->min;
494         p->prop->setFloatValue(val);
495     }
496
497     for(i=0; i<_airplane.getRotorgear()->getNumRotors(); i++) {
498         Rotor*r=(Rotor*)_airplane.getRotorgear()->getRotor(i);
499         int j = 0;
500         float f;
501         char b[256];
502         while((j = r->getValueforFGSet(j, b, &f)))
503             if(b[0]) fgSetFloat(b,f);
504         j=0;
505         while((j = _airplane.getRotorgear()->getValueforFGSet(j, b, &f)))
506             if(b[0]) fgSetFloat(b,f);
507         for(j=0; j < r->numRotorparts(); j+=r->numRotorparts()>>2) {
508             Rotorpart* s = (Rotorpart*)r->getRotorpart(j);
509             char *b;
510             int k;
511             for(k=0; k<2; k++) {
512                 b=s->getAlphaoutput(k);
513                 if(b[0]) fgSetFloat(b, s->getAlpha(k));
514             }
515         }
516     }
517
518     float fuelDensity = _airplane.getFuelDensity(0); // HACK
519     for(i=0; i<_thrusters.size(); i++) {
520         EngRec* er = (EngRec*)_thrusters.get(i);
521         Thruster* t = er->eng;
522         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
523
524         // Set: running, cranking, prop-thrust, max-hp, power-pct
525         node->setBoolValue("running", t->isRunning());
526         node->setBoolValue("cranking", t->isCranking());
527
528         float tmp[3];
529         t->getThrust(tmp);
530         float lbs = Math::mag3(tmp) * (KG2LBS/9.8);
531         node->setFloatValue("prop-thrust", lbs); // Deprecated name
532         node->setFloatValue("thrust-lbs", lbs);
533         node->setFloatValue("fuel-flow-gph",
534                             (t->getFuelFlow()/fuelDensity) * 3600 * CM2GALS);
535
536         if(t->getPropEngine()) {
537             PropEngine* p = t->getPropEngine();
538             node->setFloatValue("rpm", p->getOmega() * (1/RPM2RAD));
539             node->setFloatValue("torque-ftlb",
540                                 p->getEngine()->getTorque() * NM2FTLB);
541         
542             if(p->getEngine()->isPistonEngine()) {
543                 PistonEngine* pe = p->getEngine()->isPistonEngine();
544                 node->setFloatValue("mp-osi", pe->getMP() * (1/INHG2PA));
545                 node->setFloatValue("mp-inhg", pe->getMP() * (1/INHG2PA));
546                 node->setFloatValue("egt-degf",
547                                     pe->getEGT() * K2DEGF + K2DEGFOFFSET);
548                 node->setFloatValue("oil-temperature-degf",
549                                     pe->getOilTemp() * K2DEGF + K2DEGFOFFSET);
550                 node->setFloatValue("boost-gauge-inhg",
551                                     pe->getBoost() * (1/INHG2PA));
552             } else if(p->getEngine()->isTurbineEngine()) {
553                 TurbineEngine* te = p->getEngine()->isTurbineEngine();
554                 node->setFloatValue("n2", te->getN2());
555             }
556         }
557
558         if(t->getJet()) {
559             Jet* j = t->getJet();
560             node->setFloatValue("n1", j->getN1());
561             node->setFloatValue("n2", j->getN2());
562             node->setFloatValue("epr", j->getEPR());
563             node->setFloatValue("egt-degf",
564                                 j->getEGT() * K2DEGF + K2DEGFOFFSET);
565
566             // These are "unmodeled" values that are still needed for
567             // many cockpits.  Tie them all to the N1 speed, but
568             // normalize the numbers to the range [0:1] so the
569             // cockpit code can scale them to the right values.
570             float pnorm = j->getPerfNorm();
571             moveprop(node, "oilp-norm", pnorm, dt/3); // 3s seek time
572             moveprop(node, "oilt-norm", pnorm, dt/30); // 30s 
573             moveprop(node, "itt-norm", pnorm, dt/1); // 1s
574         }
575     }
576 }
577
578 Wing* FGFDM::parseWing(XMLAttributes* a, const char* type)
579 {
580     Wing* w = new Wing();
581
582     float defDihed = 0;
583     if(eq(type, "vstab"))
584         defDihed = 90;
585     else
586         w->setMirror(true);
587
588     float pos[3];
589     pos[0] = attrf(a, "x");
590     pos[1] = attrf(a, "y");
591     pos[2] = attrf(a, "z");
592     w->setBase(pos);
593
594     w->setLength(attrf(a, "length"));
595     w->setChord(attrf(a, "chord"));
596     w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
597     w->setTaper(attrf(a, "taper", 1));
598     w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
599     w->setCamber(attrf(a, "camber", 0));
600
601     // These come in with positive indicating positive AoA, but the
602     // internals expect a rotation about the left-pointing Y axis, so
603     // invert the sign.
604     w->setIncidence(attrf(a, "incidence", 0) * DEG2RAD * -1);
605     w->setTwist(attrf(a, "twist", 0) * DEG2RAD * -1);
606
607     // The 70% is a magic number that sorta kinda seems to match known
608     // throttle settings to approach speed.
609     w->setInducedDrag(0.7*attrf(a, "idrag", 1));
610
611     float effect = attrf(a, "effectiveness", 1);
612     w->setDragScale(w->getDragScale()*effect);
613
614     _currObj = w;
615     return w;
616 }
617
618 Rotor* FGFDM::parseRotor(XMLAttributes* a, const char* type)
619 {
620     Rotor* w = new Rotor();
621
622     // float defDihed = 0;
623
624     float pos[3];
625     pos[0] = attrf(a, "x");
626     pos[1] = attrf(a, "y");
627     pos[2] = attrf(a, "z");
628     w->setBase(pos);
629
630     float normal[3];
631     normal[0] = attrf(a, "nx");
632     normal[1] = attrf(a, "ny");
633     normal[2] = attrf(a, "nz");
634     w->setNormal(normal);
635
636     float forward[3];
637     forward[0] = attrf(a, "fx");
638     forward[1] = attrf(a, "fy");
639     forward[2] = attrf(a, "fz");
640     w->setForward(forward);
641
642     w->setMaxCyclicail(attrf(a, "maxcyclicail", 7.6));
643     w->setMaxCyclicele(attrf(a, "maxcyclicele", 4.94));
644     w->setMinCyclicail(attrf(a, "mincyclicail", -7.6));
645     w->setMinCyclicele(attrf(a, "mincyclicele", -4.94));
646     w->setMaxCollective(attrf(a, "maxcollective", 15.8));
647     w->setMinCollective(attrf(a, "mincollective", -0.2));
648     w->setDiameter(attrf(a, "diameter", 10.2));
649     w->setWeightPerBlade(attrf(a, "weightperblade", 44));
650     w->setNumberOfBlades(attrf(a, "numblades", 4));
651     w->setRelBladeCenter(attrf(a, "relbladecenter", 0.7));
652     w->setDynamic(attrf(a, "dynamic", 0.7));
653     w->setDelta3(attrf(a, "delta3", 0));
654     w->setDelta(attrf(a, "delta", 0));
655     w->setTranslift(attrf(a, "translift", 0.05));
656     w->setC2(attrf(a, "dragfactor", 1));
657     w->setStepspersecond(attrf(a, "stepspersecond", 120));
658     w->setRPM(attrf(a, "rpm", 424));
659     w->setRelLenHinge(attrf(a, "rellenflaphinge", 0.07));
660     w->setAlpha0((attrf(a, "flap0", -5))*YASIM_PI/180);
661     w->setAlphamin((attrf(a, "flapmin", -15))/180*YASIM_PI);
662     w->setAlphamax((attrf(a, "flapmax",  15))*YASIM_PI/180);
663     w->setAlpha0factor(attrf(a, "flap0factor", 1));
664     w->setTeeterdamp(attrf(a,"teeterdamp",.0001));
665     w->setMaxteeterdamp(attrf(a,"maxteeterdamp",1000));
666     w->setRelLenTeeterHinge(attrf(a,"rellenteeterhinge",0.01));
667     void setAlphamin(float f);
668     void setAlphamax(float f);
669     void setAlpha0factor(float f);
670
671     if(attrb(a,"ccw"))
672        w->setCcw(1); 
673     
674     if(a->hasAttribute("name"))
675        w->setName(a->getValue("name") );
676     if(a->hasAttribute("alphaout0"))
677        w->setAlphaoutput(0,a->getValue("alphaout0") );
678     if(a->hasAttribute("alphaout1"))  w->setAlphaoutput(1,a->getValue("alphaout1") );
679     if(a->hasAttribute("alphaout2"))  w->setAlphaoutput(2,a->getValue("alphaout2") );
680     if(a->hasAttribute("alphaout3"))  w->setAlphaoutput(3,a->getValue("alphaout3") );
681     if(a->hasAttribute("coneout"))  w->setAlphaoutput(4,a->getValue("coneout") );
682     if(a->hasAttribute("yawout"))   w->setAlphaoutput(5,a->getValue("yawout") );
683     if(a->hasAttribute("rollout"))  w->setAlphaoutput(6,a->getValue("rollout") );
684
685     w->setPitchA(attrf(a, "pitch-a", 10));
686     w->setPitchB(attrf(a, "pitch-b", 10));
687     w->setForceAtPitchA(attrf(a, "forceatpitch-a", 3000));
688     w->setPowerAtPitch0(attrf(a, "poweratpitch-0", 300));
689     w->setPowerAtPitchB(attrf(a, "poweratpitch-b", 3000));
690     if(attrb(a,"notorque"))
691        w->setNotorque(1); 
692
693 #define p(x) if (a->hasAttribute(#x)) w->setParameter((char *)#x,attrf(a,#x) );
694 #define p2(x,y) if (a->hasAttribute(y)) w->setParameter((char *)#x,attrf(a,y) );
695     p2(translift_ve,"translift-ve")
696     p2(translift_maxfactor,"translift-maxfactor")
697     p2(ground_effect_constant,"ground-effect-constant")
698     p2(vortex_state_lift_factor,"vortex-state-lift-factor")
699     p2(vortex_state_c1,"vortex-state-c1")
700     p2(vortex_state_c2,"vortex-state-c2")
701     p2(vortex_state_c3,"vortex-state_c3")
702     p2(vortex_state_e1,"vortex-state-e1")
703     p2(vortex_state_e2,"vortex-state-e2")
704     p(twist)
705     p2(number_of_segments,"number-of-segments")
706     p2(number_of_parts,"number-of-parts")
707     p2(rel_len_where_incidence_is_measured,"rel-len-where-incidence-is-measured")
708     p(chord)
709     p(taper)
710     p2(airfoil_incidence_no_lift,"airfoil-incidence-no-lift")
711     p2(rel_len_blade_start,"rel-len-blade-start")
712     p2(incidence_stall_zero_speed,"incidence-stall-zero-speed")
713     p2(incidence_stall_half_sonic_speed,"incidence-stall-half-sonic-speed")
714     p2(lift_factor_stall,"lift-factor-stall")
715     p2(stall_change_over,"stall-change-over")
716     p2(drag_factor_stall,"drag-factor-stall")
717     p2(airfoil_lift_coefficient,"airfoil-lift-coefficient")
718     p2(airfoil_drag_coefficient0,"airfoil-drag-coefficient0")
719     p2(airfoil_drag_coefficient1,"airfoil-drag-coefficient1")
720     p2(cyclic_factor,"cyclic-factor")
721     p2(rotor_correction_factor,"rotor-correction-factor")
722 #undef p
723 #undef p2
724     _currObj = w;
725     return w;
726 }
727
728 void FGFDM::parsePistonEngine(XMLAttributes* a)
729 {
730     float engP = attrf(a, "eng-power") * HP2W;
731     float engS = attrf(a, "eng-rpm") * RPM2RAD;
732
733     PistonEngine* eng = new PistonEngine(engP, engS);
734
735     if(a->hasAttribute("displacement"))
736         eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
737
738     if(a->hasAttribute("compression"))
739         eng->setCompression(attrf(a, "compression"));        
740
741     if(a->hasAttribute("turbo-mul")) {
742         float mul = attrf(a, "turbo-mul");
743         float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
744         eng->setTurboParams(mul, mp);
745         eng->setTurboLag(attrf(a, "turbo-lag", 2));
746     }
747
748     if(a->hasAttribute("supercharger"))
749         eng->setSupercharger(attrb(a, "supercharger"));
750
751     ((PropEngine*)_currObj)->setEngine(eng);
752 }
753
754 void FGFDM::parseTurbineEngine(XMLAttributes* a)
755 {
756     float power = attrf(a, "eng-power") * HP2W;
757     float omega = attrf(a, "eng-rpm") * RPM2RAD;
758     float alt = attrf(a, "alt") * FT2M;
759     float flatRating = attrf(a, "flat-rating") * HP2W;
760     TurbineEngine* eng = new TurbineEngine(power, omega, alt, flatRating);
761
762     if(a->hasAttribute("n2-low-idle"))
763         eng->setN2Range(attrf(a, "n2-low-idle"), attrf(a, "n2-high-idle"),
764                         attrf(a, "n2-max"));
765
766     // Nasty units conversion: lbs/hr per hp -> kg/s per watt
767     if(a->hasAttribute("bsfc"))
768         eng->setFuelConsumption(attrf(a, "bsfc") * (LBS2KG/(3600*HP2W)));
769
770     ((PropEngine*)_currObj)->setEngine(eng);
771 }
772
773 void FGFDM::parsePropeller(XMLAttributes* a)
774 {
775     // Legacy Handling for the old engines syntax:
776     PistonEngine* eng = 0;
777     if(a->hasAttribute("eng-power")) {
778         SG_LOG(SG_FLIGHT,SG_ALERT, "WARNING: "
779                << "Legacy engine definition in YASim configuration file.  "
780                << "Please fix.");
781         float engP = attrf(a, "eng-power") * HP2W;
782         float engS = attrf(a, "eng-rpm") * RPM2RAD;
783         eng = new PistonEngine(engP, engS);
784         if(a->hasAttribute("displacement"))
785             eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
786         if(a->hasAttribute("compression"))
787             eng->setCompression(attrf(a, "compression"));        
788         if(a->hasAttribute("turbo-mul")) {
789             float mul = attrf(a, "turbo-mul");
790             float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
791             eng->setTurboParams(mul, mp);
792         }
793     }
794
795     // Now parse the actual propeller definition:
796     float cg[3];
797     cg[0] = attrf(a, "x");
798     cg[1] = attrf(a, "y");
799     cg[2] = attrf(a, "z");
800     float mass = attrf(a, "mass") * LBS2KG;
801     float moment = attrf(a, "moment");
802     float radius = attrf(a, "radius");
803     float speed = attrf(a, "cruise-speed") * KTS2MPS;
804     float omega = attrf(a, "cruise-rpm") * RPM2RAD;
805     float power = attrf(a, "cruise-power") * HP2W;
806     float rho = Atmosphere::getStdDensity(attrf(a, "cruise-alt") * FT2M);
807
808     Propeller* prop = new Propeller(radius, speed, omega, rho, power);
809     PropEngine* thruster = new PropEngine(prop, eng, moment);
810     _airplane.addThruster(thruster, mass, cg);
811
812     // Set the stops (fine = minimum pitch, coarse = maximum pitch)
813     float fine_stop = attrf(a, "fine-stop", 0.25f);
814     float coarse_stop = attrf(a, "coarse-stop", 4.0f);
815     prop->setStops(fine_stop, coarse_stop);
816
817     if(a->hasAttribute("takeoff-power")) {
818         float power0 = attrf(a, "takeoff-power") * HP2W;
819         float omega0 = attrf(a, "takeoff-rpm") * RPM2RAD;
820         prop->setTakeoff(omega0, power0);
821     }
822
823     if(a->hasAttribute("max-rpm")) {
824         float max = attrf(a, "max-rpm") * RPM2RAD;
825         float min = attrf(a, "min-rpm") * RPM2RAD;
826         thruster->setVariableProp(min, max);
827     }
828
829     if(attrb(a, "contra"))
830         thruster->setContraPair(true);
831
832     if(a->hasAttribute("manual-pitch")) {
833         prop->setManualPitch();
834     }
835
836     thruster->setGearRatio(attrf(a, "gear-ratio", 1));
837
838     char buf[64];
839     sprintf(buf, "/engines/engine[%d]", _nextEngine++);
840     EngRec* er = new EngRec();
841     er->eng = thruster;
842     er->prefix = dup(buf);
843     _thrusters.add(er);
844
845     _currObj = thruster;
846 }
847
848 // Turns a string axis name into an integer for use by the
849 // ControlMap.  Creates a new axis if this one hasn't been defined
850 // yet.
851 int FGFDM::parseAxis(const char* name)
852 {
853     int i;
854     for(i=0; i<_axes.size(); i++) {
855         AxisRec* a = (AxisRec*)_axes.get(i);
856         if(eq(a->name, name))
857             return a->handle;
858     }
859
860     // Not there, make a new one.
861     AxisRec* a = new AxisRec();
862     a->name = dup(name);
863     fgGetNode( a->name, true ); // make sure the property name exists
864     a->handle = _airplane.getControlMap()->newInput();
865     _axes.add(a);
866     return a->handle;
867 }
868
869 int FGFDM::parseOutput(const char* name)
870 {
871     if(eq(name, "THROTTLE"))  return ControlMap::THROTTLE;
872     if(eq(name, "MIXTURE"))   return ControlMap::MIXTURE;
873     if(eq(name, "CONDLEVER")) return ControlMap::CONDLEVER;
874     if(eq(name, "STARTER"))   return ControlMap::STARTER;
875     if(eq(name, "MAGNETOS"))  return ControlMap::MAGNETOS;
876     if(eq(name, "ADVANCE"))   return ControlMap::ADVANCE;
877     if(eq(name, "REHEAT"))    return ControlMap::REHEAT;
878     if(eq(name, "BOOST"))     return ControlMap::BOOST;
879     if(eq(name, "VECTOR"))    return ControlMap::VECTOR;
880     if(eq(name, "PROP"))      return ControlMap::PROP;
881     if(eq(name, "BRAKE"))     return ControlMap::BRAKE;
882     if(eq(name, "STEER"))     return ControlMap::STEER;
883     if(eq(name, "EXTEND"))    return ControlMap::EXTEND;
884     if(eq(name, "HEXTEND"))   return ControlMap::HEXTEND;
885     if(eq(name, "LEXTEND"))   return ControlMap::LEXTEND;
886     if(eq(name, "INCIDENCE")) return ControlMap::INCIDENCE;
887     if(eq(name, "FLAP0"))     return ControlMap::FLAP0;
888     if(eq(name, "FLAP1"))     return ControlMap::FLAP1;
889     if(eq(name, "SLAT"))      return ControlMap::SLAT;
890     if(eq(name, "SPOILER"))   return ControlMap::SPOILER;
891     if(eq(name, "CASTERING")) return ControlMap::CASTERING;
892     if(eq(name, "PROPPITCH")) return ControlMap::PROPPITCH;
893     if(eq(name, "PROPFEATHER")) return ControlMap::PROPFEATHER;
894     if(eq(name, "COLLECTIVE")) return ControlMap::COLLECTIVE;
895     if(eq(name, "CYCLICAIL")) return ControlMap::CYCLICAIL;
896     if(eq(name, "CYCLICELE")) return ControlMap::CYCLICELE;
897     if(eq(name, "ROTORGEARENGINEON")) return ControlMap::ROTORENGINEON;
898     if(eq(name, "ROTORBRAKE")) return ControlMap::ROTORBRAKE;
899     if(eq(name, "REVERSE_THRUST")) return ControlMap::REVERSE_THRUST;
900     if(eq(name, "WASTEGATE")) return ControlMap::WASTEGATE;
901     SG_LOG(SG_FLIGHT,SG_ALERT,"Unrecognized control type '"
902            << name << "' in YASim aircraft description.");
903     exit(1);
904
905 }
906
907 void FGFDM::parseWeight(XMLAttributes* a)
908 {
909     WeightRec* wr = new WeightRec();
910
911     float v[3];
912     v[0] = attrf(a, "x");
913     v[1] = attrf(a, "y");
914     v[2] = attrf(a, "z");
915
916     wr->prop = dup(a->getValue("mass-prop"));
917     wr->size = attrf(a, "size", 0);
918     wr->handle = _airplane.addWeight(v, wr->size);
919
920     _weights.add(wr);
921 }
922
923 bool FGFDM::eq(const char* a, const char* b)
924 {
925     // Figure it out for yourself. :)
926     while(*a && *b && *a == *b) { a++; b++; }
927     return !(*a || *b);
928 }
929
930 char* FGFDM::dup(const char* s)
931 {
932     int len=0;
933     while(s[len++]);
934     char* s2 = new char[len+1];
935     char* p = s2;
936     while((*p++ = *s++));
937     s2[len] = 0;
938     return s2;
939 }
940
941 int FGFDM::attri(XMLAttributes* atts, char* attr)
942 {
943     if(!atts->hasAttribute(attr)) {
944         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
945                "' in YASim aircraft description");
946         exit(1);
947     }
948     return attri(atts, attr, 0);
949 }
950
951 int FGFDM::attri(XMLAttributes* atts, char* attr, int def)
952 {
953     const char* val = atts->getValue(attr);
954     if(val == 0) return def;
955     else         return atol(val);
956 }
957
958 float FGFDM::attrf(XMLAttributes* atts, char* attr)
959 {
960     if(!atts->hasAttribute(attr)) {
961         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
962                "' in YASim aircraft description");
963         exit(1);
964     }
965     return attrf(atts, attr, 0);
966 }
967
968 float FGFDM::attrf(XMLAttributes* atts, char* attr, float def)
969 {
970     const char* val = atts->getValue(attr);
971     if(val == 0) return def;
972     else         return (float)atof(val);    
973 }
974
975 // ACK: the dreaded ambiguous string boolean.  Remind me to shoot Maik
976 // when I have a chance. :).  Unless you have a parser that can check
977 // symbol constants (we don't), this kind of coding is just a Bad
978 // Idea.  This implementation, for example, silently returns a boolean
979 // falsehood for values of "1", "yes", "True", and "TRUE".  Which is
980 // especially annoying preexisting boolean attributes in the same
981 // parser want to see "1" and will choke on a "true"...
982 //
983 // Unfortunately, this usage creeped into existing configuration files
984 // while I wasn't active, and it's going to be hard to remove.  Issue
985 // a warning to nag people into changing their ways for now...
986 bool FGFDM::attrb(XMLAttributes* atts, char* attr)
987 {
988     const char* val = atts->getValue(attr);
989     if(val == 0) return false;
990
991     if(eq(val,"true")) {
992         SG_LOG(SG_FLIGHT, SG_ALERT, "Warning: " <<
993                "deprecated 'true' boolean in YASim configuration file.  " <<
994                "Use numeric booleans (attribute=\"1\") instead");
995         return true;
996     }
997     return attri(atts, attr, 0) ? true : false;
998 }
999
1000 }; // namespace yasim