fix: hit a wall lying along a sight ray so it casts its line's shadow (#26)

visibilityPolygon casts one ray per 64-gon vertex and ang, ang+-RayEps per wall
endpoint. A wall radial to the viewer is collinear with the ray that crosses it,
and rayHit rejected the collinear case; its own +-RayEps rays meet the wall's
line at the viewer (t = 0, rejected by t > Eps). So the wall got no ray, no
vertex and no shadow, and a token on the line beyond it stayed inside the
polygon: a player-view fog leak (DESIGN 3.1).

Fix: rayHit returns the nearest point of the overlap when the wall lies on the
ray's line (and Inf only for a parallel wall on another line). {.inline.} keeps
the fan's inner loop at its previous cost (CPU-time cross-check on 20k dense
polygons: 25.8s before, 32.5s without the pragma, 24.9s with it).

Proof: tgeometry visibility tests (horizontal k=0, vertical k=16, both wall
directions, a 32 px grid translation, 10 degrees, plus the non-radial and
0.5 px-off negative controls); the leak world gains a wall on the subject's own
column with a hidden token beyond it, and leakcheck's HIDDEN_TOKEN class now
asserts the token-level over-approximation (token centre + viewer->token
segment, 5.4 tolerance), which the GEOMETRY class structurally cannot see.
This commit is contained in:
2026-11-20 22:17:45 +01:00
parent a11782f00d
commit 414bb0326c
7 changed files with 169 additions and 6 deletions
+3 -1
View File
@@ -708,7 +708,9 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
These are the cases the algorithm handles. Proven by: TESTING §5.2 (port baseline, regression tests). These are the cases the algorithm handles. Proven by: TESTING §5.2 (port baseline, regression tests).
- Collinear rays skipped (neighbouring +-eps rays cover them). - Collinear rays skipped (neighbouring +-eps rays cover them) — except a wall lying *along* the ray
(radial to the viewer): it is hit at the nearest point of the overlap, so it contributes a vertex
and the line beyond it is outside the polygon (#26).
- Token standing on an endpoint: that endpoint skipped, hits at t <= 1e-9 ignored. - Token standing on an endpoint: that endpoint skipped, hits at t <= 1e-9 ignored.
- T-junction, shared vertex, free-standing wall, '<' apex, box corner, behind-viewer fan, long thin - T-junction, shared vertex, free-standing wall, '<' apex, box corner, behind-viewer fan, long thin
corridor. corridor.
+6 -1
View File
@@ -361,7 +361,12 @@ from the prototype, what was missing, what the M3 build added, and the tools it
behind each, a one-way screen, a marked window the subject sees, the same window's switch cleared behind each, a one-way screen, a marked window the subject sees, the same window's switch cleared
and restored (retraction and re-earn), a marked solid wall and a marked window the subject never and restored (retraction and re-earn), a marked solid wall and a marked window the subject never
sees. `tools/leak.test.mjs` asserts that coverage from the GM's wall frames and the subject's sees. `tools/leak.test.mjs` asserts that coverage from the GM's wall frames and the subject's
marker frames, so a rewrite that drops an element fails on its own, not only inside a fault. All marker frames, so a rewrite that drops an element fails on its own, not only inside a fault. The
world also holds a wall lying along one of the subject's vision rays with a token beyond it on the
same line: a zero-width wall hides exactly that line, and `HIDDEN_TOKEN` is the token-level
assertion for it (#26) — the class checks a token's own centre and the viewer -> token segment
against the walls, not sampled polygon points, because the `GEOMETRY` class only tests *missing*
vision and cannot see an over-approximation. All
pre-existing classes still fire under the rewrite, each as exactly its own class (all 21 entries pre-existing classes still fire under the rewrite, each as exactly its own class (all 21 entries
of the `FAULTS` table of `tools/fault.test.mjs`, 22 tests with the clean-build gate). of the `FAULTS` table of `tools/fault.test.mjs`, 22 tests with the clean-build gate).
`tools/leakcheck.nim` `tools/leakcheck.nim`
+15 -2
View File
@@ -6,6 +6,9 @@
## One-way sight (DESIGN 5.8, #58): `Wall.sightDir` names the blind side of `a -> b` (`left` = the `(-dy, dx)` normal) ## One-way sight (DESIGN 5.8, #58): `Wall.sightDir` names the blind side of `a -> b` (`left` = the `(-dy, dx)` normal)
## and `visibilityPolygon` blocks such a wall only for a viewer on that side; the other side casts rays past it. ## and `visibilityPolygon` blocks such a wall only for a viewer on that side; the other side casts rays past it.
## Movement never reads it: `moverules` gets the same wall and blocks both ways. ## Movement never reads it: `moverules` gets the same wall and blocks both ways.
## Radial walls (#26): a wall lying along a sight ray (radial to the viewer) is hit by that ray at the
## nearest point of the overlap, so it contributes a vertex and the line beyond it is outside the
## polygon. Its own +-RayEps rays meet the wall's line at the viewer, so they never covered it.
## Known limitations (DESIGN 5.4 / 12): ## Known limitations (DESIGN 5.4 / 12):
## - boundary epsilon ambiguity: RayEps 1e-4 rad, inclusive tests; token on a vision boundary is ambiguous ## - boundary epsilon ambiguity: RayEps 1e-4 rad, inclusive tests; token on a vision boundary is ambiguous
## (leak checker and explored oracle use a 0.5 px neighbourhood). ## (leak checker and explored oracle use a 0.5 px neighbourhood).
@@ -67,11 +70,21 @@ proc blindTo*(w: Wall, o: Vec): bool =
of wdLeft: s >= -Eps of wdLeft: s >= -Eps
of wdRight: s <= Eps of wdRight: s <= Eps
proc rayHit(o, d: Vec, a, b: Vec): float = proc rayHit(o, d: Vec, a, b: Vec): float {.inline.} =
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf ## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
let e = b - a let e = b - a
let den = cross(d, e) let den = cross(d, e)
if abs(den) < 1e-12: return Inf # parallel/collinear: grazing, other rays cover it if abs(den) < 1e-12:
# Parallel. A wall on another line never meets the ray. A wall *on* the ray's line (radial to the
# viewer, #26) is hit at the nearest point of the overlap: skipping the collinear case left such a
# wall without a vertex and without a shadow, so the line beyond it stayed inside the polygon (a
# player-view fog leak, DESIGN 3.1). Its own +-RayEps rays cannot cover it: they meet the wall's
# line at the viewer (t = 0) and `t > Eps` rejects them.
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) # viewer on or inside the wall: on-wall sight is ambiguous (5.5)
let ao = a - o let ao = a - o
let t = cross(ao, e) / den let t = cross(ao, e) / den
let u = cross(ao, d) / den let u = cross(ao, d) / den
+49
View File
@@ -188,6 +188,55 @@ suite "visibility":
test "radius clips": test "radius clips":
check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200) check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200)
test "wall lying along a 64-gon ray: no leak past its far end (#26)":
# A wall radial to the viewer (the line through the viewer) is collinear with the ray that
# crosses it, and `rayHit` used to reject the collinear case, while its own +-RayEps rays meet
# the wall's line at the viewer (t = 0). So no ray hit it, it cast no shadow, and a token on the
# line beyond it stayed `inside` the polygon: a player-view fog leak (DESIGN 3.1, 5.1).
# A zero-width wall hides exactly its line's continuation, so the leak was that line only.
# Both wall directions, and a 1 px-off control that light really does reach around the far end.
for w in [@[W(300, 200, 500, 200)], @[W(500, 200, 300, 200)]]:
let poly = visibilityPolygon((200.0, 200.0), w, 600) # k = 0 ray from the viewer
check poly.hasVertex((300.0, 200.0)) # the wall contributes its near end
check not poly.inside((560.0, 200.0)) # hidden on the line beyond it
check poly.inside((250.0, 200.0)) # in front of the wall: seen
check poly.inside((560.0, 201.0)) # 1 px off the line: seen round the end
test "radial wall: the same column (k = 16) and a grid-snapped translation (#26)":
# the k = 16 ray is straight up; a vertical wall on the viewer's column is the same case
for w in [@[W(200, 300, 200, 500)], @[W(200, 500, 200, 300)]]:
let poly = visibilityPolygon((200.0, 200.0), w, 600)
check poly.hasVertex((200.0, 300.0))
check not poly.inside((200.0, 560.0))
# translated onto 32 px grid lines (the maps snap there; exact collinearity is routine)
let hrow = @[W(448, 256, 608, 256)]
check not visibilityPolygon((320.0, 256.0), hrow, 600).inside((704.0, 256.0))
check visibilityPolygon((320.0, 256.0), hrow, 600).inside((704.0, 257.0))
let vcol = @[W(320, 448, 320, 608)]
check not visibilityPolygon((320.0, 256.0), vcol, 600).inside((320.0, 704.0))
test "radial wall at an arbitrary angle: the 64-gon alignment is not the condition (#26)":
# Reported as a 64-gon ray, but any wall radial to the viewer behaves the same way: its own
# +-RayEps rays land on t = 0 too. Verified at 10 degrees.
let a = 10.0 * PI / 180
let ux = cos a
let uy = sin a
let w = @[Wall(a: (200.0 + 100 * ux, 200.0 + 100 * uy),
b: (200.0 + 300 * ux, 200.0 + 300 * uy))]
let poly = visibilityPolygon((200.0, 200.0), w, 600)
check poly.hasVertex((200.0 + 100 * ux, 200.0 + 100 * uy))
check not poly.inside((200.0 + 360 * ux, 200.0 + 360 * uy))
test "negative controls: a non-radial wall with an endpoint on a ray still blocks (#26)":
# (500,200) is exactly on the k = 0 ray from (200,200) but the wall runs north from it, so the
# per-endpoint fan does cover it: the fix must not trade the leak for an under-approximation.
let w = @[W(500, 200, 500, 400)]
check not sees(w, (200.0, 200.0), (560.0, 300.0))
check sees(w, (200.0, 200.0), (560.0, 150.0))
# a wall 0.5 px off the viewer's row: not radial, so nothing is behind it on the line
let off = @[W(300, 200.5, 500, 200.5)]
check sees(off, (200.0, 200.0), (560.0, 200.0))
suite "cells": suite "cells":
test "square polygon": test "square polygon":
let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)] let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)]
+47
View File
@@ -92,6 +92,12 @@ const WORLD = [
{ role: 'far-locked', a: [1400, 820], b: [1400, 920], door: true, locked: true }, { role: 'far-locked', a: [1400, 820], b: [1400, 920], door: true, locked: true },
// One-way screen: the wall's right (east) side is blind, so a subject west of it sees across. // One-way screen: the wall's right (east) side is blind, so a subject west of it sees across.
{ role: 'one-way-screen', a: [700, 1200], b: [700, 1400], sight_dir: 'right' }, { role: 'one-way-screen', a: [700, 1200], b: [700, 1400], sight_dir: 'right' },
// A wall lying along a vision ray (#26): x = 600 is a 64-gon direction (the k = 16 ray, straight
// up) from the subject's room position (600, 640), and H1 stands beyond it on that same line. The
// fan used to hit no ray at all on such a wall, so the wall cast no shadow and H1 leaked into the
// subject's view. A zero-width wall hides exactly the line's continuation, so this is the only
// arrangement that shows it. `scenarioCoverage` reads the shape back off the frames.
{ role: 'on-ray', a: [600, 700], b: [600, 850] },
// Marked window in the room, the positive marker control: anchor (520, 800) (#59). // Marked window in the room, the positive marker control: anchor (520, 800) (#59).
{ role: 'marked-window', preset: 'window', a: [520, 700], b: [520, 900] }, { role: 'marked-window', preset: 'window', a: [520, 700], b: [520, 900] },
// Marked solid wall in the room: the switch is on but the shape is a wall, so no marker may be // Marked solid wall in the room: the switch is on but the shape is a wall, so no marker may be
@@ -130,6 +136,43 @@ export function scenarioCoverage(gmMsgs, subjMsgs) {
const marked = all.filter(w => w.player_marker) const marked = all.filter(w => w.player_marker)
const windows = marked.filter(isWindow) const windows = marked.filter(isWindow)
const occluded = windows.filter(w => anchorOf(w)[0] > FAR_WALL_X) const occluded = windows.filter(w => anchorOf(w)[0] > FAR_WALL_X)
// #26: the on-ray fixture, read off the frames rather than the WORLD constant. A subject
// position, an axis-aligned wall on that same row/column and away from it, and someone else's
// token beyond the wall on that same line inside the subject's vision radius: the one arrangement
// where a wall radial to the viewer must cast the line's shadow. A rewrite that moves any of the
// three drops this to 0 and fails in leak.test.mjs, instead of silently losing the obligation.
const mineIds = new Set()
const minePos = []
let visionR = 0
for (const m of subjMsgs) {
if (!m || typeof m.t !== 'string') continue
if (m.t === 'hello' && m.scene) visionR = m.scene.vision_radius_default
if (m.t === 'token' && m.mine) { mineIds.add(m.id); minePos.push(m.pos) }
}
const gmTokens = []
for (const m of gmMsgs) if (m && m.t === 'token') gmTokens.push({ id: m.id, pos: m.pos })
let onRayHidden = 0
for (const w of all) {
const horiz = w.a[1] === w.b[1]
const vert = w.a[0] === w.b[0]
if (!horiz && !vert) continue
const fixed = horiz ? w.a[1] : w.a[0]
const lo = horiz ? Math.min(w.a[0], w.b[0]) : Math.min(w.a[1], w.b[1])
const hi = horiz ? Math.max(w.a[0], w.b[0]) : Math.max(w.a[1], w.b[1])
for (const o of minePos) {
const along = horiz ? o[0] : o[1]
if ((horiz ? o[1] : o[0]) !== fixed) continue
if (along >= lo && along <= hi) continue
const beyond = v => (along < lo ? v < lo : v > hi)
for (const t of gmTokens) {
if (mineIds.has(t.id)) continue
if ((horiz ? t.pos[1] : t.pos[0]) !== fixed) continue
if (!beyond(horiz ? t.pos[0] : t.pos[1])) continue
if (visionR > 0 && Math.hypot(t.pos[0] - o[0], t.pos[1] - o[1]) > visionR) continue
onRayHidden++
}
}
}
return { return {
walls: all.length, walls: all.length,
oneWay: all.filter(w => w.sight_dir !== 'both').length, oneWay: all.filter(w => w.sight_dir !== 'both').length,
@@ -144,6 +187,7 @@ export function scenarioCoverage(gmMsgs, subjMsgs) {
markedWindowsOccluded: occluded.length, markedWindowsOccluded: occluded.length,
markedWindowsOccludedSeen: occluded.filter(w => received.has(anchorOf(w).join(','))).length, markedWindowsOccludedSeen: occluded.filter(w => received.has(anchorOf(w).join(','))).length,
markers: received.size, markers: received.size,
onRayHidden,
} }
} }
@@ -242,6 +286,9 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
actual_name: 'Brother Ivo' }) actual_name: 'Brother Ivo' })
await createToken('N4', { kind: 'npc', pos: [1500, 870], descriptive_name: 'a jailer', await createToken('N4', { kind: 'npc', pos: [1500, 870], descriptive_name: 'a jailer',
actual_name: 'Warden Hale' }) actual_name: 'Warden Hale' })
// Hidden behind the on-ray wall (#26) from the subject's (600, 640): same column, beyond it.
await createToken('H1', { kind: 'npc', pos: [600, 950], descriptive_name: 'a shade',
actual_name: 'The Shade' })
}) })
const A = await connect(origin, playerA.key, 'A', log, () => g) const A = await connect(origin, playerA.key, 'A', log, () => g)
+4
View File
@@ -40,6 +40,10 @@ for (const subject of ['A', 'B']) {
`the world needs a marked window behind the far wall (TESTING 5.8): ${JSON.stringify(cov)}`) `the world needs a marked window behind the far wall (TESTING 5.8): ${JSON.stringify(cov)}`)
assert.equal(cov.markedWindowsOccludedSeen, 0, assert.equal(cov.markedWindowsOccludedSeen, 0,
`a wall behind a sight blocker yields no marker: ${JSON.stringify(cov)}`) `a wall behind a sight blocker yields no marker: ${JSON.stringify(cov)}`)
// #26: a wall lying along a vision ray with a hidden token beyond it must be in the world;
// the checker's HIDDEN_TOKEN class is the assertion that it does not leak.
assert.ok(cov.onRayHidden >= 1,
`the world needs a token hidden behind a wall lying along a vision ray (#26): ${JSON.stringify(cov)}`)
} }
const check = runChecker(transcript, subject) const check = runChecker(transcript, subject)
fs.writeFileSync(path.join(results, `leak-${subject}.log`), check.output) fs.writeFileSync(path.join(results, `leak-${subject}.log`), check.output)
+45 -2
View File
@@ -8,7 +8,10 @@
## ##
## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each ## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each
## injected server fault: ## injected server fault:
## HIDDEN_TOKEN a token the subject may not see reached it ## HIDDEN_TOKEN a token the subject may not see reached it, or one its polygons admit only
## through a wall (#26: the fan's over-approximation is a token-level leak, so the
## class is checked on token centres and the viewer->token segment, never on
## sampled polygon points; a crossing within the 5.4 boundary tolerance is fine)
## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS ## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS
## WALLDATA a wall-ish key or frame reached the subject ## WALLDATA a wall-ish key or frame reached the subject
## WITHHELD a token the subject may see was not sent (or was taken away while visible) ## WITHHELD a token the subject may see was not sent (or was taken away while visible)
@@ -25,7 +28,8 @@
## CHAR_LIST another player's character record or encountered entry reached the subject ## CHAR_LIST another player's character record or encountered entry reached the subject
## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8) ## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8)
## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8) ## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8)
## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity) ## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity): it only
## tests missing vision, so an over-approximated polygon is HIDDEN_TOKEN's job
## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58) ## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58)
## MARKER_EARLY a marker arrived before the subject had seen that wall's extent (the extent ## MARKER_EARLY a marker arrived before the subject had seen that wall's extent (the extent
## gate was dropped: it reveals a position early; TESTING 10.3, #60) ## gate was dropped: it reveals a position early; TESTING 10.3, #60)
@@ -360,6 +364,38 @@ proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool =
for (_, pts) in polys: for (_, pts) in polys:
if inside(pts, p): return true if inside(pts, p): return true
const BoundaryTol = 0.5
## DESIGN 5.4: a point within 0.5 px of a vision boundary is ambiguous; the checker's
## clear-segment oracle already uses that neighbourhood (TESTING 5.4).
proc shrink(a, b: Vec, tol: float): (Vec, Vec) =
## `a -> b` with both ends pulled in by `tol`; a segment too short to shrink is kept whole.
let dx = b.x - a.x
let dy = b.y - a.y
let l = hypot(dx, dy)
if l <= 2 * tol: return (a, b)
((a.x + dx / l * tol, a.y + dy / l * tol), (b.x - dx / l * tol, b.y - dy / l * tol))
proc insideThroughWall(truth: Truth, polys: seq[(string, seq[Vec])], p: Vec): bool =
## #26: a point inside a polygon that only a wall admits. The polygons are the same fan the
## server runs, and `inside` alone cannot see this leak (the GEOMETRY class checks the opposite
## direction, missing vision), so this is the token-level assertion the class list promises:
## for the polygon containing `p`, the segment from that viewer's centre to `p` must not pass
## through the interior of a sight-blocking wall. Both segments are shrunk by the 5.4 boundary
## tolerance first, so a token grazing a corner (inside the polygon while touching the wall's
## endpoint) stays tolerated and only a real crossing is a leak.
for (pid, pts) in polys:
if not inside(pts, p): continue
if pid notin truth.tokens: continue
let o = truth.tokens[pid].pos
let (o2, p2) = shrink(o, p, BoundaryTol)
for w in truth.walls:
if checkDir and w.sightDir != wdBoth and not w.blindTo(o): continue
if not w.blocksSight: continue
let (wa, wb) = shrink(w.a, w.b, BoundaryTol)
if segsCross(o2, p2, wa, wb): return true
false
proc extentSeen(polys: seq[(string, seq[Vec])], a, b: Vec): bool = proc extentSeen(polys: seq[(string, seq[Vec])], a, b: Vec): bool =
## The checker's OWN visible-extent test (DESIGN 5.8, TESTING 10.3; never `vision.nim`): any point ## The checker's OWN visible-extent test (DESIGN 5.8, TESTING 10.3; never `vision.nim`): any point
## of the segment inside one of the subject's polygons means an endpoint is inside or the segment ## of the segment inside one of the subject's polygons means an endpoint is inside or the segment
@@ -652,6 +688,13 @@ proc main() =
fail cls, "token " & id & " sent but not visible (group " & g.label & ")" fail cls, "token " & id & " sent but not visible (group " & g.label & ")"
else: else:
seenAny.incl id seenAny.incl id
# #26: the polygon is an over-approximation by design only up to the 5.4 boundary. A
# token that is inside it with a wall crossing the viewer -> token segment (away from
# either end) is hidden, and this is the token-level assertion the class list promises.
if not wantMine and insideThroughWall(truth, polysChecks, actual.pos):
leaked[id] = "HIDDEN_TOKEN"
fail "HIDDEN_TOKEN", "token " & id &
" is inside the subject's polygon only through a wall (group " & g.label & ")"
of "token_gone": of "token_gone":
let id = m["id"].getStr let id = m["id"].getStr
if id notin view: if id notin view: