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