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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using XFEEDToolBox.Core.Models;
namespace XFEEDToolBox.Core.Navigation;

public sealed record FlightDriverCapabilities(bool Verified,string GameSha256,bool ContinuousPose,bool ContinuousHeat,bool StarEnvelopes,bool NativeSteering,bool ChargeAndCommitInterlock,string Evidence)
{
    // Pose/heat are live freshness flags in the native describe reply. Losing a
    // frame during a system transition does not revoke the build's interfaces.
    public bool InterfacesVerified=>Verified&&GameSha256.Length==64&&StarEnvelopes&&NativeSteering&&ChargeAndCommitInterlock&&Evidence.Length>0;
    public bool Ready=>InterfacesVerified&&ContinuousPose&&ContinuousHeat;
}
public sealed record FlightObservation(FlightFrame Frame,ShipThermalCalibration? Thermal);
public sealed class FlightTelemetryUnavailableException(string message,Exception? inner=null,FlightRecovery recovery=FlightRecovery.RefreshTelemetry):IOException(message,inner)
{
    public FlightRecovery Recovery {get;}=recovery;
}
public interface IFlightControlDriver
{
    // Called once for a new navigation intent, never for a reconnect on its route.
    Task BeginNavigationSessionAsync(CancellationToken token)=>Task.CompletedTask;
    Task<FlightDriverCapabilities> PreflightAsync(CancellationToken token);
    // Must lock the real game target and acknowledge that exact system before any charge/control.
    Task SelectTargetAsync(NavWaypoint next,CancellationToken token);
    Task PrepareForNavigationAsync(CancellationToken token)=>Task.CompletedTask;
    Task<FlightObservation> ReadAsync(CancellationToken token);
    // Apply on the game's owning thread, only if frame sequence, target, build, loadout and deadline still match.
    // BeginCharging is an idempotent desired state, never a toggle. The interlock is held until PermitJump.
    Task ApplyAsync(FlightDecision decision,long expectedSequence,NavWaypoint next,DateTimeOffset expiresAt,CancellationToken token);
    // Cancels owned charging and relinquishes only this driver's input overrides. Must work after cancellation.
    Task ReleaseAsync();
}
public enum NavigationRunState { Idle,Running,Completed,Stopped,Failed }
public sealed record NavigationProgress(NavigationRunState State,string Destination,string NextSystem,string Message,FlightDecision? Decision=null);

/// <summary>Closed-loop sequencing; a verified build-specific native driver is required for any flight input.</summary>
public sealed class NavigationRunner(Func<PlayerState> player,Func<DateTimeOffset>? clock=null)
{
    // The game's Journal clock can lead Windows UTC by several seconds.
    // This allowance applies only to matching Journal transitions, never to
    // native frame freshness, command expiry or jump/arrival wait deadlines.
    private const int JournalFutureAllowanceSeconds=5;
    private readonly Func<DateTimeOffset> time=clock??(()=>DateTimeOffset.UtcNow);
    private readonly object gate=new();
    private CancellationTokenSource? cancellation;
    private InputFreeJumpSnapshot? inputFreeJump;
    private FlightAutomationStopRecord? lastStop;
    private string stopRunId="";
    private CancellationToken parentCancellation;
    public FlightAutomationStopRecord? LastStop{get{lock(gate)return lastStop;}}
    public event Action<FlightAutomationStopRecord>? StopRecorded;
    public InputFreeJumpSnapshot? AwaitingInputFreeJump{get{lock(gate)return inputFreeJump;}}
    public bool IsAwaitingInputFreeJump(PlayerState current,DateTimeOffset now)
    {lock(gate)return cancellation is {IsCancellationRequested:false}&&inputFreeJump?.Matches(current,now)==true;}
    public NavigationRunState State { get; private set; }
    public Exception? Failure {get;private set;}
    public string LastMessage{get;private set;}="";
    public event Action<NavigationProgress>? Progress;
    private FlightAutomationStopRecord CaptureStopLocked(string source,bool manual=false)
    {
        if(lastStop is not null)return lastStop;
        FlightStopSnapshot? snapshot=null;try{snapshot=FlightStopSnapshot.Capture(player());}catch{}
        return lastStop=new(stopRunId,source,time(),null,FlightAutomationStage.Interstellar,parentCancellation.IsCancellationRequested,
            source=="native-player-override"?"原生飞行帧确认玩家接管。":manual?"显式停止星际导航。":"父级取消星际导航。",null,snapshot){ManualVeto=manual,ManualVetoAt=manual?time():null};
    }
    private void PublishStop(FlightAutomationStopRecord record)
    {if(StopRecorded is {} handlers)foreach(Action<FlightAutomationStopRecord> handler in handlers.GetInvocationList())try{handler(record);}catch{}}
    public void Stop()
    {
        CancellationTokenSource? stop;FlightAutomationStopRecord? record=null;
        lock(gate){inputFreeJump=null;stop=cancellation;if(stop is not null)record=CaptureStopLocked("runner-stop",manual:true);}
        if(record is not null)PublishStop(record);try{stop?.Cancel();}catch(ObjectDisposedException){}
    }
    public async Task RunAsync(string destination,IFlightControlDriver driver,CancellationToken token=default,IFlightJourneyFailureClassifier? failureClassifier=null)
    {
        Failure=null;
        CancellationTokenSource stop;
        lock(gate)
        {
            if(cancellation is not null)throw new InvalidOperationException("自动导航已经在运行。");
            stop=CancellationTokenSource.CreateLinkedTokenSource(token);cancellation=stop;inputFreeJump=null;lastStop=null;stopRunId=Guid.NewGuid().ToString("N");parentCancellation=token;
        }
        using var clearJumpOnCancellation=stop.Token.Register(()=>
        {
            FlightAutomationStopRecord? record=null;
            lock(gate)if(ReferenceEquals(cancellation,stop)){inputFreeJump=null;record=CaptureStopLocked("parent-token");}
            if(record is not null)PublishStop(record);
        });
        NavigationProgress? terminal=null;
        var lastNext="—";
        void Report(NavigationRunState state,string next,string message,FlightDecision? decision=null)
        {
            if(state!=NavigationRunState.Running){terminal=new(state,destination,next,message,decision);return;}
            lastNext=next;State=state;LastMessage=message;Progress?.Invoke(new(state,destination,next,message,decision));
        }
        try
        {
            destination=destination.Trim();var initial=player();
            if(NavigationSafety.UnhealthyHull(initial))throw new InvalidOperationException("船体已失效,无法继续自动操作。");
            // Journal event timestamps have one-second precision.
            var startedAt=DateTimeOffset.FromUnixTimeSeconds(time().ToUnixTimeSeconds());
            var journalStartedAt=GameJournalClock.Now(initial,startedAt);
            IReadOnlyList<NavWaypoint> Remaining(NavigationJournalState nav)=>NavigationProjector.RemainingRoute(nav,destination);
            var remaining=Remaining(initial.Navigation);
            if(remaining.Count==0){Report(NavigationRunState.Completed,"已抵达","已到达目标星系。");return;}
            if(!initial.InGame||initial.Docked)throw new InvalidOperationException("请在可控、安全的飞行状态下启动导航。");
            if(NavigationSafety.HasExternalThreat(initial))throw new FlightThreatPauseException();
            var route=initial.Navigation.Route.Select(w=>w.SystemAddress).ToArray();
            var finalWaypoint=initial.Navigation.Route[^1];
            void RequireSameFlight()
            {
                var state=player();
                if(NavigationSafety.UnhealthyHull(state)||!state.InGame||state.Docked)
                    throw new InvalidOperationException("游戏会话或飞船安全状态已改变,已释放导航控制。");
                if(NavigationSafety.HasExternalThreat(state))throw new FlightThreatPauseException();
                if(!NavigationRouteProgress.SameItinerary(route,state.Navigation)
                    &&!FinalJumpRouteClear.Matches(state.Navigation,finalWaypoint,journalStartedAt,GameJournalClock.Now(state,time())))
                    throw new InvalidOperationException("游戏航线已变更,已停止导航。");
            }
            await driver.BeginNavigationSessionAsync(stop.Token);
            var capabilities=await NavigationRecovery.PreflightWithRecoveryAsync(driver,
                ()=>{RequireSameFlight();Report(NavigationRunState.Running,remaining[0].Name,"正在恢复导航连接,原航线保留并自动继续。");},stop.Token);
            var navigator=new FlightNavigator();var unknownSince=(DateTimeOffset?)null;DateTimeOffset? telemetryGapSince=null,jumpWaitSince=null,lastSceneProbeAt=null;long previousSequence=0;long selectedTarget=0;
            var prepared=false;
            async Task PauseForTelemetry(string next,Exception? error=null)
            {
                var recovery=NavigationRecovery.Kind(error);telemetryGapSince??=time();
                Exception? cleanupFailure=null;
                if(recovery!=FlightRecovery.ReadNextFrame)
                {
                    try{await driver.ReleaseAsync();}
                    catch(Exception release)when(NavigationRecovery.CanRetry(release,stop.Token)){cleanupFailure=release;}
                }
                if(failureClassifier is not null&&time()-telemetryGapSince>=TimeSpan.FromSeconds(30)
                    &&(lastSceneProbeAt is null||time()-lastSceneProbeAt>=TimeSpan.FromSeconds(5)))
                {
                    // This is a read-only scene check after releasing flight
                    // input. A timeout alone never authorizes a client restart.
                    lastSceneProbeAt=time();stop.Token.ThrowIfCancellationRequested();
                    if(NavigationSafety.UnhealthyHull(player()))throw new FlightHealthPauseException();
                    if(NavigationSafety.HasExternalThreat(player()))throw new FlightThreatPauseException();
                    if(recovery==FlightRecovery.ReadNextFrame)
                    {
                        try{await driver.ReleaseAsync();}
                        catch(Exception release)when(NavigationRecovery.CanRetry(release,stop.Token)){cleanupFailure=release;}
                    }
                    var original=error??new FlightTelemetryUnavailableException("持续等待最新星际飞行遥测。");
                    if(cleanupFailure is not null)original=new AggregateException(original,cleanupFailure);
                    var classified=await failureClassifier.ClassifyFailureAsync(original,stop.Token);
                    stop.Token.ThrowIfCancellationRequested();
                    if(!ReferenceEquals(classified,original)&&(FlightConnectionRecoveryRequiredException.Find(classified) is not null
                        ||SavingSceneRecoveryRequiredException.Present(classified)))throw classified;
                }
                if(recovery==FlightRecovery.RefreshDriver)
                {
                    capabilities=await NavigationRecovery.PreflightWithRecoveryAsync(driver,
                        ()=>{RequireSameFlight();Report(NavigationRunState.Running,next,"正在恢复导航连接,原航线保留并自动继续。");},stop.Token);
                    // A renewed connection must acknowledge the same next hop
                    // before it receives any new charging or steering command.
                    selectedTarget=0;prepared=false;
                }
                if(recovery==FlightRecovery.ReselectTarget){selectedTarget=0;prepared=false;}
                Report(NavigationRunState.Running,next,recovery==FlightRecovery.ReadNextFrame?"正在更新飞行数据并自动重试。":"遥测短暂中断,正在重新连接并恢复导航。");
                await Task.Delay(recovery==FlightRecovery.ReadNextFrame?40:time()-telemetryGapSince>TimeSpan.FromSeconds(30)?1000:100,stop.Token);
            }
            DateTimeOffset? finalClearSince=null;
            bool ExpectedFinalClear(NavigationJournalState nav)=>FinalJumpRouteClear.Matches(nav,finalWaypoint,journalStartedAt,GameJournalClock.Now(player(),time()));
            Report(NavigationRunState.Running,remaining[0].Name,"正在读取并核对原生飞行遥测。");
            while(true)
            {
                stop.Token.ThrowIfCancellationRequested();var state=player();
                lock(gate)if(inputFreeJump is {} remembered&&!remembered.Matches(state,time()))inputFreeJump=null;
                if(NavigationSafety.UnhealthyHull(state))throw new InvalidOperationException("船体已失效,已停止自动导航。");
                if(!state.InGame)throw new InvalidOperationException("游戏会话结束,已停止导航。");
                if(NavigationSafety.HasExternalThreat(state))throw new FlightThreatPauseException();
                if(!NavigationRouteProgress.SameItinerary(route,state.Navigation))
                {
                    if(!ExpectedFinalClear(state.Navigation))throw new InvalidOperationException("游戏航线已变更,已停止导航。");
                    if(finalClearSince is null)
                    {
                        finalClearSince=jumpWaitSince??time();await driver.ReleaseAsync();stop.Token.ThrowIfCancellationRequested();
                        var released=player();var witness=InputFreeJumpSnapshot.AfterSuccessfulRelease(initial,released,finalWaypoint,journalStartedAt,finalClearSince.Value);
                        lock(gate)if(ReferenceEquals(cancellation,stop)&&!stop.IsCancellationRequested)inputFreeJump=witness;
                    }
                    if(!state.Navigation.JumpInProgress&&state.Navigation.CurrentSystemAddress==finalWaypoint.SystemAddress
                        &&state.Navigation.LastJumpAt>=state.Navigation.JumpStartedAt)
                    {
                        Report(NavigationRunState.Completed,"已抵达","Journal 已确认最后一跳抵达目标星系。");break;
                    }
                    if(time()-finalClearSince>TimeSpan.FromSeconds(60))throw new InvalidOperationException("最后一跳的抵达事件超时,已停止导航并释放控制。");
                    Report(NavigationRunState.Running,finalWaypoint.Name,"航线已在最后一跳中清空,等待 Journal 确认抵达。");
                    await Task.Delay(TimeSpan.FromMilliseconds(100),stop.Token);continue;
                }
                // FSDTarget for the following leg can precede FSDJump by several
                // seconds. Keep the acknowledged in-flight leg until its actual
                // arrival; do not compare that future target to the old system.
                if(state.Navigation.JumpInProgress&&state.Navigation.JumpTargetSystemAddress==remaining[0].SystemAddress
                    &&state.Navigation.JumpTargetSystem.Equals(remaining[0].Name,StringComparison.OrdinalIgnoreCase)
                    &&state.Navigation.JumpStartedAt is {} activeJump&&activeJump>=journalStartedAt&&activeJump<=GameJournalClock.Now(state,time()).AddSeconds(JournalFutureAllowanceSeconds))
                {
                    if(jumpWaitSince is null)
                    {
                        jumpWaitSince=time();await driver.ReleaseAsync();stop.Token.ThrowIfCancellationRequested();
                        var released=player();var witness=InputFreeJumpSnapshot.AfterSuccessfulRelease(initial,released,remaining[0],journalStartedAt,jumpWaitSince.Value);
                        lock(gate)if(ReferenceEquals(cancellation,stop)&&!stop.IsCancellationRequested)inputFreeJump=witness;
                    }
                    if(time()-jumpWaitSince>TimeSpan.FromSeconds(75))throw new InvalidOperationException("跃迁抵达事件超时,已释放自动控制。");
                    Report(NavigationRunState.Running,remaining[0].Name,"跃迁已开始,等待实际抵达;加载期间不发送飞行输入。");
                    await Task.Delay(100,stop.Token);continue;
                }
                jumpWaitSince=null;
                remaining=Remaining(state.Navigation);
                if(remaining.Count==0){Report(NavigationRunState.Completed,"已抵达","Journal 已确认抵达目标星系。");break;}
                if(selectedTarget!=remaining[0].SystemAddress)
                {
                    Report(NavigationRunState.Running,remaining[0].Name,"正在游戏中锁定下一跳目的地。");
                    try{await driver.SelectTargetAsync(remaining[0],stop.Token);}
                    catch(Exception error)when(NavigationRecovery.CanRetry(error,stop.Token))
                    {
                        await PauseForTelemetry(remaining[0].Name,error);continue;
                    }
                    selectedTarget=remaining[0].SystemAddress;prepared=false;
                    Report(NavigationRunState.Running,remaining[0].Name,"目的地已锁定,正在检查飞行状态与跃迁条件。");
                }
                if(!prepared)
                {
                    try{await driver.PrepareForNavigationAsync(stop.Token);prepared=true;}
                    catch(Exception error)when(NavigationRecovery.CanRetry(error,stop.Token))
                    {await PauseForTelemetry(remaining[0].Name,error);continue;}
                }
                using var readStop=CancellationTokenSource.CreateLinkedTokenSource(stop.Token);readStop.CancelAfter(TimeSpan.FromMilliseconds(500));
                FlightObservation observation;
                try{observation=await driver.ReadAsync(readStop.Token).WaitAsync(readStop.Token);}
                catch(Exception error)when(NavigationRecovery.CanRetry(error,stop.Token))
                {
                    await PauseForTelemetry(remaining[0].Name,error);continue;
                }
                var frame=observation.Frame;var now=time();
                if(NavigationSafety.MustStop(state,frame,now))throw new InvalidOperationException("无法确认危险来源,已停止导航并释放控制。");
                if(frame.Sequence<previousSequence)throw new InvalidOperationException("原生遥测序号倒退,已释放控制。");
                if(frame.Sequence==previousSequence){await PauseForTelemetry(remaining[0].Name);continue;}
                previousSequence=frame.Sequence;
                if(frame.GameSha256!=capabilities.GameSha256)throw new InvalidOperationException("游戏构建与已校验驱动不匹配。");
                if(frame.SystemAddress!=state.Navigation.CurrentSystemAddress)
                {
                    await driver.ReleaseAsync();unknownSince??=now;
                    Report(NavigationRunState.Running,remaining[0].Name,"正在自动同步星系位置,原航线保留并自动继续。");
                    await Task.Delay(now-unknownSince>TimeSpan.FromSeconds(30)?1000:100,stop.Token);continue;
                }
                if(frame.TargetSystemAddress!=remaining[0].SystemAddress)
                {await PauseForTelemetry(remaining[0].Name,new FlightTelemetryUnavailableException("重新确认下一跳。",recovery:FlightRecovery.ReselectTarget));continue;}
                // No enabled scoop cannot turn a measured shortfall into fuel.
                // Return the typed task to the journey owner instead of waiting forever.
                if(frame.PlayerOverride)
                {
                    FlightAutomationStopRecord record;lock(gate){inputFreeJump=null;record=CaptureStopLocked("native-player-override",manual:true);}PublishStop(record);
                    Report(NavigationRunState.Stopped,remaining[0].Name,"玩家已接管,自动导航停止。");break;
                }
                if(frame.GeometryVerified&&now-frame.ObservedAt<=TimeSpan.FromMilliseconds(300)&&frame.ObservedAt<=now.AddMilliseconds(100)
                    &&NavigationFuelResupply.Required(frame) is {} shortage)throw shortage;
                var decision=navigator.Decide(frame,remaining[0],observation.Thermal,now);
                if(decision.Direction is null&&!decision.PermitJump&&!decision.BeginCharging)
                {
                    await driver.ReleaseAsync();unknownSince??=now;
                    if(now-unknownSince>TimeSpan.FromSeconds(30))
                    {
                        Report(NavigationRunState.Running,remaining[0].Name,"正在恢复飞行条件,原航线保留并自动继续:"+decision.Reason,decision);
                        await Task.Delay(1000,stop.Token);continue;
                    }
                }
                else
                {
                    unknownSince=null;
                    // Recheck journal state after the asynchronous read, immediately before native application.
                    var latest=player();
                    if(latest.InGame&&!NavigationSafety.HasExternalThreat(latest)&&ExpectedFinalClear(latest.Navigation))
                    {
                        await driver.ReleaseAsync();finalClearSince??=time();continue;
                    }
                    var latestNext=Remaining(latest.Navigation).FirstOrDefault();
                    if(!latest.InGame||NavigationSafety.MustStop(latest,frame,time())||latestNext?.SystemAddress!=remaining[0].SystemAddress||latest.Navigation.CurrentSystemAddress!=frame.SystemAddress||!route.SequenceEqual(latest.Navigation.Route.Select(w=>w.SystemAddress)))throw new InvalidOperationException("应用控制前游戏状态已改变。");
                    try{await driver.ApplyAsync(decision,frame.Sequence,remaining[0],frame.ObservedAt.AddMilliseconds(300),stop.Token);}
                    catch(Exception error)when(NavigationRecovery.CanRetry(error,stop.Token))
                    {await PauseForTelemetry(remaining[0].Name,error);continue;}
                }
                telemetryGapSince=null;lastSceneProbeAt=null;
                Report(NavigationRunState.Running,remaining[0].Name,decision.Reason,decision);
                await Task.Delay(TimeSpan.FromMilliseconds(40),stop.Token);
            }
        }
        catch(OperationCanceledException)when(stop.IsCancellationRequested){Report(NavigationRunState.Stopped,"—","自动导航已停止。");}
        catch(OperationCanceledException e){Failure=e;Report(NavigationRunState.Failed,lastNext,"原生飞行遥测超时,已释放控制。");}
        catch(Exception e){Failure=e;Report(NavigationRunState.Failed,lastNext,e.Message);}
        finally
        {
            try{await driver.ReleaseAsync();}
            catch(Exception e){Failure=Failure is null?e:new AggregateException(Failure,e);terminal=new(NavigationRunState.Failed,destination,"—","释放自动控制失败:"+e.Message);}
            finally
            {
                lock(gate){inputFreeJump=null;cancellation=null;}stop.Dispose();
                if(terminal is {} final){State=final.State;LastMessage=final.Message;Progress?.Invoke(final);}
            }
        }
    }
}