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