]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
Fix an uninitialized data condition that crept in during the recent
[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     if(_wing) {
681         float gepos[3];
682         float gespan = 0;
683         gespan = _wing->getGroundEffect(gepos);
684         _model.setGroundEffect(gepos, gespan, 0.15f);
685     }
686
687     solveGear();
688     if(_wing && _tail) solve();
689     else solveHelicopter();
690
691     // Do this after solveGear, because it creates "gear" objects that
692     // we don't want to affect.
693     compileContactPoints();
694 }
695
696 void Airplane::solveGear()
697 {
698     float cg[3], pos[3];
699     _model.getBody()->getCG(cg);
700
701     // Calculate spring constant weightings for the gear.  Weight by
702     // the inverse of the distance to the c.g. in the XY plane, which
703     // should be correct for most gear arrangements.  Add 50cm of
704     // "buffer" to keep things from blowing up with aircraft with a
705     // single gear very near the c.g. (AV-8, for example).
706     float total = 0;
707     int i;
708     for(i=0; i<_gears.size(); i++) {
709         GearRec* gr = (GearRec*)_gears.get(i);
710         Gear* g = gr->gear;
711         g->getPosition(pos);
712         Math::sub3(cg, pos, pos);
713         gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
714         total += gr->wgt;
715     }
716
717     // Renormalize so they sum to 1
718     for(i=0; i<_gears.size(); i++)
719         ((GearRec*)_gears.get(i))->wgt /= total;
720     
721     // The force at max compression should be sufficient to stop a
722     // plane moving downwards at 2x the approach descent rate.  Assume
723     // a 3 degree approach.
724     float descentRate = 2.0f*_approachSpeed/19.1f;
725
726     // Spread the kinetic energy according to the gear weights.  This
727     // will results in an equal compression fraction (not distance) of
728     // each gear.
729     float energy = 0.5f*_approachWeight*descentRate*descentRate;
730
731     for(i=0; i<_gears.size(); i++) {
732         GearRec* gr = (GearRec*)_gears.get(i);
733         float e = energy * gr->wgt;
734         float comp[3];
735         gr->gear->getCompression(comp);
736         float len = Math::mag3(comp);
737
738         // Energy in a spring: e = 0.5 * k * len^2
739         float k = 2 * e / (len*len);
740
741         gr->gear->setSpring(k * gr->gear->getSpring());
742
743         // Critically damped (too damped, too!)
744         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt)
745                              * gr->gear->getDamping());
746
747         // These are pretty generic
748         gr->gear->setStaticFriction(0.8f);
749         gr->gear->setDynamicFriction(0.7f);
750     }
751 }
752
753 void Airplane::initEngines()
754 {
755     for(int i=0; i<_thrusters.size(); i++) {
756         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
757         tr->thruster->init();
758     }
759 }
760
761 void Airplane::stabilizeThrust()
762 {
763     int i;
764     for(i=0; i<_thrusters.size(); i++)
765         _model.getThruster(i)->stabilize();
766 }
767
768 void Airplane::setupWeights(bool isApproach)
769 {
770     int i;
771     for(i=0; i<_weights.size(); i++)
772         setWeight(i, 0);
773     for(i=0; i<_solveWeights.size(); i++) {
774         SolveWeight* w = (SolveWeight*)_solveWeights.get(i);
775         if(w->approach == isApproach)
776             setWeight(w->idx, w->wgt);
777     }
778 }
779
780 void Airplane::runCruise()
781 {
782     setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
783     _model.setState(&_cruiseState);
784     _model.setAir(_cruiseP, _cruiseT,
785                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
786
787     // The control configuration
788     _controls.reset();
789     int i;
790     for(i=0; i<_cruiseControls.size(); i++) {
791         Control* c = (Control*)_cruiseControls.get(i);
792         _controls.setInput(c->control, c->val);
793     }
794     _controls.applyControls(1000000); // Huge dt value
795
796     // The local wind
797     float wind[3];
798     Math::mul3(-1, _cruiseState.v, wind);
799     Math::vmul33(_cruiseState.orient, wind, wind);
800  
801     setFuelFraction(_cruiseFuel);
802     setupWeights(false);
803    
804     // Set up the thruster parameters and iterate until the thrust
805     // stabilizes.
806     for(i=0; i<_thrusters.size(); i++) {
807         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
808         t->setWind(wind);
809         t->setAir(_cruiseP, _cruiseT,
810                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
811     }
812     stabilizeThrust();
813
814     updateGearState();
815
816     // Precompute thrust in the model, and calculate aerodynamic forces
817     _model.getBody()->recalc();
818     _model.getBody()->reset();
819     _model.initIteration();
820     _model.calcForces(&_cruiseState);
821 }
822
823 void Airplane::runApproach()
824 {
825     setupState(_approachAoA, _approachSpeed, &_approachState);
826     _model.setState(&_approachState);
827     _model.setAir(_approachP, _approachT,
828                   Atmosphere::calcStdDensity(_approachP, _approachT));
829
830     // The control configuration
831     _controls.reset();
832     int i;
833     for(i=0; i<_approachControls.size(); i++) {
834         Control* c = (Control*)_approachControls.get(i);
835         _controls.setInput(c->control, c->val);
836     }
837     _controls.applyControls(1000000);
838
839     // The local wind
840     float wind[3];
841     Math::mul3(-1, _approachState.v, wind);
842     Math::vmul33(_approachState.orient, wind, wind);
843     
844     setFuelFraction(_approachFuel);
845
846     setupWeights(true);
847
848     // Run the thrusters until they get to a stable setting.  FIXME:
849     // this is lots of wasted work.
850     for(i=0; i<_thrusters.size(); i++) {
851         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
852         t->setWind(wind);
853         t->setAir(_approachP, _approachT,
854                   Atmosphere::calcStdDensity(_approachP, _approachT));
855     }
856     stabilizeThrust();
857
858     updateGearState();
859
860     // Precompute thrust in the model, and calculate aerodynamic forces
861     _model.getBody()->recalc();
862     _model.getBody()->reset();
863     _model.initIteration();
864     _model.calcForces(&_approachState);
865 }
866
867 void Airplane::applyDragFactor(float factor)
868 {
869     float applied = Math::pow(factor, SOLVE_TWEAK);
870     _dragFactor *= applied;
871     if(_wing)
872       _wing->setDragScale(_wing->getDragScale() * applied);
873     if(_tail)
874       _tail->setDragScale(_tail->getDragScale() * applied);
875     int i;
876     for(i=0; i<_vstabs.size(); i++) {
877         Wing* w = (Wing*)_vstabs.get(i);
878         w->setDragScale(w->getDragScale() * applied);
879     }
880     for(i=0; i<_surfs.size(); i++) {
881         Surface* s = (Surface*)_surfs.get(i);
882         s->setTotalDrag(s->getTotalDrag() * applied);
883     }
884 }
885
886 void Airplane::applyLiftRatio(float factor)
887 {
888     float applied = Math::pow(factor, SOLVE_TWEAK);
889     _liftRatio *= applied;
890     if(_wing)
891       _wing->setLiftRatio(_wing->getLiftRatio() * applied);
892     if(_tail)
893       _tail->setLiftRatio(_tail->getLiftRatio() * applied);
894     int i;
895     for(i=0; i<_vstabs.size(); i++) {
896         Wing* w = (Wing*)_vstabs.get(i);
897         w->setLiftRatio(w->getLiftRatio() * applied);
898     }
899 }
900
901 float Airplane::clamp(float val, float min, float max)
902 {
903     if(val < min) return min;
904     if(val > max) return max;
905     return val;
906 }
907
908 float Airplane::normFactor(float f)
909 {
910     if(f < 0) f = -f;
911     if(f < 1) f = 1/f;
912     return f;
913 }
914
915 void Airplane::solve()
916 {
917     static const float ARCMIN = 0.0002909f;
918
919     float tmp[3];
920     _solutionIterations = 0;
921     _failureMsg = 0;
922
923     while(1) {
924         if(_solutionIterations++ > 10000) { 
925             _failureMsg = "Solution failed to converge after 10000 iterations";
926             return;
927         }
928
929         // Run an iteration at cruise, and extract the needed numbers:
930         runCruise();
931
932         _model.getThrust(tmp);
933         float thrust = tmp[0];
934
935         _model.getBody()->getAccel(tmp);
936         Math::tmul33(_cruiseState.orient, tmp, tmp);
937         float xforce = _cruiseWeight * tmp[0];
938         float clift0 = _cruiseWeight * tmp[2];
939
940         _model.getBody()->getAngularAccel(tmp);
941         Math::tmul33(_cruiseState.orient, tmp, tmp);
942         float pitch0 = tmp[1];
943
944         // Run an approach iteration, and do likewise
945         runApproach();
946
947         _model.getBody()->getAngularAccel(tmp);
948         Math::tmul33(_approachState.orient, tmp, tmp);
949         double apitch0 = tmp[1];
950
951         _model.getBody()->getAccel(tmp);
952         Math::tmul33(_approachState.orient, tmp, tmp);
953         float alift = _approachWeight * tmp[2];
954
955         // Modify the cruise AoA a bit to get a derivative
956         _cruiseAoA += ARCMIN;
957         runCruise();
958         _cruiseAoA -= ARCMIN;
959
960         _model.getBody()->getAccel(tmp);
961         Math::tmul33(_cruiseState.orient, tmp, tmp);
962         float clift1 = _cruiseWeight * tmp[2];
963
964         // Do the same with the tail incidence
965         _tail->setIncidence(_tailIncidence + ARCMIN);
966         runCruise();
967         _tail->setIncidence(_tailIncidence);
968
969         _model.getBody()->getAngularAccel(tmp);
970         Math::tmul33(_cruiseState.orient, tmp, tmp);
971         float pitch1 = tmp[1];
972
973         // Now calculate:
974         float awgt = 9.8f * _approachWeight;
975
976         float dragFactor = thrust / (thrust-xforce);
977         float liftFactor = awgt / (awgt+alift);
978         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
979         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
980
981         // Sanity:
982         if(dragFactor <= 0 || liftFactor <= 0)
983             break;
984
985         // And the elevator control in the approach.  This works just
986         // like the tail incidence computation (it's solving for the
987         // same thing -- pitching moment -- by diddling a different
988         // variable).
989         const float ELEVDIDDLE = 0.001f;
990         _approachElevator.val += ELEVDIDDLE;
991         runApproach();
992         _approachElevator.val -= ELEVDIDDLE;
993
994         _model.getBody()->getAngularAccel(tmp);
995         Math::tmul33(_approachState.orient, tmp, tmp);
996         double apitch1 = tmp[1];
997         float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
998
999         // Now apply the values we just computed.  Note that the
1000         // "minor" variables are deferred until we get the lift/drag
1001         // numbers in the right ballpark.
1002
1003         applyDragFactor(dragFactor);
1004         applyLiftRatio(liftFactor);
1005
1006         // DON'T do the following until the above are sane
1007         if(normFactor(dragFactor) > STHRESH*1.0001
1008            || normFactor(liftFactor) > STHRESH*1.0001)
1009         {
1010             continue;
1011         }
1012
1013         // OK, now we can adjust the minor variables:
1014         _cruiseAoA += SOLVE_TWEAK*aoaDelta;
1015         _tailIncidence += SOLVE_TWEAK*tailDelta;
1016         
1017         _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
1018         _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
1019
1020         if(abs(xforce/_cruiseWeight) < STHRESH*0.0001 &&
1021            abs(alift/_approachWeight) < STHRESH*0.0001 &&
1022            abs(aoaDelta) < STHRESH*.000017 &&
1023            abs(tailDelta) < STHRESH*.000017)
1024         {
1025             // If this finaly value is OK, then we're all done
1026             if(abs(elevDelta) < STHRESH*0.0001)
1027                 break;
1028
1029             // Otherwise, adjust and do the next iteration
1030             _approachElevator.val += SOLVE_TWEAK * elevDelta;
1031             if(abs(_approachElevator.val) > 1) {
1032                 _failureMsg = "Insufficient elevator to trim for approach";
1033                 break;
1034             }
1035         }
1036     }
1037
1038     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
1039         _failureMsg = "Drag factor beyond reasonable bounds.";
1040         return;
1041     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
1042         _failureMsg = "Lift ratio beyond reasonable bounds.";
1043         return;
1044     } else if(Math::abs(_cruiseAoA) >= .17453293) {
1045         _failureMsg = "Cruise AoA > 10 degrees";
1046         return;
1047     } else if(Math::abs(_tailIncidence) >= .17453293) {
1048         _failureMsg = "Tail incidence > 10 degrees";
1049         return;
1050     }
1051 }
1052
1053 void Airplane::solveHelicopter()
1054 {
1055     _solutionIterations = 0;
1056     _failureMsg = 0;
1057
1058     applyDragFactor(Math::pow(15.7/1000, 1/SOLVE_TWEAK));
1059     applyLiftRatio(Math::pow(104, 1/SOLVE_TWEAK));
1060     setupState(0,0, &_cruiseState);
1061     _model.setState(&_cruiseState);
1062     _controls.reset();
1063     _model.getBody()->reset();
1064 }
1065
1066 }; // namespace yasim