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