]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
7132772aaad2c0b3a974fd18538396831c312107
[flightgear.git] / src / FDM / YASim / Airplane.cpp
1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
3 #include "Gear.hpp"
4 #include "Math.hpp"
5 #include "Glue.hpp"
6 #include "RigidBody.hpp"
7 #include "Surface.hpp"
8 #include "Thruster.hpp"
9
10 #include "Airplane.hpp"
11 namespace yasim {
12
13 Airplane::Airplane()
14 {
15     _emptyWeight = 0;
16     _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
17     _wing = 0;
18     _tail = 0;
19     _ballast = 0;
20     _cruiseP = 0;
21     _cruiseT = 0;
22     _cruiseSpeed = 0;
23     _cruiseWeight = 0;
24     _approachP = 0;
25     _approachT = 0;
26     _approachSpeed = 0;
27     _approachAoA = 0;
28     _approachWeight = 0;
29
30     _dragFactor = 1;
31     _liftRatio = 1;
32     _cruiseAoA = 0;
33     _tailIncidence = 0;
34 }
35
36 Airplane::~Airplane()
37 {
38     int i;
39     for(i=0; i<_fuselages.size(); i++)
40         delete (Fuselage*)_fuselages.get(i);
41     for(i=0; i<_tanks.size(); i++)
42         delete (Tank*)_tanks.get(i);
43     for(i=0; i<_thrusters.size(); i++)
44         delete (ThrustRec*)_thrusters.get(i);
45     for(i=0; i<_gears.size(); i++)
46         delete (GearRec*)_gears.get(i);
47     for(i=0; i<_surfs.size(); i++)
48         delete (Surface*)_surfs.get(i);    
49     for(i=0; i<_contacts.size(); i++)
50         delete[] (float*)_contacts.get(i);
51 }
52
53 void Airplane::iterate(float dt)
54 {
55     _model.iterate();
56
57     // FIXME: Consume fuel
58 }
59
60 ControlMap* Airplane::getControlMap()
61 {
62     return &_controls;
63 }
64
65 Model* Airplane::getModel()
66 {
67     return &_model;
68 }
69
70 void Airplane::getPilotAccel(float* out)
71 {
72     State* s = _model.getState();
73
74     // Gravity
75     Glue::geodUp(s->pos, out);
76     Math::mul3(-9.8, out, out);
77
78     // The regular acceleration
79     float tmp[3];
80     Math::mul3(-1, s->acc, tmp);
81     Math::add3(tmp, out, out);
82
83     // Convert to aircraft coordinates
84     Math::vmul33(s->orient, out, out);
85
86     // FIXME: rotational & centripetal acceleration needed
87 }
88
89 void Airplane::setPilotPos(float* pos)
90 {
91     int i;
92     for(i=0; i<3; i++) _pilotPos[i] = pos[i];
93 }
94
95 void Airplane::getPilotPos(float* out)
96 {
97     int i;
98     for(i=0; i<3; i++) out[i] = _pilotPos[i];
99 }
100
101 int Airplane::numGear()
102 {
103     return _gears.size();
104 }
105
106 Gear* Airplane::getGear(int g)
107 {
108     return ((GearRec*)_gears.get(g))->gear;
109 }
110
111 void Airplane::setGearState(bool down, float dt)
112 {
113     int i;
114     for(i=0; i<_gears.size(); i++) {
115         GearRec* gr = (GearRec*)_gears.get(i);
116         if(gr->time == 0) {
117             // Non-extensible
118             gr->gear->setExtension(1);
119             gr->surf->setXDrag(1);
120             gr->surf->setYDrag(1);
121             gr->surf->setZDrag(1);
122             continue;
123         }
124
125         float diff = dt / gr->time;
126         if(!down) diff = -diff;
127         float ext = gr->gear->getExtension() + diff;
128         if(ext < 0) ext = 0;
129         if(ext > 1) ext = 1;
130
131         gr->gear->setExtension(ext);
132         gr->surf->setXDrag(ext);
133         gr->surf->setYDrag(ext);
134         gr->surf->setZDrag(ext);
135     }
136 }
137
138 void Airplane::setApproach(float speed, float altitude)
139 {
140     // The zero AoA will become a calculated stall AoA in compile()
141     setApproach(speed, altitude, 0);
142 }
143
144 void Airplane::setApproach(float speed, float altitude, float aoa)
145 {
146     _approachSpeed = speed;
147     _approachP = Atmosphere::getStdPressure(altitude);
148     _approachT = Atmosphere::getStdTemperature(altitude);
149     _approachAoA = aoa;
150 }
151  
152 void Airplane::setCruise(float speed, float altitude)
153 {
154     _cruiseSpeed = speed;
155     _cruiseP = Atmosphere::getStdPressure(altitude);
156     _cruiseT = Atmosphere::getStdTemperature(altitude);
157     _cruiseAoA = 0;
158     _tailIncidence = 0;
159 }
160
161 void Airplane::addApproachControl(int control, float val)
162 {
163     Control* c = new Control();
164     c->control = control;
165     c->val = val;
166     _approachControls.add(c);
167 }
168
169 void Airplane::addCruiseControl(int control, float val)
170 {
171     Control* c = new Control();
172     c->control = control;
173     c->val = val;
174     _cruiseControls.add(c);
175 }
176
177 int Airplane::numTanks()
178 {
179     return _tanks.size();
180 }
181
182 float Airplane::getFuel(int tank)
183 {
184     return ((Tank*)_tanks.get(tank))->fill;
185 }
186
187 float Airplane::getFuelDensity(int tank)
188 {
189     return ((Tank*)_tanks.get(tank))->density;
190 }
191
192 void Airplane::setWeight(float weight)
193 {
194     _emptyWeight = weight;
195 }
196
197 void Airplane::setWing(Wing* wing)
198 {
199     _wing = wing;
200 }
201
202 void Airplane::setTail(Wing* tail)
203 {
204     _tail = tail;
205 }
206
207 void Airplane::addVStab(Wing* vstab)
208 {
209     _vstabs.add(vstab);
210 }
211
212 void Airplane::addFuselage(float* front, float* back, float width,
213                            float taper, float mid)
214 {
215     Fuselage* f = new Fuselage();
216     int i;
217     for(i=0; i<3; i++) {
218         f->front[i] = front[i];
219         f->back[i]  = back[i];
220     }
221     f->width = width;
222     f->taper = taper;
223     f->mid = mid;
224     _fuselages.add(f);
225 }
226
227 int Airplane::addTank(float* pos, float cap, float density)
228 {
229     Tank* t = new Tank();
230     int i;
231     for(i=0; i<3; i++) t->pos[i] = pos[i];
232     t->cap = cap;
233     t->fill = cap;
234     t->density = density;
235     t->handle = 0xffffffff;
236     return _tanks.add(t);
237 }
238
239 void Airplane::addGear(Gear* gear, float transitionTime)
240 {
241     GearRec* g = new GearRec();
242     g->gear = gear;
243     g->surf = 0;
244     g->time = transitionTime;
245     _gears.add(g);
246 }
247
248 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
249 {
250     ThrustRec* t = new ThrustRec();
251     t->thruster = thruster;
252     t->mass = mass;
253     int i;
254     for(i=0; i<3; i++) t->cg[i] = cg[i];
255     _thrusters.add(t);
256 }
257
258 void Airplane::addBallast(float* pos, float mass)
259 {
260     _model.getBody()->addMass(mass, pos);
261     _ballast += mass;
262 }
263
264 int Airplane::addWeight(float* pos, float size)
265 {
266     WeightRec* wr = new WeightRec();
267     wr->handle = _model.getBody()->addMass(0, pos);
268
269     wr->surf = new Surface();
270     wr->surf->setPosition(pos);
271     wr->surf->setTotalDrag(size*size);
272     _model.addSurface(wr->surf);
273     _surfs.add(wr->surf);
274
275     return _weights.add(wr);
276 }
277
278 void Airplane::setWeight(int handle, float mass)
279 {
280     WeightRec* wr = (WeightRec*)_weights.get(handle);
281
282     _model.getBody()->setMass(wr->handle, mass);
283
284     // Kill the aerodynamic drag if the mass is exactly zero.  This is
285     // how we simulate droppable stores.
286     if(mass == 0) {
287         wr->surf->setXDrag(0);
288         wr->surf->setYDrag(0);
289         wr->surf->setZDrag(0);
290     } else {
291         wr->surf->setXDrag(1);
292         wr->surf->setYDrag(1);
293         wr->surf->setZDrag(1);
294     }
295 }
296
297 void Airplane::setFuelFraction(float frac)
298 {
299     int i;
300     for(i=0; i<_tanks.size(); i++) {
301         Tank* t = (Tank*)_tanks.get(i);
302         _model.getBody()->setMass(t->handle, t->cap * frac);
303     }
304 }
305
306 float Airplane::getDragCoefficient()
307 {
308     return _dragFactor;
309 }
310
311 float Airplane::getLiftRatio()
312 {
313     return _liftRatio;
314 }
315
316 float Airplane::getCruiseAoA()
317 {
318     return _cruiseAoA;
319 }
320
321 float Airplane::getTailIncidence()
322 {
323     return _tailIncidence;
324 }
325
326 char* Airplane::getFailureMsg()
327 {
328     return _failureMsg;
329 }
330
331 int Airplane::getSolutionIterations()
332 {
333     return _solutionIterations;
334 }
335
336 void Airplane::setupState(float aoa, float speed, State* s)
337 {
338     float cosAoA = Math::cos(aoa);
339     float sinAoA = Math::sin(aoa);
340     s->orient[0] =  cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
341     s->orient[3] =       0; s->orient[4] = 1; s->orient[5] =      0;
342     s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
343
344     s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
345
346     int i;
347     for(i=0; i<3; i++)
348         s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
349
350     // Put us 1m above the origin, or else the gravity computation in
351     // Model goes nuts
352     s->pos[2] = 1;
353 }
354
355 void Airplane::addContactPoint(float* pos)
356 {
357     float* cp = new float[3];
358     cp[0] = pos[0];
359     cp[1] = pos[1];
360     cp[2] = pos[2];
361     _contacts.add(cp);
362 }
363
364 float Airplane::compileWing(Wing* w)
365 {
366     // The tip of the wing is a contact point
367     float tip[3];
368     w->getTip(tip);
369     addContactPoint(tip);
370     if(w->isMirrored()) {
371         tip[1] *= -1;
372         addContactPoint(tip);
373     }
374
375     // Make sure it's initialized.  The surfaces will pop out with
376     // total drag coefficients equal to their areas, which is what we
377     // want.
378     w->compile();
379
380     float wgt = 0;
381     int i;
382     for(i=0; i<w->numSurfaces(); i++) {
383         Surface* s = (Surface*)w->getSurface(i);
384
385         float td = s->getTotalDrag();
386         s->setTotalDrag(td);
387
388         _model.addSurface(s);
389
390         float mass = w->getSurfaceWeight(i);
391         mass = mass * Math::sqrt(mass);
392         float pos[3];
393         s->getPosition(pos);
394         _model.getBody()->addMass(mass, pos);
395         wgt += mass;
396     }
397     return wgt;
398 }
399
400 float Airplane::compileFuselage(Fuselage* f)
401 {
402     // The front and back are contact points
403     addContactPoint(f->front);
404     addContactPoint(f->back);
405
406     float wgt = 0;
407     float fwd[3];
408     Math::sub3(f->front, f->back, fwd);
409     float len = Math::mag3(fwd);
410     float wid = f->width;
411     int segs = (int)Math::ceil(len/wid);
412     float segWgt = len*wid/segs;
413     int j;
414     for(j=0; j<segs; j++) {
415         float frac = (j+0.5) / segs;
416
417         float scale = 1;
418         if(frac < f->mid)
419             scale = f->taper+(1-f->taper) * (frac / f->mid);
420         else
421             scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
422
423         // Where are we?
424         float pos[3];
425         Math::mul3(frac, fwd, pos);
426         Math::add3(f->back, pos, pos);
427
428         // _Mass_ weighting goes as surface area^(3/2)
429         float mass = scale*segWgt * Math::sqrt(scale*segWgt);
430         _model.getBody()->addMass(mass, pos);
431         wgt += mass;
432
433         // Make a Surface too
434         Surface* s = new Surface();
435         s->setPosition(pos);
436         float sideDrag = len/wid;
437         s->setYDrag(sideDrag);
438         s->setZDrag(sideDrag);
439         s->setTotalDrag(scale*segWgt);
440
441         // FIXME: fails for fuselages aligned along the Y axis
442         float o[9];
443         float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
444         Math::unit3(fwd, x);
445         y[0] = 0; y[1] = 1; y[2] = 0;
446         Math::cross3(x, y, z);
447         s->setOrientation(o);
448
449         _model.addSurface(s);
450         _surfs.add(s);
451     }
452     return wgt;
453 }
454
455 // FIXME: should probably add a mass for the gear, too
456 void Airplane::compileGear(GearRec* gr)
457 {
458     Gear* g = gr->gear;
459
460     // Make a Surface object for the aerodynamic behavior
461     Surface* s = new Surface();
462     gr->surf = s;
463
464     // Put the surface at the half-way point on the gear strut, give
465     // it a drag coefficient equal to a square of the same dimension
466     // (gear are really draggy) and make it symmetric.  Assume that
467     // the "length" of the gear is 3x the compression distance
468     float pos[3], cmp[3];
469     g->getCompression(cmp);
470     float length = 3 * Math::mag3(cmp);
471     g->getPosition(pos);
472     Math::mul3(0.5, cmp, cmp);
473     Math::add3(pos, cmp, pos);
474
475     s->setPosition(pos);
476     s->setTotalDrag(length*length);
477
478     _model.addGear(g);
479     _model.addSurface(s);
480     _surfs.add(s);
481 }
482
483 void Airplane::compileContactPoints()
484 {
485     // Figure it will compress by 20cm
486     float comp[3];
487     float DIST = 0.2;
488     comp[0] = 0; comp[1] = 0; comp[2] = DIST;
489
490     // Give it a spring constant such that at full compression it will
491     // hold up 10 times the planes mass.  That's about right.  Yeah.
492     float mass = _model.getBody()->getTotalMass();
493     float spring = (1/DIST) * 9.8 * 10 * mass;
494     float damp = 2 * Math::sqrt(spring * mass);
495
496     int i;
497     for(i=0; i<_contacts.size(); i++) {
498         float *cp = (float*)_contacts.get(i);
499
500         Gear* g = new Gear();
501         g->setPosition(cp);
502         
503         g->setCompression(comp);
504         g->setSpring(spring);
505         g->setDamping(damp);
506         g->setBrake(1);
507
508         // I made these up
509         g->setStaticFriction(0.6);
510         g->setDynamicFriction(0.5);
511
512         _model.addGear(g);
513     }
514 }
515
516 void Airplane::compile()
517 {
518     double ground[3];
519     ground[0] = 0; ground[1] = 0; ground[2] = 1;
520     _model.setGroundPlane(ground, -100000);
521
522     RigidBody* body = _model.getBody();
523     int firstMass = body->numMasses();
524
525     // Generate the point masses for the plane.  Just use unitless
526     // numbers for a first pass, then go back through and rescale to
527     // make the weight right.
528     float aeroWgt = 0;
529
530     // The Wing objects
531     aeroWgt += compileWing(_wing);
532     aeroWgt += compileWing(_tail);
533     int i;
534     for(i=0; i<_vstabs.size(); i++) {
535         aeroWgt += compileWing((Wing*)_vstabs.get(i)); 
536     }
537     
538     // The fuselage(s)
539     for(i=0; i<_fuselages.size(); i++) {
540         aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
541     }
542
543     // Count up the absolute weight we have
544     float nonAeroWgt = _ballast;
545     for(i=0; i<_thrusters.size(); i++)
546         nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
547
548     // Rescale to the specified empty weight
549     float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
550     for(i=firstMass; i<body->numMasses(); i++)
551         body->setMass(i, body->getMass(i)*wscale);
552
553     // Add the thruster masses
554     for(i=0; i<_thrusters.size(); i++) {
555         ThrustRec* t = (ThrustRec*)_thrusters.get(i);
556         body->addMass(t->mass, t->cg);
557     }
558
559     // Add the tanks, empty for now.
560     float totalFuel = 0;
561     for(i=0; i<_tanks.size(); i++) { 
562         Tank* t = (Tank*)_tanks.get(i); 
563         t->handle = body->addMass(0, t->pos);
564         totalFuel += t->cap;
565     }
566     _cruiseWeight = _emptyWeight + totalFuel*0.5;
567     _approachWeight = _emptyWeight + totalFuel*0.2;
568
569     body->recalc();
570
571     // Add surfaces for the landing gear.
572     for(i=0; i<_gears.size(); i++)
573         compileGear((GearRec*)_gears.get(i));
574
575     // The Thruster objects
576     for(i=0; i<_thrusters.size(); i++) {
577         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
578         tr->handle = _model.addThruster(tr->thruster);
579     }
580
581     // Ground effect
582     float gepos[3];
583     float gespan = _wing->getGroundEffect(gepos);
584     _model.setGroundEffect(gepos, gespan, .3);
585
586     solveGear();
587     solve();
588
589     // Do this after solveGear, because it creates "gear" objects that
590     // we don't want to affect.
591     compileContactPoints();
592
593     // Drop the gear (use a really big dt)
594     setGearState(true, 1000000);
595 }
596
597 void Airplane::solveGear()
598 {
599     float cg[3], pos[3];
600     _model.getBody()->getCG(cg);
601
602     // Calculate spring constant weightings for the gear.  Weight by
603     // the inverse of the distance to the c.g. in the XY plane, which
604     // should be correct for most gear arrangements.  Add 50cm of
605     // "buffer" to keep things from blowing up with aircraft with a
606     // single gear very near the c.g. (AV-8, for example).
607     float total = 0;
608     int i;
609     for(i=0; i<_gears.size(); i++) {
610         GearRec* gr = (GearRec*)_gears.get(i);
611         Gear* g = gr->gear;
612         g->getPosition(pos);
613         Math::sub3(cg, pos, pos);
614         gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
615         total += gr->wgt;
616     }
617
618     // Renormalize so they sum to 1
619     for(i=0; i<_gears.size(); i++)
620         ((GearRec*)_gears.get(i))->wgt /= total;
621     
622     // The force at max compression should be sufficient to stop a
623     // plane moving downwards at 3x the approach descent rate.  Assume
624     // a 3 degree approach.
625     float descentRate = 3*_approachSpeed/19.1;
626
627     // Spread the kinetic energy according to the gear weights.  This
628     // will results in an equal compression fraction (not distance) of
629     // each gear.
630     float energy = 0.5*_approachWeight*descentRate*descentRate;
631
632     for(i=0; i<_gears.size(); i++) {
633         GearRec* gr = (GearRec*)_gears.get(i);
634         float e = energy * gr->wgt;
635         float comp[3];
636         gr->gear->getCompression(comp);
637         float len = Math::mag3(comp);
638
639         // Energy in a spring: e = 0.5 * k * len^2
640         float k = 2 * e / (len*len);
641
642         gr->gear->setSpring(k);
643
644         // Critically damped (too damped, too!)
645         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
646
647         // These are pretty generic
648         gr->gear->setStaticFriction(0.8);
649         gr->gear->setDynamicFriction(0.7);
650     }
651 }
652
653 void Airplane::initEngines()
654 {
655     for(int i=0; i<_thrusters.size(); i++) {
656         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
657         tr->thruster->init();
658     }
659 }
660
661 void Airplane::stabilizeThrust()
662 {
663     int i;
664     for(i=0; i<_thrusters.size(); i++)
665         _model.getThruster(i)->stabilize();
666 }
667
668 void Airplane::runCruise()
669 {
670     setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
671     _model.setState(&_cruiseState);
672     _model.setAir(_cruiseP, _cruiseT);
673
674     // The control configuration
675     _controls.reset();
676     int i;
677     for(i=0; i<_cruiseControls.size(); i++) {
678         Control* c = (Control*)_cruiseControls.get(i);
679         _controls.setInput(c->control, c->val);
680     }
681     _controls.applyControls();
682
683     // The local wind
684     float wind[3];
685     Math::mul3(-1, _cruiseState.v, wind);
686     Math::vmul33(_cruiseState.orient, wind, wind);
687  
688     // Gear are up (if they're non-retractable, this is a noop)
689     setGearState(false, 100000);
690     
691     // Cruise is by convention at 50% tank capacity
692     setFuelFraction(0.5);
693    
694     // Set up the thruster parameters and iterate until the thrust
695     // stabilizes.
696     for(i=0; i<_thrusters.size(); i++) {
697         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
698         t->setWind(wind);
699         t->setAir(_cruiseP, _cruiseT);
700     }
701     stabilizeThrust();
702
703     // Precompute thrust in the model, and calculate aerodynamic forces
704     _model.getBody()->reset();
705     _model.initIteration();
706     _model.calcForces(&_cruiseState);
707 }
708
709 void Airplane::runApproach()
710 {
711     setupState(_approachAoA, _approachSpeed, &_approachState);
712     _model.setState(&_approachState);
713     _model.setAir(_approachP, _approachT);
714
715     // The control configuration
716     _controls.reset();
717     int i;
718     for(i=0; i<_approachControls.size(); i++) {
719         Control* c = (Control*)_approachControls.get(i);
720         _controls.setInput(c->control, c->val);
721     }
722     _controls.applyControls();
723
724     // The local wind
725     float wind[3];
726     Math::mul3(-1, _approachState.v, wind);
727     Math::vmul33(_approachState.orient, wind, wind);
728     
729     // Approach is by convention at 20% tank capacity
730     setFuelFraction(0.2);
731
732     // Gear are down
733     setGearState(true, 100000);
734
735     // Run the thrusters until they get to a stable setting.  FIXME:
736     // this is lots of wasted work.
737     for(i=0; i<_thrusters.size(); i++) {
738         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
739         t->setWind(wind);
740         t->setAir(_approachP, _approachT);
741     }
742     stabilizeThrust();
743
744     // Precompute thrust in the model, and calculate aerodynamic forces
745     _model.getBody()->reset();
746     _model.initIteration();
747     _model.calcForces(&_approachState);
748 }
749
750 void Airplane::applyDragFactor(float factor)
751 {
752     float applied = Math::sqrt(factor);
753     _dragFactor *= applied;
754     _wing->setDragScale(_wing->getDragScale() * applied);
755     _tail->setDragScale(_tail->getDragScale() * applied);
756     int i;
757     for(i=0; i<_vstabs.size(); i++) {
758         Wing* w = (Wing*)_vstabs.get(i);
759         w->setDragScale(w->getDragScale() * applied);
760     }
761     for(i=0; i<_surfs.size(); i++) {
762         Surface* s = (Surface*)_surfs.get(i);
763         s->setTotalDrag(s->getTotalDrag() * applied);
764     }
765 }
766
767 void Airplane::applyLiftRatio(float factor)
768 {
769     float applied = Math::sqrt(factor);
770     _liftRatio *= applied;
771     _wing->setLiftRatio(_wing->getLiftRatio() * applied);
772     _tail->setLiftRatio(_tail->getLiftRatio() * applied);
773     int i;
774     for(i=0; i<_vstabs.size(); i++) {
775         Wing* w = (Wing*)_vstabs.get(i);
776         w->setLiftRatio(w->getLiftRatio() * applied);
777     }
778 }
779
780 float Airplane::clamp(float val, float min, float max)
781 {
782     if(val < min) return min;
783     if(val > max) return max;
784     return val;
785 }
786
787 float Airplane::normFactor(float f)
788 {
789     if(f < 0) f = -f;
790     if(f < 1) f = 1/f;
791     return f;
792 }
793
794 void Airplane::solve()
795 {
796     static const float ARCMIN = 0.0002909;
797
798     float tmp[3];
799     _solutionIterations = 0;
800     _failureMsg = 0;
801     while(1) {
802         if(_solutionIterations++ > 10000) {
803             _failureMsg = "Solution failed to converge after 10000 iterations";
804             return;
805         }
806
807         // Run an iteration at cruise, and extract the needed numbers:
808         runCruise();
809
810         _model.getThrust(tmp);
811         float thrust = tmp[0];
812
813         _model.getBody()->getAccel(tmp);
814         float xforce = _cruiseWeight * tmp[0];
815         float clift0 = _cruiseWeight * tmp[2];
816
817         _model.getBody()->getAngularAccel(tmp);
818         float pitch0 = tmp[1];
819
820         // Run an approach iteration, and do likewise
821         runApproach();
822
823         _model.getBody()->getAccel(tmp);
824         float alift = _approachWeight * tmp[2];
825
826         // Modify the cruise AoA a bit to get a derivative
827         _cruiseAoA += ARCMIN;
828         runCruise();
829         _cruiseAoA -= ARCMIN;
830
831         _model.getBody()->getAccel(tmp);
832         float clift1 = _cruiseWeight * tmp[2];
833
834         // Do the same with the tail incidence
835         _tail->setIncidence(_tailIncidence + ARCMIN);
836         runCruise();
837         _tail->setIncidence(_tailIncidence);
838
839         _model.getBody()->getAngularAccel(tmp);
840         float pitch1 = tmp[1];
841
842         // Now calculate:
843         float awgt = 9.8 * _approachWeight;
844
845         float dragFactor = thrust / (thrust-xforce);
846         float liftFactor = awgt / (awgt+alift);
847         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
848         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
849
850         // Sanity:
851         if(dragFactor <= 0) {
852             _failureMsg = "Zero or negative drag adjustment.";
853             return;
854         } else if(liftFactor <= 0) {
855             _failureMsg = "Zero or negative lift adjustment.";
856             return;
857         }
858
859         // And apply:
860         applyDragFactor(dragFactor);
861         applyLiftRatio(liftFactor);
862
863         // DON'T do the following until the above are sane
864         if(normFactor(dragFactor) > 1.1
865            || normFactor(liftFactor) > 1.1)
866         {
867             continue;
868         }
869
870         // OK, now we can adjust the minor variables
871         _cruiseAoA += 0.5*aoaDelta;
872         _tailIncidence += 0.5*tailDelta;
873         
874         _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
875         _tailIncidence = clamp(_tailIncidence, -.174, .174);
876
877         if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
878            aoaDelta < .000017   && tailDelta < .000017)
879         {
880             break;
881         }
882     }
883
884     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
885         _failureMsg = "Drag factor beyond reasonable bounds.";
886         return;
887     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
888         _failureMsg = "Lift ratio beyond reasonable bounds.";
889         return;
890     } else if(Math::abs(_cruiseAoA) >= .174) {
891         _failureMsg = "Cruise AoA > 10 degrees";
892         return;
893     } else if(Math::abs(_tailIncidence) >= .174) {
894         _failureMsg = "Tail incidence > 10 degrees";
895         return;
896     }
897 }
898 }; // namespace yasim