1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
14 inline float norm(float f) { return f<1 ? 1/f : f; }
15 inline float abs(float f) { return f<0 ? -f : f; }
20 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
43 for(i=0; i<_fuselages.size(); i++)
44 delete (Fuselage*)_fuselages.get(i);
45 for(i=0; i<_tanks.size(); i++)
46 delete (Tank*)_tanks.get(i);
47 for(i=0; i<_thrusters.size(); i++)
48 delete (ThrustRec*)_thrusters.get(i);
49 for(i=0; i<_gears.size(); i++)
50 delete (GearRec*)_gears.get(i);
51 for(i=0; i<_surfs.size(); i++)
52 delete (Surface*)_surfs.get(i);
53 for(i=0; i<_contacts.size(); i++)
54 delete[] (float*)_contacts.get(i);
57 void Airplane::iterate(float dt)
59 // The gear might have moved. Change their aerodynamics.
64 // FIXME: Consume fuel
67 ControlMap* Airplane::getControlMap()
72 Model* Airplane::getModel()
77 void Airplane::getPilotAccel(float* out)
79 State* s = _model.getState();
82 Glue::geodUp(s->pos, out);
83 Math::mul3(-9.8f, out, out);
85 // The regular acceleration
87 Math::mul3(-1, s->acc, tmp);
88 Math::add3(tmp, out, out);
90 // Convert to aircraft coordinates
91 Math::vmul33(s->orient, out, out);
93 // FIXME: rotational & centripetal acceleration needed
96 void Airplane::setPilotPos(float* pos)
99 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
102 void Airplane::getPilotPos(float* out)
105 for(i=0; i<3; i++) out[i] = _pilotPos[i];
108 int Airplane::numGear()
110 return _gears.size();
113 Gear* Airplane::getGear(int g)
115 return ((GearRec*)_gears.get(g))->gear;
118 void Airplane::updateGearState()
120 for(int i=0; i<_gears.size(); i++) {
121 GearRec* gr = (GearRec*)_gears.get(i);
122 float ext = gr->gear->getExtension();
124 gr->surf->setXDrag(ext);
125 gr->surf->setYDrag(ext);
126 gr->surf->setZDrag(ext);
130 void Airplane::setApproach(float speed, float altitude)
132 // The zero AoA will become a calculated stall AoA in compile()
133 setApproach(speed, altitude, 0);
136 void Airplane::setApproach(float speed, float altitude, float aoa)
138 _approachSpeed = speed;
139 _approachP = Atmosphere::getStdPressure(altitude);
140 _approachT = Atmosphere::getStdTemperature(altitude);
144 void Airplane::setCruise(float speed, float altitude)
146 _cruiseSpeed = speed;
147 _cruiseP = Atmosphere::getStdPressure(altitude);
148 _cruiseT = Atmosphere::getStdTemperature(altitude);
153 void Airplane::setElevatorControl(int control)
155 _approachElevator.control = control;
156 _approachElevator.val = 0;
157 _approachControls.add(&_approachElevator);
160 void Airplane::addApproachControl(int control, float val)
162 Control* c = new Control();
163 c->control = control;
165 _approachControls.add(c);
168 void Airplane::addCruiseControl(int control, float val)
170 Control* c = new Control();
171 c->control = control;
173 _cruiseControls.add(c);
176 int Airplane::numTanks()
178 return _tanks.size();
181 float Airplane::getFuel(int tank)
183 return ((Tank*)_tanks.get(tank))->fill;
186 float Airplane::getFuelDensity(int tank)
188 return ((Tank*)_tanks.get(tank))->density;
191 void Airplane::setWeight(float weight)
193 _emptyWeight = weight;
196 void Airplane::setWing(Wing* wing)
201 void Airplane::setTail(Wing* tail)
206 void Airplane::addVStab(Wing* vstab)
211 void Airplane::addFuselage(float* front, float* back, float width,
212 float taper, float mid)
214 Fuselage* f = new Fuselage();
217 f->front[i] = front[i];
218 f->back[i] = back[i];
226 int Airplane::addTank(float* pos, float cap, float density)
228 Tank* t = new Tank();
230 for(i=0; i<3; i++) t->pos[i] = pos[i];
233 t->density = density;
234 t->handle = 0xffffffff;
235 return _tanks.add(t);
238 void Airplane::addGear(Gear* gear)
240 GearRec* g = new GearRec();
246 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
248 ThrustRec* t = new ThrustRec();
249 t->thruster = thruster;
252 for(i=0; i<3; i++) t->cg[i] = cg[i];
256 void Airplane::addBallast(float* pos, float mass)
258 _model.getBody()->addMass(mass, pos);
262 int Airplane::addWeight(float* pos, float size)
264 WeightRec* wr = new WeightRec();
265 wr->handle = _model.getBody()->addMass(0, pos);
267 wr->surf = new Surface();
268 wr->surf->setPosition(pos);
269 wr->surf->setTotalDrag(size*size);
270 _model.addSurface(wr->surf);
271 _surfs.add(wr->surf);
273 return _weights.add(wr);
276 void Airplane::setWeight(int handle, float mass)
278 WeightRec* wr = (WeightRec*)_weights.get(handle);
280 _model.getBody()->setMass(wr->handle, mass);
282 // Kill the aerodynamic drag if the mass is exactly zero. This is
283 // how we simulate droppable stores.
285 wr->surf->setXDrag(0);
286 wr->surf->setYDrag(0);
287 wr->surf->setZDrag(0);
289 wr->surf->setXDrag(1);
290 wr->surf->setYDrag(1);
291 wr->surf->setZDrag(1);
295 void Airplane::setFuelFraction(float frac)
298 for(i=0; i<_tanks.size(); i++) {
299 Tank* t = (Tank*)_tanks.get(i);
300 _model.getBody()->setMass(t->handle, t->cap * frac);
304 float Airplane::getDragCoefficient()
309 float Airplane::getLiftRatio()
314 float Airplane::getCruiseAoA()
319 float Airplane::getTailIncidence()
321 return _tailIncidence;
324 char* Airplane::getFailureMsg()
329 int Airplane::getSolutionIterations()
331 return _solutionIterations;
334 void Airplane::setupState(float aoa, float speed, State* s)
336 float cosAoA = Math::cos(aoa);
337 float sinAoA = Math::sin(aoa);
338 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
339 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
340 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
342 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
346 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
348 // Put us 1m above the origin, or else the gravity computation in
353 void Airplane::addContactPoint(float* pos)
355 float* cp = new float[3];
362 float Airplane::compileWing(Wing* w)
364 // The tip of the wing is a contact point
367 addContactPoint(tip);
368 if(w->isMirrored()) {
370 addContactPoint(tip);
373 // Make sure it's initialized. The surfaces will pop out with
374 // total drag coefficients equal to their areas, which is what we
380 for(i=0; i<w->numSurfaces(); i++) {
381 Surface* s = (Surface*)w->getSurface(i);
383 float td = s->getTotalDrag();
386 _model.addSurface(s);
388 float mass = w->getSurfaceWeight(i);
389 mass = mass * Math::sqrt(mass);
392 _model.getBody()->addMass(mass, pos);
398 float Airplane::compileFuselage(Fuselage* f)
400 // The front and back are contact points
401 addContactPoint(f->front);
402 addContactPoint(f->back);
406 Math::sub3(f->front, f->back, fwd);
407 float len = Math::mag3(fwd);
408 float wid = f->width;
409 int segs = (int)Math::ceil(len/wid);
410 float segWgt = len*wid/segs;
412 for(j=0; j<segs; j++) {
413 float frac = (j+0.5f) / segs;
417 scale = f->taper+(1-f->taper) * (frac / f->mid);
419 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
423 Math::mul3(frac, fwd, pos);
424 Math::add3(f->back, pos, pos);
426 // _Mass_ weighting goes as surface area^(3/2)
427 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
428 _model.getBody()->addMass(mass, pos);
431 // Make a Surface too
432 Surface* s = new Surface();
434 float sideDrag = len/wid;
435 s->setYDrag(sideDrag);
436 s->setZDrag(sideDrag);
437 s->setTotalDrag(scale*segWgt);
439 // FIXME: fails for fuselages aligned along the Y axis
441 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
443 y[0] = 0; y[1] = 1; y[2] = 0;
444 Math::cross3(x, y, z);
446 Math::cross3(z, x, y);
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.8f * 10.0f * 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.6f);
510 g->setDynamicFriction(0.5f);
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.5f;
567 _approachWeight = _emptyWeight + totalFuel*0.2f;
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, 0.3f);
589 // Do this after solveGear, because it creates "gear" objects that
590 // we don't want to affect.
591 compileContactPoints();
594 void Airplane::solveGear()
597 _model.getBody()->getCG(cg);
599 // Calculate spring constant weightings for the gear. Weight by
600 // the inverse of the distance to the c.g. in the XY plane, which
601 // should be correct for most gear arrangements. Add 50cm of
602 // "buffer" to keep things from blowing up with aircraft with a
603 // single gear very near the c.g. (AV-8, for example).
606 for(i=0; i<_gears.size(); i++) {
607 GearRec* gr = (GearRec*)_gears.get(i);
610 Math::sub3(cg, pos, pos);
611 gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
615 // Renormalize so they sum to 1
616 for(i=0; i<_gears.size(); i++)
617 ((GearRec*)_gears.get(i))->wgt /= total;
619 // The force at max compression should be sufficient to stop a
620 // plane moving downwards at 3x the approach descent rate. Assume
621 // a 3 degree approach.
622 float descentRate = 3.0f*_approachSpeed/19.1f;
624 // Spread the kinetic energy according to the gear weights. This
625 // will results in an equal compression fraction (not distance) of
627 float energy = 0.5f*_approachWeight*descentRate*descentRate;
629 for(i=0; i<_gears.size(); i++) {
630 GearRec* gr = (GearRec*)_gears.get(i);
631 float e = energy * gr->wgt;
633 gr->gear->getCompression(comp);
634 float len = Math::mag3(comp);
636 // Energy in a spring: e = 0.5 * k * len^2
637 float k = 2 * e / (len*len);
639 gr->gear->setSpring(k);
641 // Critically damped (too damped, too!)
642 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
644 // These are pretty generic
645 gr->gear->setStaticFriction(0.8f);
646 gr->gear->setDynamicFriction(0.7f);
650 void Airplane::initEngines()
652 for(int i=0; i<_thrusters.size(); i++) {
653 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
654 tr->thruster->init();
658 void Airplane::stabilizeThrust()
661 for(i=0; i<_thrusters.size(); i++)
662 _model.getThruster(i)->stabilize();
665 void Airplane::runCruise()
667 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
668 _model.setState(&_cruiseState);
669 _model.setAir(_cruiseP, _cruiseT);
671 // The control configuration
674 for(i=0; i<_cruiseControls.size(); i++) {
675 Control* c = (Control*)_cruiseControls.get(i);
676 _controls.setInput(c->control, c->val);
678 _controls.applyControls(1000000); // Huge dt value
682 Math::mul3(-1, _cruiseState.v, wind);
683 Math::vmul33(_cruiseState.orient, wind, wind);
685 // Cruise is by convention at 50% tank capacity
686 setFuelFraction(0.5);
688 // Set up the thruster parameters and iterate until the thrust
690 for(i=0; i<_thrusters.size(); i++) {
691 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
693 t->setAir(_cruiseP, _cruiseT);
699 // Precompute thrust in the model, and calculate aerodynamic forces
700 _model.getBody()->reset();
701 _model.initIteration();
702 _model.calcForces(&_cruiseState);
705 void Airplane::runApproach()
707 setupState(_approachAoA, _approachSpeed, &_approachState);
708 _model.setState(&_approachState);
709 _model.setAir(_approachP, _approachT);
711 // The control configuration
714 for(i=0; i<_approachControls.size(); i++) {
715 Control* c = (Control*)_approachControls.get(i);
716 _controls.setInput(c->control, c->val);
718 _controls.applyControls(1000000);
722 Math::mul3(-1, _approachState.v, wind);
723 Math::vmul33(_approachState.orient, wind, wind);
725 // Approach is by convention at 20% tank capacity
726 setFuelFraction(0.2f);
728 // Run the thrusters until they get to a stable setting. FIXME:
729 // this is lots of wasted work.
730 for(i=0; i<_thrusters.size(); i++) {
731 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
733 t->setAir(_approachP, _approachT);
739 // Precompute thrust in the model, and calculate aerodynamic forces
740 _model.getBody()->reset();
741 _model.initIteration();
742 _model.calcForces(&_approachState);
745 void Airplane::applyDragFactor(float factor)
747 float applied = Math::sqrt(factor);
748 _dragFactor *= applied;
749 _wing->setDragScale(_wing->getDragScale() * applied);
750 _tail->setDragScale(_tail->getDragScale() * applied);
752 for(i=0; i<_vstabs.size(); i++) {
753 Wing* w = (Wing*)_vstabs.get(i);
754 w->setDragScale(w->getDragScale() * applied);
756 for(i=0; i<_surfs.size(); i++) {
757 Surface* s = (Surface*)_surfs.get(i);
758 s->setTotalDrag(s->getTotalDrag() * applied);
762 void Airplane::applyLiftRatio(float factor)
764 float applied = Math::sqrt(factor);
765 _liftRatio *= applied;
766 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
767 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
769 for(i=0; i<_vstabs.size(); i++) {
770 Wing* w = (Wing*)_vstabs.get(i);
771 w->setLiftRatio(w->getLiftRatio() * applied);
775 float Airplane::clamp(float val, float min, float max)
777 if(val < min) return min;
778 if(val > max) return max;
782 float Airplane::normFactor(float f)
789 void Airplane::solve()
791 static const float ARCMIN = 0.0002909f;
794 _solutionIterations = 0;
797 if(_solutionIterations++ > 10000) {
798 _failureMsg = "Solution failed to converge after 10000 iterations";
802 // Run an iteration at cruise, and extract the needed numbers:
805 _model.getThrust(tmp);
806 float thrust = tmp[0];
808 _model.getBody()->getAccel(tmp);
809 float xforce = _cruiseWeight * tmp[0];
810 float clift0 = _cruiseWeight * tmp[2];
812 _model.getBody()->getAngularAccel(tmp);
813 float pitch0 = tmp[1];
815 // Run an approach iteration, and do likewise
818 _model.getBody()->getAngularAccel(tmp);
819 float apitch0 = tmp[1];
821 _model.getBody()->getAccel(tmp);
822 float alift = _approachWeight * tmp[2];
824 // Modify the cruise AoA a bit to get a derivative
825 _cruiseAoA += ARCMIN;
827 _cruiseAoA -= ARCMIN;
829 _model.getBody()->getAccel(tmp);
830 float clift1 = _cruiseWeight * tmp[2];
832 // Do the same with the tail incidence
833 _tail->setIncidence(_tailIncidence + ARCMIN);
835 _tail->setIncidence(_tailIncidence);
837 _model.getBody()->getAngularAccel(tmp);
838 float pitch1 = tmp[1];
841 float awgt = 9.8f * _approachWeight;
843 float dragFactor = thrust / (thrust-xforce);
844 float liftFactor = awgt / (awgt+alift);
845 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
846 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
849 if(dragFactor <= 0) {
850 _failureMsg = "Zero or negative drag adjustment.";
852 } else if(liftFactor <= 0) {
853 _failureMsg = "Zero or negative lift adjustment.";
857 // And the elevator control in the approach. This works just
858 // like the tail incidence computation (it's solving for the
859 // same thing -- pitching moment -- by diddling a different
861 const float ELEVDIDDLE = 0.0001f;
862 _approachElevator.val += ELEVDIDDLE;
864 _approachElevator.val -= ELEVDIDDLE;
866 _model.getBody()->getAngularAccel(tmp);
867 float apitch1 = tmp[1];
868 float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
870 // Now apply the values we just computed. Note that the
871 // "minor" variables are deferred until we get the lift/drag
872 // numbers in the right ballpark.
874 applyDragFactor(dragFactor);
875 applyLiftRatio(liftFactor);
877 // DON'T do the following until the above are sane
878 if(normFactor(dragFactor) > 1.1
879 || normFactor(liftFactor) > 1.1)
884 // OK, now we can adjust the minor variables:
885 _cruiseAoA += 0.5f*aoaDelta;
886 _tailIncidence += 0.5f*tailDelta;
887 _approachElevator.val += 0.5f*elevDelta;
889 _cruiseAoA = clamp(_cruiseAoA, -0.174f, 0.174f);
890 _tailIncidence = clamp(_tailIncidence, -0.174f, 0.174f);
891 _approachElevator.val = clamp(_approachElevator.val, -1.f, 1.f);
893 if(norm(dragFactor) < 1.00001 &&
894 norm(liftFactor) < 1.00001 &&
895 abs(aoaDelta) < .000017 &&
896 abs(tailDelta) < .000017 &&
897 abs(elevDelta) < 0.00001)
903 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
904 _failureMsg = "Drag factor beyond reasonable bounds.";
906 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
907 _failureMsg = "Lift ratio beyond reasonable bounds.";
909 } else if(Math::abs(_cruiseAoA) >= .174) {
910 _failureMsg = "Cruise AoA > 10 degrees";
912 } else if(Math::abs(_tailIncidence) >= .174) {
913 _failureMsg = "Tail incidence > 10 degrees";
917 }; // namespace yasim