Control passes; a-d still caught (1,2,2,1,1 expected tests), new e-j each caught. Logs regenerated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
142 lines
7.2 KiB
Nim
142 lines
7.2 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).
|
|
## 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]
|
|
Wall* = object
|
|
a*, b*: Vec
|
|
door*, open*: bool
|
|
|
|
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 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
|
|
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)
|