using System.Diagnostics;
using XFEEDToolBox.Core.Models;
namespace XFEEDToolBox.Core.Navigation;
public sealed record GameInputState(long Sequence,ulong EntityId,DateTimeOffset ObservedAt,bool Hardpoints,bool CargoScoop,bool LandingGear,long AppliedGeneration=0)
{
public bool Retracted=>!Hardpoints&&!CargoScoop&&!LandingGear;
}
public interface IGameInputChannel
{
Task ConnectAsync(int owningThread,CancellationToken token);
Task<GameInputState> ReadAsync(CancellationToken token);
Task<long> SetAsync(GameInputState frame,string input,bool value,CancellationToken token);
}
/// <summary>The application owns the travel workflow; the plugin only reads and sets native desired inputs.</summary>
public static class TravelPreparation
{
private const long Deployed=(1L<<2)|(1L<<6)|(1L<<9);
public static bool HasDeployedEquipment(PlayerState player)=>((player.Status?.Flags??0)&Deployed)!=0;
public static bool StatusConfirmed(PlayerState player,DateTimeOffset now)=>player.Status is not null
&&player.StatusAt is {} eventAt&&(eventAt<=now.AddSeconds(5)||GameJournalClock.Offset(player,now) is not null)
&&(player.LoadGameAt is not {} sessionAt||eventAt>=sessionAt)
&&player.StatusReadAt is {} readAt&&readAt<=now.AddMilliseconds(100)&&now-readAt<=TimeSpan.FromSeconds(2);
public static bool AtDockedDestination(PlayerState player,SystemNavigationTarget target)=>target.NeedsDocking&&player.InGame&&player.Docked
&&player.MarketId==target.MarketId&&player.Navigation.CurrentSystemAddress==target.SystemAddress;
public static bool PreserveOriginalLanding(SystemFlightFrame frame,SystemNavigationTarget target,DateTimeOffset now)=>target.NeedsDocking
&&frame.InGame&&!frame.PlayerOverride&&!frame.ExternalThreat&&frame.GeometryVerified&&frame.Sequence>0&&frame.ShipEntity!=0&&frame.ReferenceWorld!=0
&&frame.ObservedAt<=now&&now-frame.ObservedAt<=TimeSpan.FromMilliseconds(300)
&&frame.SystemAddress==target.SystemAddress&&frame.SelectedTarget is {} selected&&selected.SameIdentity(target)
&&frame.Mode is LocalFlightMode.Normal or LocalFlightMode.Transition&&frame.Assists.AutoDock&&frame.DockingAssist==NativeAssistState.Engaged
&&frame.Clearance is {Permission:DockingPermission.Granted} grant&&grant.MarketId==target.MarketId&&grant.ExpiresAt>=now
&&grant.ObservedAt<=now&&now-grant.ObservedAt<=TimeSpan.FromMilliseconds(300);
/// <returns>False when a verified arrival takes priority over travel equipment preparation.</returns>
public static async Task<bool> EnsureRetractedAsync(IGameInputChannel channel,Func<PlayerState> player,CancellationToken token,ulong? expectedEntity=null,
Func<CancellationToken,Task<bool>>? preserveArrival=null)
{
var initial=player();
PlayerState RequireState()
{
token.ThrowIfCancellationRequested();var current=player();
if(!current.InGame||current.CommanderId!=initial.CommanderId||current.CurrentShipId!=initial.CurrentShipId||current.LoadGameAt!=initial.LoadGameAt
||current.Navigation.CurrentSystemAddress!=initial.Navigation.CurrentSystemAddress||NavigationSafety.UnhealthyHull(current))
throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
if(NavigationSafety.HasExternalThreat(current))throw new FlightThreatPauseException();
return current;
}
async Task<bool> YieldToArrivalAsync()
{
if(preserveArrival is null)return false;
var shouldYield=await preserveArrival(token);RequireState();return shouldYield;
}
var clock=Stopwatch.StartNew();ulong entity=0;long waitingGeneration=0;string? waitingInput=null;
DateTimeOffset? clearSince=null;var sentAt=TimeSpan.Zero;
while(clock.Elapsed<TimeSpan.FromSeconds(12))
{
var state=RequireState();
if(await YieldToArrivalAsync())return false;
state=RequireState();
if(state.Docked)throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
GameInputState frame;
try{frame=await channel.ReadAsync(token);}
catch(Exception error)when(NavigationRecovery.CanRetry(error,token))
{
// A newly loaded input observer can refuse its first sample.
// Keep the same overall bound and send nothing until it is
// fresh and belongs to the selected main ship.
clearSince=null;await Task.Delay(40,token);continue;
}
var now=DateTimeOffset.UtcNow;
if(frame.Sequence<=0||frame.EntityId==0||frame.ObservedAt>now.AddMilliseconds(100)||now-frame.ObservedAt>TimeSpan.FromMilliseconds(300))throw new FlightTelemetryUnavailableException("收起设备的原生状态已过期。");
if(expectedEntity is {} expected&&expected!=frame.EntityId)throw new InvalidOperationException("输入通道与当前飞船身份不一致。");
if(await YieldToArrivalAsync())return false;
state=RequireState();if(state.Docked)throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
now=DateTimeOffset.UtcNow;
if(now-frame.ObservedAt>TimeSpan.FromMilliseconds(300))throw new FlightTelemetryUnavailableException("收起设备的原生状态已过期。");
if(!StatusConfirmed(state,now))
{
clearSince=null;
await Task.Delay(40,token);continue;
}
if(entity!=0&&entity!=frame.EntityId)throw new InvalidOperationException("收起设备时受控飞船已改变。");entity=frame.EntityId;
if(frame.Retracted&&!HasDeployedEquipment(state))
{
// Status reflects the physical deployment, independently of the
// desired input. Require a stable native confirmation as well.
clearSince??=now;if(now-clearSince>=TimeSpan.FromMilliseconds(80))return true;
}
else clearSince=null;
var next=frame.Hardpoints?"hardpoints":frame.CargoScoop?"cargoScoop":frame.LandingGear?"landingGear":null;
if(next is not null&&(waitingInput!=next||frame.AppliedGeneration>=waitingGeneration&&clock.Elapsed-sentAt>TimeSpan.FromSeconds(1)))
{
waitingGeneration=await channel.SetAsync(frame,next,false,token);waitingInput=next;sentAt=clock.Elapsed;
}
await Task.Delay(40,token);
}
throw new TimeoutException("游戏未确认武器挂点、货舱舱门和起落架全部收起,未开始跃迁。");
}
}
using System.Diagnostics;
using XFEEDToolBox.Core.Models;
namespace XFEEDToolBox.Core.Navigation;
public sealed record GameInputState(long Sequence,ulong EntityId,DateTimeOffset ObservedAt,bool Hardpoints,bool CargoScoop,bool LandingGear,long AppliedGeneration=0)
{
public bool Retracted=>!Hardpoints&&!CargoScoop&&!LandingGear;
}
public interface IGameInputChannel
{
Task ConnectAsync(int owningThread,CancellationToken token);
Task<GameInputState> ReadAsync(CancellationToken token);
Task<long> SetAsync(GameInputState frame,string input,bool value,CancellationToken token);
}
/// <summary>The application owns the travel workflow; the plugin only reads and sets native desired inputs.</summary>
public static class TravelPreparation
{
private const long Deployed=(1L<<2)|(1L<<6)|(1L<<9);
public static bool HasDeployedEquipment(PlayerState player)=>((player.Status?.Flags??0)&Deployed)!=0;
public static bool StatusConfirmed(PlayerState player,DateTimeOffset now)=>player.Status is not null
&&player.StatusAt is {} eventAt&&(eventAt<=now.AddSeconds(5)||GameJournalClock.Offset(player,now) is not null)
&&(player.LoadGameAt is not {} sessionAt||eventAt>=sessionAt)
&&player.StatusReadAt is {} readAt&&readAt<=now.AddMilliseconds(100)&&now-readAt<=TimeSpan.FromSeconds(2);
public static bool AtDockedDestination(PlayerState player,SystemNavigationTarget target)=>target.NeedsDocking&&player.InGame&&player.Docked
&&player.MarketId==target.MarketId&&player.Navigation.CurrentSystemAddress==target.SystemAddress;
public static bool PreserveOriginalLanding(SystemFlightFrame frame,SystemNavigationTarget target,DateTimeOffset now)=>target.NeedsDocking
&&frame.InGame&&!frame.PlayerOverride&&!frame.ExternalThreat&&frame.GeometryVerified&&frame.Sequence>0&&frame.ShipEntity!=0&&frame.ReferenceWorld!=0
&&frame.ObservedAt<=now&&now-frame.ObservedAt<=TimeSpan.FromMilliseconds(300)
&&frame.SystemAddress==target.SystemAddress&&frame.SelectedTarget is {} selected&&selected.SameIdentity(target)
&&frame.Mode is LocalFlightMode.Normal or LocalFlightMode.Transition&&frame.Assists.AutoDock&&frame.DockingAssist==NativeAssistState.Engaged
&&frame.Clearance is {Permission:DockingPermission.Granted} grant&&grant.MarketId==target.MarketId&&grant.ExpiresAt>=now
&&grant.ObservedAt<=now&&now-grant.ObservedAt<=TimeSpan.FromMilliseconds(300);
/// <returns>False when a verified arrival takes priority over travel equipment preparation.</returns>
public static async Task<bool> EnsureRetractedAsync(IGameInputChannel channel,Func<PlayerState> player,CancellationToken token,ulong? expectedEntity=null,
Func<CancellationToken,Task<bool>>? preserveArrival=null)
{
var initial=player();
PlayerState RequireState()
{
token.ThrowIfCancellationRequested();var current=player();
if(!current.InGame||current.CommanderId!=initial.CommanderId||current.CurrentShipId!=initial.CurrentShipId||current.LoadGameAt!=initial.LoadGameAt
||current.Navigation.CurrentSystemAddress!=initial.Navigation.CurrentSystemAddress||NavigationSafety.UnhealthyHull(current))
throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
if(NavigationSafety.HasExternalThreat(current))throw new FlightThreatPauseException();
return current;
}
async Task<bool> YieldToArrivalAsync()
{
if(preserveArrival is null)return false;
var shouldYield=await preserveArrival(token);RequireState();return shouldYield;
}
var clock=Stopwatch.StartNew();ulong entity=0;long waitingGeneration=0;string? waitingInput=null;
DateTimeOffset? clearSince=null;var sentAt=TimeSpan.Zero;
while(clock.Elapsed<TimeSpan.FromSeconds(12))
{
var state=RequireState();
if(await YieldToArrivalAsync())return false;
state=RequireState();
if(state.Docked)throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
GameInputState frame;
try{frame=await channel.ReadAsync(token);}
catch(Exception error)when(NavigationRecovery.CanRetry(error,token))
{
// A newly loaded input observer can refuse its first sample.
// Keep the same overall bound and send nothing until it is
// fresh and belongs to the selected main ship.
clearSince=null;await Task.Delay(40,token);continue;
}
var now=DateTimeOffset.UtcNow;
if(frame.Sequence<=0||frame.EntityId==0||frame.ObservedAt>now.AddMilliseconds(100)||now-frame.ObservedAt>TimeSpan.FromMilliseconds(300))throw new FlightTelemetryUnavailableException("收起设备的原生状态已过期。");
if(expectedEntity is {} expected&&expected!=frame.EntityId)throw new InvalidOperationException("输入通道与当前飞船身份不一致。");
if(await YieldToArrivalAsync())return false;
state=RequireState();if(state.Docked)throw new InvalidOperationException("收起设备时游戏会话或飞行安全状态已改变。");
now=DateTimeOffset.UtcNow;
if(now-frame.ObservedAt>TimeSpan.FromMilliseconds(300))throw new FlightTelemetryUnavailableException("收起设备的原生状态已过期。");
if(!StatusConfirmed(state,now))
{
clearSince=null;
await Task.Delay(40,token);continue;
}
if(entity!=0&&entity!=frame.EntityId)throw new InvalidOperationException("收起设备时受控飞船已改变。");entity=frame.EntityId;
if(frame.Retracted&&!HasDeployedEquipment(state))
{
// Status reflects the physical deployment, independently of the
// desired input. Require a stable native confirmation as well.
clearSince??=now;if(now-clearSince>=TimeSpan.FromMilliseconds(80))return true;
}
else clearSince=null;
var next=frame.Hardpoints?"hardpoints":frame.CargoScoop?"cargoScoop":frame.LandingGear?"landingGear":null;
if(next is not null&&(waitingInput!=next||frame.AppliedGeneration>=waitingGeneration&&clock.Elapsed-sentAt>TimeSpan.FromSeconds(1)))
{
waitingGeneration=await channel.SetAsync(frame,next,false,token);waitingInput=next;sentAt=clock.Elapsed;
}
await Task.Delay(40,token);
}
throw new TimeoutException("游戏未确认武器挂点、货舱舱门和起落架全部收起,未开始跃迁。");
}
}