using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using static XFEEDToolBox.Plugin.JsonWire;
namespace XFEEDToolBox.Plugin;
// The game layout and controller protocol are pinned to the same image as the original plugin.
internal static unsafe partial class Navigation
{
internal const string GameHash="ed5a8f8cd10f9a80d3bda5badd7ba1d4fcfc15996c8c7e018852cb170e264b63";
const nuint FlowUpdate=0x2157460, FlowAction=0x1D65500, PhysicsUpdate=0x2E6E960;
const nuint InputEvaluator=0x2E4A820, FsdUpdate=0x2C71440;
const nuint HeatInput=0x3813740, HeatTick=0x38144A0, BodyLookup=0x3CEB360;
const nuint PoseGetter=0x3CBBFE0,ThrottleSetter=0x25E5D10,ThrottleClear=0x25E9360,PoseInterfaceIdGetter=0x8AE690;
const nuint HeatPool=0x5FAA860,HeatManagerPool=0x5FD06A0,FsdPool=0x5F2F040;
[StructLayout(LayoutKind.Sequential)]
internal struct Vector
{
public double x,y,z;
public Vector(double x,double y,double z){this.x=x;this.y=y;this.z=z;}
}
[InlineArray(6)] internal struct Float6 { private float element; }
[InlineArray(10)] internal struct Double10 { private double element; }
[InlineArray(256)] internal struct Body256 { private NearbyBodyObservation element; }
internal struct Snapshot
{
public Snapshot(){this=default;heatDisplayScale=1;}
public ulong sequence,tick,utcMilliseconds,entity,referenceWorld;
public nuint life,physics,transform,inputRoot,heat,heatManager,fsd;
public Vector position,right,up,forward,angularVelocityLocal;
public double heatPercent,heatDisplayPercent,heatDisplayScale,speed,speedFraction;
public float rawChargeClock;
public byte rawFsdState,rawFsdMode,rawFsdStage;
public bool valid,playerOverride,controlApplied,angularVelocityValid;
public double hullFraction,shieldFraction;
public bool healthValid,shieldKnown,healthDamageObserved,healthEmergency;
public ulong healthStableSince;
}
internal struct Lease
{
public Lease(){this=default;throttle=-1;localKey=-1;}
public ulong expires,sequence;
public nuint inputRoot;
public Float6 axes;
public float throttle;
public ulong epoch;
public bool interlock,permitJump;
public ulong target,world;
public bool local;
public int localKey;
public uint localKind,localMarket;
public ulong localBody;
public bool yieldOnDockingGrant;
}
internal struct FsdLease
{
public FsdLease(){this=default;heatCeiling=65;}
public ulong expires,sequence,generation,entity;
public nuint fsd,inputRoot,life;
public uint command;
public float heatCeiling;
public ulong target;
public bool supercruiseEntry,local;
}
internal struct TargetLease {public ulong expires,generation,entity,target;public nuint life,fsd,inputRoot;}
internal struct RouteRequest {public ulong expires,generation,entity,destination;public nuint life,fsd,inputRoot,pilotLife,route;public bool clear;public GameRouteOptions? options;}
internal struct RouteObservation {public ulong tick,generation,destination;public nuint route;public ulong hash;public uint count;public bool topologyValid;}
internal struct FsdObservation
{
public ulong tick,generation,appliedGeneration,pulses,entity;
public nuint life,fsd;
public float clock,duration,rate,elapsed,driveChargeSeconds,driveHeatBase,driveHeatRamp,heatCapacity;
public byte state,mode,stage;
public bool owned,driveParametersValid,beginRejected;
public ulong targetAddress;
public Vector targetDirection;
public float targetDistance,throttle,speedFraction,throttleOverride;
public bool targetValid;
public float coolingPassive,coolingMaximum,coolingHeatLower,coolingHeatUpper;
public bool coolingConfigurationValid;
public float coolingActual,coolingScale;
public bool coolingActive;
}
internal struct HeatObservation
{
public ulong tick,entity,world;
public double inputUpper,seconds,pending,bucketEnergy,bucketTime,idleUpper;
public Double10 rates;
public uint buckets;
public bool valid;
}
internal struct NearbyBodyObservation {public ulong address;public uint kind,starType;public double exclusionRadius,escapeRadius;public Vector centre;}
internal struct ScoopObservation {public bool verified,active;public double fullRadius,outerRadius,maximumRate,efficiency,fullAngle,zeroAngle,speedWeight;}
internal struct GeometryObservation
{
public ulong tick,entity,worldAddress,bodyAddress,sourceUtcMilliseconds;
public uint bodyKind,starType;
public double exclusionRadius,escapeRadius;
public Vector position,right,up,forward,referenceOrigin;
public uint referenceBodyKind,bodyCount,unverifiedStationEnvelopes;
public bool unifiedReference,referenceOriginVerified;
public ScoopObservation scoop;
public Body256 bodies;
}
static HeatObservation heatObservation;
static readonly object heatLock=new();
static nuint originalHeatInput,originalHeatTick,heatInputStub,heatTickStub;
static nuint image,imageEnd;
static volatile bool active=true,initialized,inGame,overridden;
static Func<bool> enabledProvider=()=>true;
static volatile uint owningThread;
static ulong sampleAtValue,sequenceValue,inputAppliedAtValue,controllerEpochValue;
static ulong sampleAt {get=>Volatile.Read(ref sampleAtValue);set=>Volatile.Write(ref sampleAtValue,value);}
static ulong sequence {get=>Volatile.Read(ref sequenceValue);set=>Volatile.Write(ref sequenceValue,value);}
static ulong inputAppliedAt {get=>Volatile.Read(ref inputAppliedAtValue);set=>Volatile.Write(ref inputAppliedAtValue,value);}
static ulong controllerEpoch {get=>Volatile.Read(ref controllerEpochValue);set=>Volatile.Write(ref controllerEpochValue,value);}
static volatile uint sampleStage,sampleAttempts;
static ulong fsdEntryCallsValue,fsdEntryAtValue,fsdSelectedCallsValue;
static ulong fsdEntryCalls {get=>Volatile.Read(ref fsdEntryCallsValue);set=>Volatile.Write(ref fsdEntryCallsValue,value);}
static ulong fsdEntryAt {get=>Volatile.Read(ref fsdEntryAtValue);set=>Volatile.Write(ref fsdEntryAtValue,value);}
static ulong fsdSelectedCalls {get=>Volatile.Read(ref fsdSelectedCallsValue);set=>Volatile.Write(ref fsdSelectedCallsValue,value);}
static volatile uint fsdEntryThread;
static volatile float fsdEntryDt;
static readonly object snapshotLock=new(),leaseLock=new(),fsdObservationLock=new(),geometryLock=new();
static GeometryObservation geometry;
static Snapshot snapshot,healthSnapshot;
static ulong healthSequence;
static readonly Snapshot[] references=new Snapshot[32];
static Lease lease=new(){throttle=-1,localKey=-1};
static FsdLease fsdLease=new(){heatCeiling=65};
static TargetLease targetLease;
static ulong targetGenerationValue,targetConsumedValue,targetConfirmedValue,targetFailedValue;
static ulong targetGeneration {get=>Volatile.Read(ref targetGenerationValue);set=>Volatile.Write(ref targetGenerationValue,value);}
static ulong targetConsumed {get=>Volatile.Read(ref targetConsumedValue);set=>Volatile.Write(ref targetConsumedValue,value);}
static ulong targetConfirmed {get=>Volatile.Read(ref targetConfirmedValue);set=>Volatile.Write(ref targetConfirmedValue,value);}
static ulong targetFailed {get=>Volatile.Read(ref targetFailedValue);set=>Volatile.Write(ref targetFailedValue,value);}
static readonly object routeLock=new();
static RouteRequest routeRequest;
static RouteObservation routeObservation;
static ulong routeGenerationValue,routeConsumedValue,routeAppliedValue,routeFailedValue,routeReadUntilValue;
static ulong routeGeneration {get=>Volatile.Read(ref routeGenerationValue);set=>Volatile.Write(ref routeGenerationValue,value);}
static ulong routeConsumed {get=>Volatile.Read(ref routeConsumedValue);set=>Volatile.Write(ref routeConsumedValue,value);}
static ulong routeApplied {get=>Volatile.Read(ref routeAppliedValue);set=>Volatile.Write(ref routeAppliedValue,value);}
static ulong routeFailed {get=>Volatile.Read(ref routeFailedValue);set=>Volatile.Write(ref routeFailedValue,value);}
static ulong routeReadUntil {get=>Volatile.Read(ref routeReadUntilValue);set=>Volatile.Write(ref routeReadUntilValue,value);}
static string routeOwner="";
static FsdObservation fsdObservation;
static volatile bool fsdOwned;
static ulong fsdGenerationValue;
static ulong fsdGeneration {get=>Volatile.Read(ref fsdGenerationValue);set=>Volatile.Write(ref fsdGenerationValue,value);}
static ulong NextFsdGeneration()=>Interlocked.Increment(ref fsdGenerationValue);
static ulong fsdConsumedGeneration,fsdPulseCount,fsdLastPulseAt;
static uint fsdOwnedMode=1;
static readonly object clientMutex=new(),initializeMutex=new();
static bool installationAttempted;
static string clientOwner="";
static void ClaimController(string owner)
{
if(clientOwner!=owner)
{
var frame=Current();
lock(takeoverKeyboardLock)
{
Interlocked.Increment(ref controllerEpochValue);takeoverKeyboard.Reset();
takeoverKeyboardEpoch=controllerEpoch;takeoverKeyboardEntity=frame.entity;takeoverKeyboardRoot=frame.inputRoot;
}
}
clientOwner=owner;
}
enum InputIntent {None,Transient,Takeover}
struct InputBaseline {public ulong epoch,entity;public nuint root;public Float6 axes;}
static InputBaseline inputBaseline;
struct InputOverlay {public nuint root,vtable,life,physics;public ulong entity,throttleCommitVersion,diagnosticSerial;public Float6 previous,written;public bool applied;}
static nuint originalPhysics,originalInputEvaluation,originalFsd,originalBodyLookup,originalFlow,flowStub;
static T Read<T>(nuint at) where T:unmanaged=>Platform.Read<T>(at);
static void Write<T>(nuint at,T value) where T:unmanaged=>Platform.Write(at,value);
static nuint Pointer(nuint at)=>Platform.Pointer(at);
static ulong Call(nuint fn,params ulong[] args)=>Platform.Call(fn,args);
static float CallFloat(nuint fn,params ulong[] args)=>Platform.CallFloat(fn,args);
static double CallDouble(nuint fn,params ulong[] args)=>Platform.CallDouble(fn,args);
static ulong F32(float value)=>Platform.F32(value);
static ulong F64(double value)=>Platform.F64(value);
static ulong GetTickCount64()=>Platform.GetTickCount64();
static uint GetCurrentThreadId()=>Platform.GetCurrentThreadId();
static ulong UtcMilliseconds()=>(ulong)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
static bool InImage(nuint at)=>at>=image&&at<imageEnd;
static bool Enabled()=>active&&enabledProvider()&&initialized;
static bool Finite(Vector v)=>double.IsFinite(v.x)&&double.IsFinite(v.y)&&double.IsFinite(v.z);
static double Dot(Vector a,Vector b)=>a.x*b.x+a.y*b.y+a.z*b.z;
static bool Rotation(Vector r,Vector u,Vector f)=>Finite(r)&&Finite(u)&&Finite(f)&&Math.Abs(Dot(r,r)-1)<.005&&Math.Abs(Dot(u,u)-1)<.005&&Math.Abs(Dot(f,f)-1)<.005&&Math.Abs(Dot(r,u))<.005&&Math.Abs(Dot(u,f))<.005&&Math.Abs(Dot(f,r))<.005;
static bool OutwardChargingMotion(Vector position,Vector forward,Vector direction,bool charging,bool supercruiseEntry)=>charging&&!supercruiseEntry&&Dot(position,forward)>0&&Dot(position,direction)>=0;
static float StellarCruiseThrottle(float desired,double speed,double radius,double exclusion,double radialCosine)
{
if(!double.IsFinite(speed)||speed<0||!double.IsFinite(radius)||!double.IsFinite(exclusion)||exclusion<=0||!double.IsFinite(radialCosine))return 0;
if(radius>=exclusion*3)return desired;
var altitude=radius-exclusion*1.15;if(altitude<=0)return radialCosine>.3?Math.Min(desired,.7f):0;
var approach=Math.Max(.25,-radialCosine);var limit=Math.Min(10000000.0,altitude/(8*approach));
if(speed>=limit)return 0;if(speed>limit*.8)return Math.Min(desired,.25f);return desired;
}
static Snapshot Current(){lock(snapshotLock)return snapshot;}
static Snapshot CurrentHealth(){lock(snapshotLock)return healthSnapshot;}
static FsdObservation CurrentFsd(){lock(fsdObservationLock)return fsdObservation;}
static HeatObservation CurrentHeat(){lock(heatLock)return heatObservation;}
static bool ReferenceUsable(Snapshot reference,Snapshot current,ulong now)=>reference.valid&¤t.valid&&reference.sequence<=current.sequence&&reference.tick<=now&&now-reference.tick<=200&¤t.tick<=now&&now-current.tick<=200&&reference.entity==current.entity&&reference.life==current.life&&reference.inputRoot==current.inputRoot&&reference.referenceWorld==current.referenceWorld;
static Snapshot Reference(ulong expected,Snapshot current,ulong now)
{
Snapshot value;lock(snapshotLock)value=references[expected%32];
if(value.sequence!=expected||!ReferenceUsable(value,current,now))throw new InvalidOperationException("Navigation reference frame expired; read fresh telemetry and retry");return value;
}
static void Expire(){lock(leaseLock){lease.expires=0;fsdLease.expires=0;targetLease.expires=0;}ExpireLocal();lock(routeLock)routeRequest.expires=0;}
static Float6 CommandAxes(Lease control)
{
var result=control.axes;if(control.throttle>=0)result[0]=control.throttle;var fsd=CurrentFsd();
if(control.interlock&&!control.permitJump&&fsd.state==3&&fsd.duration>0&&fsd.clock>=fsd.duration-.5f)result[0]=0;return result;
}
}
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using static XFEEDToolBox.Plugin.JsonWire;
namespace XFEEDToolBox.Plugin;
// The game layout and controller protocol are pinned to the same image as the original plugin.
internal static unsafe partial class Navigation
{
internal const string GameHash="ed5a8f8cd10f9a80d3bda5badd7ba1d4fcfc15996c8c7e018852cb170e264b63";
const nuint FlowUpdate=0x2157460, FlowAction=0x1D65500, PhysicsUpdate=0x2E6E960;
const nuint InputEvaluator=0x2E4A820, FsdUpdate=0x2C71440;
const nuint HeatInput=0x3813740, HeatTick=0x38144A0, BodyLookup=0x3CEB360;
const nuint PoseGetter=0x3CBBFE0,ThrottleSetter=0x25E5D10,ThrottleClear=0x25E9360,PoseInterfaceIdGetter=0x8AE690;
const nuint HeatPool=0x5FAA860,HeatManagerPool=0x5FD06A0,FsdPool=0x5F2F040;
[StructLayout(LayoutKind.Sequential)]
internal struct Vector
{
public double x,y,z;
public Vector(double x,double y,double z){this.x=x;this.y=y;this.z=z;}
}
[InlineArray(6)] internal struct Float6 { private float element; }
[InlineArray(10)] internal struct Double10 { private double element; }
[InlineArray(256)] internal struct Body256 { private NearbyBodyObservation element; }
internal struct Snapshot
{
public Snapshot(){this=default;heatDisplayScale=1;}
public ulong sequence,tick,utcMilliseconds,entity,referenceWorld;
public nuint life,physics,transform,inputRoot,heat,heatManager,fsd;
public Vector position,right,up,forward,angularVelocityLocal;
public double heatPercent,heatDisplayPercent,heatDisplayScale,speed,speedFraction;
public float rawChargeClock;
public byte rawFsdState,rawFsdMode,rawFsdStage;
public bool valid,playerOverride,controlApplied,angularVelocityValid;
public double hullFraction,shieldFraction;
public bool healthValid,shieldKnown,healthDamageObserved,healthEmergency;
public ulong healthStableSince;
}
internal struct Lease
{
public Lease(){this=default;throttle=-1;localKey=-1;}
public ulong expires,sequence;
public nuint inputRoot;
public Float6 axes;
public float throttle;
public ulong epoch;
public bool interlock,permitJump;
public ulong target,world;
public bool local;
public int localKey;
public uint localKind,localMarket;
public ulong localBody;
public bool yieldOnDockingGrant;
}
internal struct FsdLease
{
public FsdLease(){this=default;heatCeiling=65;}
public ulong expires,sequence,generation,entity;
public nuint fsd,inputRoot,life;
public uint command;
public float heatCeiling;
public ulong target;
public bool supercruiseEntry,local;
}
internal struct TargetLease {public ulong expires,generation,entity,target;public nuint life,fsd,inputRoot;}
internal struct RouteRequest {public ulong expires,generation,entity,destination;public nuint life,fsd,inputRoot,pilotLife,route;public bool clear;public GameRouteOptions? options;}
internal struct RouteObservation {public ulong tick,generation,destination;public nuint route;public ulong hash;public uint count;public bool topologyValid;}
internal struct FsdObservation
{
public ulong tick,generation,appliedGeneration,pulses,entity;
public nuint life,fsd;
public float clock,duration,rate,elapsed,driveChargeSeconds,driveHeatBase,driveHeatRamp,heatCapacity;
public byte state,mode,stage;
public bool owned,driveParametersValid,beginRejected;
public ulong targetAddress;
public Vector targetDirection;
public float targetDistance,throttle,speedFraction,throttleOverride;
public bool targetValid;
public float coolingPassive,coolingMaximum,coolingHeatLower,coolingHeatUpper;
public bool coolingConfigurationValid;
public float coolingActual,coolingScale;
public bool coolingActive;
}
internal struct HeatObservation
{
public ulong tick,entity,world;
public double inputUpper,seconds,pending,bucketEnergy,bucketTime,idleUpper;
public Double10 rates;
public uint buckets;
public bool valid;
}
internal struct NearbyBodyObservation {public ulong address;public uint kind,starType;public double exclusionRadius,escapeRadius;public Vector centre;}
internal struct ScoopObservation {public bool verified,active;public double fullRadius,outerRadius,maximumRate,efficiency,fullAngle,zeroAngle,speedWeight;}
internal struct GeometryObservation
{
public ulong tick,entity,worldAddress,bodyAddress,sourceUtcMilliseconds;
public uint bodyKind,starType;
public double exclusionRadius,escapeRadius;
public Vector position,right,up,forward,referenceOrigin;
public uint referenceBodyKind,bodyCount,unverifiedStationEnvelopes;
public bool unifiedReference,referenceOriginVerified;
public ScoopObservation scoop;
public Body256 bodies;
}
static HeatObservation heatObservation;
static readonly object heatLock=new();
static nuint originalHeatInput,originalHeatTick,heatInputStub,heatTickStub;
static nuint image,imageEnd;
static volatile bool active=true,initialized,inGame,overridden;
static Func<bool> enabledProvider=()=>true;
static volatile uint owningThread;
static ulong sampleAtValue,sequenceValue,inputAppliedAtValue,controllerEpochValue;
static ulong sampleAt {get=>Volatile.Read(ref sampleAtValue);set=>Volatile.Write(ref sampleAtValue,value);}
static ulong sequence {get=>Volatile.Read(ref sequenceValue);set=>Volatile.Write(ref sequenceValue,value);}
static ulong inputAppliedAt {get=>Volatile.Read(ref inputAppliedAtValue);set=>Volatile.Write(ref inputAppliedAtValue,value);}
static ulong controllerEpoch {get=>Volatile.Read(ref controllerEpochValue);set=>Volatile.Write(ref controllerEpochValue,value);}
static volatile uint sampleStage,sampleAttempts;
static ulong fsdEntryCallsValue,fsdEntryAtValue,fsdSelectedCallsValue;
static ulong fsdEntryCalls {get=>Volatile.Read(ref fsdEntryCallsValue);set=>Volatile.Write(ref fsdEntryCallsValue,value);}
static ulong fsdEntryAt {get=>Volatile.Read(ref fsdEntryAtValue);set=>Volatile.Write(ref fsdEntryAtValue,value);}
static ulong fsdSelectedCalls {get=>Volatile.Read(ref fsdSelectedCallsValue);set=>Volatile.Write(ref fsdSelectedCallsValue,value);}
static volatile uint fsdEntryThread;
static volatile float fsdEntryDt;
static readonly object snapshotLock=new(),leaseLock=new(),fsdObservationLock=new(),geometryLock=new();
static GeometryObservation geometry;
static Snapshot snapshot,healthSnapshot;
static ulong healthSequence;
static readonly Snapshot[] references=new Snapshot[32];
static Lease lease=new(){throttle=-1,localKey=-1};
static FsdLease fsdLease=new(){heatCeiling=65};
static TargetLease targetLease;
static ulong targetGenerationValue,targetConsumedValue,targetConfirmedValue,targetFailedValue;
static ulong targetGeneration {get=>Volatile.Read(ref targetGenerationValue);set=>Volatile.Write(ref targetGenerationValue,value);}
static ulong targetConsumed {get=>Volatile.Read(ref targetConsumedValue);set=>Volatile.Write(ref targetConsumedValue,value);}
static ulong targetConfirmed {get=>Volatile.Read(ref targetConfirmedValue);set=>Volatile.Write(ref targetConfirmedValue,value);}
static ulong targetFailed {get=>Volatile.Read(ref targetFailedValue);set=>Volatile.Write(ref targetFailedValue,value);}
static readonly object routeLock=new();
static RouteRequest routeRequest;
static RouteObservation routeObservation;
static ulong routeGenerationValue,routeConsumedValue,routeAppliedValue,routeFailedValue,routeReadUntilValue;
static ulong routeGeneration {get=>Volatile.Read(ref routeGenerationValue);set=>Volatile.Write(ref routeGenerationValue,value);}
static ulong routeConsumed {get=>Volatile.Read(ref routeConsumedValue);set=>Volatile.Write(ref routeConsumedValue,value);}
static ulong routeApplied {get=>Volatile.Read(ref routeAppliedValue);set=>Volatile.Write(ref routeAppliedValue,value);}
static ulong routeFailed {get=>Volatile.Read(ref routeFailedValue);set=>Volatile.Write(ref routeFailedValue,value);}
static ulong routeReadUntil {get=>Volatile.Read(ref routeReadUntilValue);set=>Volatile.Write(ref routeReadUntilValue,value);}
static string routeOwner="";
static FsdObservation fsdObservation;
static volatile bool fsdOwned;
static ulong fsdGenerationValue;
static ulong fsdGeneration {get=>Volatile.Read(ref fsdGenerationValue);set=>Volatile.Write(ref fsdGenerationValue,value);}
static ulong NextFsdGeneration()=>Interlocked.Increment(ref fsdGenerationValue);
static ulong fsdConsumedGeneration,fsdPulseCount,fsdLastPulseAt;
static uint fsdOwnedMode=1;
static readonly object clientMutex=new(),initializeMutex=new();
static bool installationAttempted;
static string clientOwner="";
static void ClaimController(string owner)
{
if(clientOwner!=owner)
{
var frame=Current();
lock(takeoverKeyboardLock)
{
Interlocked.Increment(ref controllerEpochValue);takeoverKeyboard.Reset();
takeoverKeyboardEpoch=controllerEpoch;takeoverKeyboardEntity=frame.entity;takeoverKeyboardRoot=frame.inputRoot;
}
}
clientOwner=owner;
}
enum InputIntent {None,Transient,Takeover}
struct InputBaseline {public ulong epoch,entity;public nuint root;public Float6 axes;}
static InputBaseline inputBaseline;
struct InputOverlay {public nuint root,vtable,life,physics;public ulong entity,throttleCommitVersion,diagnosticSerial;public Float6 previous,written;public bool applied;}
static nuint originalPhysics,originalInputEvaluation,originalFsd,originalBodyLookup,originalFlow,flowStub;
static T Read<T>(nuint at) where T:unmanaged=>Platform.Read<T>(at);
static void Write<T>(nuint at,T value) where T:unmanaged=>Platform.Write(at,value);
static nuint Pointer(nuint at)=>Platform.Pointer(at);
static ulong Call(nuint fn,params ulong[] args)=>Platform.Call(fn,args);
static float CallFloat(nuint fn,params ulong[] args)=>Platform.CallFloat(fn,args);
static double CallDouble(nuint fn,params ulong[] args)=>Platform.CallDouble(fn,args);
static ulong F32(float value)=>Platform.F32(value);
static ulong F64(double value)=>Platform.F64(value);
static ulong GetTickCount64()=>Platform.GetTickCount64();
static uint GetCurrentThreadId()=>Platform.GetCurrentThreadId();
static ulong UtcMilliseconds()=>(ulong)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
static bool InImage(nuint at)=>at>=image&&at<imageEnd;
static bool Enabled()=>active&&enabledProvider()&&initialized;
static bool Finite(Vector v)=>double.IsFinite(v.x)&&double.IsFinite(v.y)&&double.IsFinite(v.z);
static double Dot(Vector a,Vector b)=>a.x*b.x+a.y*b.y+a.z*b.z;
static bool Rotation(Vector r,Vector u,Vector f)=>Finite(r)&&Finite(u)&&Finite(f)&&Math.Abs(Dot(r,r)-1)<.005&&Math.Abs(Dot(u,u)-1)<.005&&Math.Abs(Dot(f,f)-1)<.005&&Math.Abs(Dot(r,u))<.005&&Math.Abs(Dot(u,f))<.005&&Math.Abs(Dot(f,r))<.005;
static bool OutwardChargingMotion(Vector position,Vector forward,Vector direction,bool charging,bool supercruiseEntry)=>charging&&!supercruiseEntry&&Dot(position,forward)>0&&Dot(position,direction)>=0;
static float StellarCruiseThrottle(float desired,double speed,double radius,double exclusion,double radialCosine)
{
if(!double.IsFinite(speed)||speed<0||!double.IsFinite(radius)||!double.IsFinite(exclusion)||exclusion<=0||!double.IsFinite(radialCosine))return 0;
if(radius>=exclusion*3)return desired;
var altitude=radius-exclusion*1.15;if(altitude<=0)return radialCosine>.3?Math.Min(desired,.7f):0;
var approach=Math.Max(.25,-radialCosine);var limit=Math.Min(10000000.0,altitude/(8*approach));
if(speed>=limit)return 0;if(speed>limit*.8)return Math.Min(desired,.25f);return desired;
}
static Snapshot Current(){lock(snapshotLock)return snapshot;}
static Snapshot CurrentHealth(){lock(snapshotLock)return healthSnapshot;}
static FsdObservation CurrentFsd(){lock(fsdObservationLock)return fsdObservation;}
static HeatObservation CurrentHeat(){lock(heatLock)return heatObservation;}
static bool ReferenceUsable(Snapshot reference,Snapshot current,ulong now)=>reference.valid&¤t.valid&&reference.sequence<=current.sequence&&reference.tick<=now&&now-reference.tick<=200&¤t.tick<=now&&now-current.tick<=200&&reference.entity==current.entity&&reference.life==current.life&&reference.inputRoot==current.inputRoot&&reference.referenceWorld==current.referenceWorld;
static Snapshot Reference(ulong expected,Snapshot current,ulong now)
{
Snapshot value;lock(snapshotLock)value=references[expected%32];
if(value.sequence!=expected||!ReferenceUsable(value,current,now))throw new InvalidOperationException("Navigation reference frame expired; read fresh telemetry and retry");return value;
}
static void Expire(){lock(leaseLock){lease.expires=0;fsdLease.expires=0;targetLease.expires=0;}ExpireLocal();lock(routeLock)routeRequest.expires=0;}
static Float6 CommandAxes(Lease control)
{
var result=control.axes;if(control.throttle>=0)result[0]=control.throttle;var fsd=CurrentFsd();
if(control.interlock&&!control.permitJump&&fsd.state==3&&fsd.duration>0&&fsd.clock>=fsd.duration-.5f)result[0]=0;return result;
}
}