Files
FFF_vtt_frozen/server/views.nim
T
SirStone 5f5bf3293b server: typed recipient views and the single egress (#20)
server/views.nim is the only place where world state becomes bytes: a Recipient
builds a GmTokenView or a PlayerTokenView first, and only then a frame. Player
frames carry the public props bucket (plus owner for the controller), the
controller's vision_radius, and never kind, controller, gm_only, flags, radius_own
or either raw name; the GM gets all of it plus both names. The per-connection Known
table diffs on the built frame, so token/token_gone are exactly the changes and the
vision frame is re-sent only when the polygons move.

server/faults.nim compiles the negative-control hook only with -d:leakfault; the
shipped binary contains no LEAK_FAULT string and tools/fault.test.mjs asserts it.

hello gains the scene block (and extra for the GM); the protocol's implemented set
now names the four token intents.
2026-11-15 09:35:14 +01:00

277 lines
12 KiB
Nim

## The egress module: the one place where authoritative world state becomes bytes for a recipient
## (DESIGN 2 single egress rule, 3.1, 6.1, 6.3, 6.4; M3 slice 5, issue #20).
##
## A recipient is either the GM or one player, and the module builds a *typed* view for that
## recipient first (`GmView`, `PlayerView`) and only then turns it into frames. Raw world state never
## becomes JSON anywhere else: `main.nim` does not build a `token`, `token_gone`, `vision` or
## `explored` frame, and the record it holds (`TokenRec`) has no serializer.
##
## Rules encoded here (3.1):
## - GM: every token, all buckets, `statuses[].source`, controller/gm_only/flags/vision_radius and
## both names. No `vision`, no `explored` ever.
## - player: tokens they control (always) plus tokens inside their LOS that are not `gm_only`;
## `props` carries only the buckets they may read (public, plus owner for the controller);
## `vision_radius` only for the controller (it is the step cap, 5.5); `source` never.
## - a token's `name` is the descriptive name in this slice: the reveal machinery is slice 8 (#23),
## so no actual name has an egress path to a player at all.
##
## `Known` is the per-connection diff table (4.1/6.4): it holds the last frame sent for each token, so
## `token_gone` is sent only for a token this recipient did see, never for one it never knew. The
## comparison is on the built frame, so a coalesced state (M5) cannot desynchronise a client.
import std/[algorithm, json, math, options, sequtils, sets, tables]
import geometry, tokens, vision, world
import faults
type
Recipient* = object
isGm*: bool
playerId*: int
GmTokenView* = object
id*: string
scene*: int
name*: string
pos*: Vec
radius*: float
kind*: string
controller*: int
gmOnly*: bool
flags*: JsonNode
visionRadius*: Option[float]
radiusOwn*: Option[float]
descriptiveName*, actualName*: string
PlayerTokenView* = object
id*: string
scene*: int
name*: string
pos*: Vec
radius*: float
mine*: bool
includeVisionRadius*: bool
visionRadius*: Option[float]
GmView* = object
tokens*: seq[GmTokenView]
PlayerView* = object
tokens*: seq[PlayerTokenView]
polys*: seq[Poly]
fresh*: seq[(int, int)]
Context* = object
## Everything the egress needs, and nothing it may modify: the world plus every player's runtime
## sight state (read-only; the other players' entries are only reachable by a fault build).
scene*: SceneRec
tokens*: seq[TokenRec]
visions*: Table[int, PlayerVision]
Known* = object
## Per connection: what this recipient already has (4.1 `known`).
tokens*: Table[string, JsonNode]
vision*: string ## the last `vision` payload sent, "" = never
visionSent*: bool
# ---------------------------------------------------------------------------------------------------
# Typed views
proc gmView*(ctx: Context): GmView =
result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len)
for t in ctx.tokens:
result.tokens.add GmTokenView(id: t.id, scene: t.scene,
name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
kind: t.kind, controller: t.owner, gmOnly: t.gmOnly,
flags: t.flags, visionRadius: t.visionRadius,
radiusOwn: t.radius,
descriptiveName: t.descriptiveName,
actualName: t.actualName)
proc playerView*(ctx: Context, playerId: int): PlayerView =
var pv = ctx.visions.getOrDefault(playerId)
for t in ctx.tokens:
if not pv.visibleTo(t, playerId): continue
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene,
name: t.descriptiveName, pos: t.pos,
radius: effectiveRadius(ctx.scene, t),
mine: t.owner == playerId,
includeVisionRadius: t.owner == playerId,
visionRadius: t.visionRadius)
when defined(leakfault):
# Negative controls (DESIGN 10.3): add the tokens the honest rule just refused, so the harness
# proves it would notice. Never a second copy of the visibility rule.
if faultActive("hidden"):
for t in ctx.tokens:
if t.owner != playerId and not t.gmOnly and not pv.insideAny(t.pos):
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene, name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
mine: false, includeVisionRadius: false,
visionRadius: t.visionRadius)
if faultActive("gmOnly"):
for t in ctx.tokens:
if t.gmOnly and t.owner != playerId and pv.insideAny(t.pos):
result.tokens.add PlayerTokenView(id: t.id, scene: t.scene, name: t.descriptiveName,
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
mine: false, includeVisionRadius: false,
visionRadius: t.visionRadius)
if faultActive("withhold") and result.tokens.len > 1:
for i in countdown(result.tokens.high, 0):
if not result.tokens[i].mine:
result.tokens.delete i
break
if faultActive("otherOwner"):
for t in result.tokens.mitems:
if not t.mine: t.mine = true; break
result.polys = pv.polys
result.fresh = pv.fresh
# ---------------------------------------------------------------------------------------------------
# Frames. These builders are the only producers of state frames in the server.
proc gmTokenFrame*(v: GmTokenView): JsonNode =
result = %*{
"t": "token", "id": v.id, "scene": v.scene, "name": v.name,
"pos": [v.pos.x, v.pos.y], "radius": v.radius, "mine": false,
"statuses": [], "props": {"public": newJObject(), "owner": newJObject(), "gm": newJObject()},
"kind": v.kind, "controller": (if v.controller == GmControlled: newJNull() else: %v.controller),
"gm_only": v.gmOnly, "flags": v.flags,
"vision_radius": (if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()),
"radius_own": (if v.radiusOwn.isSome: %v.radiusOwn.get else: newJNull()),
"descriptive_name": v.descriptiveName, "actual_name": v.actualName
}
proc playerTokenFrame*(v: PlayerTokenView): JsonNode =
## One token as a player may see it. `statuses` carries no `source` (3.1: the cause is GM-only);
## `props` carries the `public` bucket, plus `owner` for the controller (6.1).
var props = newJObject()
props["public"] = newJObject()
if v.mine: props["owner"] = newJObject()
result = %*{
"t": "token", "id": v.id, "scene": v.scene, "name": v.name,
"pos": [v.pos.x, v.pos.y], "radius": v.radius, "mine": v.mine,
"statuses": [], "props": props
}
if v.includeVisionRadius:
result["vision_radius"] = if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()
proc tokenGoneFrame*(id: string): JsonNode = %*{"t": "token_gone", "id": id}
proc visionPolyJson(polys: seq[Poly]): JsonNode =
## Integer px (DESIGN 6.4 FIXED Q16): halves the payload size; 0.5 px is the documented tolerance.
result = newJArray()
for p in polys:
var pts = newJArray()
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
result.add %*{"id": p.tokenId, "pts": pts}
proc visionFrame*(polys: seq[Poly]): JsonNode =
%*{"t": "vision", "polys": visionPolyJson(polys)}
proc exploredFullFrame*(cells: seq[(int, int)]): JsonNode =
## RLE rows: `[[cy, x0, len, x0, len, ...], ...]` (DESIGN 6.1, format PROPOSED accepted here).
var rows: seq[tuple[cy: int, runs: JsonNode]]
var i = 0
while i < cells.len:
let cy = cells[i][1]
var runs = newJArray()
var j = i
while j < cells.len and cells[j][1] == cy:
let start = cells[j][0]
var last = start
while j + 1 < cells.len and cells[j + 1][1] == cy and cells[j + 1][0] == last + 1:
inc j
last = cells[j][0]
runs.add %start
runs.add %(last - start + 1)
inc j
rows.add (cy: cy, runs: runs)
i = j
var rle = newJArray()
for row in rows:
var entry = newJArray()
entry.add %row.cy
for v in row.runs: entry.add v
rle.add entry
%*{"t": "explored", "full": true, "rle": rle}
proc exploredFreshFrame*(cells: seq[(int, int)]): JsonNode =
var list = newJArray()
for (cx, cy) in cells: list.add %*[cx, cy]
%*{"t": "explored", "full": false, "cells": list}
proc sceneBlock*(sc: SceneRec): JsonNode =
## The `scene` object inside `hello` (DESIGN 6.1, 3.1: no counts, no wall data, no owned ids).
%*{"id": sc.id, "name": sc.name, "w": sc.w, "h": sc.h, "tile_size": sc.tileSize,
"cell": sc.cell, "grid_size": sc.gridSize,
"vision_radius_default": sc.visionRadiusDefault,
"token_radius_default": sc.tokenRadiusDefault, "art_version": sc.artVersion}
# ---------------------------------------------------------------------------------------------------
# Egress: the frames one recipient needs after a mutation (or a full resync)
proc otherPlayerId(ctx: Context, me: int): int =
## A deterministic "somebody else" for the negative controls: the smallest other player id.
result = 0
for id in ctx.visions.keys:
if id != me and (result == 0 or id < result): result = id
proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false): seq[JsonNode] =
## Ordered like the 6.3 resync sequence: vision, explored, then the tokens. Empty = nothing changed
## for this recipient, which is what keeps hidden mutations invisible (T11).
if r.isGm:
let view = gmView(ctx)
var seen = initHashSet[string]()
for v in view.tokens:
seen.incl v.id
let frame = gmTokenFrame(v)
if known.tokens.getOrDefault(v.id) != frame:
known.tokens[v.id] = frame
result.add frame
for id in known.tokens.keys.toSeq:
if id notin seen:
known.tokens.del id
result.add tokenGoneFrame(id)
return
let view = playerView(ctx, r.playerId)
var polysJson = visionPolyJson(view.polys)
when defined(leakfault):
if faultActive("otherVision"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
for p in other.polys:
var pts = newJArray()
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
polysJson.add %*{"id": p.tokenId, "pts": pts}
if resync or not known.visionSent or $polysJson != known.vision:
known.vision = $polysJson
known.visionSent = true
result.add %*{"t": "vision", "polys": polysJson}
if resync:
result.add exploredFullFrame(ctx.visions.getOrDefault(r.playerId).exploredFull(ctx.scene))
elif view.fresh.len > 0:
var fresh = view.fresh
when defined(leakfault):
if faultActive("explored"):
fresh.add (ctx.scene.cols - 1, ctx.scene.rows - 1)
if faultActive("otherExplored"):
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
fresh.add other.exploredFull(ctx.scene)
result.add exploredFreshFrame(fresh)
var seen = initHashSet[string]()
for v in view.tokens:
seen.incl v.id
let frame = playerTokenFrame(v)
if known.tokens.getOrDefault(v.id) != frame:
known.tokens[v.id] = frame
result.add frame
var gone: seq[string]
for id in known.tokens.keys:
if id notin seen: gone.add id
gone.sort()
for id in gone:
known.tokens.del id
if not faultActive("noremove"):
result.add tokenGoneFrame(id)