perf: test only the in-sector 64-gon chord per vision ray (#64)

Each fan ray now tests the one circle-segment chord of its angular sector
instead of all 64. A sector-boundary ray tests both meeting chords, so the
rayHit set and the picked minimum are unchanged: the polygon is bit-identical
to the all-segments fan. tests/tgeometry.nim keeps the old fan as an oracle
and asserts exact float equality over the prototype corpus, the seed scene
(all switch shapes), the 5k sparse/dense scenegen layouts, the #26
collinear/radial cases and random walls. tools/mutation.sh gains a2 (a ray
tests the next sector's chord), which fails 5 of those tests.

Bench on this host, before -> after (3-run median):
  1 poly, prototype 0.028 -> 0.008 ms (3.5x)
  1 poly, 5k sparse 0.062 -> 0.033 ms (1.9x)
  1 poly, 5k dense  1.085 -> 0.708 ms (1.5x)

Refs #64.
This commit is contained in:
2026-11-20 23:28:04 +01:00
parent 1dff520f31
commit d192381d13
4 changed files with 172 additions and 26 deletions
+129 -1
View File
@@ -1,6 +1,7 @@
# FFF_MUTATION=1 (set only by tools/mutation.sh) cuts iteration counts ~10x via scaled(); plain `devbox run test` runs full counts.
import std/[unittest, json, os, math]
import std/[unittest, json, os, math, algorithm]
import geometry, refold, testutil
import ../tools/scenegen
proc sees(walls: openArray[Wall], o, p: Vec, r = 500.0): bool =
visibilityPolygon(o, walls, r).inside(p)
@@ -330,6 +331,133 @@ suite "corpus (prototype leak transcripts)":
check n >= scaled(300) # corpus is not silently empty
check doorsSeen > 0 # and exercises opened doors
# ---- #64: the sector-limited fan must be bit-identical to the all-segments fan ----------------------------------
# The oracle is the pre-#64 `visibilityPolygon`, copied verbatim (including the #26 collinear-hit branch in
# `rayHit`). Equality is exact float equality, not a tolerance: the sector-limited fan only skips segs that the
# ray cannot hit, so every surviving `rayHit` value (and the picked min) must be identical bit for bit.
const RefRayEps = 1e-4
proc refRayHit(o, d: Vec, a, b: Vec): float {.inline.} =
let e = b - a
let den = cross(d, e)
if abs(den) < 1e-12:
if abs(cross(a - o, d)) > Eps: return Inf
let ta = (a.x - o.x) * d.x + (a.y - o.y) * d.y
let tb = (b.x - o.x) * d.x + (b.y - o.y) * d.y
let t0 = min(ta, tb)
return (if t0 > Eps: t0 else: Inf)
let ao = a - o
let t = cross(ao, e) / den
let u = cross(ao, d) / den
if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
proc referencePolygon(o: Vec, walls: openArray[Wall], radius: float, circleSegs = 64): seq[Vec] =
## The all-64-circle-segments fan, unchanged. Test-only oracle for #64.
var segs: seq[(Vec, Vec)]
var angles: seq[float]
for i in 0 ..< circleSegs:
let a0 = 2 * PI * i.float / circleSegs.float
let a1 = 2 * PI * (i + 1).float / circleSegs.float
segs.add(((o.x + radius * cos a0, o.y + radius * sin a0),
(o.x + radius * cos a1, o.y + radius * sin a1)))
angles.add arctan2(sin a0, cos a0)
for w in walls:
if not w.blocksSight: continue
if max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or
max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue
if w.sightDir != wdBoth and not w.blindTo(o): continue
segs.add((w.a, w.b))
for p in [w.a, w.b]:
if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue
let ang = arctan2(p.y - o.y, p.x - o.x)
angles.add ang
angles.add ang - RefRayEps
angles.add ang + RefRayEps
angles.sort
for ang in angles:
let d: Vec = (cos ang, sin ang)
var best = Inf
for s in segs: best = min(best, refRayHit(o, d, s[0], s[1]))
if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best))
proc wallVariants(base: seq[Wall]): seq[seq[Wall]] =
## The round-1 switch shapes geometry must see: plain, one-way both directions, window, open doors.
result.add base
var oneWay = base
for i in 0 ..< oneWay.len:
oneWay[i].sightDir = [wdLeft, wdRight, wdBoth][i mod 3]
result.add oneWay
var windows = base
for i in 0 ..< windows.len:
windows[i].sightBarrier = i mod 5 != 0
result.add windows
var opened = base
for i in 0 ..< opened.len:
if opened[i].door: opened[i].open = true
result.add opened
suite "sector-limited fan (#64: same polygon, fewer segment tests)":
test "corpus polygons are bit-identical to the all-segments fan":
let sc = loadScene()
var n = 0
var li = 0
for line in lines(currentSourcePath().parentDir / "fixtures" / "corpus.jsonl"):
inc li
if li mod (300 div scaled(300)) != 0: continue
let j = parseJson(line)
var walls = sc.walls
for w in walls.mitems:
if w.door: w.open = false
for id in j["open"]: walls[id.getInt].open = true
let o: Vec = (j["pos"][0].getFloat, j["pos"][1].getFloat)
inc n
check visibilityPolygon(o, walls, sc.radius) == referencePolygon(o, walls, sc.radius)
check n >= 1
test "seed scene tokens, doors and every switch shape: bit-identical":
let sc = loadScene()
for walls in wallVariants(sc.walls):
for p in sc.tokens:
check visibilityPolygon(p, walls, sc.radius) == referencePolygon(p, walls, sc.radius)
test "scenegen sparse and dense layouts, every switch shape: bit-identical":
for (world, seed) in [(16384.0, 1'u64), (4096.0, 1'u64)]:
let base = genScene(world, 5000, seed)
var r = Rng(s: 0xC64)
for walls in wallVariants(base):
for _ in 0 ..< scaled(8):
let o: Vec = (r.uni(400, world - 400), r.uni(400, world - 400))
check visibilityPolygon(o, walls, 400) == referencePolygon(o, walls, 400)
test "#26 collinear/radial walls: bit-identical (the fix is preserved)":
let cases: seq[(Vec, seq[Wall])] = @[
((200.0, 200.0), @[W(300, 200, 500, 200)]),
((200.0, 200.0), @[W(500, 200, 300, 200)]),
((200.0, 200.0), @[W(200, 300, 200, 500)]),
((200.0, 200.0), @[W(200, 500, 200, 300)]),
((320.0, 256.0), @[W(448, 256, 608, 256)]),
((320.0, 256.0), @[W(320, 448, 320, 608)]),
((320.0, 256.0), @[W(320, 448, 320, 608, sightDir = wdLeft)]),
((320.0, 256.0), @[Wall(a: (320.0, 448.0), b: (320.0, 608.0), sightBarrier: false)]),
]
for (o, walls) in cases:
check visibilityPolygon(o, walls, 600) == referencePolygon(o, walls, 600)
test "random walls, grid-snapped radial additions and switches: bit-identical":
var r = Rng(s: 64)
for iter in 0 ..< scaled(120):
var walls = randomWalls(r, 5 + iter mod 50, 1200)
for i in 0 ..< walls.len:
if i mod 3 == 0: walls[i].sightDir = wdLeft
if i mod 5 == 0: walls[i].sightBarrier = false
let o: Vec = (r.uni(100, 1100), r.uni(100, 1100))
if iter mod 3 == 0:
# force the #26 case: a wall on the viewer's own row or column
walls.add W(o.x + 60, o.y, o.x + 260, o.y)
walls.add W(o.x, o.y + 60, o.x, o.y + 260)
let radius = r.uni(50, 500)
check visibilityPolygon(o, walls, radius) == referencePolygon(o, walls, radius)
# ---- differential: scanline vs prototype per-cell ---------------------------------------------------------------
suite "cellsTouched differential vs prototype":
test "random visibility polygons: identical cell lists":