feat: Replace FastAStarAlgorithm with BitmapAStarAlgorithm (#2446)

## Summary

Replaces `FastAStarAlgorithm` with `BitmapAStarAlgorithm`: one cache lookup per cell expansion (8-direction mask + per-direction destination Z) instead of 8 separate `MovementImpl.CheckMovement` calls. Adds the supporting cache infrastructure to back it.

Public API unchanged — `MovementPath` / `Mobile.Move` / `CalcMoves.Find` return the same shapes; the algorithm swap is internal.

## What's in this PR

- **`BitmapAStarAlgorithm`** — A* that issues one `StepCache.TryGetMask` call per cell expansion. Inline fallthrough to the per-cell slow path for multi-Z, off-map, source-Z mismatch, and non-default walkers.
- **`StepCache`** — singleton chunk store keyed by `(mapId, chunkX, chunkY)`. Lazily built on first query, invalidated by `Sector.MultisVersion` mismatch, memory-bounded by sampled probabilistic LRU.
- **`StepProbe`** — computes static-only walkability for a single cell, mirroring `MovementImpl.Check` minus the item / mobile collision phases.
- **`StepMask` / `StepChunk`** — value / storage types for the per-cell results.
- **`CacheEvictionTimer`** — periodic cap backstop (60s interval; early-returns when not over cap).
- **`Map.Sector.MultisVersion`** promoted to `public` so the cache can detect dynamic-static invalidations cheaply.

## Eviction strategy

Sampled probabilistic LRU (Redis-style). Per eviction, sample 5 random keys from a parallel `List<long>` kept in lockstep with the chunk dictionary; evict the oldest of the sample via swap-and-pop. O(1) per eviction regardless of resident count, so sustained cap pressure has no perpetual perf hit.

## Capability handling (interim)

Non-default walkers (non-GM players, creatures with `CanSwim` / `CanFly` / `CanOpenDoors` / `CanMoveOverObstacles`) route entirely through the per-cell slow path via `BitmapAStarAlgorithm.GetSuccessorsSlowPath`. The 2-pass design (cache + capability overlay + dynamic-obstacle pass) lands in the follow-up PR.
This commit is contained in:
Kamron Batman 2026-05-05 21:53:43 -07:00 committed by GitHub
parent ee1bf23b72
commit 6a3804addc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 1832 additions and 50 deletions

View file

@ -0,0 +1,109 @@
using Server.Engines.Pathing.Cache;
using Server.Mobiles;
using Server.PathAlgorithms.BitmapAStar;
using Xunit;
using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
/// <summary>
/// Smoke tests for <see cref="BitmapAStarAlgorithm"/>'s two branches: cache-direct fast
/// path (default walkers) and per-cell slow path (capability creatures and non-GM players).
/// Exercised end-to-end against the real Trammel TileMatrix to ensure neither regresses
/// to "no path found" on reachable goals.
/// </summary>
[Collection("Sequential Pathfinding Tests")]
public class BitmapAStarAlgorithmTests
{
private readonly ITestOutputHelper _output;
public BitmapAStarAlgorithmTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
// Pinned cell (1500, 1600, z=10): mask=0xC1 → N, W, NW walkable.
// Use start.Z for goal.Z so destNode lands in the same Z plane the algorithm reaches
// during expansion (GetAverageZ at the goal cell may differ from the engine's
// runtime-computed standing Z, which would break the destNode equality check).
[InlineData(1500, 1600, 1498, 1598)] // NW, 2 cells diagonal
[InlineData(1500, 1600, 1497, 1599)] // NW-ish, 3 W + 1 N
public void DefaultWalker_FindsPath_ViaCacheFastPath(int sx, int sy, int gx, int gy)
{
StepCache.Instance.Clear();
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new DefaultWalkerStub();
map.GetAverageZ(sx, sy, out _, out var startZ, out _);
var start = new Point3D(sx, sy, (sbyte)startZ);
var goal = new Point3D(gx, gy, (sbyte)startZ);
stub.MoveToWorld(start, map);
var result = BitmapAStarAlgorithm.Instance.Find(stub, map, start, goal);
stub.Delete();
Assert.NotNull(result);
Assert.NotEmpty(result);
_output.WriteLine($"default-walker ({sx},{sy})->({gx},{gy}): {result.Length} steps");
}
[Theory]
[InlineData(1500, 1600, 1498, 1598)] // NW, 2 cells diagonal
[InlineData(1500, 1600, 1497, 1599)] // NW-ish, 3 W + 1 N
public void CapabilityCreature_FindsPath_ViaInlineSlowPath(int sx, int sy, int gx, int gy)
{
StepCache.Instance.Clear();
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new SwimmingStub(World.NewMobile);
stub.DefaultMobileInit();
stub.CanSwim = true; // forces non-default-walker → inline GetSuccessorsSlowPath
map.GetAverageZ(sx, sy, out _, out var startZ, out _);
var start = new Point3D(sx, sy, (sbyte)startZ);
var goal = new Point3D(gx, gy, (sbyte)startZ);
stub.MoveToWorld(start, map);
var result = BitmapAStarAlgorithm.Instance.Find(stub, map, start, goal);
stub.Delete();
// Capability creature: assert reachability — exact length depends on terrain and
// tie-breaking, but a swimmer should always reach a goal a default walker reaches
// on dry land (CanSwim is permissive, never restrictive).
Assert.NotNull(result);
Assert.NotEmpty(result);
_output.WriteLine($"swimmer ({sx},{sy})->({gx},{gy}): {result.Length} steps");
}
/// <summary>
/// Plain Mobile — IsDefaultWalker returns true, the bitmap algorithm uses the cache
/// fast path on every expansion.
/// </summary>
private sealed class DefaultWalkerStub : Mobile
{
public DefaultWalkerStub()
{
Body = 0xC9;
}
}
/// <summary>
/// BaseCreature with CanSwim=true — IsDefaultWalker returns false, the bitmap
/// algorithm short-circuits GetSuccessors to GetSuccessorsSlowPath on every cell.
/// Use the Serial constructor (deserialization path) to bypass NPCSpeeds init,
/// which requires the npc-speeds.json table loaded — not available in tests.
/// </summary>
private sealed class SwimmingStub : BaseCreature
{
public SwimmingStub(Serial serial) : base(serial)
{
Body = 0xC9;
}
}
}

View file

@ -0,0 +1,229 @@
using Server.Engines.Pathing.Cache;
using Xunit;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StepCacheLifecycleTests
{
[Fact]
public void Singleton_IsAvailable()
{
var cache = StepCache.Instance;
Assert.NotNull(cache);
}
[Fact]
public void Clear_OnEmptyCache_LeavesStatsZero()
{
var cache = StepCache.Instance;
cache.Clear();
var stats = cache.GetStats();
Assert.Equal(0, stats.ResidentChunks);
Assert.Equal(0L, stats.Hits);
Assert.Equal(0L, stats.BuildsTotal);
}
[Fact]
public void TryGetMask_FirstQuery_BuildsChunkAndReturnsBakerOutput()
{
var cache = StepCache.Instance;
cache.Clear();
var map = Map.Maps[1];
Assert.NotNull(map);
// Pinned cell (1500, 1600, z=10): mask=0xC1
var ok = cache.TryGetMask(
map, 1500, 1600, sourceZ: 10,
out var mask,
out var dN, out var dNE, out var dE, out var dSE,
out var dS, out var dSW, out var dW, out var dNW,
out var hitKind
);
Assert.True(ok);
Assert.Equal(CacheHitKind.Miss_NotBuilt, hitKind);
Assert.Equal((byte)0xC1, mask);
Assert.Equal((sbyte)10, dN);
Assert.Equal((sbyte)10, dW);
Assert.Equal((sbyte)10, dNW);
var stats = cache.GetStats();
Assert.Equal(1, stats.ResidentChunks);
Assert.Equal(1L, stats.MissesNotBuilt);
Assert.Equal(1L, stats.BuildsTotal);
// Second query of same cell → Hit
var ok2 = cache.TryGetMask(
map, 1500, 1600, sourceZ: 10,
out var mask2,
out _, out _, out _, out _, out _, out _, out _, out _,
out var hitKind2
);
Assert.True(ok2);
Assert.Equal(CacheHitKind.Hit, hitKind2);
Assert.Equal((byte)0xC1, mask2);
var stats2 = cache.GetStats();
Assert.Equal(1, stats2.ResidentChunks);
Assert.Equal(1L, stats2.Hits);
}
[Fact]
public void TryGetMask_OffMap_ReturnsFalseFallthrough()
{
var cache = StepCache.Instance;
cache.Clear();
var map = Map.Maps[1];
var ok = cache.TryGetMask(
map, -1, -1, sourceZ: 0,
out var mask, out _, out _, out _, out _, out _, out _, out _, out _,
out var hitKind
);
Assert.False(ok);
Assert.Equal(CacheHitKind.Fallthrough_OffMap, hitKind);
Assert.Equal((byte)0, mask);
}
[Fact]
public void MultisVersion_Bump_TriggersDirtyRebuild()
{
var cache = StepCache.Instance;
cache.Clear();
var map = Map.Maps[1];
var sector = map.GetRealSector(1500 >> 4, 1600 >> 4);
// First query: builds chunk, snapshots current MultisVersion.
cache.TryGetMask(map, 1500, 1600, 10,
out _, out _, out _, out _, out _, out _, out _, out _, out _,
out var firstHitKind);
Assert.Equal(CacheHitKind.Miss_NotBuilt, firstHitKind);
// Bump _multisVersion via reflection.
var versionField = typeof(Map.Sector).GetField(
"_multisVersion",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
);
Assert.NotNull(versionField);
var current = (int)versionField.GetValue(sector);
versionField.SetValue(sector, current + 1);
// Second query: detects version mismatch, rebuilds.
cache.TryGetMask(map, 1500, 1600, 10,
out _, out _, out _, out _, out _, out _, out _, out _, out _,
out var secondHitKind);
Assert.Equal(CacheHitKind.Miss_DirtyRebuild, secondHitKind);
var stats = cache.GetStats();
Assert.Equal(1L, stats.MissesDirtyRebuild);
Assert.Equal(2L, stats.BuildsTotal);
// Mutual-exclusivity invariant: every successful TryGetMask hits exactly one
// outcome counter. Two queries above both returned true (the test cell is not
// multi-Z and not off-map), so the three outcome counters must sum to 2 and the
// fallthrough counters must be zero.
Assert.Equal(2L, stats.MissesNotBuilt + stats.MissesDirtyRebuild + stats.Hits);
Assert.Equal(0L, stats.FallthroughMultiZ);
Assert.Equal(0L, stats.FallthroughOffMap);
}
[Fact]
public void MultiZCell_RoutesToFallthrough()
{
var cache = StepCache.Instance;
cache.Clear();
var map = Map.Maps[1];
// Build a chunk first so it exists.
cache.TryGetMask(map, 1500, 1600, 10,
out _, out _, out _, out _, out _, out _, out _, out _, out _, out _);
// Snapshot current FallthroughMultiZ in case (1500, 1600) is naturally multi-Z
// in real tile data; we only assert the synthetic injection produces a delta of 1.
var preInjectionFallthroughMultiZ = cache.GetStats().FallthroughMultiZ;
// Inject a multi-Z bit via reflection on the resident chunk.
var chunksField = typeof(StepCache).GetField(
"_chunks",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
);
Assert.NotNull(chunksField);
var chunks = (System.Collections.Generic.Dictionary<long, StepChunk>)chunksField.GetValue(cache);
var key = StepCache.EncodeKey(map.MapID, 1500 >> 4, 1600 >> 4);
Assert.True(chunks.ContainsKey(key));
var chunk = chunks[key];
// Mark cell at (1500, 1600) within the chunk as multi-Z.
var cellIndex = ((1600 - ((1600 >> 4) << 4)) << 4) | (1500 - ((1500 >> 4) << 4));
chunk.MarkCellMultiZ(cellIndex);
var ok = cache.TryGetMask(map, 1500, 1600, 10,
out _, out _, out _, out _, out _, out _, out _, out _, out _,
out var hitKind);
Assert.False(ok);
Assert.Equal(CacheHitKind.Fallthrough_MultiZ, hitKind);
var stats = cache.GetStats();
Assert.Equal(preInjectionFallthroughMultiZ + 1L, stats.FallthroughMultiZ);
}
[Fact]
public void LruCap_OverflowEvictsToCap()
{
var cache = StepCache.Instance;
cache.Clear();
cache.MaxResidentChunks = 4;
try
{
var map = Map.Maps[1];
// Build 5 distinct chunks by querying different sectors.
for (var i = 0; i < 5; i++)
{
var x = 1500 + (i * 16);
var y = 1600;
cache.TryGetMask(map, x, y, 10,
out _, out _, out _, out _, out _, out _, out _, out _, out _, out _);
System.Threading.Thread.Sleep(2); // ensure LastTouchedTicks differs
}
cache.EnforceLruCap();
Assert.Equal(4, cache.GetStats().ResidentChunks);
Assert.True(cache.GetStats().EvictionsByLruCap >= 1L);
// _keysList must stay in lockstep with _chunks. A desync would silently
// break sampled eviction (KeyNotFoundException on stale keys, or a stuck
// resident set on missing keys).
var chunksField = typeof(StepCache).GetField(
"_chunks",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
);
var keysListField = typeof(StepCache).GetField(
"_keysList",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance
);
var chunks = (System.Collections.Generic.Dictionary<long, StepChunk>)chunksField.GetValue(cache);
var keysList = (System.Collections.Generic.List<long>)keysListField.GetValue(cache);
Assert.Equal(chunks.Count, keysList.Count);
foreach (var k in keysList)
{
Assert.True(chunks.ContainsKey(k), $"keysList holds key {k} not in _chunks");
}
}
finally
{
cache.MaxResidentChunks = 8192;
}
}
}

View file

@ -0,0 +1,90 @@
using Server.Engines.Pathing.Cache;
using Xunit;
using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StepCacheParityTests
{
private readonly ITestOutputHelper _output;
public StepCacheParityTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("britain_inn_dense", 1480, 1610, 32)]
[InlineData("trammel_open_plain", 1500, 1600, 32)]
[InlineData("britain_causeway", 1475, 1641, 32)]
public void CacheMatchesBaker(string label, int xStart, int yStart, int size)
{
var cache = StepCache.Instance;
cache.Clear();
var map = Map.Maps[1];
Assert.NotNull(map);
var disagreements = 0;
var samples = 0;
var multiZ = 0;
for (var x = xStart; x < xStart + size; x++)
{
for (var y = yStart; y < yStart + size; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
// The cache bakes from the slow path's standing Z (the Z a creature actually
// stands at on this cell). Query with the same Z so the source-Z guard
// doesn't false-positive on every paver cell.
var sourceZ = (sbyte)StepProbe.ComputeStandingZ(map, x, y, avgZ);
var baker = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
var ok = cache.TryGetMask(
map, x, y, sourceZ,
out var mask,
out var dN, out var dNE, out var dE, out var dSE,
out var dS, out var dSW, out var dW, out var dNW,
out var hitKind
);
samples++;
if (hitKind == CacheHitKind.Fallthrough_MultiZ)
{
multiZ++;
continue;
}
Assert.True(ok, $"Cache returned !ok at ({x},{y}) hitKind={hitKind}");
if (mask != baker.Mask)
{
disagreements++;
_output.WriteLine($"MASK DIFF @ ({x},{y}) cache=0x{mask:X2} baker=0x{baker.Mask:X2}");
continue;
}
if (dN != baker.DestZ_N || dNE != baker.DestZ_NE || dE != baker.DestZ_E || dSE != baker.DestZ_SE
|| dS != baker.DestZ_S || dSW != baker.DestZ_SW || dW != baker.DestZ_W || dNW != baker.DestZ_NW)
{
disagreements++;
_output.WriteLine($"Z DIFF @ ({x},{y}) cache=({dN},{dNE},{dE},{dSE},{dS},{dSW},{dW},{dNW}) baker=({baker.DestZ_N},{baker.DestZ_NE},{baker.DestZ_E},{baker.DestZ_SE},{baker.DestZ_S},{baker.DestZ_SW},{baker.DestZ_W},{baker.DestZ_NW})");
}
}
}
_output.WriteLine($"[{label}] samples={samples} disagreements={disagreements} multiZ={multiZ}");
// Non-vacuity: at least the inn region must have at least one cell that produced a real cache answer.
if (label == "britain_inn_dense")
{
Assert.True(samples - multiZ > 0, "expected real cache answers in dense region");
}
Assert.Equal(0, disagreements);
}
}

View file

@ -0,0 +1,126 @@
using Server.Engines.Pathing.Cache;
using Xunit;
using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StaticWalkabilityParityTests
{
private readonly ITestOutputHelper _output;
public StaticWalkabilityParityTests(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData("britain_inn_dense", 1480, 1610, 32)]
[InlineData("trammel_open_plain", 1500, 1600, 32)]
public void BakerMatchesCheckMovement(string label, int xStart, int yStart, int size)
{
var map = Map.Maps[1];
Assert.NotNull(map);
var stub = new ParityStubMobile();
stub.MoveToWorld(new Point3D(xStart, yStart, 0), map);
var disagreements = 0;
var samples = 0;
var oldWalkable = 0;
var newWalkable = 0;
for (var x = xStart; x < xStart + size; x++)
{
for (var y = yStart; y < yStart + size; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var loc = new Point3D(x, y, sourceZ);
var bakerResult = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
for (var d = 0; d < 8; d++)
{
var dir = (Direction)d;
samples++;
var oldOk = Movement.Movement.CheckMovement(stub, map, loc, dir, out var oldZ);
// Apply creature diagonal corner-cut rule at query time:
// diagonal walkable iff raw-diagonal AND (left-partner OR right-partner).
// (Raw masks are correct per spec; baker omits diagonal logic per design.)
var newOk = bakerResult.IsWalkable(dir);
if (newOk && ((d & 1) == 1))
{
var leftPartner = (Direction)((d - 1) & 7);
var rightPartner = (Direction)((d + 1) & 7);
if (!bakerResult.IsWalkable(leftPartner) && !bakerResult.IsWalkable(rightPartner))
{
newOk = false;
}
}
var newZ = bakerResult.GetDestZ(dir);
if (oldOk)
{
oldWalkable++;
}
if (newOk)
{
newWalkable++;
}
if (oldOk != newOk)
{
disagreements++;
_output.WriteLine(
$"DISAGREE walkable @ ({x},{y},{sourceZ}) dir={dir}: " +
$"old={oldOk} new={newOk}"
);
}
else if (oldOk && oldZ != newZ)
{
disagreements++;
_output.WriteLine(
$"DISAGREE destZ @ ({x},{y},{sourceZ}) dir={dir}: " +
$"old={oldZ} new={newZ}"
);
}
}
}
}
stub.Delete();
_output.WriteLine(
$"[{label}] Samples: {samples}, Disagreements: {disagreements}, " +
$"OldWalkable: {oldWalkable}, NewWalkable: {newWalkable}"
);
// Non-vacuity guard for the variety case: at least one region must show some
// blocked directions. The open_plain region is allowed to be all-walkable.
if (label == "britain_inn_dense")
{
Assert.NotEqual(0, oldWalkable);
Assert.NotEqual(samples, oldWalkable);
}
Assert.Equal(0, disagreements);
}
/// <summary>
/// Minimal Mobile stub for parity testing. Inherits directly from Mobile so that
/// MovementImpl sees no BaseCreature-specific flags (CanSwim=false, CanFly=false,
/// bc==null → BaseCreature branches skipped) giving us the default static walker baseline.
/// </summary>
private class ParityStubMobile : Mobile
{
public ParityStubMobile()
{
Body = 0xC9; // arbitrary horse body
}
}
}

View file

@ -0,0 +1,248 @@
using Server.Engines.Pathing.Cache;
using Xunit;
using Xunit.Abstractions;
namespace Server.Tests.Pathfinding;
[Collection("Sequential Pathfinding Tests")]
public class StepProbeTests
{
private readonly ITestOutputHelper _output;
public StepProbeTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void ComputeMaskAt_NullMap_ReturnsDefault()
{
var result = StepProbe.ComputeMaskAt(null, 100, 100, 0);
Assert.Equal(0, result.Mask);
for (var d = 0; d < 8; d++)
{
Assert.Equal(0, result.GetDestZ((Direction)d));
}
}
[Fact]
public void ComputeMaskAt_InternalMap_ReturnsDefault()
{
var result = StepProbe.ComputeMaskAt(Map.Internal, 100, 100, 0);
Assert.Equal(0, result.Mask);
for (var d = 0; d < 8; d++)
{
Assert.Equal(0, result.GetDestZ((Direction)d));
}
}
[Fact]
public void ComputeMaskAt_TopLeftCorner_OffMapDirectionsBlocked()
{
// From source (0, 0), these neighbor cells are off-map and MUST be blocked,
// regardless of map content:
// N = (0, -1) bit 0
// NE = (1, -1) bit 1
// SW = (-1, 1) bit 5
// W = (-1, 0) bit 6
// NW = (-1, -1) bit 7
// Bits 2 (E), 3 (SE), 4 (S) depend on map content and aren't asserted.
var map = Map.Maps[1];
Assert.NotNull(map);
var result = StepProbe.ComputeMaskAt(map, 0, 0, 0);
Assert.False(result.IsWalkable(Direction.North), "N should be off-map");
Assert.False(result.IsWalkable(Direction.Right), "NE should be off-map");
Assert.False(result.IsWalkable(Direction.Left), "SW should be off-map");
Assert.False(result.IsWalkable(Direction.West), "W should be off-map");
Assert.False(result.IsWalkable(Direction.Up), "NW should be off-map");
}
[Fact]
public void ComputeMaskAt_BottomRightCorner_OffMapDirectionsBlocked()
{
var map = Map.Maps[1];
Assert.NotNull(map);
var x = map.Width - 1;
var y = map.Height - 1;
var result = StepProbe.ComputeMaskAt(map, x, y, 0);
// From the SE corner, S/SE/SW/E/NE all go off-map (only N/NW/W in-map).
Assert.False(result.IsWalkable(Direction.Right), "NE should be off-map");
Assert.False(result.IsWalkable(Direction.East), "E should be off-map");
Assert.False(result.IsWalkable(Direction.Down), "SE should be off-map");
Assert.False(result.IsWalkable(Direction.South), "S should be off-map");
Assert.False(result.IsWalkable(Direction.Left), "SW should be off-map");
}
[Fact]
public void ComputeMaskAt_TrammelOpenPlain_HasFlatCellWithAllDirectionsWalkable()
{
// Invariant: somewhere in the open-plain region, there must be a fully-flat cell
// whose mask is 0xFF and all 8 destZ values equal sourceZ (no slope).
// This protects against a regression where the baker stops detecting flat cells.
var map = Map.Maps[1];
Assert.NotNull(map);
var found = false;
for (var x = 1500; x < 1532 && !found; x++)
{
for (var y = 1600; y < 1632 && !found; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
if (result.Mask != 0xFF)
{
continue;
}
var allSameZ = true;
for (var d = 0; d < 8; d++)
{
if (result.GetDestZ((Direction)d) != sourceZ)
{
allSameZ = false;
break;
}
}
if (allSameZ)
{
found = true;
_output.WriteLine($"Flat-open cell found at ({x}, {y}, {sourceZ})");
}
}
}
Assert.True(found, "Expected at least one fully-flat open cell in (1500..1532, 1600..1632)");
}
[Fact]
public void ComputeMaskAt_BritainInnDense_HasCellWithBlockedDirections()
{
// Invariant: inside the dense Britain inn region, at least one cell must have
// at least one direction blocked by a static. Protects against a regression
// where the baker reports everything as walkable (the original false-pass bug).
var map = Map.Maps[1];
Assert.NotNull(map);
var blockedCellCount = 0;
for (var x = 1480; x < 1512; x++)
{
for (var y = 1610; y < 1642; y++)
{
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
if (result.Mask != 0xFF)
{
blockedCellCount++;
}
}
}
_output.WriteLine($"Cells with at least one blocked direction: {blockedCellCount} / 1024");
Assert.True(blockedCellCount > 0, "Expected at least one cell with a blocked direction in the dense region");
}
[Theory]
[InlineData(1500, 1600)]
[InlineData(1480, 1610)]
[InlineData(0, 0)]
public void ComputeMaskAt_IsDeterministic(int x, int y)
{
// Same inputs must always produce identical output. Catches accidental
// statefulness in the baker (e.g., a static cache that gets corrupted).
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(x, y, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var first = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
var second = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
var third = StepProbe.ComputeMaskAt(map, x, y, sourceZ);
Assert.Equal(first.Mask, second.Mask);
Assert.Equal(first.Mask, third.Mask);
for (var d = 0; d < 8; d++)
{
Assert.Equal(first.GetDestZ((Direction)d), second.GetDestZ((Direction)d));
Assert.Equal(first.GetDestZ((Direction)d), third.GetDestZ((Direction)d));
}
}
[Fact]
public void ComputeMaskAt_PinnedCell_TrammelOpenPlainOrigin()
{
// PINNING test: locks specific output for Trammel (1500, 1600).
// Cell at z=10 with mask 0xC1 (N + W + NW only walkable). The other five
// directions are blocked by water (E/SE/S/SW are wet tiles, NE is shore).
// If this changes, either the baker logic changed or the underlying tile
// data changed; re-run the parity test to confirm before updating expected values.
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(1500, 1600, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, 1500, 1600, sourceZ);
Assert.Equal((sbyte)10, sourceZ);
Assert.Equal((byte)0xC1, result.Mask);
Assert.True(result.IsWalkable(Direction.North));
Assert.False(result.IsWalkable(Direction.Right));
Assert.False(result.IsWalkable(Direction.East));
Assert.False(result.IsWalkable(Direction.Down));
Assert.False(result.IsWalkable(Direction.South));
Assert.False(result.IsWalkable(Direction.Left));
Assert.True(result.IsWalkable(Direction.West));
Assert.True(result.IsWalkable(Direction.Up));
Assert.Equal((sbyte)10, result.GetDestZ(Direction.North));
Assert.Equal((sbyte)10, result.GetDestZ(Direction.West));
Assert.Equal((sbyte)10, result.GetDestZ(Direction.Up));
}
[Fact]
public void ComputeMaskAt_PinnedCell_BritainInnDenseOrigin()
{
// PINNING test: locks specific output for Trammel (1480, 1610).
// Cell at z=20 with mask 0x3F (N/NE/E/SE/S/SW walkable, W/NW blocked by
// a wall to the west). All walkable directions stay flat at z=20.
var map = Map.Maps[1];
Assert.NotNull(map);
map.GetAverageZ(1480, 1610, out _, out var avgZ, out _);
var sourceZ = (sbyte)avgZ;
var result = StepProbe.ComputeMaskAt(map, 1480, 1610, sourceZ);
Assert.Equal((sbyte)20, sourceZ);
Assert.Equal((byte)0x3F, result.Mask);
Assert.True(result.IsWalkable(Direction.North));
Assert.True(result.IsWalkable(Direction.Right));
Assert.True(result.IsWalkable(Direction.East));
Assert.True(result.IsWalkable(Direction.Down));
Assert.True(result.IsWalkable(Direction.South));
Assert.True(result.IsWalkable(Direction.Left));
Assert.False(result.IsWalkable(Direction.West));
Assert.False(result.IsWalkable(Direction.Up));
for (var d = 0; d < 6; d++)
{
Assert.Equal((sbyte)20, result.GetDestZ((Direction)d));
}
}
}