1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
15 inline float norm(float f) { return f<1 ? 1/f : f; }
16 inline float abs(float f) { return f<0 ? -f : f; }
21 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
44 for(i=0; i<_fuselages.size(); i++)
45 delete (Fuselage*)_fuselages.get(i);
46 for(i=0; i<_tanks.size(); i++)
47 delete (Tank*)_tanks.get(i);
48 for(i=0; i<_thrusters.size(); i++)
49 delete (ThrustRec*)_thrusters.get(i);
50 for(i=0; i<_gears.size(); i++)
51 delete (GearRec*)_gears.get(i);
52 for(i=0; i<_surfs.size(); i++)
53 delete (Surface*)_surfs.get(i);
54 for(i=0; i<_contacts.size(); i++)
55 delete[] (float*)_contacts.get(i);
58 void Airplane::iterate(float dt)
60 // The gear might have moved. Change their aerodynamics.
65 // FIXME: Consume fuel
68 ControlMap* Airplane::getControlMap()
73 Model* Airplane::getModel()
78 void Airplane::getPilotAccel(float* out)
80 State* s = _model.getState();
83 Glue::geodUp(s->pos, out);
84 Math::mul3(-9.8f, out, out);
86 // The regular acceleration
88 Math::mul3(-1, s->acc, tmp);
89 Math::add3(tmp, out, out);
91 // Convert to aircraft coordinates
92 Math::vmul33(s->orient, out, out);
94 // FIXME: rotational & centripetal acceleration needed
97 void Airplane::setPilotPos(float* pos)
100 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
103 void Airplane::getPilotPos(float* out)
106 for(i=0; i<3; i++) out[i] = _pilotPos[i];
109 int Airplane::numGear()
111 return _gears.size();
114 Gear* Airplane::getGear(int g)
116 return ((GearRec*)_gears.get(g))->gear;
119 void Airplane::updateGearState()
121 for(int i=0; i<_gears.size(); i++) {
122 GearRec* gr = (GearRec*)_gears.get(i);
123 float ext = gr->gear->getExtension();
125 gr->surf->setXDrag(ext);
126 gr->surf->setYDrag(ext);
127 gr->surf->setZDrag(ext);
131 void Airplane::setApproach(float speed, float altitude)
133 // The zero AoA will become a calculated stall AoA in compile()
134 setApproach(speed, altitude, 0);
137 void Airplane::setApproach(float speed, float altitude, float aoa)
139 _approachSpeed = speed;
140 _approachP = Atmosphere::getStdPressure(altitude);
141 _approachT = Atmosphere::getStdTemperature(altitude);
145 void Airplane::setCruise(float speed, float altitude)
147 _cruiseSpeed = speed;
148 _cruiseP = Atmosphere::getStdPressure(altitude);
149 _cruiseT = Atmosphere::getStdTemperature(altitude);
154 void Airplane::setElevatorControl(int control)
156 _approachElevator.control = control;
157 _approachElevator.val = 0;
158 _approachControls.add(&_approachElevator);
161 void Airplane::addApproachControl(int control, float val)
163 Control* c = new Control();
164 c->control = control;
166 _approachControls.add(c);
169 void Airplane::addCruiseControl(int control, float val)
171 Control* c = new Control();
172 c->control = control;
174 _cruiseControls.add(c);
177 int Airplane::numTanks()
179 return _tanks.size();
182 float Airplane::getFuel(int tank)
184 return ((Tank*)_tanks.get(tank))->fill;
187 float Airplane::getFuelDensity(int tank)
189 return ((Tank*)_tanks.get(tank))->density;
192 void Airplane::setWeight(float weight)
194 _emptyWeight = weight;
197 void Airplane::setWing(Wing* wing)
202 void Airplane::setTail(Wing* tail)
207 void Airplane::addVStab(Wing* vstab)
212 void Airplane::addFuselage(float* front, float* back, float width,
213 float taper, float mid)
215 Fuselage* f = new Fuselage();
218 f->front[i] = front[i];
219 f->back[i] = back[i];
227 int Airplane::addTank(float* pos, float cap, float density)
229 Tank* t = new Tank();
231 for(i=0; i<3; i++) t->pos[i] = pos[i];
234 t->density = density;
235 t->handle = 0xffffffff;
236 return _tanks.add(t);
239 void Airplane::addGear(Gear* gear)
241 GearRec* g = new GearRec();
247 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
249 ThrustRec* t = new ThrustRec();
250 t->thruster = thruster;
253 for(i=0; i<3; i++) t->cg[i] = cg[i];
257 void Airplane::addBallast(float* pos, float mass)
259 _model.getBody()->addMass(mass, pos);
263 int Airplane::addWeight(float* pos, float size)
265 WeightRec* wr = new WeightRec();
266 wr->handle = _model.getBody()->addMass(0, pos);
268 wr->surf = new Surface();
269 wr->surf->setPosition(pos);
270 wr->surf->setTotalDrag(size*size);
271 _model.addSurface(wr->surf);
272 _surfs.add(wr->surf);
274 return _weights.add(wr);
277 void Airplane::setWeight(int handle, float mass)
279 WeightRec* wr = (WeightRec*)_weights.get(handle);
281 _model.getBody()->setMass(wr->handle, mass);
283 // Kill the aerodynamic drag if the mass is exactly zero. This is
284 // how we simulate droppable stores.
286 wr->surf->setXDrag(0);
287 wr->surf->setYDrag(0);
288 wr->surf->setZDrag(0);
290 wr->surf->setXDrag(1);
291 wr->surf->setYDrag(1);
292 wr->surf->setZDrag(1);
296 void Airplane::setFuelFraction(float frac)
299 for(i=0; i<_tanks.size(); i++) {
300 Tank* t = (Tank*)_tanks.get(i);
301 _model.getBody()->setMass(t->handle, t->cap * frac);
305 float Airplane::getDragCoefficient()
310 float Airplane::getLiftRatio()
315 float Airplane::getCruiseAoA()
320 float Airplane::getTailIncidence()
322 return _tailIncidence;
325 char* Airplane::getFailureMsg()
330 int Airplane::getSolutionIterations()
332 return _solutionIterations;
335 void Airplane::setupState(float aoa, float speed, State* s)
337 float cosAoA = Math::cos(aoa);
338 float sinAoA = Math::sin(aoa);
339 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
340 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
341 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
343 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
347 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
349 // Put us 1m above the origin, or else the gravity computation in
354 void Airplane::addContactPoint(float* pos)
356 float* cp = new float[3];
363 float Airplane::compileWing(Wing* w)
365 // The tip of the wing is a contact point
368 addContactPoint(tip);
369 if(w->isMirrored()) {
371 addContactPoint(tip);
374 // Make sure it's initialized. The surfaces will pop out with
375 // total drag coefficients equal to their areas, which is what we
381 for(i=0; i<w->numSurfaces(); i++) {
382 Surface* s = (Surface*)w->getSurface(i);
384 float td = s->getTotalDrag();
387 _model.addSurface(s);
389 float mass = w->getSurfaceWeight(i);
390 mass = mass * Math::sqrt(mass);
393 _model.getBody()->addMass(mass, pos);
399 float Airplane::compileFuselage(Fuselage* f)
401 // The front and back are contact points
402 addContactPoint(f->front);
403 addContactPoint(f->back);
407 Math::sub3(f->front, f->back, fwd);
408 float len = Math::mag3(fwd);
409 float wid = f->width;
410 int segs = (int)Math::ceil(len/wid);
411 float segWgt = len*wid/segs;
413 for(j=0; j<segs; j++) {
414 float frac = (j+0.5f) / segs;
418 scale = f->taper+(1-f->taper) * (frac / f->mid);
420 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
424 Math::mul3(frac, fwd, pos);
425 Math::add3(f->back, pos, pos);
427 // _Mass_ weighting goes as surface area^(3/2)
428 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
429 _model.getBody()->addMass(mass, pos);
432 // Make a Surface too
433 Surface* s = new Surface();
435 float sideDrag = len/wid;
436 s->setYDrag(sideDrag);
437 s->setZDrag(sideDrag);
438 s->setTotalDrag(scale*segWgt);
440 // FIXME: fails for fuselages aligned along the Y axis
442 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
444 y[0] = 0; y[1] = 1; y[2] = 0;
445 Math::cross3(x, y, z);
447 Math::cross3(z, x, y);
448 s->setOrientation(o);
450 _model.addSurface(s);
456 // FIXME: should probably add a mass for the gear, too
457 void Airplane::compileGear(GearRec* gr)
461 // Make a Surface object for the aerodynamic behavior
462 Surface* s = new Surface();
465 // Put the surface at the half-way point on the gear strut, give
466 // it a drag coefficient equal to a square of the same dimension
467 // (gear are really draggy) and make it symmetric. Assume that
468 // the "length" of the gear is 3x the compression distance
469 float pos[3], cmp[3];
470 g->getCompression(cmp);
471 float length = 3 * Math::mag3(cmp);
473 Math::mul3(0.5, cmp, cmp);
474 Math::add3(pos, cmp, pos);
477 s->setTotalDrag(length*length);
480 _model.addSurface(s);
484 void Airplane::compileContactPoints()
486 // Figure it will compress by 20cm
489 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
491 // Give it a spring constant such that at full compression it will
492 // hold up 10 times the planes mass. That's about right. Yeah.
493 float mass = _model.getBody()->getTotalMass();
494 float spring = (1/DIST) * 9.8f * 10.0f * mass;
495 float damp = 2 * Math::sqrt(spring * mass);
498 for(i=0; i<_contacts.size(); i++) {
499 float *cp = (float*)_contacts.get(i);
501 Gear* g = new Gear();
504 g->setCompression(comp);
505 g->setSpring(spring);
510 g->setStaticFriction(0.6f);
511 g->setDynamicFriction(0.5f);
517 void Airplane::compile()
520 ground[0] = 0; ground[1] = 0; ground[2] = 1;
521 _model.setGroundPlane(ground, -100000);
523 RigidBody* body = _model.getBody();
524 int firstMass = body->numMasses();
526 // Generate the point masses for the plane. Just use unitless
527 // numbers for a first pass, then go back through and rescale to
528 // make the weight right.
532 aeroWgt += compileWing(_wing);
533 aeroWgt += compileWing(_tail);
535 for(i=0; i<_vstabs.size(); i++) {
536 aeroWgt += compileWing((Wing*)_vstabs.get(i));
540 for(i=0; i<_fuselages.size(); i++) {
541 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
544 // Count up the absolute weight we have
545 float nonAeroWgt = _ballast;
546 for(i=0; i<_thrusters.size(); i++)
547 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
549 // Rescale to the specified empty weight
550 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
551 for(i=firstMass; i<body->numMasses(); i++)
552 body->setMass(i, body->getMass(i)*wscale);
554 // Add the thruster masses
555 for(i=0; i<_thrusters.size(); i++) {
556 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
557 body->addMass(t->mass, t->cg);
560 // Add the tanks, empty for now.
562 for(i=0; i<_tanks.size(); i++) {
563 Tank* t = (Tank*)_tanks.get(i);
564 t->handle = body->addMass(0, t->pos);
567 _cruiseWeight = _emptyWeight + totalFuel*0.5f;
568 _approachWeight = _emptyWeight + totalFuel*0.2f;
572 // Add surfaces for the landing gear.
573 for(i=0; i<_gears.size(); i++)
574 compileGear((GearRec*)_gears.get(i));
576 // The Thruster objects
577 for(i=0; i<_thrusters.size(); i++) {
578 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
579 tr->handle = _model.addThruster(tr->thruster);
584 float gespan = _wing->getGroundEffect(gepos);
585 _model.setGroundEffect(gepos, gespan, 0.15f);
590 // Do this after solveGear, because it creates "gear" objects that
591 // we don't want to affect.
592 compileContactPoints();
595 void Airplane::solveGear()
598 _model.getBody()->getCG(cg);
600 // Calculate spring constant weightings for the gear. Weight by
601 // the inverse of the distance to the c.g. in the XY plane, which
602 // should be correct for most gear arrangements. Add 50cm of
603 // "buffer" to keep things from blowing up with aircraft with a
604 // single gear very near the c.g. (AV-8, for example).
607 for(i=0; i<_gears.size(); i++) {
608 GearRec* gr = (GearRec*)_gears.get(i);
611 Math::sub3(cg, pos, pos);
612 gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
616 // Renormalize so they sum to 1
617 for(i=0; i<_gears.size(); i++)
618 ((GearRec*)_gears.get(i))->wgt /= total;
620 // The force at max compression should be sufficient to stop a
621 // plane moving downwards at 3x the approach descent rate. Assume
622 // a 3 degree approach.
623 float descentRate = 3.0f*_approachSpeed/19.1f;
625 // Spread the kinetic energy according to the gear weights. This
626 // will results in an equal compression fraction (not distance) of
628 float energy = 0.5f*_approachWeight*descentRate*descentRate;
630 for(i=0; i<_gears.size(); i++) {
631 GearRec* gr = (GearRec*)_gears.get(i);
632 float e = energy * gr->wgt;
634 gr->gear->getCompression(comp);
635 float len = Math::mag3(comp);
637 // Energy in a spring: e = 0.5 * k * len^2
638 float k = 2 * e / (len*len);
640 gr->gear->setSpring(k * gr->gear->getSpring());
642 // Critically damped (too damped, too!)
643 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt)
644 * gr->gear->getDamping());
646 // These are pretty generic
647 gr->gear->setStaticFriction(0.8f);
648 gr->gear->setDynamicFriction(0.7f);
652 void Airplane::initEngines()
654 for(int i=0; i<_thrusters.size(); i++) {
655 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
656 tr->thruster->init();
660 void Airplane::stabilizeThrust()
663 for(i=0; i<_thrusters.size(); i++)
664 _model.getThruster(i)->stabilize();
667 void Airplane::runCruise()
669 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
670 _model.setState(&_cruiseState);
671 _model.setAir(_cruiseP, _cruiseT,
672 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
674 // The control configuration
677 for(i=0; i<_cruiseControls.size(); i++) {
678 Control* c = (Control*)_cruiseControls.get(i);
679 _controls.setInput(c->control, c->val);
681 _controls.applyControls(1000000); // Huge dt value
685 Math::mul3(-1, _cruiseState.v, wind);
686 Math::vmul33(_cruiseState.orient, wind, wind);
688 // Cruise is by convention at 50% tank capacity
689 setFuelFraction(0.5);
691 // Set up the thruster parameters and iterate until the thrust
693 for(i=0; i<_thrusters.size(); i++) {
694 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
696 t->setAir(_cruiseP, _cruiseT,
697 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
703 // Precompute thrust in the model, and calculate aerodynamic forces
704 _model.getBody()->recalc();
705 _model.getBody()->reset();
706 _model.initIteration();
707 _model.calcForces(&_cruiseState);
710 void Airplane::runApproach()
712 setupState(_approachAoA, _approachSpeed, &_approachState);
713 _model.setState(&_approachState);
714 _model.setAir(_approachP, _approachT,
715 Atmosphere::calcStdDensity(_approachP, _approachT));
717 // The control configuration
720 for(i=0; i<_approachControls.size(); i++) {
721 Control* c = (Control*)_approachControls.get(i);
722 _controls.setInput(c->control, c->val);
724 _controls.applyControls(1000000);
728 Math::mul3(-1, _approachState.v, wind);
729 Math::vmul33(_approachState.orient, wind, wind);
731 // Approach is by convention at 20% tank capacity
732 setFuelFraction(0.2f);
734 // Run the thrusters until they get to a stable setting. FIXME:
735 // this is lots of wasted work.
736 for(i=0; i<_thrusters.size(); i++) {
737 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
739 t->setAir(_approachP, _approachT,
740 Atmosphere::calcStdDensity(_approachP, _approachT));
746 // Precompute thrust in the model, and calculate aerodynamic forces
747 _model.getBody()->recalc();
748 _model.getBody()->reset();
749 _model.initIteration();
750 _model.calcForces(&_approachState);
753 void Airplane::applyDragFactor(float factor)
755 float applied = Math::sqrt(factor);
756 _dragFactor *= applied;
757 _wing->setDragScale(_wing->getDragScale() * applied);
758 _tail->setDragScale(_tail->getDragScale() * applied);
760 for(i=0; i<_vstabs.size(); i++) {
761 Wing* w = (Wing*)_vstabs.get(i);
762 w->setDragScale(w->getDragScale() * applied);
764 for(i=0; i<_surfs.size(); i++) {
765 Surface* s = (Surface*)_surfs.get(i);
766 s->setTotalDrag(s->getTotalDrag() * applied);
770 void Airplane::applyLiftRatio(float factor)
772 float applied = Math::sqrt(factor);
773 _liftRatio *= applied;
774 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
775 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
777 for(i=0; i<_vstabs.size(); i++) {
778 Wing* w = (Wing*)_vstabs.get(i);
779 w->setLiftRatio(w->getLiftRatio() * applied);
783 float Airplane::clamp(float val, float min, float max)
785 if(val < min) return min;
786 if(val > max) return max;
790 float Airplane::normFactor(float f)
797 void Airplane::solve()
799 static const float ARCMIN = 0.0002909f;
802 _solutionIterations = 0;
806 printf("%d %f %f %f %f %f\n", //DEBUG
812 _approachElevator.val);
815 if(_solutionIterations++ > 10000) {
816 _failureMsg = "Solution failed to converge after 10000 iterations";
820 // Run an iteration at cruise, and extract the needed numbers:
823 _model.getThrust(tmp);
824 float thrust = tmp[0];
826 _model.getBody()->getAccel(tmp);
827 Math::tmul33(_cruiseState.orient, tmp, tmp);
828 float xforce = _cruiseWeight * tmp[0];
829 float clift0 = _cruiseWeight * tmp[2];
831 _model.getBody()->getAngularAccel(tmp);
832 Math::tmul33(_cruiseState.orient, tmp, tmp);
833 float pitch0 = tmp[1];
835 // Run an approach iteration, and do likewise
838 _model.getBody()->getAngularAccel(tmp);
839 Math::tmul33(_approachState.orient, tmp, tmp);
840 double apitch0 = tmp[1];
842 _model.getBody()->getAccel(tmp);
843 Math::tmul33(_approachState.orient, tmp, tmp);
844 float alift = _approachWeight * tmp[2];
846 // Modify the cruise AoA a bit to get a derivative
847 _cruiseAoA += ARCMIN;
849 _cruiseAoA -= ARCMIN;
851 _model.getBody()->getAccel(tmp);
852 Math::tmul33(_cruiseState.orient, tmp, tmp);
853 float clift1 = _cruiseWeight * tmp[2];
855 // Do the same with the tail incidence
856 _tail->setIncidence(_tailIncidence + ARCMIN);
858 _tail->setIncidence(_tailIncidence);
860 _model.getBody()->getAngularAccel(tmp);
861 Math::tmul33(_cruiseState.orient, tmp, tmp);
862 float pitch1 = tmp[1];
865 float awgt = 9.8f * _approachWeight;
867 float dragFactor = thrust / (thrust-xforce);
868 float liftFactor = awgt / (awgt+alift);
869 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
870 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
873 if(dragFactor <= 0 || liftFactor <= 0)
876 // And the elevator control in the approach. This works just
877 // like the tail incidence computation (it's solving for the
878 // same thing -- pitching moment -- by diddling a different
880 const float ELEVDIDDLE = 0.001f;
881 _approachElevator.val += ELEVDIDDLE;
883 _approachElevator.val -= ELEVDIDDLE;
885 _model.getBody()->getAngularAccel(tmp);
886 Math::tmul33(_approachState.orient, tmp, tmp);
887 double apitch1 = tmp[1];
888 float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
890 // Now apply the values we just computed. Note that the
891 // "minor" variables are deferred until we get the lift/drag
892 // numbers in the right ballpark.
894 applyDragFactor(dragFactor);
895 applyLiftRatio(liftFactor);
897 // DON'T do the following until the above are sane
898 if(normFactor(dragFactor) > 1.0001
899 || normFactor(liftFactor) > 1.0001)
904 // OK, now we can adjust the minor variables:
905 _cruiseAoA += 0.5f*aoaDelta;
906 _tailIncidence += 0.5f*tailDelta;
908 _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
909 _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
911 if(abs(xforce/_cruiseWeight) < 0.0001 &&
912 abs(alift/_approachWeight) < 0.0001 &&
913 abs(aoaDelta) < .000017 &&
914 abs(tailDelta) < .000017)
916 // If this finaly value is OK, then we're all done
917 if(abs(elevDelta) < 0.0001)
920 // Otherwise, adjust and do the next iteration
921 _approachElevator.val += 0.8 * elevDelta;
922 if(abs(_approachElevator.val) > 1) {
923 _failureMsg = "Insufficient elevator to trim for approach";
929 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
930 _failureMsg = "Drag factor beyond reasonable bounds.";
932 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
933 _failureMsg = "Lift ratio beyond reasonable bounds.";
935 } else if(Math::abs(_cruiseAoA) >= .17453293) {
936 _failureMsg = "Cruise AoA > 10 degrees";
938 } else if(Math::abs(_tailIncidence) >= .17453293) {
939 _failureMsg = "Tail incidence > 10 degrees";
943 }; // namespace yasim