Files
FFF_vtt_frozen/tests/tviews.nim
T

473 lines
23 KiB
Nim

## Egress (#20, DESIGN 2 single egress rule, 3.1, 6.1, 6.3, 6.4): the typed per-recipient view, the
## per-connection diff that produces `token`/`token_gone`/`vision`/`explored`, and the field rules
## that keep GM-only data out of a player's frames. The black-box proof over a real socket is
## tools/leak.test.mjs with tools/leakcheck.nim.
import std/[algorithm, json, options, sequtils, sets, tables, unittest]
import characters, geometry, props, tokens, views, vision, world
const Pid = 2 # the subject player
const Other = 3 # another player
proc sceneWith(walls: seq[WallRec]): SceneRec =
SceneRec(id: 1, name: "Scene", w: 4096, h: 4096, tileSize: 32, cell: 32, gridSize: 0,
visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1,
extra: newJObject(), walls: walls)
proc tok(id: string, x, y: float, owner: int, gmOnly = false, visionFlag = true): TokenRec =
TokenRec(id: id, scene: 1, kind: "npc", descriptiveName: "a " & id, actualName: "Sir " & id,
pos: (x, y), owner: owner, gmOnly: gmOnly,
flags: (if visionFlag: %*{"vision": true} else: %*{}))
proc ctxOf(sc: SceneRec, tokens: seq[TokenRec], players: seq[int]): Context =
result = Context(scene: sc, tokens: tokens)
for pid in players:
var pv: PlayerVision
pv.refresh(sc, tokens, pid)
result.visions[pid] = pv
proc refreshAll(ctx: var Context) =
## What main.refreshAll does: recompute every player's sight in place, keeping explored cells.
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].refresh(ctx.scene, ctx.tokens, pid)
proc pass(ctx: var Context, known: var Known, resync = false, player = Pid): seq[JsonNode] =
## One egress pass exactly as main runs it: build, diff, then clear the fresh cells (4.2 step 8).
result = egressFrames(Recipient(isGm: false, playerId: player), ctx, known, resync)
for pid in ctx.visions.keys.toSeq: ctx.visions[pid].clearFresh()
proc typesOf(frames: seq[JsonNode]): seq[string] = frames.mapIt(it["t"].getStr)
proc keysDeep(node: JsonNode): HashSet[string] =
result = initHashSet[string]()
if node.kind == JObject:
for k, v in node:
result.incl k
for inner in keysDeep(v): result.incl inner
elif node.kind == JArray:
for v in node:
for inner in keysDeep(v): result.incl inner
const ForbiddenToPlayers = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller",
"gm_only", "flags", "descriptive_name", "actual_name", "reveal_all",
"revealed", "source", "radius_own", "extra"]
suite "GM view (3.1: everything, with the GM-only extras)":
test "every token, in token order, with controller and both names":
let sc = sceneWith(@[])
let tokens = @[tok("a", 100, 100, 0), tok("b", 3000, 3000, Pid), tok("c", 2000, 2000, 0)]
let view = gmView(ctxOf(sc, tokens, @[Pid]))
check view.tokens.len == 3
check view.tokens.mapIt(it.id) == @["a", "b", "c"]
let frame = gmTokenFrame(view.tokens[1])
check frame["mine"].getBool == false # `mine` is a player-facing flag
check frame["controller"].getInt == Pid
check frame["kind"].getStr == "npc"
check frame["gm_only"].getBool == false
check frame["descriptive_name"].getStr == "a b"
check frame["actual_name"].getStr == "Sir b"
check frame["props"].len == 3 # public, owner, gm
check frame["radius"].getFloat == 20.0 # the scene default (#4, slice 7)
test "a GM-controlled token shows controller null":
let sc = sceneWith(@[])
let view = gmView(ctxOf(sc, @[tok("a", 100, 100, 0)], @[Pid]))
check gmTokenFrame(view.tokens[0])["controller"].kind == JNull
test "the GM never gets vision polygons or explored cells":
let sc = sceneWith(@[])
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctxOf(sc, @[tok("a", 100, 100, Pid)], @[Pid]), known, resync = true)
check typesOf(frames) == @["token"]
suite "player view (3.1: controlled always, LOS + not gm_only otherwise)":
test "the set of tokens follows the visibility rule":
let sc = sceneWith(@[])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0),
tok("outside", 3000, 3000, 0), tok("secret", 500, 500, 0, gmOnly = true),
tok("theirs", 3500, 3500, Other)]
let view = playerView(ctxOf(sc, tokens, @[Pid, Other]), Pid)
check view.tokens.mapIt(it.id) == @["mine", "near"]
test "a player frame carries no GM-only field and no wall-like key":
let sc = sceneWith(@[])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)]
let view = playerView(ctxOf(sc, tokens, @[Pid]), Pid)
check view.tokens.len == 2
let frame = playerTokenFrame(view.tokens[1])
let keys = keysDeep(frame)
for key in ForbiddenToPlayers:
check key notin keys
check frame["name"].getStr == "a near" # the descriptive name (slice 5)
check frame["props"].keys.toSeq == @["public"]
check not frame.hasKey("vision_radius") # only the controller gets the field at all
test "the controller gets `mine`, the owner bucket and its vision_radius":
let sc = sceneWith(@[])
var mine = tok("mine", 400, 400, Pid)
mine.visionRadius = some(250.0)
let view = playerView(ctxOf(sc, @[mine], @[Pid]), Pid)
let frame = playerTokenFrame(view.tokens[0])
check frame["mine"].getBool
check frame["props"].keys.toSeq.sorted == @["owner", "public"]
check frame["vision_radius"].getFloat == 250.0
let other = playerView(ctxOf(sc, @[tok("mine", 400, 400, Pid), tok("x", 500, 400, 0)], @[Pid]), Pid)
check other.tokens[1].visionRadius.isNone
check other.tokens[1].includeVisionRadius == false
test "a scan of every player frame finds no wall-ish or GM-only key":
let sc = sceneWith(@[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())])
let tokens = @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0),
tok("secret", 500, 500, 0, gmOnly = true)]
var known: Known
let ctx = ctxOf(sc, tokens, @[Pid])
for f in egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true):
for key in ForbiddenToPlayers:
check key notin keysDeep(f)
suite "diff (6.4: only what changed)":
test "the first pass sends the resync order, then nothing changes and nothing is sent":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first) == @["encountered", "vision", "explored", "token"]
check first[0]["full"].getBool # 6.3: the whole list on connect/resync
check first[0]["set"].len == 0
check first[2]["full"].getBool
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token that moved sends one `token` frame with the new position":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[0].pos = (440.0, 400.0)
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["vision", "explored", "token"]
check frames[2]["pos"][0].getFloat == 440.0
check frames[2]["id"].getStr == "mine"
test "leaving view sends `token_gone` once, and never for a token that was never sent":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
var known: Known
let first = pass(ctx, known, resync = true)
check typesOf(first).contains("token")
ctx.tokens[1].pos = (3000.0, 3000.0) # far out of sight
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["token_gone"]
check frames[0]["id"].getStr == "near"
check typesOf(pass(ctx, known)) == newSeq[string]()
test "a token becoming gm_only is taken away from a player who could see it (6.1)":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 600, 400, 0)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[1].gmOnly = true
refreshAll(ctx)
let frames = pass(ctx, known)
check typesOf(frames) == @["token_gone"]
check frames[0]["id"].getStr == "near"
test "vision is re-sent only when the polygons change":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
check typesOf(pass(ctx, known)) == newSeq[string]()
ctx.tokens[0].pos = (500.0, 400.0)
refreshAll(ctx)
let moved = pass(ctx, known)
check moved[0]["t"].getStr == "vision"
check moved[0]["polys"][0]["pts"].len > 60
test "a changed wall is enough to re-send vision":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.scene.walls = @[WallRec(a: (700, 0), b: (700, 4096), flags: newJObject())]
refreshAll(ctx)
let frames = pass(ctx, known)
check frames[0]["t"].getStr == "vision" # the polygons shrank
check typesOf(frames) == @["vision"] # no new cells: the wall only removed sight
suite "frames (6.1)":
test "explored full is RLE rows of contiguous columns":
let sc = sceneWith(@[])
var pv: PlayerVision
pv.refresh(sc, @[tok("mine", 400, 400, Pid)], Pid)
let frame = exploredFullFrame(pv.exploredFull(sc))
check frame["full"].getBool
for row in frame["rle"]:
check row.len >= 3
check row.len mod 2 == 1 # cy followed by (x0, len) pairs
var cx = row[1].getInt
for i in countup(1, row.len - 1, 2):
check row[i].getInt == cx
cx += row[i + 1].getInt
test "explored fresh is a list of [cx, cy]":
let frame = exploredFreshFrame(@[(3, 4), (5, 6)])
check frame["full"].getBool == false
check frame["cells"] == %*[[3, 4], [5, 6]]
test "the vision payload uses integer pixels (6.4, Q16 FIXED)":
let frame = visionFrame(@[Poly(tokenId: "abc", pts: @[(10.4, 20.6), (30.5, 40.5)])])
check frame["polys"][0]["id"].getStr == "abc"
for pt in frame["polys"][0]["pts"]:
check pt[0].kind == JInt and pt[1].kind == JInt
check frame["polys"][0]["pts"] == %*[[10, 21], [31, 41]]
test "the hello scene block carries the 6.1 fields and no counts":
let sceneJson = sceneBlock(sceneWith(@[]))
check sceneJson["id"].getInt == 1
check sceneJson["w"].getFloat == 4096.0
check sceneJson["cell"].getInt == 32
check sceneJson["vision_radius_default"].getFloat == 400.0
check sceneJson["token_radius_default"].getFloat == 20.0
check sceneJson["art_version"].getInt == 1
for key in ["walls", "tokens", "entities", "walls_count", "count"]:
check not sceneJson.hasKey(key)
suite "props and statuses (#22, 6.1: the bucket and the source are per-recipient)":
proc withProps(id: string, x, y: float, owner: int): TokenRec =
result = tok(id, x, y, owner)
result.props[pbPublic] = %*{"aura": "cold", "tag": "wolf"}
result.props[pbOwner] = %*{"hp": 7}
result.props[pbGm] = %*{"secret": "the duke"}
test "the GM frame carries all three buckets and the source of every status":
var t = withProps("a", 100, 100, 0)
t.statuses = @[(stStuck, ssWalls), (stSqueezed, ssGM)]
let frame = gmTokenFrame(gmView(ctxOf(sceneWith(@[]), @[t], @[Pid])).tokens[0])
check frame["props"].keys.toSeq.sorted == @["gm", "owner", "public"]
check frame["props"]["public"]["aura"].getStr == "cold"
check frame["props"]["owner"]["hp"].getInt == 7
check frame["props"]["gm"]["secret"].getStr == "the duke"
check frame["statuses"] == %*[{"status": "stuck", "source": "walls"},
{"status": "squeezed", "source": "GM"}]
test "a player who sees the token gets the public bucket only":
let sc = sceneWith(@[])
let tokens = @[withProps("mine", 400, 400, Pid), withProps("near", 500, 400, 0)]
let view = playerView(ctxOf(sc, tokens, @[Pid]), Pid)
let other = playerTokenFrame(view.tokens[1])
check other["props"].keys.toSeq == @["public"]
check other["props"]["public"]["tag"].getStr == "wolf"
check not other["props"].hasKey("owner")
check not other["props"].hasKey("gm")
test "the controller gets public + owner, never the gm bucket":
let sc = sceneWith(@[])
let view = playerView(ctxOf(sc, @[withProps("mine", 400, 400, Pid)], @[Pid]), Pid)
let frame = playerTokenFrame(view.tokens[0])
check frame["props"].keys.toSeq.sorted == @["owner", "public"]
check frame["props"]["owner"]["hp"].getInt == 7
check not frame["props"].hasKey("gm")
test "the controller is not told what caused a status either (5.5, 6.1 note 6)":
var t = withProps("mine", 400, 400, Pid)
t.statuses = @[(stStuck, ssWalls), (stSqueezed, ssGM)]
let frame = playerTokenFrame(playerView(ctxOf(sceneWith(@[]), @[t], @[Pid]), Pid).tokens[0])
check frame["statuses"] == %*[{"status": "stuck"}, {"status": "squeezed"}]
check "source" notin keysDeep(frame)
check frame["statuses"][0].len == 1
test "a prop change and a status change each reach a viewer as one `token` frame":
var ctx = ctxOf(sceneWith(@[]), @[withProps("mine", 400, 400, Pid)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
check typesOf(pass(ctx, known)) == newSeq[string]()
var changed = ctx.tokens[0]
changed.props[pbPublic] = %*{"aura": "warm", "tag": "wolf"}
ctx.tokens[0] = changed
let frames = pass(ctx, known)
check typesOf(frames) == @["token"]
check frames[0]["props"]["public"]["aura"].getStr == "warm"
var stuck = ctx.tokens[0]
stuck.statuses = @[(stStuck, ssWalls)]
ctx.tokens[0] = stuck
let after = pass(ctx, known)
check typesOf(after) == @["token"]
check after[0]["statuses"] == %*[{"status": "stuck"}]
test "a radius change reaches every viewer as the effective radius":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
var known: Known
discard pass(ctx, known, resync = true)
ctx.tokens[1].radius = some(35.0)
let frames = pass(ctx, known)
check typesOf(frames) == @["token"]
check frames[0]["radius"].getFloat == 35.0
check not frames[0].hasKey("radius_own") # the GM-only own-radius field stays out
# ---------------------------------------------------------------------------------------------------
# Slice 8 (#23): characters, names and the encountered list in the typed view.
proc charOf(id: string, owner: int, dname = "a grumpy man", actual = "Lord Vex"): CharacterRec =
CharacterRec(id: id, owner: owner, descriptiveName: dname, actualName: actual, props: newProps())
proc withChar(ctx: var Context, c: CharacterRec): int =
ctx.characters.add c
ctx.characters.len - 1
proc linked(id: string, x, y: float, owner: int, characterId: string): TokenRec =
TokenRec(id: id, scene: 1, kind: "pc", characterId: some(characterId), pos: (x, y),
owner: owner, flags: %*{"vision": true}, props: newProps())
suite "characters in the egress (3.1, 6.1, 8)":
test "the GM gets every character with owner, reveal_all, revealed and all three buckets":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
var c = charOf("c1", 2)
c.revealAll = true
c.props[pbGm] = %*{"trap": true}
discard ctx.withChar(c)
ctx.reveals.withReveal(Other, "c1")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
check frames.len == 1
let f = frames[0]
check f["t"].getStr == "character"
check f["owner"].getInt == 2
check f["descriptive_name"].getStr == "a grumpy man"
check f["actual_name"].getStr == "Lord Vex"
check f["reveal_all"].getBool
check f["revealed"] == %*[Other]
check f["props"].keys.toSeq.sorted == @["gm", "owner", "public"]
test "a player gets only its own characters, without owner, reveal_all or revealed":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("mine", Pid))
discard ctx.withChar(charOf("theirs", Other))
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
let chars = frames.filterIt(it["t"].getStr == "character")
check chars.len == 1
check chars[0]["id"].getStr == "mine"
check chars[0]["actual_name"].getStr == "Lord Vex" # the owner always knows it (8)
check chars[0]["props"].keys.toSeq.sorted == @["owner", "public"]
for key in ["owner", "reveal_all", "revealed", "nhidden"]:
check not chars[0].hasKey(key)
test "a reassignment withdraws the record from the old owner and sends it to the new one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
var known: Known
check typesOf(egressFrames(Recipient(isGm: false, playerId: Other), ctx, known, resync = true))
.contains("character")
var otherKnown: Known
check not typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
ctx.characters[idx].owner = Pid
let otherFrames = egressFrames(Recipient(isGm: false, playerId: Other), ctx, known)
check typesOf(otherFrames) == @["character_gone"]
check otherFrames[0]["id"].getStr == "c1"
check typesOf(egressFrames(Recipient(isGm: false, playerId: Pid), ctx, otherKnown))
.contains("character")
test "a linked token's name follows the character, and the owner sees the actual one":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
# the subject controls the token but does not own the character
var known: Known
var frame = playerView(ctx, Pid).tokens[0]
check frame.name == "a grumpy man"
check frame.characterId.isNone # 6.1 leak note 2
check frame.cpropsPublic.len == 0
# the character's owner sees the actual name and the link
let owner = playerView(ctx, Other)
check owner.tokens.len == 0 # no LOS of its own: the token is not in its view
discard known
test "cprops carries the character's public bucket to a non-owner, and never the owner bucket":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
let idx = ctx.withChar(charOf("c1", Other))
ctx.characters[idx].props[pbPublic] = %*{"rank": "noble"}
ctx.characters[idx].props[pbOwner] = %*{"hp": 3}
ctx.characters[idx].props[pbGm] = %*{"trap": true}
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
let frame = playerTokenFrame(playerView(ctx, Pid).tokens[0])
check frame["cprops"].keys.toSeq == @["public"]
check frame["cprops"]["public"]["rank"].getStr == "noble"
check "owner" notin keysDeep(frame["cprops"])
check "gm" notin keysDeep(frame)
check frame["props"].keys.toSeq.sorted == @["owner", "public"] # its own buckets
test "a player sees the actual name only when the GM revealed it to them (8)":
var ctx = ctxOf(sceneWith(@[]), @[], @[Pid, Other])
discard ctx.withChar(charOf("c1", Other))
ctx.tokens = @[linked("t1", 400, 400, Pid, "c1")]
var known: Known
check playerView(ctx, Pid).tokens[0].name == "a grumpy man"
ctx.reveals.withReveal(Pid, "c1")
check playerView(ctx, Pid).tokens[0].name == "Lord Vex"
discard known
suite "the encountered list (8)":
proc entryFor(id: string, name: string, grey = false): EncounteredView =
EncounteredView(id: id, name: name, grey: grey)
test "a resync sends the whole list, then only what changed, then what was removed":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid])
ctx.encountered[Pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine",
descriptiveName: "a mine")
var known: Known
let full = pass(ctx, known, resync = true)
let enc = full.filterIt(it["t"].getStr == "encountered")
check enc.len == 1
check enc[0]["full"].getBool
check enc[0]["set"] == %*[{"id": "mine", "name": "a mine", "grey": false}]
# nothing changed: no frame
check pass(ctx, known).len == 0
# greyed: the entry is re-sent, nothing is deleted
ctx.encountered[Pid]["mine"].actualName = some("Mine")
let changed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check changed.len == 1
check changed[0]["full"].getBool == false
check changed[0]["set"] == %*[{"id": "mine", "name": "Mine", "grey": false}]
check changed[0]["del"] == newJArray()
# removed: only a `del`
ctx.encountered[Pid].del "mine"
let removed = pass(ctx, known).filterIt(it["t"].getStr == "encountered")
check removed.len == 1
check removed[0]["set"] == newJArray()
check removed[0]["del"] == %*["mine"]
test "an entry for a token that is gone (or out of view) is grey":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("near", 500, 400, 0)], @[Pid])
check not ctx.greyFor(Pid, "near") # in LOS
check ctx.greyFor(Pid, "unknown") # removed from the world
ctx.tokens[1].pos = (3000.0, 3000.0)
check ctx.greyFor(Pid, "near") # moved away
ctx.tokens[1].gmOnly = true
ctx.tokens[1].pos = (500.0, 400.0)
check ctx.greyFor(Pid, "near") # a gm_only flip greys it, it is not deleted
test "the GM gets one list per player, tagged with the player id":
var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid), tok("theirs", 400, 400, Other)],
@[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Pid]["mine"] = EncounteredEntry(entityId: "mine", descriptiveName: "a mine")
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: true, playerId: 1), ctx, known, resync = true)
let lists = frames.filterIt(it["t"].getStr == "encountered")
check lists.len == 2
check lists[0]["player"].getInt == Pid
check lists[0]["set"][0]["id"].getStr == "mine"
check lists[1]["player"].getInt == Other
check lists[1]["set"][0]["id"].getStr == "theirs"
test "a player never receives another player's list":
var ctx = ctxOf(sceneWith(@[]), @[tok("theirs", 400, 400, Other)], @[Pid, Other])
for pid in [Pid, Other]:
ctx.encountered[pid] = initTable[string, characters.EncounteredEntry]()
ctx.encountered[Other]["theirs"] = EncounteredEntry(entityId: "theirs",
descriptiveName: "a theirs")
var known: Known
let frames = egressFrames(Recipient(isGm: false, playerId: Pid), ctx, known, resync = true)
for f in frames.filterIt(it["t"].getStr == "encountered"):
check f["set"].len == 0
check not f.hasKey("player")