XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;

namespace XFEEDToolBox.Core.Navigation;

public enum CruiseFuelRangeScope { Unverified,OriginalScoConsumptionCurve }
public sealed record OriginalCruiseFuelRange(ulong Entity,ulong ReferenceWorld,DateTimeOffset ObservedAt,bool Verified,
    CruiseFuelRangeScope Scope,double LowerTonnesPerSecond,double UpperTonnesPerSecond);

/// <summary>A confirmed original method call or a renewal of its same expiring control lease.</summary>
public sealed record OriginalOverchargeReceipt(string RequestId,int ProcessId,long ProcessStartedUtcTicks,string GameSha256,
    string Owner,long SelectionGeneration,ulong Entity,ulong ReferenceWorld,long FrameSequence,DateTimeOffset FrameObservedAt,
    DateTimeOffset AppliedAt,DateTimeOffset ExpiresAt,bool Enable,bool Applied,bool OriginalMethodCalled)
{
    public long CommandGeneration{get;init;}
}

public sealed record EmptyCruiseSample(DateTimeOffset At,ulong Entity,ulong ReferenceWorld,CruiseOverchargeState State,
    double HeatPercent,double HeatRisePercentPerSecond,double FuelMainTonnes,double FuelCapacityTonnes,
    double MeasuredFuelBurnTonnesPerSecond,double OriginalFuelLowerTonnesPerSecond,double OriginalFuelUpperTonnesPerSecond);
public sealed record EmptyStationFlightEvidence(bool OriginalEnableCalled,bool ActualOverchargeActive,bool OriginalDisableCalled,
    bool ActualOverchargeInactive,int ActiveSamples,int TotalSamples,bool OriginalThrottleZero,bool OriginalAiStartCalled,
    bool ActualAiEngaged,bool NonzeroResetReproduced,DateTimeOffset? GrantedAt,DateTimeOffset? AiEngagedAt,
    IReadOnlyList<EmptyCruiseSample> CruiseSamples,IReadOnlyList<OriginalOverchargeReceipt> OriginalCommands);

/// <summary>
/// Evidence for one empty approach. It owns no game calls, input sources, controller or health observer.
/// Acknowledgements alone cannot prove SCO, zero throttle, native AI or docking.
/// </summary>
public sealed class EmptyStationFlightProof(int processId,long processStartedUtcTicks,string gameSha256,long destinationMarketId,double fuelReserveTonnes)
{
    private readonly List<EmptyCruiseSample> samples=[];
    private readonly Dictionary<string,OriginalOverchargeReceipt> receipts=new(StringComparer.Ordinal);
    private OriginalOverchargeReceipt? lease,lastOriginalDisable;
    private bool originalEnable,activeObserved,originalDisable,inactiveObserved,zero,aiStart,ai,nonzero;
    private int activeSamples;
    private DateTimeOffset? grantAt,aiAt,aiRequestedAt;
    private ulong arrivalEntity,arrivalWorld;

    private static bool Fresh(DateTimeOffset at,DateTimeOffset now,double milliseconds=250)=>at<=now&&now-at<=TimeSpan.FromMilliseconds(milliseconds);
    private static bool ScaInactive(SystemFlightFrame flight,bool? enabled)=>enabled==false&&flight.SupercruiseAssist is not(NativeAssistState.Requested or NativeAssistState.Aligning or NativeAssistState.Engaged);
    private void RequireFlight(SystemFlightFrame frame,DateTimeOffset now)
    {
        if(!frame.InGame||frame.PlayerOverride||frame.ExternalThreat||!frame.GeometryVerified||frame.GameSha256!=gameSha256
            ||frame.ShipEntity==0||frame.ReferenceWorld==0||frame.SelectedTarget?.MarketId!=destinationMarketId||!Fresh(frame.ObservedAt,now)
            ||!double.IsFinite(frame.HeatPercent??double.NaN)||frame.HeatPercent>=CruiseOverchargePolicy.MaximumHeatPercent)
            throw new InvalidDataException("Empty station evidence does not belong to a fresh healthy original destination frame.");
    }
    public void ObserveOriginalOverchargeReceipt(OriginalOverchargeReceipt value,DateTimeOffset now)
    {
        if(value.ProcessId!=processId||value.ProcessStartedUtcTicks!=processStartedUtcTicks||value.GameSha256!=gameSha256
            ||!Guid.TryParseExact(value.RequestId,"N",out _)||!Guid.TryParseExact(value.Owner,"N",out _)||value.SelectionGeneration<=0||value.CommandGeneration<=0||value.FrameSequence<=0
            ||value.Entity==0||value.ReferenceWorld==0||!value.Applied||value.AppliedAt<value.FrameObservedAt||value.AppliedAt>value.ExpiresAt
            ||value.ExpiresAt>value.FrameObservedAt.AddMilliseconds(250)||!Fresh(value.AppliedAt,now))
            throw new InvalidDataException("Original SCO receipt, owner, deadline or applied result is unverified.");
        if(receipts.TryGetValue(value.RequestId,out var existing))
        {
            if(existing!=value)throw new InvalidDataException("One original SCO request ID has contradictory receipts.");
            return; // Reconciliation of the same immutable request is not a new command.
        }
        if(lease is {} previous&&(previous.Owner!=value.Owner||previous.SelectionGeneration!=value.SelectionGeneration||previous.Entity!=value.Entity||previous.ReferenceWorld!=value.ReferenceWorld
            ||value.CommandGeneration<previous.CommandGeneration
            ||value.FrameSequence<previous.FrameSequence||value.AppliedAt<previous.AppliedAt))
            throw new InvalidDataException("The SCO control lease changed ownership or moved backwards.");
        if(value.Enable&&lease is not{Enable:true})
        {
            if(!value.OriginalMethodCalled)throw new InvalidDataException("A renewal cannot substitute for an original SCO enable transition.");
            originalDisable=false;lastOriginalDisable=null;
        }
        receipts.Add(value.RequestId,value);lease=value;
        if(value.Enable)
        {
            originalEnable|=value.OriginalMethodCalled;inactiveObserved=false;
        }
        else if(value.OriginalMethodCalled)
        {
            originalDisable=true;lastOriginalDisable=value;inactiveObserved=false;
        }
    }
    public void ObserveCruise(SystemFlightFrame frame,CruiseOverchargeObservation observed,OriginalCruiseFuelRange range,bool? scaEnabled,DateTimeOffset now)
    {
        RequireFlight(frame,now);
        if(frame.Mode!=LocalFlightMode.Supercruise||!ScaInactive(frame,scaEnabled)||!observed.OriginalInterfacesVerified||observed.GameSha256!=gameSha256
            ||observed.ShipEntity!=frame.ShipEntity||observed.ReferenceWorld!=frame.ReferenceWorld||!Fresh(observed.ObservedAt,now)
            ||!Enum.IsDefined(observed.State)||observed.State==CruiseOverchargeState.Unverified)
            throw new InvalidDataException("Actual SCO state or the disabled game SCA is not verified for this ship.");
        if(!range.Verified||range.Scope!=CruiseFuelRangeScope.OriginalScoConsumptionCurve||range.Entity!=frame.ShipEntity||range.ReferenceWorld!=frame.ReferenceWorld||!Fresh(range.ObservedAt,now)
            ||!double.IsFinite(range.LowerTonnesPerSecond)||!double.IsFinite(range.UpperTonnesPerSecond)||range.LowerTonnesPerSecond<0||range.UpperTonnesPerSecond<=0
            ||range.LowerTonnesPerSecond>range.UpperTonnesPerSecond||!double.IsFinite(observed.FuelRateUpperTonnesPerSecond)
            ||Math.Abs(range.UpperTonnesPerSecond-observed.FuelRateUpperTonnesPerSecond)>Math.Max(1e-9,range.UpperTonnesPerSecond*1e-6))
            throw new InvalidDataException("The original SCO consumption curve must supply both verified fuel bounds; measured idle burn is not a substitute.");
        if(!double.IsFinite(observed.HeatPercent)||observed.HeatPercent<0||observed.HeatPercent>=CruiseOverchargePolicy.MaximumHeatPercent
            ||!double.IsFinite(observed.FuelMainTonnes)||!double.IsFinite(observed.FuelCapacityTonnes)||observed.FuelCapacityTonnes<=0||observed.FuelMainTonnes>observed.FuelCapacityTonnes+.001
            ||!double.IsFinite(fuelReserveTonnes)||fuelReserveTonnes<=0||observed.FuelMainTonnes<fuelReserveTonnes)
            throw new InvalidDataException("Original SCO heat or reserved fuel limits were exceeded.");
        if(samples.Count>0&&observed.ObservedAt<=samples[^1].At)throw new InvalidDataException("SCO acceptance requires distinct monotonically increasing original samples.");
        var active=observed.State==CruiseOverchargeState.Active;
        if(active)
        {
            if(!originalEnable||lease is not{Enable:true} current||current.Entity!=frame.ShipEntity||current.ReferenceWorld!=frame.ReferenceWorld
                ||observed.ObservedAt<current.AppliedAt||observed.ObservedAt>current.ExpiresAt
                ||!double.IsFinite(observed.HeatRisePercentPerSecond)||!double.IsFinite(observed.FuelBurnTonnesPerSecond)||observed.FuelBurnTonnesPerSecond<0)
                throw new InvalidDataException("Real active SCO must follow its original enable and a current lease, with measured heat/fuel slopes.");
            activeObserved=true;activeSamples++;
        }
        if(observed.State is CruiseOverchargeState.Idle or CruiseOverchargeState.Cooling&&lease is{Enable:false}&&lastOriginalDisable is {} disabled
            &&disabled.Entity==frame.ShipEntity&&disabled.ReferenceWorld==frame.ReferenceWorld&&observed.ObservedAt>=disabled.AppliedAt)inactiveObserved=true;
        samples.Add(new(observed.ObservedAt,frame.ShipEntity,frame.ReferenceWorld,observed.State,observed.HeatPercent,observed.HeatRisePercentPerSecond,
            observed.FuelMainTonnes,observed.FuelCapacityTonnes,observed.FuelBurnTonnesPerSecond,range.LowerTonnesPerSecond,range.UpperTonnesPerSecond));
    }
    public bool OverchargeCompleted=>originalEnable&&activeObserved&&activeSamples>=5&&originalDisable&&inactiveObserved&&lease is{Enable:false};
    public void RequireSafeCruiseExit(SystemFlightFrame frame,bool? scaEnabled,DateTimeOffset now)
    {
        RequireFlight(frame,now);
        if(!OverchargeCompleted||frame.Mode!=LocalFlightMode.Supercruise||!ScaInactive(frame,scaEnabled))
            throw new InvalidOperationException("Original SCO must actually stop before requesting its original safe supercruise exit.");
    }
    public void RequireDockingApproach(SystemFlightFrame frame,bool? scaEnabled,DateTimeOffset now)
    {
        RequireFlight(frame,now);
        if(!OverchargeCompleted||frame.Mode!=LocalFlightMode.Normal||!ScaInactive(frame,scaEnabled))
            throw new InvalidOperationException("Original SCO stop and normal space must be verified before the destination ATC request.");
    }
    public void ObserveDockingGrant(SystemFlightFrame frame,bool? scaEnabled,DateTimeOffset now)
    {
        RequireDockingApproach(frame,scaEnabled,now);
        if(frame.Clearance?.Permission==DockingPermission.Granted&&frame.Clearance.Allows(frame.SelectedTarget!,now)&&frame.TargetDistance<=7500)
        {
            if(grantAt is not null)
            {
                if(arrivalEntity!=frame.ShipEntity||arrivalWorld!=frame.ReferenceWorld)throw new InvalidDataException("The actual docking grant belongs to another ship entity or reference world.");
                return;
            }
            grantAt??=frame.Clearance.ObservedAt;arrivalEntity=frame.ShipEntity;arrivalWorld=frame.ReferenceWorld;
            if(!Fresh(grantAt.Value,now))throw new InvalidDataException("The first actual docking grant is stale.");
            return;
        }
        throw new InvalidDataException("Actual station ATC, pad and destination identity have not been granted.");
    }
    public void ObserveOriginalDockingReset(JsonElement receipt,SystemFlightFrame frame,DateTimeOffset now)
    {
        static bool Flag(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.True;
        static bool False(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.False;
        static long Stamp(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.TryGetInt64(out var at)?at:-1;
        RequireFlight(frame,now);
        var requestAt=Stamp(receipt,"dockingStartAtUnixMilliseconds");var expires=Stamp(receipt,"expiresAtUnixMilliseconds");
        if(grantAt is not {} granted||frame.Mode!=LocalFlightMode.Normal||arrivalEntity!=frame.ShipEntity||arrivalWorld!=frame.ReferenceWorld||now-granted>TimeSpan.FromSeconds(2)
            ||!DockingValidationProof.OriginalResetZero(receipt,arrivalEntity,destinationMarketId,granted,now)||!Flag(receipt,"dockingStartRequested")||!Flag(receipt,"originalDockingStartCalled")
            ||!False(receipt,"gameAccumulatorWrittenBySdk")||!False(receipt,"gameOutputWrittenBySdk")||!False(receipt,"activeFlagWritten")||!False(receipt,"aiWritten")
            ||requestAt<granted.ToUnixTimeMilliseconds()||requestAt>now.ToUnixTimeMilliseconds()||requestAt>expires||expires>frame.ObservedAt.AddMilliseconds(250).ToUnixTimeMilliseconds())
            throw new InvalidDataException("The original source reset and real AI request were not confirmed inside the ATC handoff window.");
        zero=true;aiStart=true;aiRequestedAt=DateTimeOffset.FromUnixTimeMilliseconds(requestAt);nonzero=DockingValidationProof.OriginalResetZero(receipt,arrivalEntity,destinationMarketId,granted,now,requireNonzeroBefore:true);
    }
    public void ObserveAi(SystemFlightFrame frame,DateTimeOffset now)
    {
        RequireFlight(frame,now);
        if(grantAt is not {} granted||arrivalEntity!=frame.ShipEntity||arrivalWorld!=frame.ReferenceWorld||!zero||!aiStart||frame.DockingAssist!=NativeAssistState.Engaged
            ||aiRequestedAt is not {} requested||frame.ObservedAt<requested||now-granted>TimeSpan.FromSeconds(2))
            throw new InvalidDataException("Actual original docking AI did not engage inside two seconds.");
        ai=true;aiAt??=frame.ObservedAt;
    }
    public void RequireComplete()
    {
        if(!OverchargeCompleted||!zero||!aiStart||!ai)throw new InvalidDataException("SCO activation, original shutdown, zero throttle and original docking AI evidence are incomplete.");
    }
    public EmptyStationFlightEvidence Snapshot()=>new(originalEnable,activeObserved,originalDisable,inactiveObserved,activeSamples,samples.Count,zero,aiStart,ai,nonzero,grantAt,aiAt,samples.ToArray(),receipts.Values.ToArray());
}