1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
16 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
39 for(i=0; i<_fuselages.size(); i++)
40 delete (Fuselage*)_fuselages.get(i);
41 for(i=0; i<_tanks.size(); i++)
42 delete (Tank*)_tanks.get(i);
43 for(i=0; i<_thrusters.size(); i++)
44 delete (ThrustRec*)_thrusters.get(i);
45 for(i=0; i<_gears.size(); i++)
46 delete (GearRec*)_gears.get(i);
47 for(i=0; i<_surfs.size(); i++)
48 delete (Surface*)_surfs.get(i);
49 for(i=0; i<_contacts.size(); i++)
50 delete[] (float*)_contacts.get(i);
53 void Airplane::iterate(float dt)
57 // FIXME: Consume fuel
60 ControlMap* Airplane::getControlMap()
65 Model* Airplane::getModel()
70 void Airplane::getPilotAccel(float* out)
72 State* s = _model.getState();
75 Glue::geodUp(s->pos, out);
76 Math::mul3(-9.8, out, out);
78 // The regular acceleration
80 Math::mul3(-1, s->acc, tmp);
81 Math::add3(tmp, out, out);
83 // Convert to aircraft coordinates
84 Math::vmul33(s->orient, out, out);
86 // FIXME: rotational & centripetal acceleration needed
89 void Airplane::setPilotPos(float* pos)
92 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
95 void Airplane::getPilotPos(float* out)
98 for(i=0; i<3; i++) out[i] = _pilotPos[i];
101 int Airplane::numGear()
103 return _gears.size();
106 Gear* Airplane::getGear(int g)
108 return ((GearRec*)_gears.get(g))->gear;
111 void Airplane::setGearState(bool down, float dt)
114 for(i=0; i<_gears.size(); i++) {
115 GearRec* gr = (GearRec*)_gears.get(i);
118 gr->gear->setExtension(1);
119 gr->surf->setXDrag(1);
120 gr->surf->setYDrag(1);
121 gr->surf->setZDrag(1);
125 float diff = dt / gr->time;
126 if(!down) diff = -diff;
127 float ext = gr->gear->getExtension() + diff;
131 gr->gear->setExtension(ext);
132 gr->surf->setXDrag(ext);
133 gr->surf->setYDrag(ext);
134 gr->surf->setZDrag(ext);
138 void Airplane::setApproach(float speed, float altitude)
140 // The zero AoA will become a calculated stall AoA in compile()
141 setApproach(speed, altitude, 0);
144 void Airplane::setApproach(float speed, float altitude, float aoa)
146 _approachSpeed = speed;
147 _approachP = Atmosphere::getStdPressure(altitude);
148 _approachT = Atmosphere::getStdTemperature(altitude);
152 void Airplane::setCruise(float speed, float altitude)
154 _cruiseSpeed = speed;
155 _cruiseP = Atmosphere::getStdPressure(altitude);
156 _cruiseT = Atmosphere::getStdTemperature(altitude);
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, float transitionTime)
241 GearRec* g = new GearRec();
244 g->time = transitionTime;
248 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
250 ThrustRec* t = new ThrustRec();
251 t->thruster = thruster;
254 for(i=0; i<3; i++) t->cg[i] = cg[i];
258 void Airplane::addBallast(float* pos, float mass)
260 _model.getBody()->addMass(mass, pos);
264 int Airplane::addWeight(float* pos, float size)
266 WeightRec* wr = new WeightRec();
267 wr->handle = _model.getBody()->addMass(0, pos);
269 wr->surf = new Surface();
270 wr->surf->setPosition(pos);
271 wr->surf->setTotalDrag(size*size);
272 _model.addSurface(wr->surf);
273 _surfs.add(wr->surf);
275 return _weights.add(wr);
278 void Airplane::setWeight(int handle, float mass)
280 WeightRec* wr = (WeightRec*)_weights.get(handle);
282 _model.getBody()->setMass(wr->handle, mass);
284 // Kill the aerodynamic drag if the mass is exactly zero. This is
285 // how we simulate droppable stores.
287 wr->surf->setXDrag(0);
288 wr->surf->setYDrag(0);
289 wr->surf->setZDrag(0);
291 wr->surf->setXDrag(1);
292 wr->surf->setYDrag(1);
293 wr->surf->setZDrag(1);
297 void Airplane::setFuelFraction(float frac)
300 for(i=0; i<_tanks.size(); i++) {
301 Tank* t = (Tank*)_tanks.get(i);
302 _model.getBody()->setMass(t->handle, t->cap * frac);
306 float Airplane::getDragCoefficient()
311 float Airplane::getLiftRatio()
316 float Airplane::getCruiseAoA()
321 float Airplane::getTailIncidence()
323 return _tailIncidence;
326 char* Airplane::getFailureMsg()
331 int Airplane::getSolutionIterations()
333 return _solutionIterations;
336 void Airplane::setupState(float aoa, float speed, State* s)
338 float cosAoA = Math::cos(aoa);
339 float sinAoA = Math::sin(aoa);
340 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
341 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
342 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
344 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
348 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
350 // Put us 1m above the origin, or else the gravity computation in
355 void Airplane::addContactPoint(float* pos)
357 float* cp = new float[3];
364 float Airplane::compileWing(Wing* w)
366 // The tip of the wing is a contact point
369 addContactPoint(tip);
370 if(w->isMirrored()) {
372 addContactPoint(tip);
375 // Make sure it's initialized. The surfaces will pop out with
376 // total drag coefficients equal to their areas, which is what we
382 for(i=0; i<w->numSurfaces(); i++) {
383 Surface* s = (Surface*)w->getSurface(i);
385 float td = s->getTotalDrag();
388 _model.addSurface(s);
390 float mass = w->getSurfaceWeight(i);
391 mass = mass * Math::sqrt(mass);
394 _model.getBody()->addMass(mass, pos);
400 float Airplane::compileFuselage(Fuselage* f)
402 // The front and back are contact points
403 addContactPoint(f->front);
404 addContactPoint(f->back);
408 Math::sub3(f->front, f->back, fwd);
409 float len = Math::mag3(fwd);
410 float wid = f->width;
411 int segs = (int)Math::ceil(len/wid);
412 float segWgt = len*wid/segs;
414 for(j=0; j<segs; j++) {
415 float frac = (j+0.5) / segs;
419 scale = f->taper+(1-f->taper) * (frac / f->mid);
421 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
425 Math::mul3(frac, fwd, pos);
426 Math::add3(f->back, pos, pos);
428 // _Mass_ weighting goes as surface area^(3/2)
429 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
430 _model.getBody()->addMass(mass, pos);
433 // Make a Surface too
434 Surface* s = new Surface();
436 float sideDrag = len/wid;
437 s->setYDrag(sideDrag);
438 s->setZDrag(sideDrag);
439 s->setTotalDrag(scale*segWgt);
441 // FIXME: fails for fuselages aligned along the Y axis
443 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
445 y[0] = 0; y[1] = 1; y[2] = 0;
446 Math::cross3(x, y, z);
447 s->setOrientation(o);
449 _model.addSurface(s);
455 // FIXME: should probably add a mass for the gear, too
456 void Airplane::compileGear(GearRec* gr)
460 // Make a Surface object for the aerodynamic behavior
461 Surface* s = new Surface();
464 // Put the surface at the half-way point on the gear strut, give
465 // it a drag coefficient equal to a square of the same dimension
466 // (gear are really draggy) and make it symmetric. Assume that
467 // the "length" of the gear is 3x the compression distance
468 float pos[3], cmp[3];
469 g->getCompression(cmp);
470 float length = 3 * Math::mag3(cmp);
472 Math::mul3(0.5, cmp, cmp);
473 Math::add3(pos, cmp, pos);
476 s->setTotalDrag(length*length);
479 _model.addSurface(s);
483 void Airplane::compileContactPoints()
485 // Figure it will compress by 20cm
488 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
490 // Give it a spring constant such that at full compression it will
491 // hold up 10 times the planes mass. That's about right. Yeah.
492 float mass = _model.getBody()->getTotalMass();
493 float spring = (1/DIST) * 9.8 * 10 * mass;
494 float damp = 2 * Math::sqrt(spring * mass);
497 for(i=0; i<_contacts.size(); i++) {
498 float *cp = (float*)_contacts.get(i);
500 Gear* g = new Gear();
503 g->setCompression(comp);
504 g->setSpring(spring);
509 g->setStaticFriction(0.6);
510 g->setDynamicFriction(0.5);
516 void Airplane::compile()
519 ground[0] = 0; ground[1] = 0; ground[2] = 1;
520 _model.setGroundPlane(ground, -100000);
522 RigidBody* body = _model.getBody();
523 int firstMass = body->numMasses();
525 // Generate the point masses for the plane. Just use unitless
526 // numbers for a first pass, then go back through and rescale to
527 // make the weight right.
531 aeroWgt += compileWing(_wing);
532 aeroWgt += compileWing(_tail);
534 for(i=0; i<_vstabs.size(); i++) {
535 aeroWgt += compileWing((Wing*)_vstabs.get(i));
539 for(i=0; i<_fuselages.size(); i++) {
540 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
543 // Count up the absolute weight we have
544 float nonAeroWgt = _ballast;
545 for(i=0; i<_thrusters.size(); i++)
546 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
548 // Rescale to the specified empty weight
549 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
550 for(i=firstMass; i<body->numMasses(); i++)
551 body->setMass(i, body->getMass(i)*wscale);
553 // Add the thruster masses
554 for(i=0; i<_thrusters.size(); i++) {
555 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
556 body->addMass(t->mass, t->cg);
559 // Add the tanks, empty for now.
561 for(i=0; i<_tanks.size(); i++) {
562 Tank* t = (Tank*)_tanks.get(i);
563 t->handle = body->addMass(0, t->pos);
566 _cruiseWeight = _emptyWeight + totalFuel*0.5;
567 _approachWeight = _emptyWeight + totalFuel*0.2;
571 // Add surfaces for the landing gear.
572 for(i=0; i<_gears.size(); i++)
573 compileGear((GearRec*)_gears.get(i));
575 // The Thruster objects
576 for(i=0; i<_thrusters.size(); i++) {
577 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
578 tr->handle = _model.addThruster(tr->thruster);
583 float gespan = _wing->getGroundEffect(gepos);
584 _model.setGroundEffect(gepos, gespan, .3);
589 // Do this after solveGear, because it creates "gear" objects that
590 // we don't want to affect.
591 compileContactPoints();
593 // Drop the gear (use a really big dt)
594 setGearState(true, 1000000);
597 void Airplane::solveGear()
600 _model.getBody()->getCG(cg);
602 // Calculate spring constant weightings for the gear. Weight by
603 // the inverse of the distance to the c.g. in the XY plane, which
604 // should be correct for most gear arrangements. Add 50cm of
605 // "buffer" to keep things from blowing up with aircraft with a
606 // single gear very near the c.g. (AV-8, for example).
609 for(i=0; i<_gears.size(); i++) {
610 GearRec* gr = (GearRec*)_gears.get(i);
613 Math::sub3(cg, pos, pos);
614 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
618 // Renormalize so they sum to 1
619 for(i=0; i<_gears.size(); i++)
620 ((GearRec*)_gears.get(i))->wgt /= total;
622 // The force at max compression should be sufficient to stop a
623 // plane moving downwards at 3x the approach descent rate. Assume
624 // a 3 degree approach.
625 float descentRate = 3*_approachSpeed/19.1;
627 // Spread the kinetic energy according to the gear weights. This
628 // will results in an equal compression fraction (not distance) of
630 float energy = 0.5*_approachWeight*descentRate*descentRate;
632 for(i=0; i<_gears.size(); i++) {
633 GearRec* gr = (GearRec*)_gears.get(i);
634 float e = energy * gr->wgt;
636 gr->gear->getCompression(comp);
637 float len = Math::mag3(comp);
639 // Energy in a spring: e = 0.5 * k * len^2
640 float k = 2 * e / (len*len);
642 gr->gear->setSpring(k);
644 // Critically damped (too damped, too!)
645 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
647 // These are pretty generic
648 gr->gear->setStaticFriction(0.8);
649 gr->gear->setDynamicFriction(0.7);
653 void Airplane::stabilizeThrust()
656 for(i=0; i<_thrusters.size(); i++)
657 _model.getThruster(i)->stabilize();
660 void Airplane::runCruise()
662 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
663 _model.setState(&_cruiseState);
664 _model.setAir(_cruiseP, _cruiseT);
666 // The control configuration
669 for(i=0; i<_cruiseControls.size(); i++) {
670 Control* c = (Control*)_cruiseControls.get(i);
671 _controls.setInput(c->control, c->val);
673 _controls.applyControls();
677 Math::mul3(-1, _cruiseState.v, wind);
678 Math::vmul33(_cruiseState.orient, wind, wind);
680 // Gear are up (if they're non-retractable, this is a noop)
681 setGearState(false, 100000);
683 // Cruise is by convention at 50% tank capacity
684 setFuelFraction(0.5);
686 // Set up the thruster parameters and iterate until the thrust
688 for(i=0; i<_thrusters.size(); i++) {
689 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
691 t->setAir(_cruiseP, _cruiseT);
695 // Precompute thrust in the model, and calculate aerodynamic forces
696 _model.getBody()->reset();
697 _model.initIteration();
698 _model.calcForces(&_cruiseState);
701 void Airplane::runApproach()
703 setupState(_approachAoA, _approachSpeed, &_approachState);
704 _model.setState(&_approachState);
705 _model.setAir(_approachP, _approachT);
707 // The control configuration
710 for(i=0; i<_approachControls.size(); i++) {
711 Control* c = (Control*)_approachControls.get(i);
712 _controls.setInput(c->control, c->val);
714 _controls.applyControls();
718 Math::mul3(-1, _approachState.v, wind);
719 Math::vmul33(_approachState.orient, wind, wind);
721 // Approach is by convention at 20% tank capacity
722 setFuelFraction(0.2);
725 setGearState(true, 100000);
727 // Run the thrusters until they get to a stable setting. FIXME:
728 // this is lots of wasted work.
729 for(i=0; i<_thrusters.size(); i++) {
730 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
732 t->setAir(_approachP, _approachT);
736 // Precompute thrust in the model, and calculate aerodynamic forces
737 _model.getBody()->reset();
738 _model.initIteration();
739 _model.calcForces(&_approachState);
742 void Airplane::applyDragFactor(float factor)
744 float applied = Math::sqrt(factor);
745 _dragFactor *= applied;
746 _wing->setDragScale(_wing->getDragScale() * applied);
747 _tail->setDragScale(_tail->getDragScale() * applied);
749 for(i=0; i<_vstabs.size(); i++) {
750 Wing* w = (Wing*)_vstabs.get(i);
751 w->setDragScale(w->getDragScale() * applied);
753 for(i=0; i<_surfs.size(); i++) {
754 Surface* s = (Surface*)_surfs.get(i);
755 s->setTotalDrag(s->getTotalDrag() * applied);
759 void Airplane::applyLiftRatio(float factor)
761 float applied = Math::sqrt(factor);
762 _liftRatio *= applied;
763 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
764 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
766 for(i=0; i<_vstabs.size(); i++) {
767 Wing* w = (Wing*)_vstabs.get(i);
768 w->setLiftRatio(w->getLiftRatio() * applied);
772 float Airplane::clamp(float val, float min, float max)
774 if(val < min) return min;
775 if(val > max) return max;
779 float Airplane::normFactor(float f)
786 void Airplane::solve()
788 static const float ARCMIN = 0.0002909;
791 _solutionIterations = 0;
794 if(_solutionIterations++ > 10000) {
795 _failureMsg = "Solution failed to converge after 10000 iterations";
799 // Run an iteration at cruise, and extract the needed numbers:
802 _model.getThrust(tmp);
803 float thrust = tmp[0];
805 _model.getBody()->getAccel(tmp);
806 float xforce = _cruiseWeight * tmp[0];
807 float clift0 = _cruiseWeight * tmp[2];
809 _model.getBody()->getAngularAccel(tmp);
810 float pitch0 = tmp[1];
812 // Run an approach iteration, and do likewise
815 _model.getBody()->getAccel(tmp);
816 float alift = _approachWeight * tmp[2];
818 // Modify the cruise AoA a bit to get a derivative
819 _cruiseAoA += ARCMIN;
821 _cruiseAoA -= ARCMIN;
823 _model.getBody()->getAccel(tmp);
824 float clift1 = _cruiseWeight * tmp[2];
826 // Do the same with the tail incidence
827 _tail->setIncidence(_tailIncidence + ARCMIN);
829 _tail->setIncidence(_tailIncidence);
831 _model.getBody()->getAngularAccel(tmp);
832 float pitch1 = tmp[1];
835 float awgt = 9.8 * _approachWeight;
837 float dragFactor = thrust / (thrust-xforce);
838 float liftFactor = awgt / (awgt+alift);
839 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
840 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
843 if(dragFactor <= 0) {
844 _failureMsg = "Zero or negative drag adjustment.";
846 } else if(liftFactor <= 0) {
847 _failureMsg = "Zero or negative lift adjustment.";
852 applyDragFactor(dragFactor);
853 applyLiftRatio(liftFactor);
855 // DON'T do the following until the above are sane
856 if(normFactor(dragFactor) > 1.1
857 || normFactor(liftFactor) > 1.1)
862 // OK, now we can adjust the minor variables
863 _cruiseAoA += 0.5*aoaDelta;
864 _tailIncidence += 0.5*tailDelta;
866 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
867 _tailIncidence = clamp(_tailIncidence, -.174, .174);
869 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
870 aoaDelta < .000017 && tailDelta < .000017)
876 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
877 _failureMsg = "Drag factor beyond reasonable bounds.";
879 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
880 _failureMsg = "Lift ratio beyond reasonable bounds.";
882 } else if(Math::abs(_cruiseAoA) >= .174) {
883 _failureMsg = "Cruise AoA > 10 degrees";
885 } else if(Math::abs(_tailIncidence) >= .174) {
886 _failureMsg = "Tail incidence > 10 degrees";
890 }; // namespace yasim