Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/OrbitEntryControlTests.h

Source at documentation-generation time. See Test catalog for fixture associations.

1#pragma once
2#include "BillEntryFixture.h"
3
4// Independent body-axis plant: actual attitude, engine rate limit, reverser
5// travel, translation filter, mass loss and nonzero aero-model error. The
6// trajectory is never assigned to the simulated vessel.
7Vec EntryPlantAero(const Input& in,const BodyFrame& f,double multiplier)
8{
9 const auto air=EntryPhysics::Atmosphere(in,in.own);
10 const Vec body=InBody(f,air.velocity);
11 const double angle=std::atan2(-body.y,body.z);
12 const double index=(std::clamp)((angle*180/Pi+4)/2,0.0,7.99999);
13 const auto& a=in.entryAero[size_t(index)];const auto& b=in.entryAero[size_t(index)+1];
14 auto mix=[&](double x,double y){return x+(y-x)*(index-std::floor(index));};
15 const double q=air.effectiveDensity*.003085346*std::pow(body.z*EntryPhysics::FeetPerKm,2)*EntryPhysics::PsfToPa;
16 const double drag=in.bodyDragAcceleration*in.massKg*air.effectiveDensity;
17 const double forward=-std::copysign(drag*body.z*body.z+q*(in.wingAreaM2*mix(a.cd,b.cd)+mix(a.tailDragArea,b.tailDragArea))/1000,body.z);
18 const double vertical=-drag*in.entryVehicle.normalDragRatio*body.y*std::abs(body.y)+
19 q*(in.wingAreaM2*mix(a.cl,b.cl)+mix(a.tailLiftArea,b.tailLiftArea))/1000;
20 return (f.forward*forward+f.up*vertical+f.right*(-drag*2*body.x*std::abs(body.x)))*multiplier;
21}
22struct EntryFlightResult {
23 double seconds=0,minimumAltitude=0,tas=0,fuel=0,peakIas=0,peakAft=0,peakMain=0,coastIdleSeconds=0;
24 Input finalInput;
25};
26EntryFlightResult FlyEntry(double arrival,double massScale=1,double aeroError=1,double windKms=0,bool runway=false,const Input* recorded=nullptr,
27 const Plan* frozen=nullptr,bool timingGaps=false)
28{
29 auto in=recorded?*recorded:BillEntryFixture();
30 const double epoch=in.now;
31 const double bodyForce=in.bodyDragAcceleration*in.massKg;
32 in.massKg*=massScale;in.bodyDragAcceleration=bodyForce/in.massKg;
33 const Vec initialWind=recorded?in.entryVehicle.wind:Vec{windKms,0,0};
34 in.entryVehicle.wind=initialWind;
35 RotationState rotation;rotation.effort=1;
37 rotation.frame=RotationFrame(q);in.entryVehicle.nose=rotation.frame.forward;
38 Request request;request.entryOrigin=true;request.passTime=PassTime::Manual;request.arrivalEpoch=in.now+arrival;
39 if(recorded&&!frozen) request.final=Final::Ils;
40 if(runway) {
41 request.final=Final::Visual;in.arrivalSite.runway=true;in.arrivalSite.threshold=in.target.r;
42 const Vec normal=Unit(Cross(in.own.r,in.target.r));
43 in.arrivalSite.heading=ArrivalPlanning::AircraftHeading(in.target.r,Cross(normal,Unit(in.target.r)))+15*Pi/180;
44 }
45 Snapshot snapshot;
46 if(frozen) {snapshot.mode=Mode::Return;snapshot.plan=*frozen;}
47 else snapshot=Solve(in,request);
48 std::wcout<<L"Entry plant plan: "<<snapshot.plan.surface.reason<<L" AFT "<<snapshot.plan.entry.peakAftC<<L" IAS "<<snapshot.plan.entry.peakIasFraction<<L"\n";
49 Check(snapshot.plan.valid&&!snapshot.plan.planningOnly,"Bill entry fixture has an executable profile");
50 Executor executor;AttitudeController attitude;Guidance g=executor.Begin(in,request,snapshot);
51 double output=0,reverser=0;bool reverseCommand=false;Vec filtered;
52 double maxIas=0,maxHeat=0,maxError=0,minAltitude=1e10;int guards=0,align=0,step=0,gaps=0;
53 double peakMain=0,coastIdle=0,peakLoad=0;
54 constexpr double dt=.1;const double initialFuel=in.fuelKg;
55 for(;step<int((arrival+300)/dt)&&executor.Active();++step) {
56 auto& ev=in.entryVehicle;
57 ev.wind=Rotate(initialWind,{0,0,1},in.spin*(in.now-epoch));
58 ev.airVelocity=in.own.v-Cross({0,0,in.spin},in.own.r)-EntryPhysics::Wind(in,in.own.r);ev.nose=rotation.frame.forward;
59 in.bodyUp=rotation.frame.up;
60 ev.aoa=std::atan2(-Dot(ev.airVelocity,rotation.frame.up),Dot(ev.airVelocity,rotation.frame.forward));
61 ev.aeroAcceleration=EntryPlantAero(in,rotation.frame,aeroError)/in.massKg;ev.aeroValid=true;
62 ev.temperatureK=EntryPhysics::NominalTemperature(Norm(in.own.r)-in.radius);
63 if(step%2==0) {
64 bool stale=false;
65 if(timingGaps&&((gaps==0&&in.now-epoch>=73.1)||(gaps==1&&in.now-epoch>=601))) {
66 // Recorded long frames skip vehicle physics but advance the
67 // mission clock. The first module sample is stale; the next
68 // physical sample permits recapture of the unchanged plan.
69 in.now+=gaps==0?1.2907:2.564;++gaps;stale=true;
70 }
71 rotation.acceleration=RotationAuthority(in.massKg*2.20462262,124.982147,186.511765,71.806427,16.714558,48.750797,1,1,1,1);
72 Input sensed=in;const double angle=in.spin*(in.now-epoch);
73 auto fixed=[&](Vec v){return Rotate(v,{0,0,1},-angle);};
74 sensed.own={fixed(in.own.r),fixed(in.own.v)};
75 sensed.bodyUp=fixed(in.bodyUp);sensed.entryVehicle.aeroAcceleration=fixed(ev.aeroAcceleration);
76 sensed.entryVehicle.nose=fixed(ev.nose);sensed.entryVehicle.airVelocity=fixed(ev.airVelocity);sensed.entryVehicle.wind=fixed(ev.wind);
77 sensed.entryVehicle.deliveredAcceleration=fixed(ev.deliveredAcceleration);
78 if(stale) {sensed.entryVehicle.airValid=false;sensed.entryVehicle.airAge=2.564;}
79 g=executor.Step(sensed,request);
80 if(stale) Check(g.valid&&!g.thrust&&!g.attitude&&executor.EntryActive()&&g.status==L"ENTRY DATA WAIT",
81 "frame gap retains the entry plan with all commands inhibited");
82 g.pointing=Rotate(g.pointing,{0,0,1},angle);g.accelerationCommand=Rotate(g.accelerationCommand,{0,0,1},angle);
83 g.coastRotation=HorizonRotation(in.own,0);
84 Check(attitude.Step(g,rotation,in.own.r,.2),"entry attitude remains controllable");
85 if(g.entryLimited) {
86 if(guards<3) std::wcout<<L"Entry guard "<<g.status<<L" t "<<in.now-epoch<<L" load "<<g.entryForecastLoadFraction<<L" skip "<<g.entrySkipRisk<<L"\n";
87 ++guards;
88 }
89 if(g.phase==Phase::Align) ++align;
90 }
91 const Vec command=g.thrust?InBody(rotation.frame,g.accelerationCommand):Vec{};
92 const double density=std::exp(-(Norm(in.own.r)-in.radius)/in.scaleHeight),eff=1+(in.seaLevelEfficiency-1)*density;
93 const auto main=EntryControl::MainEngine(command.z,in.entryForwardKN*eff/in.massKg,in.entryReverseKN*eff/in.massKg,output,reverser,reverseCommand);
94 reverseCommand=main.reverse;
95 reverser=(std::clamp)(reverser+(main.reverse?dt*.5:-dt*.5),0.0,1.0);
96 output+=(std::clamp)(main.lever-output,-dt/ev.spoolSeconds,dt/ev.spoolSeconds);
97 peakMain=(std::max)(peakMain,output);
98 if(EntryProfile::Coasting(snapshot.plan.entry,in.now-epoch)&&output<.02) coastIdle+=dt;
99 filtered=filtered+(command-filtered)*dt;
100 const double x=(std::clamp)(filtered.x,-in.entrySideKN/in.massKg,in.entrySideKN/in.massKg);
101 const double y=(std::clamp)(filtered.y,-in.entryDownKN/in.massKg,in.entryUpKN/in.massKg);
102 const double z=(in.entryForwardKN*(1-reverser)-in.entryReverseKN*reverser)*eff/in.massKg*output;
103 const Vec thrust=rotation.frame.right*x+rotation.frame.up*y+rotation.frame.forward*z;
104 ev.deliveredAcceleration=thrust;
105 const auto air=EntryPhysics::Atmosphere(in,in.own);
106 ev.aftC=EntryPhysics::Heat(ev,air,ev.aftC,dt);
107 maxHeat=(std::max)(maxHeat,ev.aftC);maxIas=(std::max)(maxIas,air.ias/in.vneKms);
108 const auto aero=EntryPlantAero(in,rotation.frame,aeroError);
109 peakLoad=(std::max)(peakLoad,EntryEnvelope::Fraction(in,EntryEnvelope::BodyG(thrust+aero/in.massKg,rotation.frame.forward,rotation.frame.up)));
110 Check(peakLoad<1,"physical entry remains below occupant and wing damage thresholds");
111 in.own=PoweredStep(in.own,thrust+aero/in.massKg,dt,in.gm);in.now+=dt;
112 minAltitude=(std::min)(minAltitude,Norm(in.own.r)-in.radius);
113 const double flow=in.idleFlowKgS+(in.flowKgS-in.idleFlowKgS)*
114 (output+(std::abs(x)+std::abs(y))*in.massKg/in.thrustKN);
115 in.fuelKg-=flow*dt;in.massKg-=flow*dt;in.bodyDragAcceleration=bodyForce/in.massKg;
116 BusState control;control.guidance=g;control.sourceTime=in.now;
117 const Vec turn=g.phase==Phase::Wait||g.phase==Phase::Coast?CoastRotationCommand(control,in.now,rotation,{}):g.rotationCommand;
118 RotateVehicle(q,rotation,turn,dt);
119 // Small unmodeled atmospheric pitching moment, absent from the inverse profile.
120 rotation.rates.x+=.00002*(std::min)(1.0,air.q/5000)*dt;
121 if(g.thrust) maxError=(std::max)(maxError,g.positionErrorKm);
122 Check(Norm(in.own.r)>in.radius+15&&in.fuelKg>0,"entry plant keeps terrain reserve and fuel");
123 }
124 const double finalTas=Norm(in.own.v-Cross({0,0,in.spin},in.own.r)-EntryPhysics::Wind(in,in.own.r));
125 std::wcout<<L"Entry plant: "<<g.status<<L" time "<<in.now-epoch<<L" h "<<Norm(in.own.r)-in.radius<<
126 L" min h "<<minAltitude<<L" speed "<<finalTas<<L" error "<<g.positionErrorKm<<L" IAS "<<maxIas<<L" AFT "<<maxHeat<<
127 L" fuel "<<initialFuel-in.fuelKg<<L" main "<<peakMain<<L" coast idle "<<coastIdle<<
128 L" guards "<<guards<<L" align "<<align<<L" max error "<<maxError<<L" peak load fraction "<<peakLoad<<L"\n";
129 Check(g.entryHandoff&&g.phase==Phase::Complete,"finite-actuator entry reaches handoff instead of an expired rendezvous");
130 Check(minAltitude>=snapshot.plan.entry.handoffAltitudeKm-(snapshot.plan.entry.handoffFpa<0?.1:.05),"entry never sinks through handoff altitude tolerance");
131 if(timingGaps) Check(gaps==2,"recovery flight exercises both recorded long-frame interruptions");
132 Check(std::abs(finalTas-snapshot.plan.entry.handoffSpeedKms)<.005,"entry handoff reaches selected measured TAS tolerance");
133 Check(maxIas<EntryPhysics::IasReserve&&maxHeat<EntryPhysics::AftLimitC,"entry plant respects IAS reserve and selected heat margin");
134 if(snapshot.plan.entry.handoffFpa<0)
135 Check(Dot(in.own.v,Unit(in.own.r))<-.01,"runway handoff retains descent rather than leveling at 30km");
136 auto fixed=[&](Vec v){return Rotate(v,{0,0,1},-in.spin*(in.now-epoch));};
137 auto end=in;end.own={fixed(in.own.r),fixed(in.own.v)};end.bodyUp=fixed(in.bodyUp);
138 end.entryVehicle.wind=fixed(in.entryVehicle.wind);end.entryVehicle.nose=fixed(in.entryVehicle.nose);
139 end.entryVehicle.airVelocity=end.own.v-Cross({0,0,in.spin},end.own.r)-EntryPhysics::Wind(end,end.own.r);
140 return {in.now-epoch,minAltitude,finalTas,initialFuel-in.fuelKg,maxIas,maxHeat,peakMain,coastIdle,end};
141}
142void EntryControlTests()
143{
144 FlyEntry(2400);
145 FlyEntry(2400,1,1.10,.015);
146 FlyEntry(4800,1.8,.9);
147 FlyEntry(4800,1,1,0,true);
148 auto in=BillEntryFixture();Request r;r.entryOrigin=true;r.arrivalEpoch=in.now+2400;
149 const auto plan=Solve(in,r);
150 Check(plan.plan.entry.samples.front().aftC>0&&plan.plan.entry.samples.front().iasKms>0,
151 "coast reference records heat and IAS instead of zero placeholders");
152 for(int fault=0;fault<6;++fault) {
153 Executor ex;Check(ex.Begin(in,r,plan).valid,"entry can be armed for state-change regression");
154 auto bad=in;auto changed=r;
155 if(fault==0) bad.entryVehicle.airAge=1;
156 if(fault==1) bad.entryVehicle.aftC=NAN;
157 if(fault==2) bad.entryReverseKN=0;
158 if(fault==3) bad.entryVehicle.clean=false;
159 if(fault==4) ++changed.revision;
160 if(fault==5) bad.targetId++;
161 const auto g=ex.Step(bad,changed);
162 if(fault==0) {
163 Check(g.valid&&!g.thrust&&!g.attitude&&ex.EntryActive()&&g.status==L"ENTRY DATA WAIT",
164 "stale entry air data inhibits commands without canceling the accepted mission");
165 Check(ex.Step(in,r).valid&&ex.EntryActive(),"fresh entry air data resumes the same mission");
166 } else Check(!g.valid&&!g.thrust&&!ex.Active()&&g.phase==Phase::Abort,"entry rejects invalid, unavailable or changed control state");
167 }
168 auto urgent=r;urgent.arrivalEpoch=in.now+600;
169 Check(!Solve(in,urgent).plan.valid,"earlier arrival cannot override IAS/heat/thrust constraints");
170 const double time=plan.plan.end-100;
171 auto actual=in;actual.own=EntryControl::InCurrentFrame(plan.plan,time,in.spin,in.gm).state;
172 actual.entryVehicle.airVelocity=actual.own.v-Cross({0,0,in.spin},actual.own.r);
173 actual.entryVehicle.temperatureK=EntryPhysics::NominalTemperature(Norm(actual.own.r)-in.radius);
174 actual.entryVehicle.aftC=210;
175 Vec integral;const auto guarded=EntryControl::Command(actual,plan.plan,time,integral,.2);
176 Check(guarded.valid&&guarded.thrust&&guarded.entryLimited,"hot entry actively brakes instead of dropping into an unpowered coast");
177 Check(Dot(guarded.accelerationCommand,Unit(actual.entryVehicle.airVelocity))<0,"thermal protection requests nose-first reverse thrust");
178 for(bool reverse:{false,true}) {
179 const double sign=reverse?-1:1;
180 const auto unload=EntryControl::MainEngine(sign*.01,.02,.01,.8,reverse?0:1);
181 Check(unload.lever==0&&unload.reverse!=reverse,"reversal idles before moving a loaded bucket");
182 const auto transit=EntryControl::MainEngine(sign*.01,.02,.01,0,.5);
183 Check(transit.lever==0&&transit.reverse==reverse,"reverser travel stays unpowered");
184 const auto ready=EntryControl::MainEngine(sign*.01,.02,.01,0,reverse?1:0);
185 Check(ready.lever>0&&ready.lever<=1&&ready.reverse==reverse,"settled bucket enables bounded force");
186 }
187 struct Controls {
188 enum Vertical {AltitudeMsl,FlightPathAngle};enum Lateral {Heading,Navigation};
189 bool DorOn=true,TvmOn=false,AutopilotEngaged=false,AutothrottleEngaged=false;
190 double DesiredAltitudeKm=0,DesiredTasKms=0,DesiredHeadingRadians=0,DesiredRadians=0,DesiredCourseRadians=0,DesiredFpaRadians=0;
191 Vertical CurrentVerticalMode=AltitudeMsl;Lateral CurrentLateralMode=Heading;
192 } afcs;
193 Guidance complete;complete.entryHandoff=true;complete.phase=Phase::Complete;int sounds=0;
194 auto disconnect=[&]{afcs.DorOn=false;++sounds;};
195 Check(!FinishEntryExecution(in,r,complete,true,afcs,disconnect)&&afcs.DorOn,"freeze does not hand off early");
196 Check(FinishEntryExecution(in,r,complete,false,afcs,disconnect),"achieved handoff engages aircraft modes");
197 Check(!afcs.DorOn&&afcs.AutopilotEngaged&&afcs.AutothrottleEngaged&&!afcs.TvmOn&&sounds==1&&
198 afcs.DesiredAltitudeKm==30&&afcs.DesiredTasKms==.5,"handoff engages altitude heading and TAS hold with one disconnect sound");
199 Check(!FinishEntryExecution(in,r,complete,false,afcs,disconnect)&&sounds==1,"handoff cannot rearm after pilot takeover");
200 // Speed hold has a real thrust loop: lag, drag bias and both speed directions.
201 for(double initial:{.43,.58}) {
202 auto hold=in;hold.spin=0;hold.own={{hold.radius+30,0,0},{0,initial,0}};
203 hold.entryVehicle.nose={0,1,0};double errorIntegral=0,output=0,reverser=0;
204 for(int j=0;j<4000;++j) {
205 hold.entryVehicle.airVelocity=hold.own.v;hold.entryVehicle.temperatureK=EntryPhysics::NominalTemperature(30);
206 const double wanted=EntryControl::SpeedHold(hold,.5,errorIntegral,.1);
207 const auto main=EntryControl::MainEngine(wanted,in.entryForwardKN/in.massKg,in.entryReverseKN/in.massKg,output,reverser);
208 output+=(std::clamp)(main.lever-output,-.1/5.8,.1/5.8);reverser=(std::clamp)(reverser+(main.reverse?.05:-.05),0.0,1.0);
209 const auto air=EntryPhysics::Atmosphere(hold,hold.own);
210 const double drag=Dot(EntryPhysics::AerodynamicForce(hold,air,EntryPhysics::EntryAero(hold),hold.own.r),hold.entryVehicle.nose)*1.1/hold.massKg;
211 hold.own.v.y+=((1-2*reverser)*output*in.entryForwardKN/in.massKg+drag)*.1;
212 }
213 Check(std::abs(hold.own.v.y-.5)<.003,"throttle TAS hold converges despite spool and drag mismatch");
214 }
215}
SCRIPT_CONTROL SCRIPT_STATE const void int
float fuel
Definition globals.cpp:90
bool Unit(Vector3 &v)
float Dot(const Vector3 &a, const Vector3 &b)
double Heading(Vec position, Vec direction)
Plan Solve(const Input &in, const Request &r, bool geometry)
Definition OrbitEntry.h:332
Vec CoastRotationCommand(const BusState &data, double now, const RotationState &in, Vec pilot)
Vec HorizonRotation(State own, double spin)
Vec InBody(const BodyFrame &f, Vec v)
Vec Rotate(Vec v, Vec axis, double angle)
Definition OrbitMath.h:22
constexpr double Pi
Definition OrbitMath.h:10
Vec RotationAuthority(double weight, double pitchInertia, double yawInertia, double rollInertia, double arm, double span, double leftWing, double rightWing, double effort, double wear)
double Norm(Vec a)
Definition OrbitMath.h:18
Vec Cross(Vec a, Vec b)
Definition OrbitMath.h:17
bool FinishEntryExecution(const Input &in, const Request &r, Guidance &g, bool frozen, Afcs &afcs, Disconnect stopDor)
Quaternion * QuaternionRotationYawPitchRoll(Quaternion *out, float yaw, float pitch, float roll)
Definition ClientMath.h:169