Files
FFF_vtt_frozen/server/markers.nim
T
SirStone c3c0a39188 feat(walls): marker retraction, re-earn and marker fault classes (#60)
Retract a player marker when the GM removes the wall, clears
player_marker, makes the wall stop deriving window, or moves its
geometry (a/b, thickness, position). Retraction emits del only and
never the new anchor; a re-earned marker gets a fresh id. The
marker_seen deletes ride the same derived-memory NORMAL transaction as
the explored chunks, after the wall row commits and before the ack.

Replace the leak checker's aggregate MARKER class with MARKER_EARLY,
MARKER_EXTRA and MARKER_OFF, add their leakfault hooks and exact-class
fault tests, and extend the leak scenario with an unseen marked window
and a marked solid wall as the negative controls. WS black-box tests
cover all four causes, fresh re-earns, no untouched re-send, no
set/del for one id in a frame, no explored write from a retraction,
and delete/cascade durability across a restart.
2026-11-19 23:43:44 +01:00

165 lines
8.6 KiB
Nim

## Player marker emission, retraction and persistence (DESIGN 5.8, 6.1, 6.3, 8; ADR-0015, #59/#60).
##
## A marker exists for a player exactly when a wall is both `player_marker:true` and derives
## `window`, and any point of the wall's visible extent has been inside one of that player's vision
## polygons. In this round the visible extent is the drawn segment (thickness is inert, 5.10), so the
## test is: an endpoint inside the polygon, or the segment crossing one of its edges. The gate is the
## player's own polygon, the same one that decides token visibility (5.1), so nothing behind a
## sight-blocking wall qualifies and the check never needs a second vision implementation.
##
## The marker is per-player memory like explored: it is minted once, gets that player's own opaque
## 12-character id (never the wall id), keeps the wall's drawn midpoint rounded once as its anchor,
## and is persisted in `marker_seen` as part of the same derived-memory transaction as the explored
## chunks (4.2 step 6). `vision.PlayerVision.markers` holds it in memory and `restore` loads it at
## startup, before the first connection (4.4).
##
## Lifetime (5.8, #60): walking away, a door and lost sight never retract a marker. The GM's causes
## do: removing the wall, clearing `player_marker`, making the wall stop deriving `window`, or
## moving its geometry (`a`/`b`, `thickness`, `position`). Every cause reduces to "the wall is gone
## or its marker signature changed", so `syncMarkers` retracts those markers and then mints anew for
## whatever qualifies now. A retraction is a `del` id only (never the new anchor), and a re-earned
## marker always gets a fresh id because the old one died. A moved wall therefore cannot reveal its
## new position early: the new geometry qualifies only through the normal extent gate on a refresh
## whose polygon contains it.
##
## No DB transaction control here: the caller owns it, exactly like explored.nim.
import std/[math, options, strutils, tables]
import db_connector/db_sqlite
import faults, geometry, tokens, vision, world
proc anchorOf*(w: WallRec): (int, int) =
## The wall's drawn midpoint, rounded once to integer px and fixed for the wall (5.8, 6.1).
(int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0)))
proc wallSig(w: WallRec): string =
## Everything whose change retracts a marker (5.8, #60): endpoints, thickness, placement, the
## `player_marker` switch and the derived `window` gate. Height and label have no marker
## consequence and are deliberately absent.
$w.a.x & "," & $w.a.y & "," & $w.b.x & "," & $w.b.y & "," &
$w.thickness & "," & $w.position & "," & $w.playerMarker & "," & derivedKind(w)
proc extentSeen*(pv: PlayerVision, a, b: Vec): bool =
## True when any point of the wall's visible extent (the segment in this round) is inside one of
## the player's polygons: an endpoint inside, or the segment crossing a polygon edge. Boundary
## contacts are inclusive, which is the generous side of "any point" and cannot admit anything
## behind a sight blocker (the polygon itself stops there).
for poly in pv.polys:
if poly.pts.len < 3: continue
if inside(poly.pts, a) or inside(poly.pts, b): return true
for i in 0 ..< poly.pts.len:
if segsCross(a, b, poly.pts[i], poly.pts[(i + 1) mod poly.pts.len]): return true
proc qualifies*(pv: PlayerVision, w: WallRec): bool =
## The complete emission gate of 5.8: the switch on, the derived shape label a window, and part of
## the visible extent seen. A solid wall with `player_marker:true` fails the kind gate.
var kindOk = derivedKind(w) == "window"
var seen = pv.extentSeen(w.a, w.b)
when defined(leakfault):
# Negative controls (TESTING 10.3, #60): MARKER_EARLY drops the visible-extent gate, so a
# marker is sent before the player has seen the window; MARKER_EXTRA drops the derived-window
# gate, so any wall with the switch on (a solid wall included) emits one.
if faultActive("markerEarly"): seen = true
if faultActive("markerExtra"): kindOk = true
w.playerMarker and kindOk and seen
proc markerIdTaken(pv: PlayerVision, id: string): bool =
for marker in pv.markers.values:
if marker.id == id: return true
# A re-earned marker in the same refresh must not reuse an id that is being retracted: one frame
# may carry `set` and `del`, but never for the same id (5.8, 6.1).
for dead in pv.markerDead:
if dead == id: return true
proc freshMarkerId(pv: PlayerVision): string =
result = newTokenId()
var tries = 0
while markerIdTaken(pv, result) and tries < 64:
result = newTokenId()
inc tries
proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int =
## Reconciles one player's marker memory with the current scene (DESIGN 5.8, #60): retract every
## marker whose wall is gone or whose cause changed, then mint one for every wall that now
## qualifies and is not in memory. Returns how many were minted.
##
## Retraction is first, so a moved wall gives up its old id even when the new geometry is already
## in sight; the mint below is still the ordinary extent gate, never a "the wall moved" shortcut.
## `markerDead` feeds the same derived-memory transaction as `markerFresh` (4.2 step 6).
var retract: seq[int]
for wallId in pv.markers.keys:
let wall = sc.wallById(wallId)
if wall.isNone or pv.markers[wallId].sig != wallSig(wall.get):
retract.add wallId
for wallId in retract:
pv.markerDead.add pv.markers[wallId].id
pv.markers.del wallId
when defined(leakfault):
# MARKER_OFF: the player-facing computation never mints a marker (retraction still runs).
if faultActive("markerOff"): return 0
for w in sc.walls:
if w.id in pv.markers: continue
if not pv.qualifies(w): continue
let (x, y) = anchorOf(w)
let marker = Marker(id: freshMarkerId(pv), x: x, y: y, sig: wallSig(w))
pv.markers[w.id] = marker
pv.markerFresh.add (w.id, marker)
inc result
# ---------------------------------------------------------------------------------------------------
# Persistence (marker_seen, migration step 8; the caller owns the transaction)
const InsertSql = """INSERT INTO marker_seen (player_id, scene_id, wall_id, marker_id)
VALUES (?, ?, ?, ?)"""
const DeleteSql = """DELETE FROM marker_seen WHERE player_id = ? AND marker_id = ?"""
proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)]): int =
## Inserts the markers the last refresh minted for one player and clears the buffer. Called inside
## the mutation's transaction, after the wall row (for a wall write) committed and before the ack:
## a marker can never precede the wall that causes it (5.8, 4.2 step 6).
if fresh.len == 0: return 0
let ps = db.prepare(InsertSql)
try:
for (wallId, marker) in fresh:
db.exec(ps, playerId, sceneId, wallId, marker.id)
inc result
finally:
finalize(ps)
fresh.setLen(0)
proc writeDead*(db: DbConn, playerId: int, dead: var seq[string]): int =
## Deletes the markers the last refresh retracted for one player and clears the buffer. Same
## transaction and ordering rule as `writeNew` (5.8, 4.2 step 6): derived player memory rides the
## mutation's `NORMAL` transaction, after the wall row commits and before the ack, so a
## retraction's `del` can never precede the wall change it reports. A wall removal already took
## its rows through the composite FK cascade, so that delete is a no-op here (and still correct).
if dead.len == 0: return 0
let ps = db.prepare(DeleteSql)
try:
for id in dead:
db.exec(ps, playerId, id)
inc result
finally:
finalize(ps)
dead.setLen(0)
proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) =
## Startup (4.4): every `marker_seen` row back into its player's memory, before the first
## connection, with the anchor recomputed from the loaded wall (the anchor is derived, not stored)
## and the marker signature taken from the wall as loaded. A row whose wall is missing cannot
## exist (the composite FK cascades); skipping one defensively keeps a hand-edited DB from
## crashing startup.
for row in db.getAllRows(sql"""
SELECT player_id, wall_id, marker_id FROM marker_seen WHERE scene_id = ?""", sc.id):
let pid = parseInt(row[0])
let wallId = parseInt(row[1])
let wall = sc.wallById(wallId)
if wall.isNone: continue
let (x, y) = anchorOf(wall.get)
visions.mgetOrPut(pid, PlayerVision()).markers[wallId] =
Marker(id: row[2], x: x, y: y, sig: wallSig(wall.get))
proc markerCount*(db: DbConn, sceneId: int): int =
## Scene-wide marker rows: an O(1) startup log number (11.3) and a test probe.
parseInt(db.getValue(sql"SELECT count(*) FROM marker_seen WHERE scene_id = ?", sceneId))