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