Files
FFF_vtt_frozen/server/views.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

698 lines
33 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 slices 5, 7 and 8: issues #20, #22, #23).
##
## 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`,
## `explored`, `character`, `character_gone` or `encountered` frame, and the records it holds
## (`TokenRec`, `CharacterRec`, `EncounteredEntry`) have no serializer.
##
## Rules encoded here (3.1):
## - GM: every token and every character, all buckets, `statuses[].source`, controller/gm_only/
## flags/vision_radius, both names, `reveal_all` and who a name was revealed to; one encountered
## list per player. 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);
## `statuses` carries the status names only, never `source` (6.1 leak notes 5-6); `vision_radius`
## only for the controller (it is the step cap, 5.5); the characters they own and nothing else
## (no browsable list, T16); their own encountered list and nothing else.
## - names: the one name a recipient sees comes from characters.subjectNamesOf + nameFor. A player
## sees the descriptive name until the GM reveals the actual one to them, or they own the
## character, or `reveal_all` is set (8). There is no other copy of that rule, and the raw name
## pair only ever travels to the GM.
## - character props: `owner` bucket to the character's owner; other players who see a token of the
## character get `cprops` with the `public` bucket only, always present so its presence does not
## mark a token as character-linked (6.1 leak note 3).
##
## The bucket filter is applied when the *typed view* is built, not when the frame is serialised: a
## `PlayerTokenView` has no field for the `gm` bucket at all, so no later change to the frame builder
## can leak one. `statuses` for a player are `StatusKind` values, not `(kind, source)` entries, for
## the same reason, and `PlayerCharacterView` has no `reveal_all`/`revealed`/`owner` fields.
##
## `Known` is the per-connection diff table (4.1/6.4): it holds the last frame sent for each token,
## character and encountered entry, so `token_gone`/`character_gone` are sent only for something this
## recipient did see. The comparison is on the built frame, so a coalesced state (M5) cannot
## desynchronise a client.
import std/[algorithm, json, math, options, sequtils, sets, strutils, tables]
import characters, geometry, props, 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]
characterId*: Option[string]
descriptiveName*, actualName*: string ## "" for a linked token: the character has the names
revealAll*: bool ## plain tokens only
revealed*: seq[int] ## plain tokens only: who was told the actual name
statuses*: seq[StatusEntry] ## every entry, source included (GM only, 6.1)
props*: Props ## all three buckets, never nil
PlayerTokenView* = object
id*: string
scene*: int
name*: string
pos*: Vec
radius*: float
mine*: bool
includeVisionRadius*: bool
visionRadius*: Option[float]
characterId*: Option[string] ## only for a player who owns the character (6.1 leak note 2)
statuses*: seq[StatusKind] ## status names only: the cause is GM-only (5.5, 6.1 note 6)
propsPublic*: JsonNode ## the `public` bucket; never nil
propsOwner*: JsonNode ## the `owner` bucket, only for the controller (nil otherwise)
cpropsPublic*: JsonNode ## the character's `public` bucket; never nil, `{}` when none
when defined(leakfault):
# Negative controls only (DESIGN 10.3): the shipped build has neither the fields nor the
# branches that would emit them, so a production binary is incapable of these two leaks.
faultGmProps*: JsonNode ## the `gm` bucket, when the `gmProp` fault is active
faultStatusEntries*: seq[StatusEntry] ## statuses with `source`, for the `statusSource` fault
GmCharacterView* = object
id*: string
owner*: int
descriptiveName*, actualName*: string
revealAll*: bool
revealed*: seq[int]
props*: Props
PlayerCharacterView* = object
## A character as its owner may see it: no `owner` (theirs), never `reveal_all`/`revealed`
## (they already know, and the list would name other players), and no `gm` bucket.
id*: string
descriptiveName*, actualName*: string
propsPublic*: JsonNode
propsOwner*: JsonNode
EncounteredView* = object
## One entry as one player may see it: the token id and the name that player knows. No position,
## no `character_id`, no other player's list (6.1 leak notes).
id*: string
name*: string
grey*: bool
MarkerView* = object
## One player marker (DESIGN 5.8, 6.1): the player's own opaque id and the wall's drawn midpoint
## in integer px. There is deliberately no wall id, kind, state, label or switch here.
id*: string
x*, y*: int
GmEncounteredView* = object
player*: int
entries*: seq[EncounteredView]
GmView* = object
tokens*: seq[GmTokenView]
characters*: seq[GmCharacterView]
encountered*: seq[GmEncounteredView]
PlayerView* = object
tokens*: seq[PlayerTokenView]
characters*: seq[PlayerCharacterView]
encountered*: seq[EncounteredView]
markers*: seq[MarkerView]
polys*: seq[Poly]
fresh*: seq[(int, int)]
Context* = object
## A read-only *borrow* of the world and every player's runtime sight state (DESIGN 4.2/4.3;
## #28). Every field is a pointer, so building a Context copies nothing: no `PlayerVision`, no
## explored `HashSet`, no `Table`, however large the explored sets grew. `main.egressContext`
## points it at the App's fields (stable for the process lifetime) while it holds the global
## lock, so the whole egress pass reads one consistent state.
##
## The templates below keep the field syntax (`ctx.tokens`, `ctx.visions[pid]`) at every use
## site; a settable template target also keeps `ctx.visions[pid].explored` an lvalue.
pScene*: ptr SceneRec
pTokens*: ptr seq[TokenRec]
pCharacters*: ptr seq[CharacterRec]
pReveals*: ptr Reveals
pEncountered*: ptr Encountered
pVisions*: ptr Table[int, PlayerVision]
ContextStore* = object
## Owning storage with the same six fields, for tests and fixtures (`borrow` hands out a
## Context over it). The server never uses it: `App` owns the world and hands out pointers.
scene*: SceneRec
tokens*: seq[TokenRec]
characters*: seq[CharacterRec]
reveals*: Reveals
encountered*: Encountered
visions*: Table[int, PlayerVision]
Known* = object
## Per connection: what this recipient already has (4.1 `known`).
tokens*: Table[string, JsonNode]
characters*: Table[string, JsonNode]
encountered*: Table[string, JsonNode] ## GM: "<player>/<token>"; player: "<token>"
markers*: Table[string, JsonNode] ## player: marker id -> the `{id,pos}` entry sent
vision*: string ## the last `vision` payload sent, "" = never
visionSent*: bool
template scene*(ctx: Context): untyped = ctx.pScene[]
template tokens*(ctx: Context): untyped = ctx.pTokens[]
template characters*(ctx: Context): untyped = ctx.pCharacters[]
template reveals*(ctx: Context): untyped = ctx.pReveals[]
template encountered*(ctx: Context): untyped = ctx.pEncountered[]
template visions*(ctx: Context): untyped = ctx.pVisions[]
proc contextOf*(scene: var SceneRec, tokens: var seq[TokenRec],
characters: var seq[CharacterRec], reveals: var Reveals,
encountered: var Encountered,
visions: var Table[int, PlayerVision]): Context =
## Six addresses, not six copies: this is the whole cost of building an egress context (#28).
Context(pScene: addr scene, pTokens: addr tokens, pCharacters: addr characters,
pReveals: addr reveals, pEncountered: addr encountered, pVisions: addr visions)
proc borrow*(store: ref ContextStore): Context =
## The test/fixture entry point: a heap store outlives the Context that points into it.
contextOf(store.scene, store.tokens, store.characters, store.reveals, store.encountered,
store.visions)
proc visionAt(ctx: Context, playerId: int, fallback: var PlayerVision): ptr PlayerVision =
## One player's live sight state, borrowed: never a `getOrDefault` copy (#28). A player with no
## sight state (never connected) gets `fallback`, an empty record the caller owns, so no GC'd
## global is read from a `{.gcsafe.}` handler.
if ctx.visions.hasKey(playerId): addr ctx.visions[playerId]
else: addr fallback
proc visibleIds(ctx: Context, playerId: int, pv: ptr PlayerVision): HashSet[string] =
## The visibility rule once per recipient per frame: every encountered entry's `grey` is then a
## set test, not a token scan plus a polygon test per entry (#28).
for t in ctx.tokens:
if pv[].visibleTo(t, playerId): result.incl t.id
# ---------------------------------------------------------------------------------------------------
# Typed views
proc objectOf(node: JsonNode): JsonNode =
## A bucket as a JSON object, never nil: a stored record always has three, but the typed view is
## also built in tests and a nil must not become a `null` in a frame.
if node.isNil or node.kind != JObject: newJObject() else: node
proc statusKinds(statuses: seq[StatusEntry]): seq[StatusKind] =
## The player-facing half of a token's status set: the names, in the stored order.
for e in statuses: result.add e.kind
proc characterOf(ctx: Context, t: TokenRec): Option[CharacterRec] =
## The character a token figures, if any (a dangling link cannot exist: the FK and `in-use`).
if t.characterId.isNone: return none(CharacterRec)
characterById(ctx.characters, t.characterId.get)
proc greyFor*(ctx: Context, playerId: int, entityId: string): bool =
## DESIGN 8 `encountered.grey`: the token is no longer in that player's view, whether because it
## moved away, was removed, or became `gm_only`. The entry stays either way. This is the
## single-entry form (tests, and a caller holding one id); a view builds `visibleIds` once instead
## of calling this per entry (#28).
let idx = tokenIndex(ctx.tokens, entityId)
if idx.isNone: return true
var fallback: PlayerVision
not visionAt(ctx, playerId, fallback)[].visibleTo(ctx.tokens[idx.get], playerId)
proc gmView*(ctx: Context): GmView =
result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len)
for t in ctx.tokens:
let ch = ctx.characterOf(t)
var view = GmTokenView(id: t.id, scene: t.scene,
name: (if ch.isSome: ch.get.descriptiveName else: 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, characterId: t.characterId,
statuses: t.statuses, props: t.props)
if ch.isNone:
# The names and the reveal state of a plain token; a linked token's live on its character.
view.descriptiveName = t.descriptiveName
view.actualName = t.actualName
view.revealAll = t.revealAll
view.revealed = ctx.reveals.revealedPlayers(t.id)
result.tokens.add view
for c in ctx.characters:
result.characters.add GmCharacterView(id: c.id, owner: c.owner,
descriptiveName: c.descriptiveName,
actualName: c.actualName, revealAll: c.revealAll,
revealed: ctx.reveals.revealedPlayers(c.id),
props: c.props)
# One list per player, only for players that have one (an empty list needs no frame on a diff, and
# a resync sends `full:true` even when empty).
var pids: seq[int]
for pid in ctx.encountered.keys: pids.add pid
pids.sort()
for pid in pids:
# #28: one visibility pass per player's list, then a set test per entry.
var fallback: PlayerVision
let visible = visibleIds(ctx, pid, visionAt(ctx, pid, fallback))
var entries: seq[EncounteredView]
for eid, e in ctx.encountered[pid]:
entries.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
result.encountered.add GmEncounteredView(player: pid, entries: entries)
proc playerView*(ctx: Context, playerId: int): PlayerView =
# A borrowed pointer, not `getOrDefault`: the explored set is never copied (#28).
var noSight: PlayerVision
let pv = visionAt(ctx, playerId, noSight)
for t in ctx.tokens:
if not pv[].visibleTo(t, playerId): continue
let mine = t.owner == playerId
let ch = ctx.characterOf(t)
let names = subjectNamesOf(t, ctx.characters)
# 6.1 leak note 2: `character_id` goes only to the GM and the character's owner.
let ownsCharacter = ch.isSome and ch.get.owner == playerId
result.tokens.add PlayerTokenView(
id: t.id, scene: t.scene,
name: names.nameFor(playerId, ctx.reveals), pos: t.pos,
radius: effectiveRadius(ctx.scene, t),
mine: mine,
includeVisionRadius: mine,
visionRadius: t.visionRadius,
characterId: (if ownsCharacter: t.characterId else: none(string)),
statuses: statusKinds(t.statuses),
propsPublic: objectOf(t.props[pbPublic]),
propsOwner: (if mine: objectOf(t.props[pbOwner]) else: nil),
# DESIGN 3.1: the character's public bucket to anyone who sees one of its tokens; `{}` for a
# plain token and for the owner (who reads it from the character record).
cpropsPublic: objectOf(if ch.isSome and not ownsCharacter: ch.get.props[pbPublic]
else: newJObject()))
for c in ctx.characters:
if c.owner != playerId: continue
result.characters.add PlayerCharacterView(id: c.id, descriptiveName: c.descriptiveName,
actualName: c.actualName,
propsPublic: objectOf(c.props[pbPublic]),
propsOwner: objectOf(c.props[pbOwner]))
if ctx.encountered.hasKey(playerId):
# #28: one visibility pass for the whole list.
let visible = visibleIds(ctx, playerId, pv)
for eid, e in ctx.encountered[playerId]:
result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
when defined(leakfault):
# Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves
# it would notice. Never a second copy of the visibility rule. # The two "add a token the honest rule refused" controls build the frame exactly as the honest
# path would, so the class they report stays the one they were built for (a bucket mismatch here
# would add an OWNER_PROP/CHAR_OWNER_PROP class and blunt the assertion).
proc leakedView(t: TokenRec): PlayerTokenView =
let ch = ctx.characterOf(t)
PlayerTokenView(id: t.id, scene: t.scene,
name: subjectNamesOf(t, ctx.characters).nameFor(playerId, ctx.reveals),
pos: t.pos, radius: effectiveRadius(ctx.scene, t),
mine: false, includeVisionRadius: false,
visionRadius: t.visionRadius,
statuses: statusKinds(t.statuses),
propsPublic: objectOf(t.props[pbPublic]),
propsOwner: nil,
cpropsPublic: objectOf(if ch.isSome: ch.get.props[pbPublic]
else: newJObject()))
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 leakedView(t)
if faultActive("gmOnly"):
for t in ctx.tokens:
if t.gmOnly and t.owner != playerId and pv[].insideAny(t.pos):
result.tokens.add leakedView(t)
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"):
# OTHER_PLAYER: somebody else's token presented as this player's own, owner bucket included so
# the fault stays one class (the checker reports the `mine` flag, not a bucket mismatch).
for t in result.tokens.mitems:
if not t.mine:
t.mine = true
for src in ctx.tokens:
if src.id == t.id: t.propsOwner = src.props[pbOwner]
break
if faultActive("ownerProp"):
# OWNER_PROP: the controller bucket reaches everyone.
for t in ctx.tokens:
if t.owner == playerId: continue
for v in result.tokens.mitems:
if v.id == t.id: v.propsOwner = t.props[pbOwner]
if faultActive("gmProp"):
# GM_PROP: the GM-only bucket reaches a player.
for t in ctx.tokens:
for v in result.tokens.mitems:
if v.id == t.id: v.faultGmProps = t.props[pbGm]
if faultActive("statusSource"):
# STATUS_SOURCE: a viewer learns what caused the lock (5.5, 6.1 note 6).
for t in ctx.tokens:
for v in result.tokens.mitems:
if v.id == t.id: v.faultStatusEntries = t.statuses
if faultActive("actualName"):
# ACTUAL_NAME: the unrevealed actual name reaches a player (8, 10.3).
for t in ctx.tokens:
let names = subjectNamesOf(t, ctx.characters)
for v in result.tokens.mitems:
if v.id == t.id and names.owner != playerId: v.name = names.actual
if faultActive("charList"):
# CHAR_LIST: another player's character is sent to this player.
for c in ctx.characters:
if c.owner == playerId: continue
result.characters.add PlayerCharacterView(id: c.id, descriptiveName: c.descriptiveName,
actualName: c.actualName,
propsPublic: objectOf(c.props[pbPublic]),
propsOwner: objectOf(c.props[pbOwner]))
break
if faultActive("charOwnerProp"):
# CHAR_OWNER_PROP: a character's owner bucket reaches a player who does not own it.
for t in ctx.tokens:
let ch = ctx.characterOf(t)
if ch.isNone or ch.get.owner == playerId: continue
for v in result.tokens.mitems:
if v.id == t.id: v.cpropsPublic = objectOf(ch.get.props[pbOwner])
result.markers = newSeqOfCap[MarkerView](pv[].markers.len)
for _, marker in pv[].markers.pairs:
result.markers.add MarkerView(id: marker.id, x: marker.x, y: marker.y)
# Deterministic order by the opaque id: the full set is compared byte-for-byte on resync, and the
# order must not reveal wall order or count (the ids are random, 5.8).
result.markers.sort(proc (a, b: MarkerView): int = cmp(a.id, b.id))
result.polys = pv[].polys
result.fresh = pv[].fresh
# ---------------------------------------------------------------------------------------------------
# Frames. These builders are the only producers of state frames in the server.
proc statusesJson(entries: seq[StatusEntry]): JsonNode =
## GM shape: `statuses:[{status, source}]` (6.1).
result = newJArray()
for e in entries: result.add %*{"status": $e.kind, "source": $e.source}
proc statusKindsJson(kinds: seq[StatusKind]): JsonNode =
## Player shape: `statuses:[{status}]`, never a `source` (5.5, 6.1 leak note 6).
result = newJArray()
for k in kinds: result.add %*{"status": $k}
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": statusesJson(v.statuses), "props": props.propsJson(v.props),
"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()),
"character_id": (if v.characterId.isSome: %v.characterId.get else: newJNull())
}
if v.characterId.isNone:
# A linked token's names and reveal state live on the character record (6.1).
result["descriptive_name"] = %v.descriptiveName
result["actual_name"] = %v.actualName
result["reveal_all"] = %v.revealAll
result["revealed"] = %*v.revealed
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). `playerView` fills
## `propsOwner` only for the controller, so "the view carries the bucket" *is* the rule; the
## leakfault build can carry it for a non-controller, which is what proves the checker notices.
## The typed view has no field for the `gm` bucket, so this builder cannot emit one.
var buckets = newJObject()
buckets["public"] = if v.propsPublic.isNil: newJObject() else: v.propsPublic
if not v.propsOwner.isNil:
buckets["owner"] = v.propsOwner
var cprops = newJObject()
cprops["public"] = if v.cpropsPublic.isNil: newJObject() else: v.cpropsPublic
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": statusKindsJson(v.statuses), "props": buckets, "cprops": cprops
}
if v.characterId.isSome:
result["character_id"] = %v.characterId.get
if v.includeVisionRadius:
result["vision_radius"] = if v.visionRadius.isSome: %v.visionRadius.get else: newJNull()
when defined(leakfault):
if faultActive("gmProp") and not v.faultGmProps.isNil:
buckets["gm"] = v.faultGmProps
if faultActive("statusSource") and v.faultStatusEntries.len > 0:
result["statuses"] = statusesJson(v.faultStatusEntries)
if faultActive("wallHeight"):
# WALLDATA positive control (#54): a wall field name (`height`) in a player token frame.
result["height"] = %1.8
proc tokenGoneFrame*(id: string): JsonNode = %*{"t": "token_gone", "id": id}
proc gmCharacterFrame*(v: GmCharacterView): JsonNode =
%*{"t": "character", "id": v.id, "owner": v.owner,
"descriptive_name": v.descriptiveName, "actual_name": v.actualName,
"reveal_all": v.revealAll, "revealed": %*v.revealed,
"props": props.propsJson(v.props)}
proc playerCharacterFrame*(v: PlayerCharacterView): JsonNode =
## The owner's view of a character: both names (an owner always knows the actual one, 8) and the
## `public`/`owner` buckets. No `owner`, `reveal_all` or `revealed` field exists here.
var buckets = newJObject()
buckets["public"] = if v.propsPublic.isNil: newJObject() else: v.propsPublic
buckets["owner"] = if v.propsOwner.isNil: newJObject() else: v.propsOwner
%*{"t": "character", "id": v.id, "descriptive_name": v.descriptiveName,
"actual_name": v.actualName, "props": buckets}
proc characterGoneFrame*(id: string): JsonNode = %*{"t": "character_gone", "id": id}
proc encounteredFrame*(entries: seq[EncounteredView], full: bool, del: seq[string],
player = 0): JsonNode =
## `encountered {full, set:[{id, name, grey}], del}`; the GM's copy adds `player` (6.1).
var set = newJArray()
for e in entries: set.add %*{"id": e.id, "name": e.name, "grey": e.grey}
var removals = newJArray()
for id in del: removals.add %id
result = %*{"t": "encountered", "full": full, "set": set}
if player != 0: result["player"] = %player
if not full: result["del"] = removals
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 markerEntryJson(m: MarkerView): JsonNode =
## One entry of a `marker` set: only the opaque id and the integer-px anchor (5.8, 6.1).
%*{"id": m.id, "pos": [m.x, m.y]}
proc markerFrame*(entries: seq[MarkerView], full: bool, del: seq[string]): JsonNode =
## `marker {full, set:[{id, pos}], del:[id]}` (DESIGN 6.1). `full:true` replaces the whole set on
## connect/resync and carries no `del`; a diff carries additions in `set` and retractions in `del`,
## never both for one id.
var set: JsonNode = newJArray()
for m in entries: set.add markerEntryJson(m)
result = %*{"t": "marker", "full": full, "set": set}
if not full:
var removals = newJArray()
for id in del: removals.add %id
result["del"] = removals
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 diffCharacters(known: var Known, views: seq[(string, JsonNode)]): seq[JsonNode] =
## The character half of the diff: `character` for new or changed records, `character_gone` for
## ones this recipient may no longer see (a reassignment is exactly that, for the old owner).
var seen = initHashSet[string]()
for (id, frame) in views:
seen.incl id
if known.characters.getOrDefault(id) != frame:
known.characters[id] = frame
result.add frame
var gone: seq[string]
for id in known.characters.keys:
if id notin seen: gone.add id
gone.sort()
for id in gone:
known.characters.del id
result.add characterGoneFrame(id)
proc diffEncountered(known: var Known, key: string, entries: seq[EncounteredView],
full: bool, player = 0): JsonNode =
## One `encountered` message or nil. `full` replaces the list (connect/resync, 6.1); otherwise only
## the entries that changed are sent, plus a `del` list for the ones the GM removed.
var set: seq[EncounteredView]
var del: seq[string]
var seen = initHashSet[string]()
for e in entries:
seen.incl e.id
let frame = %*{"id": e.id, "name": e.name, "grey": e.grey}
if full or known.encountered.getOrDefault(key & e.id) != frame:
known.encountered[key & e.id] = frame
set.add e
# `encountered.remove` (and `player.remove`) are the only ways an entry disappears; a `full`
# message replaces the list wholesale, so it never carries a `del`.
for k in known.encountered.keys.toSeq:
if not k.startsWith(key): continue
let id = k[key.len .. ^1]
if id in seen: continue
known.encountered.del k
if not full: del.add id
if set.len == 0 and del.len == 0 and not full: return nil
del.sort()
encounteredFrame(set, full, del, player)
proc diffMarkers(known: var Known, markers: seq[MarkerView], full: bool): JsonNode =
## One `marker` message or nil (DESIGN 5.8, 6.1): on connect/resync `full:true` with the whole set
## (after `explored`, 6.3); afterwards additions in `set` and retractions in `del`, each sorted and
## never the same id in both (a re-earned marker is a new id, 5.8, #60).
var seen = initHashSet[string]()
var set: seq[MarkerView]
var del: seq[string]
for m in markers:
seen.incl m.id
let frame = markerEntryJson(m)
if full or known.markers.getOrDefault(m.id) != frame:
known.markers[m.id] = frame
set.add m
for id in known.markers.keys.toSeq:
if id in seen: continue
known.markers.del id
if not full: del.add id
if full or set.len > 0 or del.len > 0:
del.sort()
return markerFrame(set, full, del)
proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false): seq[JsonNode] =
## Ordered like the 6.3 resync sequence: characters, encountered, then vision/explored and the
## tokens. Empty = nothing changed for this recipient, which is what keeps hidden mutations
## invisible (T11).
if r.isGm:
let view = gmView(ctx)
var charViews: seq[(string, JsonNode)]
for v in view.characters: charViews.add (v.id, gmCharacterFrame(v))
result.add diffCharacters(known, charViews)
for list in view.encountered:
let key = $list.player & "/"
if list.entries.len == 0 and not resync: continue
let frame = diffEncountered(known, key, list.entries, resync, player = list.player)
if not frame.isNil: result.add frame
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 charViews: seq[(string, JsonNode)]
for v in view.characters: charViews.add (v.id, playerCharacterFrame(v))
result.add diffCharacters(known, charViews)
let enc = diffEncountered(known, "", view.encountered, resync)
if not enc.isNil: result.add enc
var polysJson = visionPolyJson(view.polys)
when defined(leakfault):
if faultActive("otherVision"):
var otherStore: PlayerVision
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
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:
var noSight: PlayerVision
result.add exploredFullFrame(visionAt(ctx, r.playerId, noSight)[].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"):
var otherStore: PlayerVision
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
fresh.add other.exploredFull(ctx.scene)
result.add exploredFreshFrame(fresh)
# 6.3: `marker` (full) sits after `explored` because it is the same kind of memory and the client
# draws it over the fog `explored` just rebuilt. A diff follows the explored diff for the same
# reason. The GM never reaches this branch (3.1, 5.8).
let markerMsg = diffMarkers(known, view.markers, resync)
if not markerMsg.isNil: result.add markerMsg
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)