Files
FFF_vtt_frozen/server/vision.nim
T
SirStone 30b35592c7 fix: forward -- args through devbox scripts, fail serve loudly (#84)
devbox 0.17.2 runs .devbox/gen/scripts/<name>.sh with the args as positional
parameters but does not append "$@", so tools/serve.sh (and seed, bench,
mutation, import-scale, fogbench) saw an empty argv and a documented
`serve -- --image=...` silently served the default 4096 scene. End every
argument-taking script body with "$@".

serve: --dry-run parses and prints the options without building; unknown
options, non-numeric ports/tile sizes and --tile-size without --image fail
loudly; a no-image start prints the current map read from state.db; NixOS
gets security.pki.certificateFiles instead of the Debian trust steps.

Guard the faults import in worldmap/vision/markers with
`when defined(leakfault)` (it is only used inside those blocks), removing
the three UnusedImport warnings; leakfault builds still compile.

tools/devboxargs.test.mjs goes through `devbox run <script> -- <args>` for
serve (dry-run, unknown flag, tile-size without image) and seed (--help,
unknown flag), the seam the direct-tool tests missed.
2026-11-21 21:35:39 +01:00

134 lines
6.8 KiB
Nim

## Per-player vision and explored state (DESIGN 3.1, 4.1, 4.2, 5.1, 8; M3 slice 5, issue #20).
## Pure and in-process: no IO, no clock, no wire shapes. main.nim holds one `PlayerVision` per player
## id and calls `refresh` after every mutation that can change that player's sight.
##
## Vision (5.1): one visibility polygon per token the player controls that carries the `vision` flag,
## cast from the token centre against the scene's blocking walls with the token's range (Q7: the
## token's `vision_radius` if it sets one, else the scene's `vision_radius_default`). Open doors do
## not block; geometry.nim does the casting. A sight-blocking one-way wall blocks only a viewer on
## its blind side (the side `sight_dir` names), one sign test inline after the radius cull (#58).
##
## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly
## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells`
## are `(cx, cy)` from the world origin, cell size = the scene's `cell` (= `tile_size` in v1, Q4).
## Persistence (chunked bitmaps, #21) lives in server/explored.nim, which stores this module's
## `explored` set and restores it at startup; this module owns the in-memory set only.
##
## Token visibility to a player (3.1): a token this player controls is always visible; any other
## token only while its centre is inside one of the player's polygons and it is not `gm_only`.
## `Poly` ids are token ids, which the controlling player already knows (`mine`).
##
## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4)
## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress).
##
## Player markers (DESIGN 5.8, ADR-0015, #59/#60) are per-player memory like explored: `markers`
## maps a wall id to that player's own opaque marker id, its fixed anchor (integer px) and the
## wall-cause signature it was minted for. A marker is retracted when the wall goes, the switch is
## cleared, the wall stops deriving `window`, or its geometry (`a`/`b`, `thickness`, `position`)
## moves; a re-earn gets a fresh id. `markerFresh`/`markerDead` hold the markers minted/retracted by
## the current refresh so the mutation's transaction can persist them (server/markers.nim).
import std/[algorithm, math, sets, tables]
import tokens, worldmap, geometry, world
when defined(leakfault):
import faults # faultActive() is only referenced inside the leakfault block below (#84)
type
Poly* = object
tokenId*: string
pts*: seq[Vec]
Marker* = object
## One player's marker memory for one wall (DESIGN 5.8, 6.1). The id is opaque and per player;
## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated. `sig`
## is the retraction-relevant wall state (geometry, switch, derived kind) the marker was earned
## for: a different signature at the next refresh means the cause changed and the marker dies.
## It is compared field by field, never as a formatted string.
id*: string
x*, y*: int
sig*: MarkerSig
PlayerVision* = object
polys*: seq[Poly]
explored*: HashSet[int] ## cell index cy * cols + cx
ver*: int ## bumped when `polys` changes
fresh*: seq[(int, int)] ## cells added by the current mutation (cx, cy), sorted
markers*: Table[int, Marker] ## wall id -> this player's marker (5.8, #59)
markerFresh*: seq[(int, Marker)] ## markers minted by the last refresh, awaiting the DB write
markerDead*: seq[string] ## marker ids retracted by the last refresh, awaiting the DB delete
proc cols*(sc: SceneRec): int =
## Cells across the scene (DESIGN 8: ceil(w / cell)).
max(1, int(ceil(sc.w / float(sc.cell))))
proc rows*(sc: SceneRec): int =
max(1, int(ceil(sc.h / float(sc.cell))))
proc cellIndex*(sc: SceneRec, cx, cy: int): int = cy * sc.cols + cx
proc cellOf*(sc: SceneRec, idx: int): (int, int) =
let c = sc.cols
(idx mod c, idx div c)
proc computePolys*(sc: SceneRec, tokens: seq[TokenRec], playerId: int): seq[Poly] =
## One polygon per token of this player that has vision, in token order (a stable wire order).
## The wall list is hoisted and viewer-independent: the one-way filter is inline in the ray fan
## (geometry.visibilityPolygon), one sign test per one-way wall per viewer (5.8, #58).
if playerId <= 0: return
var walls = geometryWalls(sc, forSight = true)
when defined(leakfault):
# Negative control (DESIGN 10.3, TESTING 10.3): the ONEWAY fault drops `sight_dir` from the
# player-facing computation, so a sight-blocking one-way wall blocks both sides.
if faultActive("oneWay"):
for w in walls.mitems: w.sightDir = wdBoth
for t in tokens:
if t.owner != playerId or not t.hasVision: continue
result.add Poly(tokenId: t.id,
pts: visibilityPolygon(t.pos, walls, visionRange(sc, t)))
proc refresh*(pv: var PlayerVision, sc: SceneRec, tokens: seq[TokenRec], playerId: int) =
## Recomputes the polygons, bumps `ver` when they changed, and folds every newly seen cell into
## `explored`/`fresh`. Cells already explored are never re-announced.
let polys = computePolys(sc, tokens, playerId)
if polys != pv.polys:
pv.polys = polys
inc pv.ver
var added = initHashSet[int]()
for poly in pv.polys:
for (cx, cy) in cellsTouched(poly.pts, float(sc.cell)):
if cx < 0 or cy < 0 or cx >= sc.cols or cy >= sc.rows: continue
let idx = sc.cellIndex(cx, cy)
if idx in pv.explored or idx in added: continue
added.incl idx
pv.fresh.add (cx, cy)
for idx in added: pv.explored.incl idx
pv.fresh.sort()
proc clearFresh*(pv: var PlayerVision) =
## 4.2 step 8: after the egress fan-out every connection has the cells. `markerFresh` and
## `markerDead` are cleared by their own write (markers.writeNew/writeDead), which ran before the
## egress under the same lock.
pv.fresh.setLen(0)
proc exploredFull*(pv: PlayerVision, sc: SceneRec): seq[(int, int)] =
## Every explored cell, sorted by (cy, cx): the connect/resync payload (6.1 `explored full`).
var idx = newSeq[int](pv.explored.len)
var i = 0
for k in pv.explored:
idx[i] = k
inc i
idx.sort()
result = newSeqOfCap[(int, int)](idx.len)
for k in idx: result.add sc.cellOf(k)
proc insideAny*(pv: PlayerVision, p: Vec): bool =
for poly in pv.polys:
if inside(poly.pts, p): return true
proc visibleTo*(pv: PlayerVision, t: TokenRec, playerId: int): bool =
## DESIGN 3.1: controlled tokens always, anything else only inside own LOS and not `gm_only`.
## This is the only copy of the rule: the leak-fault builds add tokens that this returns false for
## instead of re-implementing it, so a mutation here still breaks the clean path (DESIGN 10.3).
if t.owner == playerId: return true
if t.gmOnly: return false
pv.insideAny(t.pos)