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 GameRouteStatus(long Generation,bool Applied,bool Pending,bool Failed,long DestinationAddress,long TargetAddress,bool TargetFresh,bool TopologyFresh=false,int WaypointCount=0,ulong RouteFingerprint=0);
public sealed record GameRoutePlan(IReadOnlyList<NavWaypoint> Route,NavWaypoint Next,DateTimeOffset? ObservedAt,ulong NativeRouteFingerprint);
public static class GameRouteFingerprint
{
    public static ulong Compute(IReadOnlyList<NavWaypoint> route)
    {var hash=14695981039346656037UL;foreach(var waypoint in route)hash=unchecked((hash^(ulong)waypoint.SystemAddress)*1099511628211UL);return hash;}
}
public interface IGameRoutePlanningDriver
{
    bool SupportsGameRoutePlanning { get; }
    Task<long> RequestGameRouteAsync(NavWaypoint destination,CancellationToken token);
    Task<GameRouteStatus> ReadGameRouteStatusAsync(long generation,long destinationAddress,CancellationToken token);
}

/// <summary>Submits an endpoint to the original game planner and verifies its Journal result.
/// Never constructs a route, searches a galaxy graph or substitutes a direct jump.</summary>
public sealed class GameRoutePlanner(Func<PlayerState> player,TimeSpan? timeout=null)
{
    public async Task<GameRoutePlan> PlanAsync(NavWaypoint destination,IGameRoutePlanningDriver driver,Action<string>? progress=null,CancellationToken token=default,GameRoutePlotOptions? options=null)
    {
        if(destination.SystemAddress<=0||string.IsNullOrWhiteSpace(destination.Name))throw new InvalidOperationException("目标星系缺少有效的游戏地址。");
        if(!driver.SupportsGameRoutePlanning)throw new InvalidOperationException("游戏中加载的插件尚不支持航线规划,请更新插件并重新启动游戏。");
        var before=player();var origin=before.Navigation.CurrentSystemAddress;
        if(!before.InGame||origin is not >0)throw new InvalidOperationException("请先进入游戏,读取当前星系后再规划航线。");
        if(origin==destination.SystemAddress)throw new InvalidOperationException("当前已在目标星系,无需规划航线。");
        if(before.Navigation.JumpInProgress)throw new InvalidOperationException("请等待当前跃迁完成后再规划航线。");
        options?.Validate(before.CargoCapacity);
        if(options?.HasOverrides==true&&driver is not IGameRouteOptionsPlanningDriver{SupportsGameRouteOptions:true})
            throw new InvalidOperationException("当前游戏插件尚不支持航线设置,请更新插件或选择保留游戏当前设置。");
        if(options?.StarClassFilter is not null&&driver is not IGameRouteOptionsPlanningDriver{SupportsRouteStarClassFilter:true})
            throw new InvalidOperationException("当前游戏插件尚不支持恒星类别路线筛选,请更新插件或保留游戏当前筛选。");
        if(options?.MapFilter is not null&&driver is not IGameRouteOptionsPlanningDriver{SupportsRouteMapFilters:true})
            throw new InvalidOperationException("当前游戏插件尚不支持此类别的路线筛选,请更新插件或保留游戏当前筛选。");
        using var deadline=CancellationTokenSource.CreateLinkedTokenSource(token);deadline.CancelAfter(timeout??TimeSpan.FromMinutes(3));
        var generation=options?.HasOverrides==true
            ?await ((IGameRouteOptionsPlanningDriver)driver).RequestGameRouteAsync(destination,options,deadline.Token)
            :await driver.RequestGameRouteAsync(destination,deadline.Token);
        if(generation<=0)throw new InvalidDataException("游戏航线请求缺少有效的回执。");
        progress?.Invoke("游戏正在计算航线,等待确认完整航路与下一跳…");
        try
        {
            while(true)
            {
                deadline.Token.ThrowIfCancellationRequested();
                GameRouteStatus status;
                try{status=await driver.ReadGameRouteStatusAsync(generation,destination.SystemAddress,deadline.Token);}
                catch(Exception error)when(NavigationRecovery.CanRetry(error,deadline.Token))
                {progress?.Invoke("正在重新读取游戏航线确认…");await Task.Delay(150,deadline.Token);continue;}
                if(status.Generation!=generation)throw new InvalidDataException("游戏航线回执与本次请求不一致。");
                if(status.Failed||!status.Applied&&!status.Pending)throw new InvalidOperationException("游戏未接受本次航线规划请求,请重试。");
                var current=player();var nav=current.Navigation;
                if(!current.InGame||nav.CurrentSystemAddress!=origin||nav.JumpInProgress)throw new InvalidOperationException("规划期间游戏会话或当前星系改变,请重新规划。");
                if(status.Applied&&status.DestinationAddress!=0&&status.DestinationAddress!=destination.SystemAddress)
                    throw new InvalidOperationException("游戏内的航线终点已改变,请重新规划。");
                var route=nav.Route;
                if(status.Applied&&status.TopologyFresh&&status.WaypointCount==route.Count&&route.Count>=2
                    &&GameRouteFingerprint.Compute(route)==status.RouteFingerprint&&route[^1].SystemAddress==destination.SystemAddress
                    &&!route[^1].Name.Equals(destination.Name,StringComparison.OrdinalIgnoreCase))
                    throw new InvalidDataException("游戏航线终点名称与所选星系不一致,请重新搜索目标。");
                // The game's route cache may avoid rewriting NavRoute.json. In either
                // case the entire ordered path must match the live original game list.
                if(status.Applied&&status.DestinationAddress==destination.SystemAddress&&status.TopologyFresh&&status.WaypointCount==route.Count
                    &&route.Count>=2&&route[^1].SystemAddress==destination.SystemAddress&&route[^1].Name.Equals(destination.Name,StringComparison.OrdinalIgnoreCase))
                {
                    if(route.Count>25000||route.Any(w=>w.SystemAddress<=0||w.Name.Length==0||!w.Position.IsValid))
                        throw new InvalidDataException("游戏返回的航路包含无效数据。");
                    var index=-1;for(var i=0;i<route.Count;i++)if(route[i].SystemAddress==origin){index=i;break;}
                    if(index<0||index+1>=route.Count)throw new InvalidDataException("游戏航路未包含当前星系和下一跳。");
                    var next=route[index+1];
                    if(status.TargetFresh&&status.TargetAddress==next.SystemAddress&&GameRouteFingerprint.Compute(route)==status.RouteFingerprint)
                        return new(route,next,nav.RouteAt,status.RouteFingerprint);
                }
                await Task.Delay(100,deadline.Token);
            }
        }
        catch(OperationCanceledException)when(!token.IsCancellationRequested)
        {throw new TimeoutException("等待游戏航线规划结果超时,尚未确认成功。请检查游戏中的规划提示后重试。");}
    }
}