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