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