geometry: scanline cellsTouched, differential + independent oracle tests, prototype corpus

cellsTouched is now a scanline over cell rows (prototype per-cell version kept test-only in
tests/refold.nim). Differential tests (random polygons, concave, grid-aligned) and a brute-force
explored oracle (0.5 px tolerance) cover it; regression corpus = prototype leak-run polygons.
moveBlocked leaves geometry.nim (replaced by server/moverules.nim next); geometry primitives exported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 12:08:21 +01:00
co-authored by Claude Sonnet 5.5
parent 206f99deda
commit 67fa96e23d
5 changed files with 667 additions and 114 deletions
+220 -86
View File
@@ -1,5 +1,5 @@
import std/[unittest, json, os]
import geometry
import std/[unittest, json, os, math]
import geometry, refold
proc W(ax, ay, bx, by: float, door = false, open = false): Wall =
Wall(a: (ax, ay), b: (bx, by), door: door, open: open)
@@ -171,31 +171,6 @@ suite "visibility":
test "radius clips":
check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200)
suite "moves":
let wall = W(0, -50, 0, 50)
test "crossing blocked, parallel ok":
check moveBlocked([wall], (-10.0, 0.0), (10.0, 0.0))
check not moveBlocked([wall], (-10.0, 0.0), (-10.0, 30.0))
check not moveBlocked([wall], (-10.0, 60.0), (10.0, 60.0)) # passes beyond the end
test "grazing an endpoint is blocked":
check moveBlocked([wall], (-10.0, 50.0), (10.0, 50.0))
check moveBlocked([wall], (-10.0, -60.0), (10.0, -40.0)) # crosses
test "no leak through shared vertex":
let w = [W(0, -50, 0, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (-10.0, 0.0), (10.0, 0.0))
test "diagonal squeeze through corner vertex of L":
let w = [W(0, 0, 50, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (10.0, -10.0), (-10.0, 10.0))
test "moving along a collinear wall is blocked":
check moveBlocked([wall], (0.0, -100.0), (0.0, 100.0))
test "doors":
var d = W(0, -10, 0, 10, true, false)
check moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
d.open = true
check not moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
test "zero-length move":
check not moveBlocked([wall], (-5.0, 0.0), (-5.0, 0.0))
suite "cells":
test "square polygon":
let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)]
@@ -209,68 +184,227 @@ suite "cells":
test "big polygon includes fully covered interior cells":
let big = [(0.0, 0.0), (200.0, 0.0), (200.0, 200.0), (0.0, 200.0)]
check (3, 3) in cellsTouched(big, 32)
test "degenerate input: fewer than 3 vertices":
check cellsTouched([(1.0, 1.0), (50.0, 50.0)], 32).len == 0
test "touching a cell line: inclusive on the max side, not on the bbox minimum side":
let sq = [(32.0, 32.0), (64.0, 32.0), (64.0, 64.0), (32.0, 64.0)] # exactly cell (1,1)
# (prototype-compatible: no cell on the low side of the bbox minimum lines)
check cellsTouched(sq, 32) == @[(1, 1), (2, 1), (1, 2), (2, 2)]
test "concave polygon: a notch cell is not filled":
# U shape open at the top: notch x 60..100, y 0..80; cells (2,0) and (2,1) (x 64..96) lie wholly inside it
let u = [(0.0, 0.0), (60.0, 0.0), (60.0, 80.0), (100.0, 80.0), (100.0, 0.0), (160.0, 0.0), (160.0, 128.0), (0.0, 128.0)]
let c = cellsTouched(u, 32)
check (2, 0) notin c and (2, 1) notin c
check (2, 2) in c and (2, 3) in c # the bridge below the notch
check (0, 0) in c and (4, 0) in c
# ---- fixtures ----------------------------------------------------------------------------------------------------
type Scene = object
walls: seq[Wall]
tokens: seq[Vec]
radius, cell, tokenRadius: float
proc loadScene(): Scene =
# fixtures are copies of prototype-server-vision/data/scene.json; a missing file fails, never skips
let j = parseFile(currentSourcePath().parentDir / "fixtures" / "scene.json")
for w in j["walls"]:
result.walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w{"door"}.getBool, open: w{"open"}.getBool)
for t in j["tokens"]: result.tokens.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
result.radius = j["visionRadius"].getFloat
result.cell = j["exploredCell"].getFloat
result.tokenRadius = j["tokenRadius"].getFloat
suite "seed":
test "every token in seed sees itself and is not walled in":
# fixture copied from prototype-server-vision/data/scene.json (tests/fixtures/); a missing file fails, never skips
let sp = currentSourcePath().parentDir / "fixtures" / "scene.json"
block:
let j = parseFile(sp)
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w{"door"}.getBool, open: w{"open"}.getBool)
for t in j["tokens"]:
let p: Vec = (t["pos"][0].getFloat, t["pos"][1].getFloat)
let poly = visibilityPolygon(p, walls, j["visionRadius"].getFloat)
check poly.len > 8
check cellsTouched(poly, j["exploredCell"].getFloat).len > 0
check not moveBlocked(walls, p, p, j["tokenRadius"].getFloat)
let sc = loadScene()
for p in sc.tokens:
let poly = visibilityPolygon(p, sc.walls, sc.radius)
check poly.len > 8
check cellsTouched(poly, sc.cell).len > 0
for w in sc.walls: # token circle clear of every wall
check segDist(p, w.a, w.b) >= sc.tokenRadius
suite "token clearance (r=20)":
const r = 20.0
test "near pillar: circle overlapping blocked, clear ok":
let pil = box(600, 600, 680, 680)
check moveBlocked(pil, (500.0, 640.0), (585.0, 640.0), r) # center outside, circle inside wall
check not moveBlocked(pil, (500.0, 640.0), (570.0, 640.0), r) # 30 away
test "near closed door blocks, open door passes":
let cl = @[W(0, 0, 0, 64, door = true)]
check moveBlocked(cl, (-50.0, 32.0), (10.0, 32.0), r) # dest 10 from the wall
check moveBlocked(cl, (-50.0, 32.0), (-10.0, 32.0), r)
let op = @[W(0, 0, 0, 64, door = true, open = true)]
check not moveBlocked(op, (-50.0, 32.0), (50.0, 32.0), r)
test "64px corridor and doorway passable on centerline":
let c = @[W(0, 0, 500, 0), W(0, 64, 500, 64)]
check not moveBlocked(c, (10.0, 32.0), (490.0, 32.0), r)
check not moveBlocked(c, (10.0, 32.0), (11.0, 32.0), r)
let door = @[W(0, -200, 0, -32), W(0, 32, 0, 200)]
check not moveBlocked(door, (-30.0, 0.0), (30.0, 0.0), r)
test "legacy overlap can escape, not stay overlapped":
let w = @[W(0, 0, 100, 0)]
check not moveBlocked(w, (50.0, 5.0), (50.0, 40.0), r)
check moveBlocked(w, (50.0, 5.0), (50.0, 15.0), r)
# ---- regression corpus: new == prototype output ---------------------------------------------------------------
# tests/fixtures/corpus.jsonl (tools/mkcorpus.nim): every player `vision` message of the two prototype leak runs
# (viewer position + open doors at that gseq + the polygon the OLD server computed). 5.5 "regression baseline".
proc samePoly(a, b: openArray[Vec], tol = 1e-6): bool =
if a.len != b.len: return false
for i in 0 ..< a.len:
if abs(a[i].x - b[i].x) > tol or abs(a[i].y - b[i].y) > tol: return false
true
suite "door/wall closing on a token (M1 pins current behaviour)":
test "door closed on a token: Q14 undecided, DESIGN 5.4 vs 12 H2 conflict":
# DESIGN section 14 Q14 (allow walk-out / auto-nudge / refuse edit) is OPEN. DESIGN 5.4 says the token "may step
# perpendicular out"; H2 says the server keeps tokens >= r off walls. Pinned: current moveBlocked only.
const r = 20.0
let door = @[W(0, -50, 0, 50, door = true)] # closed, token radius 20
# token centre 10 off the door (circle overlaps it): may leave to a clear spot, but not cross or stay overlapped
check not moveBlocked(door, (10.0, 0.0), (40.0, 0.0), r) # walk away: dest 40 off
check moveBlocked(door, (10.0, 0.0), (15.0, 0.0), r) # still overlapping: blocked
check moveBlocked(door, (10.0, 0.0), (-40.0, 0.0), r) # through the closed door: blocked
var op = door
op[0].open = true # opening it lifts everything
check not moveBlocked(op, (10.0, 0.0), (-40.0, 0.0), r)
suite "corpus (prototype leak transcripts)":
test "visibilityPolygon and cellsTouched equal the prototype results":
var sc = loadScene()
let base = sc.walls
var n, doorsSeen = 0
for line in lines(currentSourcePath().parentDir / "fixtures" / "corpus.jsonl"):
let j = parseJson(line)
var walls = base
for w in walls.mitems:
if w.door: w.open = false
for id in j["open"]: walls[id.getInt].open = true; inc doorsSeen
let o: Vec = (j["pos"][0].getFloat, j["pos"][1].getFloat)
var rec: seq[Vec]
for p in j["poly"]: rec.add (p[0].getFloat, p[1].getFloat)
let poly = visibilityPolygon(o, walls, sc.radius)
check samePoly(poly, rec)
check cellsTouched(poly, sc.cell) == cellsTouchedOld(poly, sc.cell)
check cellsTouched(rec, sc.cell) == cellsTouchedOld(rec, sc.cell)
inc n
check n >= 300 # corpus is not silently empty
check doorsSeen > 0 # and exercises opened doors
test "KNOWN LIMITATION: token exactly on a wall cannot move off it":
# prototype-server-vision/HANDOFF.md ("token exactly on a wall cannot move off it", inclusive segsCross);
# DESIGN 5.4 / H2 / Q14. A future fix deliberately flips these checks.
let wall = W(0, -50, 0, 50)
check moveBlocked([wall], (0.0, 10.0), (30.0, 10.0)) # perpendicular, away
check moveBlocked([wall], (0.0, 10.0), (-30.0, 10.0))
check moveBlocked([wall], (0.0, 10.0), (0.0, 80.0)) # along the wall, off its end
check moveBlocked([wall], (0.0, 10.0), (1.0, 10.0)) # one pixel
check moveBlocked([wall], (0.0, 10.0), (0.0, 10.0)) # even a zero-length move
check moveBlocked([wall], (0.0, 10.0), (30.0, 10.0), 20.0) # with a token radius too
# ---- differential: scanline vs prototype per-cell ---------------------------------------------------------------
# Tiny deterministic PRNG so the tests do not depend on std/random version behaviour.
type Rng = object
s: uint64
proc next(r: var Rng): uint64 =
r.s = r.s xor (r.s shl 13); r.s = r.s xor (r.s shr 7); r.s = r.s xor (r.s shl 17); r.s
proc uni(r: var Rng, lo, hi: float): float = lo + (hi - lo) * float(r.next shr 11) / float(1'u64 shl 53)
proc randomWalls(r: var Rng, n: int, span: float): seq[Wall] =
for i in 0 ..< n:
let a: Vec = (r.uni(0, span), r.uni(0, span))
let ang = r.uni(0, 2 * PI)
let l = r.uni(10, 300)
result.add Wall(a: a, b: (a.x + l * cos ang, a.y + l * sin ang), door: i mod 7 == 0, open: i mod 14 == 0)
suite "cellsTouched differential vs prototype":
test "random visibility polygons: identical cell lists":
var r = Rng(s: 0x9E3779B97F4A7C15'u64)
var total = 0
for iter in 0 ..< 300:
let walls = randomWalls(r, 5 + iter mod 40, 1200)
let o: Vec = (r.uni(100, 1100), r.uni(100, 1100))
let cell = [32.0, 64.0, 25.0][iter mod 3]
let poly = visibilityPolygon(o, walls, r.uni(50, 500))
let (a, b) = (cellsTouched(poly, cell), cellsTouchedOld(poly, cell))
check a == b
total += a.len
check total > 10000
test "random simple polygons (star-shaped, concave): identical cell lists":
var r = Rng(s: 12345'u64)
for iter in 0 ..< 300:
let c: Vec = (r.uni(100, 500), r.uni(100, 500))
let n = 3 + iter mod 20
var poly: seq[Vec]
for i in 0 ..< n:
let a = 2 * PI * (i.float + r.uni(0, 0.9)) / n.float
let rad = r.uni(2, 150)
poly.add (c.x + rad * cos a, c.y + rad * sin a)
check cellsTouched(poly, 32) == cellsTouchedOld(poly, 32)
test "grid-aligned integer polygons (edges on cell lines): identical cell lists":
var r = Rng(s: 777'u64)
for iter in 0 ..< 300:
let x0 = float(int(r.uni(0, 10))) * 16
let y0 = float(int(r.uni(0, 10))) * 16
let poly = [(x0, y0), (x0 + float(1 + int(r.uni(0, 8))) * 16, y0),
(x0 + float(1 + int(r.uni(0, 8))) * 16, y0 + float(1 + int(r.uni(0, 8))) * 16),
(x0, y0 + float(1 + int(r.uni(0, 8))) * 16)]
check cellsTouched(poly, 32) == cellsTouchedOld(poly, 32)
# ---- independent explored oracle ---------------------------------------------------------------------------------
# Brute force over a point lattice with its own segment maths (nothing from visibilityPolygon / cellsTouched / the old
# cell test). Tolerance TolPx = 0.5 px, as the leak checker (DESIGN T14, 5.5).
# sure = cells holding a lattice point that is in range (inscribed 64-gon radius, minus TolPx) and sees the viewer
# with every blocking wall farther than TolPx from the line of sight: must all be in cellsTouched (no missed cell)
# maybe = cellsTouched cells must each hold a point that is visible when walls only block by PROPER crossing and the
# point may move TolPx (no invented cell). 9x9 lattice per cell first, 65x65 (0.5 px) for slivers.
const TolPx = 0.5
proc pSegDist(p, a, b: Vec): float =
let (ex, ey) = (b.x - a.x, b.y - a.y)
let l2 = ex * ex + ey * ey
let t = if l2 == 0: 0.0 else: max(0.0, min(1.0, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2))
hypot(p.x - a.x - t * ex, p.y - a.y - t * ey)
proc properCross(p, q, a, b: Vec): bool =
proc o(a, b, c: Vec): float = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
let (d1, d2, d3, d4) = (o(p, q, a), o(p, q, b), o(a, b, p), o(a, b, q))
d1 * d2 < 0 and d3 * d4 < 0
proc segSegGap(p, q, a, b: Vec): float = # 0 when they cross
if properCross(p, q, a, b): 0.0
else: min(min(pSegDist(p, a, b), pSegDist(q, a, b)), min(pSegDist(a, p, q), pSegDist(b, p, q)))
proc oracleCheck(o: Vec, walls: openArray[Wall], radius, cell: float, touched: openArray[(int, int)]): tuple[sure, extra, miss: int] =
var blocking: seq[Wall]
for w in walls:
if w.blocks: blocking.add w
let rin = radius * cos(PI / 64) - TolPx
# sure: every strictly visible lattice point's cell must be touched
var y = o.y - radius + 1.3
while y < o.y + radius:
var x = o.x - radius + 1.7
while x < o.x + radius:
let p: Vec = (x, y)
if hypot(x - o.x, y - o.y) <= rin:
var clear = true
for w in blocking:
if segSegGap(o, p, w.a, w.b) <= TolPx: clear = false; break
if clear:
inc result.sure
if (int(floor(x / cell)), int(floor(y / cell))) notin touched: inc result.miss
x += 4
y += 4
# maybe: every touched cell must contain a (tolerantly) visible point
proc visibleTol(p: Vec): bool =
for (dx, dy) in [(0.0, 0.0), (TolPx, 0.0), (-TolPx, 0.0), (0.0, TolPx), (0.0, -TolPx)]:
let q: Vec = (p.x + dx, p.y + dy)
if hypot(q.x - o.x, q.y - o.y) > radius + TolPx: continue
var clear = true
for w in blocking:
if properCross(o, q, w.a, w.b): clear = false; break
if clear: return true
for (ix, iy) in touched:
var found = false
for n in [8, 64]:
for j in 0 .. n:
for i in 0 .. n:
if not found and visibleTol((ix.float * cell + cell * i.float / n.float, iy.float * cell + cell * j.float / n.float)):
found = true
if found: break
if not found: inc result.extra
proc oracleOf(o: Vec, walls: openArray[Wall], radius, cell: float): tuple[sure, extra, miss: int] =
oracleCheck(o, walls, radius, cell, cellsTouched(visibilityPolygon(o, walls, radius), cell))
suite "explored oracle (independent, tolerance 0.5 px)":
test "prototype scene, all tokens, doors closed and opened":
let sc = loadScene()
var opened = sc.walls
for w in opened.mitems:
if w.door: w.open = true
var sure = 0
for walls in [sc.walls, opened]:
for p in sc.tokens:
let r = oracleOf((p.x + 7.3, p.y - 3.1), walls, sc.radius, sc.cell)
check r.miss == 0
check r.extra == 0
sure += r.sure
check sure > 100000 # the oracle really sampled
test "random wall fields, cell 32 and 25":
var r = Rng(s: 4242'u64)
for iter in 0 ..< 6:
let walls = randomWalls(r, 30, 1200)
let o: Vec = (r.uni(200, 1000), r.uni(200, 1000))
let res = oracleOf(o, walls, 300, [32.0, 25.0][iter mod 2])
check res.miss == 0
check res.extra == 0
test "negative control: the oracle notices a missing and an invented cell":
let sc = loadScene()
let o = sc.tokens[0]
let good = cellsTouched(visibilityPolygon(o, sc.walls, sc.radius), sc.cell)
check oracleCheck(o, sc.walls, sc.radius, sc.cell, good).miss == 0
# drop a cell well inside the lit area
let dropped = good[good.len div 2]
var fewer: seq[(int, int)]
for c in good:
if c != dropped: fewer.add c
check oracleCheck(o, sc.walls, sc.radius, sc.cell, fewer).miss > 0
# add a cell beyond the wall box that nothing can see
check oracleCheck(o, sc.walls, sc.radius, sc.cell, good & @[(100, 100)]).extra > 0
# replace the polygon by a half-radius one: many clearly visible cells are missed
check oracleCheck(o, sc.walls, sc.radius, sc.cell, cellsTouched(visibilityPolygon(o, sc.walls, sc.radius / 2), sc.cell)).miss > 0