Keep SpectatorRing Cleared sticky and prevent occluded lateral coordinate leaks

This commit is contained in:
Meta Vens 2026-12-04 16:48:10 +01:00
commit 2fdbc56d9f
2 changed files with 379 additions and 97 deletions

View file

@ -84,8 +84,18 @@ namespace RustToDust.Core
public const int DefaultSpectatorCount = 56; public const int DefaultSpectatorCount = 56;
public const float TargetMemoryDuration = 4.0f; public const float TargetMemoryDuration = 4.0f;
private sealed class ContenderAwareness
{
public bool HasKnownPos;
public float LastKnownX;
public float LastKnownY;
public float LastKnownZ;
public float TimeSinceSeen = TargetMemoryDuration + 1f;
}
private readonly List<SpectatorState> _spectators = new(); private readonly List<SpectatorState> _spectators = new();
private readonly Dictionary<int, bool> _aliveById = new(); private readonly Dictionary<int, bool> _aliveById = new();
private readonly Dictionary<int, ContenderAwareness> _awarenessByContender = new();
public SpectatorRing(int seed = 1337, int count = DefaultSpectatorCount) public SpectatorRing(int seed = 1337, int count = DefaultSpectatorCount)
{ {
@ -123,68 +133,83 @@ namespace RustToDust.Core
_aliveById[contenders[i].Id] = contenders[i].Alive; _aliveById[contenders[i].Id] = contenders[i].Alive;
} }
Span<int> prevTargets = _spectators.Count <= 256 // Step 1: Update per-contender ring awareness ONLY from spectators with live LOS.
? stackalloc int[_spectators.Count] for (int c = 0; c < contenders.Length; c++)
: new int[_spectators.Count]; {
Span<float> prevTimesSinceSeen = _spectators.Count <= 256 var contender = contenders[c];
? stackalloc float[_spectators.Count] var aw = GetOrCreateAwareness(contender.Id);
: new float[_spectators.Count]; if (!contender.Alive || ComputeOutsideDist(contender) <= 0f)
{
aw.HasKnownPos = false;
aw.TimeSinceSeen = TargetMemoryDuration + 1f;
continue;
}
// Keep Provoked lock while target is alive; reset Cleared to Neutral for clean re-evaluation. aw.TimeSinceSeen += dt;
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (!spec.Alive)
{
continue;
}
if (hasLos is null || hasLos(spec, contender))
{
aw.HasKnownPos = true;
aw.LastKnownX = contender.X;
aw.LastKnownY = contender.Y;
aw.LastKnownZ = contender.Z;
aw.TimeSinceSeen = 0f;
break;
}
}
}
// Step 2: Maintain existing Provoked and Cleared assignments sticky while target is valid.
for (int i = 0; i < _spectators.Count; i++) for (int i = 0; i < _spectators.Count; i++)
{ {
var spec = _spectators[i]; var spec = _spectators[i];
prevTargets[i] = spec.TargetContenderId ?? -1;
prevTimesSinceSeen[i] = spec.TimeSinceLastSeen;
if (!spec.Alive) if (!spec.Alive)
{ {
spec.TargetContenderId = null; ResetToNeutral(spec);
spec.HasTargetLos = false;
spec.TimeSinceLastSeen = TargetMemoryDuration + 1f;
continue; continue;
} }
if (spec.Stance == SpectatorStance.Provoked) if (spec.Stance == SpectatorStance.Provoked)
{ {
if (!spec.TargetContenderId.HasValue || if (!spec.TargetContenderId.HasValue ||
!_aliveById.TryGetValue(spec.TargetContenderId.Value, out bool alive) || !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact))
!alive)
{ {
spec.Stance = SpectatorStance.Neutral; ResetToNeutral(spec);
spec.TargetContenderId = null;
spec.HasTargetLos = false;
spec.TimeSinceLastSeen = TargetMemoryDuration + 1f;
} }
else else
{ {
var contact = FindContact(contenders, spec.TargetContenderId.Value); UpdateWatcherTracking(spec, contact, dt, hasLos);
bool los = hasLos is null || hasLos(spec, contact); }
if (los) }
{ else if (spec.Stance == SpectatorStance.Cleared)
spec.HasTargetLos = true; {
spec.LastKnownTargetX = contact.X; if (!spec.TargetContenderId.HasValue ||
spec.LastKnownTargetY = contact.Y; !TryFindAliveContact(contenders, spec.TargetContenderId.Value, out var contact) ||
spec.LastKnownTargetZ = contact.Z; ComputeOutsideDist(contact) <= 0f)
spec.TimeSinceLastSeen = 0f; {
} ResetToNeutral(spec);
else }
{ else
spec.HasTargetLos = false; {
spec.TimeSinceLastSeen += dt; UpdateWatcherTracking(spec, contact, dt, hasLos);
}
} }
} }
else else
{ {
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null; spec.TargetContenderId = null;
spec.HasTargetLos = false; spec.HasTargetLos = false;
spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; spec.TimeSinceLastSeen = TargetMemoryDuration + 1f;
} }
} }
// Assign Cleared spectators to contenders outside the Safe Circle, prioritizing spectators with LOS. // Step 3: Balance Cleared assignments per outside contender without reading occluded coords.
for (int c = 0; c < contenders.Length; c++) for (int c = 0; c < contenders.Length; c++)
{ {
var contender = contenders[c]; var contender = contenders[c];
@ -193,18 +218,40 @@ namespace RustToDust.Core
continue; continue;
} }
float distFromCenter = MathF.Sqrt(contender.X * contender.X + contender.Z * contender.Z); float outsideDist = ComputeOutsideDist(contender);
float outsideDist = MathF.Max(0f, distFromCenter - SafeRadius);
if (outsideDist <= 0f) if (outsideDist <= 0f)
{ {
continue; continue;
} }
int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f)); int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f));
int assigned = 0; int currentCleared = CountClearedFor(contender.Id);
// Pass 1: Spectators with direct LOS to the offender. // Drop excess if outsideDist shrank (prefer dropping stale no-LOS watchers first).
while (assigned < allowedCleared) while (currentCleared > allowedCleared)
{
int dropIdx = FindExcessClearedToDrop(contender.Id);
if (dropIdx < 0)
{
break;
}
ResetToNeutral(_spectators[dropIdx]);
currentCleared--;
}
// If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot.
if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos))
{
int staleIdx = FindStaleNoLosCleared(contender.Id);
if (staleIdx >= 0)
{
ResetToNeutral(_spectators[staleIdx]);
currentCleared--;
}
}
// Pass 1: Spectators with direct live LOS to the offender.
while (currentCleared < allowedCleared)
{ {
int bestIdx = -1; int bestIdx = -1;
float bestDistSq = float.PositiveInfinity; float bestDistSq = float.PositiveInfinity;
@ -245,66 +292,63 @@ namespace RustToDust.Core
chosen.LastKnownTargetY = contender.Y; chosen.LastKnownTargetY = contender.Y;
chosen.LastKnownTargetZ = contender.Z; chosen.LastKnownTargetZ = contender.Z;
chosen.TimeSinceLastSeen = 0f; chosen.TimeSinceLastSeen = 0f;
assigned++; currentCleared++;
} }
// Pass 2: If fewer than allowedCleared have LOS (e.g. offender ducked behind a ridge), // Pass 2: Reinforce from already-observed LastKnownPos ONLY (never read live occluded contender.X/Z).
// clear nearby spectators with recent memory or closest flanking interceptors so they maneuver over the ridge. if (currentCleared < allowedCleared &&
while (assigned < allowedCleared && hasLos is not null) hasLos is not null &&
_awarenessByContender.TryGetValue(contender.Id, out var aw) &&
aw.HasKnownPos)
{ {
int bestIdx = -1; const float maxPass2RadiusSq = 240f * 240f;
float bestScore = float.PositiveInfinity; while (currentCleared < allowedCleared)
for (int i = 0; i < _spectators.Count; i++)
{ {
var spec = _spectators[i]; int bestIdx = -1;
if (!spec.Alive || spec.Stance != SpectatorStance.Neutral) float bestDistSq = float.PositiveInfinity;
for (int i = 0; i < _spectators.Count; i++)
{ {
continue; var spec = _spectators[i];
if (!spec.Alive || spec.Stance != SpectatorStance.Neutral)
{
continue;
}
float dx = spec.X - aw.LastKnownX;
float dz = spec.Z - aw.LastKnownZ;
float d2 = dx * dx + dz * dz;
if (d2 <= maxPass2RadiusSq && d2 < bestDistSq)
{
bestDistSq = d2;
bestIdx = i;
}
} }
float dx = spec.X - contender.X; if (bestIdx < 0)
float dz = spec.Z - contender.Z;
float d2 = dx * dx + dz * dz;
bool hadTarget = prevTargets[i] == contender.Id;
bool hasMemory = hadTarget && prevTimesSinceSeen[i] < TargetMemoryDuration;
float score = hasMemory ? d2 * 0.2f : (hadTarget ? d2 * 0.35f : d2);
if (score < bestScore)
{ {
bestScore = score; break;
bestIdx = i;
} }
}
if (bestIdx < 0) var chosen = _spectators[bestIdx];
{ chosen.Stance = SpectatorStance.Cleared;
break; chosen.TargetContenderId = contender.Id;
chosen.HasTargetLos = false;
chosen.LastKnownTargetX = aw.LastKnownX;
chosen.LastKnownTargetY = aw.LastKnownY;
chosen.LastKnownTargetZ = aw.LastKnownZ;
chosen.TimeSinceLastSeen = aw.TimeSinceSeen;
currentCleared++;
} }
var chosen = _spectators[bestIdx];
chosen.Stance = SpectatorStance.Cleared;
chosen.TargetContenderId = contender.Id;
chosen.HasTargetLos = false;
if (prevTargets[bestIdx] == contender.Id)
{
chosen.TimeSinceLastSeen = prevTimesSinceSeen[bestIdx] + dt;
}
else
{
float dirX = distFromCenter > 1e-3f ? contender.X / distFromCenter : 1f;
float dirZ = distFromCenter > 1e-3f ? contender.Z / distFromCenter : 0f;
float boundaryRadius = SafeRadius + 6f;
chosen.LastKnownTargetX = dirX * boundaryRadius;
chosen.LastKnownTargetY = chosen.Y;
chosen.LastKnownTargetZ = dirZ * boundaryRadius;
chosen.TimeSinceLastSeen = TargetMemoryDuration;
}
assigned++;
} }
} }
} }
public bool OnSpectatorDamaged(SpectatorState spectator, int attackerContenderId) public bool OnSpectatorDamaged(
SpectatorState spectator,
int attackerContenderId,
float? incomingDirX = null,
float? incomingDirZ = null)
{ {
if (!spectator.Alive) if (!spectator.Alive)
{ {
@ -313,14 +357,176 @@ namespace RustToDust.Core
if (spectator.Stance == SpectatorStance.Neutral || spectator.Stance == SpectatorStance.Cleared) if (spectator.Stance == SpectatorStance.Neutral || spectator.Stance == SpectatorStance.Cleared)
{ {
bool sameTargetWithFreshMemory = spectator.TargetContenderId == attackerContenderId &&
(spectator.HasTargetLos || spectator.TimeSinceLastSeen < TargetMemoryDuration);
spectator.Stance = SpectatorStance.Provoked; spectator.Stance = SpectatorStance.Provoked;
spectator.TargetContenderId = attackerContenderId; spectator.TargetContenderId = attackerContenderId;
if (!sameTargetWithFreshMemory)
{
spectator.HasTargetLos = false;
if (_awarenessByContender.TryGetValue(attackerContenderId, out var aw) &&
aw.HasKnownPos &&
aw.TimeSinceSeen < TargetMemoryDuration)
{
spectator.LastKnownTargetX = aw.LastKnownX;
spectator.LastKnownTargetY = aw.LastKnownY;
spectator.LastKnownTargetZ = aw.LastKnownZ;
spectator.TimeSinceLastSeen = aw.TimeSinceSeen;
}
else if (incomingDirX.HasValue && incomingDirZ.HasValue)
{
float dLen = MathF.Sqrt(incomingDirX.Value * incomingDirX.Value + incomingDirZ.Value * incomingDirZ.Value);
float nx = dLen > 1e-4f ? incomingDirX.Value / dLen : MathF.Sin(spectator.Yaw);
float nz = dLen > 1e-4f ? incomingDirZ.Value / dLen : MathF.Cos(spectator.Yaw);
spectator.LastKnownTargetX = spectator.X + nx * 60f;
spectator.LastKnownTargetY = spectator.Y;
spectator.LastKnownTargetZ = spectator.Z + nz * 60f;
spectator.TimeSinceLastSeen = 0.5f;
}
else
{
spectator.LastKnownTargetX = spectator.X + MathF.Sin(spectator.Yaw) * 40f;
spectator.LastKnownTargetY = spectator.Y;
spectator.LastKnownTargetZ = spectator.Z + MathF.Cos(spectator.Yaw) * 40f;
spectator.TimeSinceLastSeen = TargetMemoryDuration;
}
}
return true; return true;
} }
return false; return false;
} }
private ContenderAwareness GetOrCreateAwareness(int contenderId)
{
if (!_awarenessByContender.TryGetValue(contenderId, out var aw))
{
aw = new ContenderAwareness();
_awarenessByContender[contenderId] = aw;
}
return aw;
}
private float ComputeOutsideDist(in RingContact contact)
{
float distFromCenter = MathF.Sqrt(contact.X * contact.X + contact.Z * contact.Z);
return MathF.Max(0f, distFromCenter - SafeRadius);
}
private static void ResetToNeutral(SpectatorState spec)
{
spec.Stance = SpectatorStance.Neutral;
spec.TargetContenderId = null;
spec.HasTargetLos = false;
spec.TimeSinceLastSeen = TargetMemoryDuration + 1f;
}
private static void UpdateWatcherTracking(
SpectatorState spec,
in RingContact contact,
float dt,
Func<SpectatorState, RingContact, bool>? hasLos)
{
bool los = hasLos is null || hasLos(spec, contact);
if (los)
{
spec.HasTargetLos = true;
spec.LastKnownTargetX = contact.X;
spec.LastKnownTargetY = contact.Y;
spec.LastKnownTargetZ = contact.Z;
spec.TimeSinceLastSeen = 0f;
}
else
{
spec.HasTargetLos = false;
spec.TimeSinceLastSeen += dt;
}
}
private static bool TryFindAliveContact(ReadOnlySpan<RingContact> contenders, int id, out RingContact contact)
{
for (int i = 0; i < contenders.Length; i++)
{
if (contenders[i].Id == id && contenders[i].Alive)
{
contact = contenders[i];
return true;
}
}
contact = default;
return false;
}
private int FindExcessClearedToDrop(int contenderId)
{
int bestIdx = -1;
bool bestNoLos = false;
float bestAge = -1f;
float bestDistSq = -1f;
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (!spec.Alive || spec.Stance != SpectatorStance.Cleared || spec.TargetContenderId != contenderId)
{
continue;
}
bool noLos = !spec.HasTargetLos;
float age = spec.TimeSinceLastSeen;
float dx = spec.X - spec.LastKnownTargetX;
float dz = spec.Z - spec.LastKnownTargetZ;
float d2 = dx * dx + dz * dz;
if (bestIdx < 0 ||
(noLos && !bestNoLos) ||
(noLos == bestNoLos && (age > bestAge + 1e-4f || (MathF.Abs(age - bestAge) <= 1e-4f && d2 > bestDistSq))))
{
bestIdx = i;
bestNoLos = noLos;
bestAge = age;
bestDistSq = d2;
}
}
return bestIdx;
}
private bool AnyNeutralHasLos(in RingContact contender, Func<SpectatorState, RingContact, bool> hasLos)
{
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (spec.Alive && spec.Stance == SpectatorStance.Neutral && hasLos(spec, contender))
{
return true;
}
}
return false;
}
private int FindStaleNoLosCleared(int contenderId)
{
int bestIdx = -1;
float bestAge = TargetMemoryDuration;
for (int i = 0; i < _spectators.Count; i++)
{
var spec = _spectators[i];
if (spec.Alive &&
spec.Stance == SpectatorStance.Cleared &&
spec.TargetContenderId == contenderId &&
!spec.HasTargetLos &&
spec.TimeSinceLastSeen >= bestAge)
{
bestAge = spec.TimeSinceLastSeen;
bestIdx = i;
}
}
return bestIdx;
}
public void AdvancePerimeterOrbits(float dt) public void AdvancePerimeterOrbits(float dt)
{ {
for (int i = 0; i < _spectators.Count; i++) for (int i = 0; i < _spectators.Count; i++)
@ -502,18 +708,6 @@ namespace RustToDust.Core
return drops; return drops;
} }
private static RingContact FindContact(ReadOnlySpan<RingContact> contenders, int id)
{
for (int i = 0; i < contenders.Length; i++)
{
if (contenders[i].Id == id)
{
return contenders[i];
}
}
return default;
}
private void SpawnRing(Random rng, int count) private void SpawnRing(Random rng, int count)
{ {
int touristCount = (int)MathF.Round(count * 0.45f); int touristCount = (int)MathF.Round(count * 0.45f);

View file

@ -322,5 +322,93 @@ namespace RustToDust.Tests
Assert.Equal(clearedInitialKnownX, cAimX, precision: 3); Assert.Equal(clearedInitialKnownX, cAimX, precision: 3);
Assert.Equal(clearedInitialKnownZ, cAimZ, precision: 3); Assert.Equal(clearedInitialKnownZ, cAimZ, precision: 3);
} }
[Fact]
public void Probe2_OccludedLateralArc_FullRingDoesNotLeakOrTrackPlayerPosition()
{
var ring = new SpectatorRing(seed: 42);
Assert.Equal(56, ring.Spectators.Count);
const float dt = 1f / 60f;
// Phase 1 (10 ticks): Player pops out of safe circle briefly at 0 degrees with LOS to nearby 0-deg watchers.
float startR = ring.SafeRadius + 15f;
for (int tick = 0; tick < 10; tick++)
{
var contact = new RingContact(0, startR, 0f, true);
ring.UpdateClearance(new[] { contact }, dt, (spec, _) =>
{
float specAng = MathF.Atan2(spec.Z, spec.X);
return MathF.Abs(specAng) < 0.45f;
});
}
int initialCleared = ring.CountClearedFor(0);
Assert.True(initialCleared >= 1, "Expected at least one Cleared spectator at 0 degrees during initial pop-out");
Assert.Contains(ring.Spectators, s => s.Stance == SpectatorStance.Cleared && s.HasTargetLos);
// Phase 2 (600 ticks = 10s): 100% occlusion while player moves laterally 0 -> 80 deg and steps further out.
float playerX = startR;
float playerZ = 0f;
float maxArcRad = 80f * (MathF.PI / 180f);
for (int tick = 0; tick < 600; tick++)
{
float t = tick / 599f;
float angle = t * maxArcRad;
float r = ring.SafeRadius + 15f + t * 70f;
playerX = MathF.Cos(angle) * r;
playerZ = MathF.Sin(angle) * r;
var contact = new RingContact(0, playerX, playerZ, true);
ring.UpdateClearance(new[] { contact }, dt, static (_, _) => false);
foreach (var s in ring.Spectators)
{
Assert.False(s.HasTargetLos, $"No spectator may have LOS during occluded arc (tick {tick}, spec {s.Id})");
if (s.Stance == SpectatorStance.Cleared)
{
float targetAngle = MathF.Atan2(s.LastKnownTargetZ, s.LastKnownTargetX);
Assert.True(MathF.Abs(targetAngle) < 0.35f,
$"Cleared spectator {s.Id} leaked lateral angle {targetAngle * 180f / MathF.PI:F1} deg at tick {tick}");
}
}
}
// At end of 80-deg hidden move, no spectator has LastKnownTarget near the player's hidden position,
// and spectators stationed along 35..90 degrees remain Neutral.
foreach (var s in ring.Spectators)
{
if (s.Stance == SpectatorStance.Cleared)
{
float dx = s.LastKnownTargetX - playerX;
float dz = s.LastKnownTargetZ - playerZ;
float distToHiddenPlayer = MathF.Sqrt(dx * dx + dz * dz);
Assert.True(distToHiddenPlayer > 400f,
$"Cleared spectator {s.Id} LastKnownTarget ({s.LastKnownTargetX:F1}, {s.LastKnownTargetZ:F1}) too close to hidden player ({distToHiddenPlayer:F1}m)");
}
float specAngleDeg = MathF.Atan2(s.Z, s.X) * (180f / MathF.PI);
if (specAngleDeg >= 35f && specAngleDeg <= 95f)
{
Assert.Equal(SpectatorStance.Neutral, s.Stance);
}
}
}
[Fact]
public void OnSpectatorDamaged_WithoutLos_SeedsIncomingDirectionInsteadOfStaleTarget()
{
var ring = new SpectatorRing(seed: 77);
var spec = ring.Spectators[0];
spec.LastKnownTargetX = 0f;
spec.LastKnownTargetZ = 0f;
bool provoked = ring.OnSpectatorDamaged(spec, attackerContenderId: 0, incomingDirX: 0f, incomingDirZ: 1f);
Assert.True(provoked);
Assert.Equal(SpectatorStance.Provoked, spec.Stance);
Assert.False(spec.HasTargetLos);
Assert.True(spec.LastKnownTargetZ > spec.Z + 10f,
$"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}");
}
} }
} }