Files
FFF_vtt_frozen/server/moverules.nim
T

235 lines
11 KiB
Nim

## Move rules and the `blocked` flag (DESIGN 5.5). Pure and in-process: plain data in, plain data out, no IO, no clock.
## The WebSocket layer (M3) only maps `MoveResult` to `moveAck`; nothing here knows about the wire.
##
## Player move s -> d (checks in order, any failure = the same nack):
## 1. owner (else mkError, never an ack: an ack would echo an unseen position) and token not `blocked`;
## 2. in bounds, and |d - s| <= stepCap (token vision radius if it has vision and sets one, else scene default);
## 3. per blocking wall W: start overlapping W (dist(s,W) < r, "escape"): allowed iff the path does not cross W
## farther than EscapeEps from s AND dist(d,W) >= r; otherwise swept circle: allowed iff dist(seg s->d, W) >= r.
## GM move: bounds only (no walls, no cap, ignores `blocked`), then blocked = overlaps any blocking wall.
## `blocked` ("stuck", DESIGN 5.5): overlap = dist(token centre, W) < r. SET: wall added / updated; GM places or moves a token onto a blocking wall. KEEP: stays while ANY blocking wall
## overlaps. CLEAR: wall removed / door opened -> tokens that overlapped it get blocked = overlaps any remaining blocking wall; GM move to a
## free spot; gmClearBlocked (unconditional). Only tokens touched by the event change. wall update = remove then add.
##
## Door closing on a token = PUSH, not stuck (owner 2026-11-08): each token with dist(centre, door) < r moves
## perpendicular to the door, to the side its centre is on, by the minimal distance that ends >= r (+ PushEps); if the
## projection falls past the door's end the perpendicular offset is sqrt(r^2 - e^2), e = along-axis overshoot. Centre
## exactly on the door line (|side| <= Eps): side of `prev` (position before its most recent move/push); no history
## or prev also on the line: the left side of a->b (cross(b-a, p-a) > 0). Valid = in bounds and >= r from EVERY blocking
## wall (the closed door included); else try the opposite side; neither valid -> token stays and becomes `blocked`
## (opening that door later clears it, Clear rule). A pushed token gets blocked = false (its new spot overlaps no wall).
## Pushes are returned (Push list), no step cap. Each token is pushed independently; tokens never block tokens here
## (no token-token collision exists; `blocks_move` is not modelled), so pushed tokens may end overlapping each other.
## Wall add/update and GM placement/move inside a wall are unchanged (stuck). Door OPEN unchanged.
##
## Thresholds (px unless noted):
## EscapeEps = 1e-6: a crossing this close to the start is "the token stands on the wall", not a crossing. A token
## within 1e-6 of a wall can only exist via GM placement/edit (a player move keeps dist >= r), so this cannot be
## used to tunnel; 1e-6 is far below one pixel and far above float noise at world scale (|coords| < 1e5, ~1e-11).
## geometry.Eps = 1e-9 (parallel/collinear/touch tolerance, shared with the vision code).
## Interpretation notes: removing/opening affects only a BLOCKING wall (removing an open door changes nothing).
## removeWall shifts later wall indices down (dense ids); M3 owns id stability.
## Escape corner case (spec-normative): an escaping token may graze closer to W than it started, mid-path; only
## crossing and the destination are checked. Moving along the wall's own line counts as crossing.
## Not checked here: path crossing a wall W2 whose capsule distance is >= r is fine by definition.
import std/math
import geometry
const
EscapeEps* = 1e-6
NoOwner* = -1
PushEps* = 1e-6 # extra clearance of a pushed token so float noise never leaves it at dist < r
type
Role* = enum rolePlayer, roleGM
Actor* = object
role*: Role
player*: int # player id, meaningful for rolePlayer
Token* = object
pos*: Vec
owner*: int # player id or NoOwner (GM-controlled)
hasVision*: bool # `vision` flag
visionRadius*: float # <= 0: unset, use the scene default
blocked*: bool
prev*: Vec # position before the most recent move/push (valid iff hasPrev); decides the door-push side
hasPrev*: bool
Push* = object # server-originated position change (M3: broadcast + recompute vision)
ti*: int
pos*: Vec
Scene* = object
w*, h*: float
tokenRadius*, visionDefault*: float
walls*: seq[Wall]
tokens*: seq[Token]
MoveKind* = enum mkAck, mkNack, mkError
MoveResult* = object
kind*: MoveKind
pos*: Vec # mkAck: destination; mkNack: the old position; mkError: (0,0), must not be sent
proc dot(a, b: Vec): float = a.x * b.x + a.y * b.y
proc segSegDist*(p, q, a, b: Vec): float =
## distance between segments pq and ab (0 if they touch or cross)
if segsCross(p, q, a, b): return 0.0
min(min(segDist(p, a, b), segDist(q, a, b)), min(segDist(a, p, q), segDist(b, p, q)))
proc pathCrosses*(s, d, a, b: Vec): bool =
## does the path s->d meet segment ab at a point farther than EscapeEps from s? Collinear overlap beyond that counts.
let m = d - s
let len = hypot(m.x, m.y)
if len <= EscapeEps: return false
let e = b - a
let le = hypot(e.x, e.y)
let sa = a - s
if le < Eps: # degenerate wall = a point
return segDist(a, s, d) < Eps and hypot(sa.x, sa.y) > EscapeEps
let den = cross(m, e)
if abs(den) <= 1e-12 * len * le: # parallel
if abs(cross(sa, e)) / le > Eps: return false # offset parallel
let ta = dot(sa, m) / len
let tb = dot(b - s, m) / len
return max(ta, tb) > EscapeEps and min(ta, tb) <= len
let t = cross(sa, e) / den # fraction along s->d
let u = cross(sa, m) / den # fraction along ab
t * len > EscapeEps and t <= 1 + Eps / len and u >= -Eps / le and u <= 1 + Eps / le
proc pathClear*(walls: openArray[Wall], s, d: Vec, r: float): bool =
## DESIGN 5.5 step 3 for a player move (no owner/cap checks)
let (bx0, bx1) = (min(s.x, d.x) - r, max(s.x, d.x) + r)
let (by0, by1) = (min(s.y, d.y) - r, max(s.y, d.y) + r)
for w in walls:
if not w.blocks: continue
# a wall whose bbox misses the capsule bbox can neither be within r of the path nor of s
if max(w.a.x, w.b.x) < bx0 or min(w.a.x, w.b.x) > bx1 or
max(w.a.y, w.b.y) < by0 or min(w.a.y, w.b.y) > by1: continue
if segDist(s, w.a, w.b) < r:
if pathCrosses(s, d, w.a, w.b) or segDist(d, w.a, w.b) < r: return false
elif segsCross(s, d, w.a, w.b) or segSegDist(s, d, w.a, w.b) < r: return false
true
proc stepCap*(sc: Scene, t: Token): float =
if t.hasVision and t.visionRadius > 0: t.visionRadius else: sc.visionDefault
proc inBounds(sc: Scene, p: Vec): bool = # written so NaN fails
p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h
proc overlaps(sc: Scene, t: Token, w: Wall): bool = segDist(t.pos, w.a, w.b) < sc.tokenRadius
proc overlapsAny(sc: Scene, t: Token): bool =
for w in sc.walls:
if w.blocks and overlaps(sc, t, w): return true
proc nack(s: Vec): MoveResult = MoveResult(kind: mkNack, pos: s)
proc moveToken*(sc: var Scene, who: Actor, ti: int, d: Vec): MoveResult =
## validates and, on mkAck, applies the move. mkNack / mkError mutate nothing.
if ti < 0 or ti >= sc.tokens.len: return MoveResult(kind: mkError)
let s = sc.tokens[ti].pos
case who.role
of roleGM:
if not inBounds(sc, d): return nack(s)
of rolePlayer:
if sc.tokens[ti].owner != who.player: return MoveResult(kind: mkError)
if sc.tokens[ti].blocked or not inBounds(sc, d): return nack(s)
let dd = d - s
if hypot(dd.x, dd.y) > stepCap(sc, sc.tokens[ti]): return nack(s)
if not pathClear(sc.walls, s, d, sc.tokenRadius): return nack(s)
sc.tokens[ti].prev = s; sc.tokens[ti].hasPrev = true
sc.tokens[ti].pos = d
if who.role == roleGM: sc.tokens[ti].blocked = overlapsAny(sc, sc.tokens[ti])
MoveResult(kind: mkAck, pos: d)
# ---- `blocked` bookkeeping -------------------------------------------------------------------------------------
proc addToken*(sc: var Scene, t: Token): int =
## GM placement: ignores walls; blocked = given flag or overlapping a blocking wall
sc.tokens.add t
sc.tokens[^1].blocked = t.blocked or overlapsAny(sc, t)
sc.tokens.high
proc gmClearBlocked*(sc: var Scene, ti: int) =
if ti >= 0 and ti < sc.tokens.len: sc.tokens[ti].blocked = false
proc applyAdded(sc: var Scene, w: Wall) =
if w.blocks:
for i in 0 ..< sc.tokens.len:
if overlaps(sc, sc.tokens[i], w): sc.tokens[i].blocked = true
proc applyRemoved(sc: var Scene, w: Wall) =
if w.blocks:
for i in 0 ..< sc.tokens.len:
if overlaps(sc, sc.tokens[i], w): sc.tokens[i].blocked = overlapsAny(sc, sc.tokens[i])
proc addWall*(sc: var Scene, w: Wall): int =
sc.walls.add w
applyAdded(sc, w)
sc.walls.high
proc removeWall*(sc: var Scene, id: int): bool =
if id < 0 or id >= sc.walls.len: return false
let w = sc.walls[id]
sc.walls.delete id
applyRemoved(sc, w)
true
proc updateWall*(sc: var Scene, id: int, w: Wall): bool =
## remove then add, id kept
if id < 0 or id >= sc.walls.len: return false
let old = sc.walls[id]
sc.walls[id] = w
applyRemoved(sc, old) # remaining set includes the new wall; applyAdded then covers tokens only the new wall touches
applyAdded(sc, w)
true
proc pushFrom(sc: Scene, t: Token, w: Wall): tuple[ok: bool, pos: Vec] =
## door-close push of t off w (see header); ok=false if neither side is valid
let e = w.b - w.a
let le = hypot(e.x, e.y)
let r = sc.tokenRadius
var n: Vec = (0.0, 1.0) # degenerate door (a point): push along +y
var along = 0.0 # projection of the centre on the door axis, from a
var side = 1.0
if le >= Eps:
n = (-e.y / le, e.x / le) # left normal of a->b
along = dot(t.pos - w.a, e) / le
side = dot(t.pos - w.a, n)
if abs(side) <= Eps:
side = if t.hasPrev: dot(t.prev - w.a, n) else: 0.0
if abs(side) <= Eps: side = 1.0
let over = if along < 0: -along elif along > le: along - le else: 0.0
let perp = sqrt(max(0.0, r * r - over * over)) + PushEps
let foot: Vec = if le >= Eps: (w.a.x + e.x * along / le, w.a.y + e.y * along / le) else: w.a
for sg in [(if side > 0: 1.0 else: -1.0), (if side > 0: -1.0 else: 1.0)]:
let p: Vec = (foot.x + n.x * sg * perp, foot.y + n.y * sg * perp)
var tt = t
tt.pos = p
if inBounds(sc, p) and not overlapsAny(sc, tt): return (true, p)
(false, t.pos)
proc setDoor*(sc: var Scene, id: int, open: bool, pushed: var seq[Push]): bool =
## false if `id` is not a door. Closing pushes overlapped tokens aside (appended to `pushed`; those with no valid
## spot become `blocked`); opening clears `blocked` per the Clear rule.
if id < 0 or id >= sc.walls.len or not sc.walls[id].door: return false
if sc.walls[id].open == open: return true
if open:
let closed = sc.walls[id] # it blocked until now
sc.walls[id].open = true
applyRemoved(sc, closed)
else:
sc.walls[id].open = false
let w = sc.walls[id]
for i in 0 ..< sc.tokens.len:
if not overlaps(sc, sc.tokens[i], w): continue
let (ok, p) = pushFrom(sc, sc.tokens[i], w)
if ok:
sc.tokens[i].prev = sc.tokens[i].pos; sc.tokens[i].hasPrev = true
sc.tokens[i].pos = p
sc.tokens[i].blocked = false
pushed.add Push(ti: i, pos: p)
else: sc.tokens[i].blocked = true
true
proc setDoor*(sc: var Scene, id: int, open: bool): bool =
var ignored: seq[Push]
setDoor(sc, id, open, ignored)