Files
FFF_vtt_frozen/server/geometry.nim
T
SirStone 9fcbe885c1 feat(walls): one-way sight per-viewer filter and ONEWAY fault (#58)
The vision fan blocks a sight-blocking one-way wall only for a viewer on
its blind side (sight_dir names it; left is the (-dy,dx) normal of a->b),
one sign test inline after the radius cull, so the hoisted wall list stays
viewer-independent. Movement never reads the direction: one-way walls block
both ways. Explored and tiles therefore differ by side and only ever grow.

- geometry: WallDir + Wall.sightDir + blindTo, filter in visibilityPolygon.
- worldmap: sight_dir mapping (movement mapping unchanged).
- vision: the ONEWAY leak-fault build drops sight_dir player-side.
- leakcheck: own side test for the fan and the clear-segment oracle; ONEWAY
  class detected against the sight_dir-dropped fan.
- leak scenario gains a one-way wall the subject sees across; fault test
  asserts exactly ONEWAY.
- oneway.test.mjs: both sides, tile sweep with its own oracle, flip with
  fixed endpoints, monotone explored/tiles, restart, two-way movement.
- docs: DESIGN 5.8 mechanism sentence corrected; TESTING #58 markers built.
- nginx harness: temp dirs created recursively (restart on one state dir).
2026-11-19 22:57:39 +01:00

172 lines
8.9 KiB
Nim

## 2D vision geometry. Pure, stdlib only. Ported from prototype-server-vision/src/geometry.nim (M1), revised in M2.
## Move rules (swept circle, token-on-wall escape, step cap, `blocked`) live in server/moverules.nim, not here.
## Fixed in M2 (DESIGN 5.5): token exactly on a wall can move off it (moverules escape rule); the move check is the
## swept circle, not centre path + destination only; `moveBlocked` is gone from this module; cellsTouched is a scanline
## (prototype per-cell version kept test-only in tests/refold.nim, differential-tested).
## 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.
## Movement never reads it: `moverules` gets the same wall and blocks both ways.
## Known limitations (DESIGN 5.4 / 12):
## - 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).
## - cellsTouched keeps a prototype quirk on purpose: a cell touching the polygon only along its bbox minimum x / y line
## is not marked (every other touch is). The regression corpus has such polygons (walls on x = 256).
## - vision is O(rays x walls in bbox): bbox cull, no spatial grid (H3: not built, 5k bench met target; results/bench.log).
## A dense 5k layout (4096 px world, ~200 walls per vision box) costs ~1.3 ms per polygon.
## - circle range limit is an inscribed 64-gon: error <= ~0.12% of R.
import std/[math, algorithm]
type
Vec* = tuple[x, y: float]
WallDir* = enum
## Which side of the drawn `a -> b` order cannot see across (DESIGN 5.8, #47/#58). `left` is
## the `(-dy, dx)` side, the same formula as `position` (5.10) and the door-push side (5.5).
## This is a sight-only field: movement is always two-way and never reads it.
wdBoth = "both"
wdLeft = "left"
wdRight = "right"
Wall* = object
a*, b*: Vec
door*, open*: bool
sightDir*: WallDir
const
Eps* = 1e-9 # geometric tolerance (px)
RayEps = 1e-4 # angular nudge past endpoints (rad)
proc blocks*(w: Wall): bool = not (w.door and w.open)
proc cross*(a, b: Vec): float = a.x * b.y - a.y * b.x
proc `-`*(a, b: Vec): Vec = (a.x - b.x, a.y - b.y)
proc blindTo*(w: Wall, o: Vec): bool =
## DESIGN 5.8: true when `o` stands on the side the wall's `sight_dir` names blind. One sign test
## of the viewer against the `a -> b` left normal: cross(a->b, o - a) is the signed distance along
## `(-dy, dx)`, so positive is the left side. A viewer exactly on the drawn line (|s| <= Eps) is
## blind to either direction: the predicate is never ambiguous, even though the fan's own rays
## start on the segment and a token standing on a wall already sees along it (5.5).
if w.sightDir == wdBoth: return false
let s = cross(w.b - w.a, o - w.a)
case w.sightDir
of wdBoth: false
of wdLeft: s >= -Eps
of wdRight: s <= Eps
proc rayHit(o, d: Vec, a, b: Vec): float =
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
let e = b - a
let den = cross(d, e)
if abs(den) < 1e-12: return Inf # parallel/collinear: grazing, other rays cover it
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 visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float,
circleSegs = 64): seq[Vec] =
## CCW polygon of what `o` sees, bounded by an inscribed circleSegs-gon of `radius`.
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) # same (-pi,pi] range as the wall angles, else the sort scrambles the fan
for w in walls:
if not w.blocks: continue
# shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid
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
# Per-viewer one-way filter (5.8, #58), inline and after the radius cull so the hoisted wall
# list stays viewer-independent: a sight-blocking one-way wall blocks only a viewer on its
# blind side; the other side sees across it. Two-way walls skip the test entirely.
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 # token on endpoint
let ang = arctan2(p.y - o.y, p.x - o.x)
angles.add ang
angles.add ang - RayEps
angles.add ang + RayEps
angles.sort
for ang in angles:
let d: Vec = (cos ang, sin ang)
var best = Inf
for s in segs: best = min(best, rayHit(o, d, s[0], s[1]))
if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best))
proc segsCross*(p, q, a, b: Vec): bool =
## inclusive segment intersection (touching and collinear overlap count)
proc orient(a, b, c: Vec): int =
let v = cross(b - a, c - a)
if v > Eps: 1 elif v < -Eps: -1 else: 0
proc onSeg(a, b, c: Vec): bool = # c collinear with ab: within bbox?
c.x >= min(a.x, b.x) - Eps and c.x <= max(a.x, b.x) + Eps and
c.y >= min(a.y, b.y) - Eps and c.y <= max(a.y, b.y) + Eps
let o1 = orient(p, q, a); let o2 = orient(p, q, b)
let o3 = orient(a, b, p); let o4 = orient(a, b, q)
if o1 != o2 and o3 != o4: return true
(o1 == 0 and onSeg(p, q, a)) or (o2 == 0 and onSeg(p, q, b)) or
(o3 == 0 and onSeg(a, b, p)) or (o4 == 0 and onSeg(a, b, q))
proc segDist*(p, a, b: Vec): float =
let e = b - a
let l2 = e.x * e.x + e.y * e.y
let t = if l2 < Eps: 0.0 else: clamp(((p.x - a.x) * e.x + (p.y - a.y) * e.y) / l2, 0.0, 1.0)
hypot(p.x - a.x - t * e.x, p.y - a.y - t * e.y)
proc inside*(poly: openArray[Vec], p: Vec): bool =
## even-odd point-in-polygon (boundary ambiguous)
var j = poly.len - 1
for i in 0 ..< poly.len:
if (poly[i].y > p.y) != (poly[j].y > p.y) and
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x:
result = not result
j = i
proc cellsTouched*(poly: openArray[Vec], cell: float): seq[(int, int)] =
## grid cells (ix, iy) overlapped by the polygon (area overlap; boundary touch within Eps included, except along the bbox minimum lines, see below), sorted by (iy, ix).
## Scanline over the cell rows, O(edges x rows spanned + cells). Per row band [by0, by1] the part of the polygon in
## the band projects on x as (a) the clipped extent of every edge plus (b) the even-odd fill spans at the band's
## lower line (a vertical line in the band that meets no edge is wholly inside or wholly outside, and inside iff
## inside at by0). Differential-tested against the prototype per-cell version (tests/refold.nim).
if poly.len < 3: return
var x0, y0 = Inf
var x1, y1 = -Inf
for p in poly:
x0 = min(x0, p.x); x1 = max(x1, p.x); y0 = min(y0, p.y); y1 = max(y1, p.y)
# closed touch: a value exactly on (or within Eps of) a cell line belongs to both neighbours
proc lo(v, cell: float): int = int(ceil((v - Eps) / cell)) - 1
proc hi(v, cell: float): int = int(floor((v + Eps) / cell))
# prototype-compatible quirk: the grid starts at floor(bbox min), so a cell touching only the bbox minimum line is
# not marked (the regression corpus has such polygons: walls on x = 256). Every other touch is inclusive.
let (ix0, ix1, iy0, iy1) = (int(floor(x0 / cell)), hi(x1, cell), int(floor(y0 / cell)), hi(y1, cell))
let nx = ix1 - ix0 + 1
var hit = newSeq[bool](nx * (iy1 - iy0 + 1))
var xs = newSeq[seq[float]](iy1 - iy0 + 1) # fill crossings per row at the row's lower line
proc mark(row: int, xa, xb: float) =
for ix in max(lo(xa, cell), ix0) .. min(hi(xb, cell), ix1): hit[row * nx + ix - ix0] = true
for i in 0 ..< poly.len:
let p = poly[i]; let q = poly[(i + 1) mod poly.len]
let (ylo, yhi) = (min(p.y, q.y), max(p.y, q.y))
let (exlo, exhi) = (min(p.x, q.x), max(p.x, q.x))
proc xAt(y: float): float =
if p.y == q.y: exlo else: clamp(p.x + (y - p.y) * (q.x - p.x) / (q.y - p.y), exlo, exhi)
for iy in max(lo(ylo, cell), iy0) .. min(hi(yhi, cell), iy1):
let by0 = iy.float * cell
let row = iy - iy0
if p.y == q.y: mark(row, exlo, exhi)
else:
let (a, b) = (xAt(max(ylo, by0)), xAt(min(yhi, by0 + cell)))
mark(row, min(a, b), max(a, b))
if (p.y > by0) != (q.y > by0): xs[row].add xAt(by0)
for row in 0 ..< xs.len:
xs[row].sort
for k in countup(0, xs[row].len - 2, 2): mark(row, xs[row][k], xs[row][k + 1])
for row in 0 ..< xs.len:
for c in 0 ..< nx:
if hit[row * nx + c]: result.add (ix0 + c, iy0 + row)