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