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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

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

namespace XFEEDToolBox.Core.Navigation;

/// <summary>Reads original SCO observations; owns no flight input or overcharge command.</summary>
public sealed class NativeCruiseObservationChannel(int processId,string expectedGameSha256)
{
    private readonly NavigationPipeClient pipe=new(processId,"CruiseObservation0514c");
    private readonly CruiseOverchargeSampleHistory history=new(expectedGameSha256);
    private ulong boundEntity,boundWorld;

    public async Task<CruiseOverchargeObservation> ReadAsync(SystemFlightFrame flight,CancellationToken token)
    {
        if(flight.ShipEntity==0||flight.ReferenceWorld==0||flight.GameSha256!=expectedGameSha256)
            throw new InvalidDataException("SCO observation requires the current original ship and game identity.");
        var rebind=boundEntity!=flight.ShipEntity||boundWorld!=flight.ReferenceWorld;
        var response=await pipe.CallAsync(new{op=rebind?"watch":"read"},token);
        if(response.GetProperty("gameSha256").GetString()!=expectedGameSha256||response.GetProperty("processId").GetInt32()!=processId)
            throw new InvalidDataException("SCO observation belongs to a different client.");
        if(rebind){boundEntity=flight.ShipEntity;boundWorld=flight.ReferenceWorld;history.Reset();}
        return history.Read(response,flight,DateTimeOffset.UtcNow);
    }
}

/// <summary>Preserves sample identity/time and derives heat and total-fuel slopes from two real samples.</summary>
public sealed class CruiseOverchargeSampleHistory(string expectedGameSha256)
{
    private CruiseOverchargeObservation? previous;
    private JsonElement? previousSample;
    private double previousTotalFuel=double.NaN;
    public void Reset(){previous=null;previousSample=null;previousTotalFuel=double.NaN;}

    public CruiseOverchargeObservation Read(JsonElement response,SystemFlightFrame flight,DateTimeOffset now,bool allowRepeated=false)
    {
        var unavailable=new CruiseOverchargeObservation{GameSha256=expectedGameSha256,ShipEntity=flight.ShipEntity,ReferenceWorld=flight.ReferenceWorld};
        static bool True(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.True;
        static bool Boolean(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind is JsonValueKind.True or JsonValueKind.False;
        static double Number(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.Number&&value.TryGetDouble(out var number)?number:double.NaN;
        static ulong Identity(JsonElement e,string key)=>e.TryGetProperty(key,out var value)&&value.ValueKind==JsonValueKind.String
            &&ulong.TryParse(value.GetString(),NumberStyles.None,CultureInfo.InvariantCulture,out var id)?id:0;
        if(!True(response,"enabled")||!True(response,"sampleReady")||!response.TryGetProperty("gameSha256",out var hash)||hash.GetString()!=expectedGameSha256
            ||!response.TryGetProperty("sample",out var sample)||sample.ValueKind!=JsonValueKind.Object)return unavailable;
        var entity=Identity(sample,"entityId");var world=Identity(sample,"referenceWorldAddress");
        if(entity==0||world==0||entity!=flight.ShipEntity||world!=flight.ReferenceWorld||flight.GameSha256!=expectedGameSha256
            ||!True(sample,"verified")||!True(sample,"inSupercruise")||!True(sample,"stableFsd"))return unavailable;
        if(!sample.TryGetProperty("observedAtUnixMilliseconds",out var timestamp)||!timestamp.TryGetInt64(out var milliseconds)
            ||!sample.TryGetProperty("rawFsdState",out var raw)||!raw.TryGetInt32(out var rawState)||rawState!=2
            ||!sample.TryGetProperty("state",out var stateValue)||!stateValue.TryGetInt32(out var state)||state is <0 or >3)return unavailable;
        DateTimeOffset at;try{at=DateTimeOffset.FromUnixTimeMilliseconds(milliseconds);}catch(ArgumentOutOfRangeException){return unavailable;}
        if(at>now||now-at>TimeSpan.FromMilliseconds(250))return unavailable;
        if(previous is {} prior&&prior.ShipEntity==entity&&prior.ReferenceWorld==world&&at<=prior.ObservedAt)
        {
            // An owned lease may read the same still-fresh engine update twice.
            // Keep its original timestamp and measured derivatives; a changed
            // same-time sample, backward sample or new enable cannot reuse it.
            return allowRepeated&&at==prior.ObservedAt&&previousSample is {} saved&&JsonElement.DeepEquals(sample,saved)
                ?prior:unavailable;
        }
        var heat=Number(sample,"heatPercent");var main=Number(sample,"fuelMainTonnes");var capacity=Number(sample,"fuelCapacityTonnes");var reserve=Number(sample,"reserveFuelTonnes");
        var fuelVerified=True(sample,"fuelVerified")&&double.IsFinite(main)&&double.IsFinite(capacity)&&double.IsFinite(reserve)&&main>=0&&capacity>0&&main<=capacity+.001&&reserve>=0;
        var upper=True(sample,"fuelBoundVerified")?Number(sample,"fuelRateUpperTonnesPerSecond"):double.NaN;
        if(!double.IsFinite(upper)||upper<=0)upper=double.NaN;
        var slope=double.NaN;var burn=double.NaN;var total=fuelVerified?main+reserve:double.NaN;
        if(previous is {} last&&last.ShipEntity==entity&&last.ReferenceWorld==world)
        {
            var elapsed=(at-last.ObservedAt).TotalSeconds;
            if(elapsed is >=.01 and <=1)
            {
                if(double.IsFinite(heat)&&double.IsFinite(last.HeatPercent))slope=(heat-last.HeatPercent)/elapsed;
                if(double.IsFinite(total)&&double.IsFinite(previousTotalFuel))burn=Math.Max(0,(previousTotalFuel-total)/elapsed);
            }
        }
        var result=new CruiseOverchargeObservation{ObservedAt=at,GameSha256=expectedGameSha256,ShipEntity=entity,ReferenceWorld=world,
            OriginalInterfacesVerified=true,OriginalCanEngage=True(sample,"nativeCanEngage"),State=(CruiseOverchargeState)(state+1),
            NativeFlightConstraintsVerified=Boolean(sample,"geometryVerified")&&Boolean(sample,"collisionCourse")&&Boolean(sample,"nativeAssistEnabled"),
            NativeGeometryVerified=True(sample,"geometryVerified"),NativeCollisionCourse=True(sample,"collisionCourse"),NativeAssistEnabled=True(sample,"nativeAssistEnabled"),
            HeatPercent=heat,HeatRisePercentPerSecond=slope,FuelMainTonnes=fuelVerified?main:double.NaN,FuelCapacityTonnes=fuelVerified?capacity:double.NaN,
            FuelBurnTonnesPerSecond=burn,FuelRateUpperTonnesPerSecond=upper,ThermalInput=ScoThermalJson.Read(sample,entity,world,at),ExitApproach=ScoExitApproachDecision.Read(sample)};
        previous=result;previousSample=sample.Clone();previousTotalFuel=total;return result;
    }
}