namespace XFEEDToolBox.Core.Navigation;
public readonly record struct AttitudeInput(double Yaw,double Pitch,double Roll,double ErrorDegrees)
{
public double YawErrorDegrees{get;init;}
public double PitchErrorDegrees{get;init;}
public double RollErrorDegrees{get;init;}
}
/// <summary>Ship-local yaw/pitch steering. Axis signs are pinned to actual native input tests.</summary>
public static class AttitudeController
{
public static double FastAxis(double errorDegrees,double measuredRateDegreesPerSecond)
{
if(!double.IsFinite(errorDegrees)||!double.IsFinite(measuredRateDegreesPerSecond))throw new ArgumentException("Invalid angular state.");
return Math.Abs(errorDegrees)<.04&&Math.Abs(measuredRateDegreesPerSecond)<.15?0:Math.Clamp(errorDegrees*.18-measuredRateDegreesPerSecond*.065,-1,1);
}
public static AttitudeInput Aim(Vector3d forward,Vector3d up,Vector3d direction,double maximumAxis=.12)
{
if(!forward.Finite||!up.Finite||!direction.Finite||!double.IsFinite(maximumAxis)||maximumAxis<=0||maximumAxis>1)
throw new ArgumentException("Invalid attitude input or authority limit.");
var f=forward.Unit();var right=Vector3d.Cross(up.Unit(),f).Unit();var u=Vector3d.Cross(f,right).Unit();var wanted=direction.Unit();
var x=Vector3d.Dot(wanted,right);var y=Vector3d.Dot(wanted,u);var z=Vector3d.Dot(wanted,f);
var yaw=Math.Atan2(x,z)*180/Math.PI;
var pitch=-Math.Atan2(y,Math.Sqrt(x*x+z*z))*180/Math.PI;
static double Axis(double error,double limit)=>Math.Abs(error)<.06?0:Math.Clamp(error*.018,-limit,limit);
return new(Axis(yaw,maximumAxis),Axis(pitch,maximumAxis),0,Vector3d.AngleDegrees(f,wanted));
}
public static AttitudeInput AimBanked(Vector3d forward,Vector3d up,Vector3d direction,Vector3d preferredUp,Vector3d localAngularRate=default)
{
if(!forward.Finite||!up.Finite||!direction.Finite||!preferredUp.Finite||!localAngularRate.Finite)throw new ArgumentException("Invalid banked attitude.");
var f=forward.Unit();var r=Vector3d.Cross(up.Unit(),f).Unit();var u=Vector3d.Cross(f,r).Unit();var wanted=direction.Unit();
var desiredUp=FlightGeometry.Perpendicular(wanted,preferredUp);
var bankUp=desiredUp-f*Vector3d.Dot(desiredUp,f);
if(bankUp.Length<.2)
{
// When facing the star, its projection is initially undefined.
// The orbit plane's right vector gives a continuous pitch plane.
var desiredRight=Vector3d.Cross(desiredUp,wanted).Unit();
bankUp=Vector3d.Cross(f,FlightGeometry.Perpendicular(f,desiredRight));
}
bankUp=bankUp.Unit();
var roll=Math.Atan2(Vector3d.Dot(f,Vector3d.Cross(u,bankUp)),Vector3d.Dot(u,bankUp))*180/Math.PI;
var x=Vector3d.Dot(wanted,r);var y=Vector3d.Dot(wanted,u);var z=Vector3d.Dot(wanted,f);
var yaw=Math.Atan2(x,z)*180/Math.PI;var pitch=-Math.Atan2(y,Math.Sqrt(x*x+z*z))*180/Math.PI;
return new(FastAxis(yaw,localAngularRate.X),FastAxis(pitch,localAngularRate.Y),FastAxis(roll,localAngularRate.Z),Vector3d.AngleDegrees(f,wanted)){YawErrorDegrees=yaw,PitchErrorDegrees=pitch,RollErrorDegrees=roll};
}
}
/// <summary>Application-side three-axis control using pose-derived rates; no game access.</summary>
public sealed class BankedAttitudeController
{
private FlightFrame? previous;
private Vector3d rates,command;
private bool ratesKnown;
private bool bankReliable=true,rollSettled;
private Vector3d? antipodalTurnAxis;
private int antipodalRollSign;
private sealed class ResponseProfile
{
public AdaptiveAttitudeAxis[] Axes{get;}=[new(),new(),new()];
public double SpeedFraction{get;set;}
}
private readonly Dictionary<(string Ship,bool Cruise,int Pips),ResponseProfile> profiles=[];
private AdaptiveAttitudeAxis[]? axes;
private ResponseProfile? profile;
private (string Ship,bool Cruise,int Pips)? context;
private DateTimeOffset origin;
public IReadOnlyList<AxisResponse> Responses=>axes?.Select(a=>a.Model.Response).ToArray()??[];
public void Reset(){previous=null;rates=command=Vector3d.Zero;ratesKnown=false;bankReliable=true;rollSettled=false;antipodalTurnAxis=null;antipodalRollSign=0;foreach(var axis in axes??[])axis.BreakObservation();}
public void ConfirmApplied(DateTimeOffset at,AttitudeInput input)
{
if(axes is null||previous is null)return;
var time=(at-origin).TotalSeconds;
axes[0].Model.Acknowledge(time,input.Yaw);axes[1].Model.Acknowledge(time,input.Pitch);axes[2].Model.Acknowledge(time,input.Roll);
command=new(input.Yaw,input.Pitch,input.Roll);
}
public AttitudeInput Update(FlightFrame frame,Vector3d direction,Vector3d preferredUp,Vector3d? originalAngularRate=null,bool controlRoll=true)
{
var nextContext=(frame.LoadoutFingerprint,frame.InSupercruise,frame.EnginePips??-1);
if(context!=nextContext)
{
Reset();context=nextContext;origin=frame.ObservedAt;
if(!profiles.TryGetValue(nextContext,out profile))
{
if(profiles.Count>=128)profiles.Remove(profiles.Keys.First());
profile=new(){SpeedFraction=frame.SpeedFraction};profiles.Add(nextContext,profile);
}
axes=profile.Axes;
foreach(var axis in axes)axis.BreakObservation();
}
if(Math.Abs(frame.SpeedFraction-profile!.SpeedFraction)>.2)
{
foreach(var axis in axes!)axis.Model.Relearn();
profile.SpeedFraction=frame.SpeedFraction;
}
var f=frame.Forward.Unit();var r=Vector3d.Cross(frame.Up.Unit(),f).Unit();var u=Vector3d.Cross(f,r).Unit();
var dt=previous is {} p?(frame.ObservedAt-p.ObservedAt).TotalSeconds:0;
var continuous=previous is {} before&&before.SystemAddress==frame.SystemAddress&&frame.Sequence>before.Sequence&&dt is >=.002 and <=.3;
if(continuous)
{
var oldForward=previous!.Forward.Unit();var oldRight=Vector3d.Cross(previous.Up.Unit(),oldForward).Unit();var oldUp=Vector3d.Cross(oldForward,oldRight).Unit();
var angle=Math.Acos(Math.Clamp((Vector3d.Dot(oldRight,r)+Vector3d.Dot(oldUp,u)+Vector3d.Dot(oldForward,f)-1)*.5,-1,1));
if(angle<.5)
{
var omega=(Vector3d.Cross(oldRight,r)+Vector3d.Cross(oldUp,u)+Vector3d.Cross(oldForward,f))*.5;
omega*=((angle>1e-6?angle/Math.Sin(angle):1)*180/Math.PI/dt);
var measured=new Vector3d(Vector3d.Dot(omega,u),Vector3d.Dot(omega,r),Vector3d.Dot(omega,f));
var alpha=1-Math.Exp(-dt/.035);rates=ratesKnown?rates+(measured-rates)*alpha:measured;ratesKnown=true;
}
else{rates=Vector3d.Zero;ratesKnown=false;}
}
else{rates=command=Vector3d.Zero;ratesKnown=false;dt=.05;antipodalTurnAxis=null;antipodalRollSign=0;foreach(var axis in axes!)axis.BreakObservation();}
// Original rigid-body rates avoid differentiating rounded or changing
// reference-frame poses during local supercruise. Other callers retain
// the independently tested pose-derived fallback.
var native=originalAngularRate??frame.AngularVelocityDegrees;
if(native is {Finite:true} actual&&actual.Length<600&&(actual.Length>.01||!ratesKnown||rates.Length<.5)){rates=actual;ratesKnown=true;}
if(ratesKnown)
{
var time=(frame.ObservedAt-origin).TotalSeconds;
axes![0].Model.Observe(time,rates.X);axes[1].Model.Observe(time,rates.Y);axes[2].Model.Observe(time,rates.Z);
}
var wanted=AttitudeController.AimBanked(f,u,direction,preferredUp,rates);
// A spherical direction error has no yaw singularity at an overhead
// target. atan2(x,z) alone can flip by 180 degrees there. At the exact
// antipode keep one world-space turn plane until it becomes observable.
var goal=direction.Unit();var cosine=Vector3d.Dot(f,goal);var turn=Vector3d.Cross(f,goal);
if(cosine<-.99&&antipodalTurnAxis is null)
antipodalTurnAxis=turn.Length>.02?turn.Unit():r;
else if(cosine>-.95)antipodalTurnAxis=null;
var turnAxis=antipodalTurnAxis is {} fixedAxis?FlightGeometry.Perpendicular(f,fixedAxis):turn.Length>1e-7?turn.Unit():Vector3d.Zero;
wanted=wanted with{YawErrorDegrees=wanted.ErrorDegrees*Vector3d.Dot(turnAxis,u),PitchErrorDegrees=wanted.ErrorDegrees*Vector3d.Dot(turnAxis,r)};
if(Math.Abs(wanted.RollErrorDegrees)>170&&antipodalRollSign==0)antipodalRollSign=Math.Sign(wanted.RollErrorDegrees);
else if(Math.Abs(wanted.RollErrorDegrees)<150)antipodalRollSign=0;
if(antipodalRollSign!=0)wanted=wanted with{RollErrorDegrees=antipodalRollSign*Math.Abs(wanted.RollErrorDegrees)};
// The bank reference is singular when initially facing the star.
// Hysteresis prevents chasing its sign flips with Q/E roll inputs.
var desiredUp=FlightGeometry.Perpendicular(direction.Unit(),preferredUp);
var bankProjection=(desiredUp-f*Vector3d.Dot(desiredUp,f)).Length;
if(bankProjection<.25)bankReliable=false;
else if(bankProjection>.45)bankReliable=true;
if(Math.Abs(wanted.RollErrorDegrees)<.25&&Math.Abs(rates.Z)<.3)rollSettled=true;
else if(Math.Abs(wanted.RollErrorDegrees)>.65||Math.Abs(rates.Z)>.8)rollSettled=false;
var seconds=(frame.ObservedAt-origin).TotalSeconds;
var yaw=axes![0].Control(wanted.YawErrorDegrees,rates.X,seconds,dt);
var pitch=axes[1].Control(wanted.PitchErrorDegrees,rates.Y,seconds,dt);
var roll=controlRoll?axes[2].Control(wanted.RollErrorDegrees,rates.Z,seconds,dt,bankReliable):0;
if(rollSettled&&bankReliable)roll=0;
previous=frame;
return wanted with{Yaw=yaw,Pitch=pitch,Roll=roll};
}
}
namespace XFEEDToolBox.Core.Navigation;
public readonly record struct AttitudeInput(double Yaw,double Pitch,double Roll,double ErrorDegrees)
{
public double YawErrorDegrees{get;init;}
public double PitchErrorDegrees{get;init;}
public double RollErrorDegrees{get;init;}
}
/// <summary>Ship-local yaw/pitch steering. Axis signs are pinned to actual native input tests.</summary>
public static class AttitudeController
{
public static double FastAxis(double errorDegrees,double measuredRateDegreesPerSecond)
{
if(!double.IsFinite(errorDegrees)||!double.IsFinite(measuredRateDegreesPerSecond))throw new ArgumentException("Invalid angular state.");
return Math.Abs(errorDegrees)<.04&&Math.Abs(measuredRateDegreesPerSecond)<.15?0:Math.Clamp(errorDegrees*.18-measuredRateDegreesPerSecond*.065,-1,1);
}
public static AttitudeInput Aim(Vector3d forward,Vector3d up,Vector3d direction,double maximumAxis=.12)
{
if(!forward.Finite||!up.Finite||!direction.Finite||!double.IsFinite(maximumAxis)||maximumAxis<=0||maximumAxis>1)
throw new ArgumentException("Invalid attitude input or authority limit.");
var f=forward.Unit();var right=Vector3d.Cross(up.Unit(),f).Unit();var u=Vector3d.Cross(f,right).Unit();var wanted=direction.Unit();
var x=Vector3d.Dot(wanted,right);var y=Vector3d.Dot(wanted,u);var z=Vector3d.Dot(wanted,f);
var yaw=Math.Atan2(x,z)*180/Math.PI;
var pitch=-Math.Atan2(y,Math.Sqrt(x*x+z*z))*180/Math.PI;
static double Axis(double error,double limit)=>Math.Abs(error)<.06?0:Math.Clamp(error*.018,-limit,limit);
return new(Axis(yaw,maximumAxis),Axis(pitch,maximumAxis),0,Vector3d.AngleDegrees(f,wanted));
}
public static AttitudeInput AimBanked(Vector3d forward,Vector3d up,Vector3d direction,Vector3d preferredUp,Vector3d localAngularRate=default)
{
if(!forward.Finite||!up.Finite||!direction.Finite||!preferredUp.Finite||!localAngularRate.Finite)throw new ArgumentException("Invalid banked attitude.");
var f=forward.Unit();var r=Vector3d.Cross(up.Unit(),f).Unit();var u=Vector3d.Cross(f,r).Unit();var wanted=direction.Unit();
var desiredUp=FlightGeometry.Perpendicular(wanted,preferredUp);
var bankUp=desiredUp-f*Vector3d.Dot(desiredUp,f);
if(bankUp.Length<.2)
{
// When facing the star, its projection is initially undefined.
// The orbit plane's right vector gives a continuous pitch plane.
var desiredRight=Vector3d.Cross(desiredUp,wanted).Unit();
bankUp=Vector3d.Cross(f,FlightGeometry.Perpendicular(f,desiredRight));
}
bankUp=bankUp.Unit();
var roll=Math.Atan2(Vector3d.Dot(f,Vector3d.Cross(u,bankUp)),Vector3d.Dot(u,bankUp))*180/Math.PI;
var x=Vector3d.Dot(wanted,r);var y=Vector3d.Dot(wanted,u);var z=Vector3d.Dot(wanted,f);
var yaw=Math.Atan2(x,z)*180/Math.PI;var pitch=-Math.Atan2(y,Math.Sqrt(x*x+z*z))*180/Math.PI;
return new(FastAxis(yaw,localAngularRate.X),FastAxis(pitch,localAngularRate.Y),FastAxis(roll,localAngularRate.Z),Vector3d.AngleDegrees(f,wanted)){YawErrorDegrees=yaw,PitchErrorDegrees=pitch,RollErrorDegrees=roll};
}
}
/// <summary>Application-side three-axis control using pose-derived rates; no game access.</summary>
public sealed class BankedAttitudeController
{
private FlightFrame? previous;
private Vector3d rates,command;
private bool ratesKnown;
private bool bankReliable=true,rollSettled;
private Vector3d? antipodalTurnAxis;
private int antipodalRollSign;
private sealed class ResponseProfile
{
public AdaptiveAttitudeAxis[] Axes{get;}=[new(),new(),new()];
public double SpeedFraction{get;set;}
}
private readonly Dictionary<(string Ship,bool Cruise,int Pips),ResponseProfile> profiles=[];
private AdaptiveAttitudeAxis[]? axes;
private ResponseProfile? profile;
private (string Ship,bool Cruise,int Pips)? context;
private DateTimeOffset origin;
public IReadOnlyList<AxisResponse> Responses=>axes?.Select(a=>a.Model.Response).ToArray()??[];
public void Reset(){previous=null;rates=command=Vector3d.Zero;ratesKnown=false;bankReliable=true;rollSettled=false;antipodalTurnAxis=null;antipodalRollSign=0;foreach(var axis in axes??[])axis.BreakObservation();}
public void ConfirmApplied(DateTimeOffset at,AttitudeInput input)
{
if(axes is null||previous is null)return;
var time=(at-origin).TotalSeconds;
axes[0].Model.Acknowledge(time,input.Yaw);axes[1].Model.Acknowledge(time,input.Pitch);axes[2].Model.Acknowledge(time,input.Roll);
command=new(input.Yaw,input.Pitch,input.Roll);
}
public AttitudeInput Update(FlightFrame frame,Vector3d direction,Vector3d preferredUp,Vector3d? originalAngularRate=null,bool controlRoll=true)
{
var nextContext=(frame.LoadoutFingerprint,frame.InSupercruise,frame.EnginePips??-1);
if(context!=nextContext)
{
Reset();context=nextContext;origin=frame.ObservedAt;
if(!profiles.TryGetValue(nextContext,out profile))
{
if(profiles.Count>=128)profiles.Remove(profiles.Keys.First());
profile=new(){SpeedFraction=frame.SpeedFraction};profiles.Add(nextContext,profile);
}
axes=profile.Axes;
foreach(var axis in axes)axis.BreakObservation();
}
if(Math.Abs(frame.SpeedFraction-profile!.SpeedFraction)>.2)
{
foreach(var axis in axes!)axis.Model.Relearn();
profile.SpeedFraction=frame.SpeedFraction;
}
var f=frame.Forward.Unit();var r=Vector3d.Cross(frame.Up.Unit(),f).Unit();var u=Vector3d.Cross(f,r).Unit();
var dt=previous is {} p?(frame.ObservedAt-p.ObservedAt).TotalSeconds:0;
var continuous=previous is {} before&&before.SystemAddress==frame.SystemAddress&&frame.Sequence>before.Sequence&&dt is >=.002 and <=.3;
if(continuous)
{
var oldForward=previous!.Forward.Unit();var oldRight=Vector3d.Cross(previous.Up.Unit(),oldForward).Unit();var oldUp=Vector3d.Cross(oldForward,oldRight).Unit();
var angle=Math.Acos(Math.Clamp((Vector3d.Dot(oldRight,r)+Vector3d.Dot(oldUp,u)+Vector3d.Dot(oldForward,f)-1)*.5,-1,1));
if(angle<.5)
{
var omega=(Vector3d.Cross(oldRight,r)+Vector3d.Cross(oldUp,u)+Vector3d.Cross(oldForward,f))*.5;
omega*=((angle>1e-6?angle/Math.Sin(angle):1)*180/Math.PI/dt);
var measured=new Vector3d(Vector3d.Dot(omega,u),Vector3d.Dot(omega,r),Vector3d.Dot(omega,f));
var alpha=1-Math.Exp(-dt/.035);rates=ratesKnown?rates+(measured-rates)*alpha:measured;ratesKnown=true;
}
else{rates=Vector3d.Zero;ratesKnown=false;}
}
else{rates=command=Vector3d.Zero;ratesKnown=false;dt=.05;antipodalTurnAxis=null;antipodalRollSign=0;foreach(var axis in axes!)axis.BreakObservation();}
// Original rigid-body rates avoid differentiating rounded or changing
// reference-frame poses during local supercruise. Other callers retain
// the independently tested pose-derived fallback.
var native=originalAngularRate??frame.AngularVelocityDegrees;
if(native is {Finite:true} actual&&actual.Length<600&&(actual.Length>.01||!ratesKnown||rates.Length<.5)){rates=actual;ratesKnown=true;}
if(ratesKnown)
{
var time=(frame.ObservedAt-origin).TotalSeconds;
axes![0].Model.Observe(time,rates.X);axes[1].Model.Observe(time,rates.Y);axes[2].Model.Observe(time,rates.Z);
}
var wanted=AttitudeController.AimBanked(f,u,direction,preferredUp,rates);
// A spherical direction error has no yaw singularity at an overhead
// target. atan2(x,z) alone can flip by 180 degrees there. At the exact
// antipode keep one world-space turn plane until it becomes observable.
var goal=direction.Unit();var cosine=Vector3d.Dot(f,goal);var turn=Vector3d.Cross(f,goal);
if(cosine<-.99&&antipodalTurnAxis is null)
antipodalTurnAxis=turn.Length>.02?turn.Unit():r;
else if(cosine>-.95)antipodalTurnAxis=null;
var turnAxis=antipodalTurnAxis is {} fixedAxis?FlightGeometry.Perpendicular(f,fixedAxis):turn.Length>1e-7?turn.Unit():Vector3d.Zero;
wanted=wanted with{YawErrorDegrees=wanted.ErrorDegrees*Vector3d.Dot(turnAxis,u),PitchErrorDegrees=wanted.ErrorDegrees*Vector3d.Dot(turnAxis,r)};
if(Math.Abs(wanted.RollErrorDegrees)>170&&antipodalRollSign==0)antipodalRollSign=Math.Sign(wanted.RollErrorDegrees);
else if(Math.Abs(wanted.RollErrorDegrees)<150)antipodalRollSign=0;
if(antipodalRollSign!=0)wanted=wanted with{RollErrorDegrees=antipodalRollSign*Math.Abs(wanted.RollErrorDegrees)};
// The bank reference is singular when initially facing the star.
// Hysteresis prevents chasing its sign flips with Q/E roll inputs.
var desiredUp=FlightGeometry.Perpendicular(direction.Unit(),preferredUp);
var bankProjection=(desiredUp-f*Vector3d.Dot(desiredUp,f)).Length;
if(bankProjection<.25)bankReliable=false;
else if(bankProjection>.45)bankReliable=true;
if(Math.Abs(wanted.RollErrorDegrees)<.25&&Math.Abs(rates.Z)<.3)rollSettled=true;
else if(Math.Abs(wanted.RollErrorDegrees)>.65||Math.Abs(rates.Z)>.8)rollSettled=false;
var seconds=(frame.ObservedAt-origin).TotalSeconds;
var yaw=axes![0].Control(wanted.YawErrorDegrees,rates.X,seconds,dt);
var pitch=axes[1].Control(wanted.PitchErrorDegrees,rates.Y,seconds,dt);
var roll=controlRoll?axes[2].Control(wanted.RollErrorDegrees,rates.Z,seconds,dt,bankReliable):0;
if(rollSettled&&bankReliable)roll=0;
previous=frame;
return wanted with{Yaw=yaw,Pitch=pitch,Roll=roll};
}
}