using System.Globalization; using System.Text.Json; using XFEEDToolBox.Core.Models; namespace XFEEDToolBox.Core.Navigation; /// Journal Undocked attests leaving a pad, not a safe station exit or an inactive original launch duty. public static class StationDepartureContinuity { private static bool Flag(JsonElement value,string key,bool expected)=>value.ValueKind==JsonValueKind.Object&&value.TryGetProperty(key,out var found) &&found.ValueKind==(expected?JsonValueKind.True:JsonValueKind.False); private static bool DutyFlagsKnown(JsonElement dock)=>new[]{"nativeLaunchActive","nativeLaunchRequested","nativeDutyActive"} .All(name=>Flag(dock,name,false)||Flag(dock,name,true)); /// All-false fields are defaults when the original computer could not be resolved. public static bool NativeDutySourceVerified(JsonElement dock)=>DutyFlagsKnown(dock) &&(Flag(dock,"computerAvailable",true)||Flag(dock,"nativeLaunchActive",true)||Flag(dock,"nativeLaunchRequested",true) ||Flag(dock,"nativeDutyActive",true)||Flag(dock,"throttleZero",true)||Flag(dock,"zeroThrottleInputSent",true)); public static bool NativeLaunchInactive(JsonElement dock)=>NativeDutySourceVerified(dock)&&Flag(dock,"nativeLaunchActive",false) &&Flag(dock,"nativeLaunchRequested",false)&&Flag(dock,"nativeDutyActive",false); public static bool VerifiedNoInstalledDockingComputer(PlayerState player,DateTimeOffset now) { var ship=player.Ships.SingleOrDefault(row=>row.ShipId==player.CurrentShipId); return player.LoadGameAt is {} loaded&&ship is {ConfigurationChanged:false,Modules.Count:>0,Type.Length:>0,ConfigurationAt:{} configured} &&configured>=loaded&&configured<=GameJournalClock.Now(player,now).AddSeconds(5) &&ship.Modules.All(module=>module.Item.Length>0&&module.Slot.Length>0) &&!ship.Modules.Any(module=>module.Item.Equals("int_dockingcomputer_standard",StringComparison.OrdinalIgnoreCase) ||module.Item.Equals("int_dockingcomputer_advanced",StringComparison.OrdinalIgnoreCase)); } public static SystemNavigationTarget ObservationTarget(CurrentSystemSnapshot catalogue,ulong reference) { var bodies=catalogue.Locations.Where(row=>row.Category is SystemLocationCategory.Star or SystemLocationCategory.Planet or SystemLocationCategory.LandablePlanet &&row.WorldAddress>0&&row.Key>=0&&row.NativeKind>0&&row.Name.Length is >0 and <=160&&row.Identity.Length==64&&row.Identity.All(Uri.IsHexDigit)).ToArray(); var body=bodies.FirstOrDefault(row=>row.WorldAddress==reference)??bodies.FirstOrDefault(row=>row.Category==SystemLocationCategory.Star) ??bodies.FirstOrDefault(row=>row.Selected)??bodies.FirstOrDefault() ??throw new InvalidDataException("缺少具有完整原版身份的物理天体观察目标,未选择信号源或猜测离站站点。"); return new(catalogue.SystemAddress,body.WorldAddress,body.Name,SystemTargetKind.Orbit,body.MarketId) {NativeKey=body.Key,NativeKind=body.NativeKind,NativeIdentity=body.Identity}; } private static ulong Id(JsonElement value,string key)=>value.TryGetProperty(key,out var found)&&found.ValueKind==JsonValueKind.String &&ulong.TryParse(found.GetString(),NumberStyles.None,CultureInfo.InvariantCulture,out var id)?id:0; private static bool Fresh(JsonElement value,DateTimeOffset now)=>value.TryGetProperty("observedAtUnixMilliseconds",out var found)&&found.TryGetInt64(out var at) &&at<=now.ToUnixTimeMilliseconds()&&now.ToUnixTimeMilliseconds()-at<=300; public static Station? KnownOrigin(PlayerState player,DateTimeOffset now) { var nav=player.Navigation;var at=nav.UndockedAt; return player.InGame&&!player.Docked&&player.LoadGameAt is {} loaded&&at>=loaded&&at<=GameJournalClock.Now(player,now).AddSeconds(5) &&nav.UndockedMarketId is >0&&nav.UndockedStationName.Length>0&&nav.UndockedSystemAddress is >0 &&nav.UndockedSystemAddress==nav.CurrentSystemAddress&&!(nav.LastJumpAt>at)&&!(nav.SupercruiseEnteredAt>at) ?new(){MarketId=nav.UndockedMarketId.Value,Name=nav.UndockedStationName,SystemName=player.SystemName,Position=player.Position}:null; } private static bool CompletedSupercruiseTransit(PlayerState player,DateTimeOffset now) { var nav=player.Navigation; return player.LoadGameAt is {} loaded&&nav.SupercruiseEnteredAt is {} entered&&nav.SupercruiseExitedAt is {} exited &&entered>=loaded&&exited>entered&&exited<=GameJournalClock.Now(player,now).AddSeconds(5) &&!(nav.UndockedAt>=entered)&&!(nav.UndockedAt>=exited)&&!(nav.LastJumpAt>=exited); } /// True only for actual supercruise/hyperspace, where an original station launch cannot own the current flight. public static bool RequireFreshMain(PlayerState player,JsonElement raw,DateTimeOffset now) { if(!player.InGame||player.CurrentShipId is null||player.LoadGameAt is null||!Flag(raw,"inGame",true)||!Flag(raw,"localPlayerShipVerified",true) ||!Fresh(raw,now)||Id(raw,"entityId")==0||Id(raw,"referenceWorldAddress")==0) throw new FlightTelemetryUnavailableException("等待当前主船的离站连续性观测,尚未发送驾驶输入。"); if(player.Navigation.CurrentSystemAddress is not >0||NativeFrameProjector.SystemAddressFromBody(Id(raw,"referenceWorldAddress"))!=player.Navigation.CurrentSystemAddress) throw new FlightTelemetryUnavailableException("等待原版离站参考系与当前星系一致。"); if(!Flag(raw,"playerOverride",false))throw new InvalidDataException("玩家已接管或接管状态未确认,未接续原版离站。"); if(!raw.TryGetProperty("shipHealth",out var health)||!Flag(health,"verified",true)||Id(health,"entityId")!=Id(raw,"entityId")||!Fresh(health,now)) throw new FlightTelemetryUnavailableException("等待离站中的实际健康状态。"); if(!Flag(health,"emergency",false)||!Flag(health,"damageObserved",false)||!health.TryGetProperty("hullFraction",out var hull) ||!hull.TryGetDouble(out var fraction)||!double.IsFinite(fraction)||fraction is <=0 or >1)throw new FlightHealthPauseException(); if(NavigationSafety.HasExternalThreat(player))throw new FlightThreatPauseException(); if(!TravelPreparation.StatusConfirmed(player,now))throw new FlightTelemetryUnavailableException("等待当前驾驶舱状态,未接续离站。"); var fsd=raw.GetProperty("rawFsdState").GetInt32(); return fsd==4||(player.Status!.Flags&16)!=0&&fsd is 2 or 3; } public static bool NeedsContinuation(PlayerState player,JsonElement raw,JsonElement local,long? localDestinationMarket,DateTimeOffset now) { if(RequireFreshMain(player,raw,now))return false; if(local.ValueKind!=JsonValueKind.Object||!Fresh(local,now)||Id(local,"entityId")!=Id(raw,"entityId") ||Id(local,"referenceWorldAddress")!=Id(raw,"referenceWorldAddress")||!Flag(local,"geometryVerified",true) ||!local.TryGetProperty("docking",out var dock))throw new FlightTelemetryUnavailableException("等待原版起降任务的最新状态,尚未启动后续驾驶。"); if(!NativeDutySourceVerified(dock)) { // A manual departure can retain its old Journal origin. The // independent verified absence + unlocked free-flight proof does // not depend on that old launch obligation disappearing first. if(DutyFlagsKnown(dock)&&VerifiedNoInstalledDockingComputer(player,now)&&raw.GetProperty("rawFsdState").GetInt32()==2 &&(player.Status!.Flags&((1L<<16)|16|1))==0)return false; if(KnownOrigin(player,now) is not null)return true; if(!DutyFlagsKnown(dock)||!VerifiedNoInstalledDockingComputer(player,now)) throw new InvalidDataException("原版起降任务读取来源尚未确认,不能把默认未激活值当作已停止。"); // Only a complete current loadout with no installed computer may // establish free flight without a computer observation. Disabled // or damaged fitted computers are still installed. return raw.GetProperty("rawFsdState").GetInt32()!=2||(player.Status!.Flags&((1L<<16)|1))!=0; } if(!Flag(dock,"nativeLaunchActive",false)||!Flag(dock,"nativeLaunchRequested",false))return true; if(!Flag(dock,"nativeDutyActive",false)) { // Preserve a real incoming original landing at the user's actual // local destination; it is not a departure to be cancelled. return !(localDestinationMarket is >0&&Flag(dock,"verified",true)&&Flag(dock,"clearanceGranted",true) &&local.GetProperty("target").GetProperty("marketId").GetInt64()==localDestinationMarket &&local.GetProperty("rawDockingState").GetInt32() is 3 or 4); } // A real same-session SC journey has physically left the launch area. // Its normal-space exit can still be mass locked at an arrival station; // require current native inactive evidence, never just historical music // or an exit event without its actual entry and ordering proof. if(NativeLaunchInactive(dock)&&raw.GetProperty("rawFsdState").GetInt32()==2&&(player.Status!.Flags&(16|1))==0 &&Flag(local,"inSupercruise",false)&&CompletedSupercruiseTransit(player,now))return false; if(localDestinationMarket is >0&&KnownOrigin(player,now)?.MarketId==localDestinationMarket)return false; return raw.GetProperty("rawFsdState").GetInt32()!=2||(player.Status!.Flags&((1L<<16)|1))!=0; } }