Files
FFF_vtt_frozen/server/world.nim
T

450 lines
20 KiB
Nim

## Scene and wall state: the authoring half of the world (DESIGN 3.1, 4.1, 4.2, 4.4, 6.1, 8;
## M3 slice 4, issue #19). In-memory authoritative state, SQLite as write-through persistence: rows
## are read once at startup (`loadScene`) and never queried at runtime for reads.
##
## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused
## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the
## wire. Doors are walls with `kind = door`; `blocks = not (kind == door and open)` comes from
## geometry.Wall when slice 5 feeds the vision code. `flags` is a free JSON object the server never
## interprets (M6/Beyond: window, one-way, secret door live there).
##
## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED
## owner-delegated, #19, in DESIGN 6.1/14):
## - `scene` is an integer id; in v1 it is always the one seeded scene (id 1), and any other value
## is `not-found` (no existence oracle either way: only the GM can send these intents).
## - `scene.set` (slice 10, #25): the patch rules of 6.1 ("Scene payload rules"); `w`, `h`,
## `tile_size`, `cell` and `art_version` are not patch fields. `patched`/`writeSceneRow` are pure
## and transaction-free so main.nim can commit the scene row with the tokens it resized.
## - `wall.add`: `open` omitted = false; `open` on a `kind: "wall"` is `invalid` (a wall is never
## open), and the stored row normalizes it to false regardless.
## - `wall.update` patches `a`, `b`, `kind`, `flags` only (`open` belongs to `door.set`; an `open`
## field here is an unknown field and is ignored); at least one patch field is required, else
## `invalid`. Changing `kind` door -> wall closes the door.
## - `a != b` (a zero-length wall is refused) and both endpoints inside `[0,w] x [0,h]`.
## - `flags` must be a JSON object; omitted = `{}`. Coordinates must be finite numbers.
##
## Persistence order (4.2 step 6): a wall write runs in one transaction with `synchronous=FULL`
## around it (Q12 FIXED: GM authoring is the expensive-to-lose data) and the in-memory state is
## updated only after COMMIT, so a failing write leaves memory and DB identical. This module does
## no locking: the caller holds the global lock (4.3).
import std/[json, math, options, strutils]
import db_connector/db_sqlite
import geometry, text
type
WallKind* = enum
wkWall = "wall"
wkDoor = "door"
WallPosition* = enum
wpCenter = "center"
wpLeft = "left"
wpRight = "right"
SightDir* = enum
sdBoth = "both"
sdLeft = "left"
sdRight = "right"
WallRec* = object
## The typed wall record of DESIGN 8. The wire still carries the legacy `kind`/`open` pair in
## this round (#53); `kind` is derived from `door` and nothing else is exposed there yet (#54).
id*: int
a*, b*: Vec
thickness*: float
position*: WallPosition
blocksSight*, blocksMovement*: bool
sightDir*: SightDir
playerMarker*: bool
door*, open*, secret*, locked*: bool
height*: Option[float] ## metres; none = full height (DESIGN 5.7)
label*: Option[string] ## GM-only free text, 1..64 code points (DESIGN 5.8)
flags*: JsonNode ## JObject; never nil for a loaded or created wall
SceneRec* = object
## The one v1 scene (Q3 FIXED). Walls are kept in id order (ids only grow, appends only).
id*: int
name*: string
w*, h*: float
tileSize*, cell*: int
gridSize*: float
visionRadiusDefault*, tokenRadiusDefault*: float
artVersion*: int
nextWallId*: int
extra*: JsonNode
walls*: seq[WallRec]
WallApply* = enum
## Outcome of a persistent wall operation; main.nim maps it to the 6.5 codes.
waOk
waInvalid ## geometry/field semantics: `invalid`
waNotFound ## no such wall in the scene: `not-found`
waNotDoor ## door.set on a plain wall: `invalid`
WallPatch* = object
## The updatable fields of `wall.update` (DESIGN 6.1); none = the field keeps its value.
a*, b*: Option[Vec]
kind*: Option[WallKind]
flags*: Option[JsonNode]
ScenePatch* = object
## `scene.set` (DESIGN 6.1): every field is optional; an absent field keeps its value.
## `w`, `h`, `tile_size`, `cell` and `art_version` are not patch fields (import is the M6 CLI):
## they are unknown fields and ignored (6.2), so a patch with only one of them has no field at
## all and is `invalid`.
name*: Option[string]
gridSize*: Option[float]
visionRadiusDefault*: Option[float]
tokenRadiusDefault*: Option[float]
extra*: Option[JsonNode]
SceneError* = object of CatchableError
## The DB and this build disagree about the scene (missing seed, unreadable row).
const
DefaultSceneId* = 1
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
WallKinds* = [wkWall, wkDoor]
SceneNameMaxLen* = 64
## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25).
proc defaultWall*(a, b: Vec): WallRec =
## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings.
WallRec(a: a, b: b, blocksSight: true, blocksMovement: true, flags: newJObject())
proc kind*(w: WallRec): WallKind =
## The legacy wire label for this round: only the door axis exists on it (#53). #54 replaces
## this with the full derived shape label.
if w.door: wkDoor else: wkWall
proc `kind=`*(w: var WallRec, k: WallKind) =
## Legacy update path (`wall.update {kind}`): a wall is never open; clearing the door switch
## also drops the door-only settings so the DB CHECK cannot see an impossible row.
if k == wkDoor:
w.door = true
else:
w.door = false
w.open = false
w.secret = false
w.locked = false
# ---------------------------------------------------------------------------------------------------
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
proc parseKind*(raw: string): Option[WallKind] =
for k in WallKinds:
if $k == raw: return some(k)
proc parseVec*(node: JsonNode): Option[Vec] =
## `a:[x,y]` / `b:[x,y]`: exactly two finite JSON numbers.
if node.isNil or node.kind != JArray or node.len != 2: return none(Vec)
var v: Vec
for i, field in [node[0], node[1]]:
var f: float
case field.kind
of JInt: f = float(field.getInt)
of JFloat: f = field.getFloat
else: return none(Vec)
if classify(f) in {fcNan, fcInf, fcNegInf}: return none(Vec)
if i == 0: v.x = f else: v.y = f
some(v)
proc parseFlags*(node: JsonNode): Option[JsonNode] =
## `flags?`: an object or absent (DESIGN 6.1). A non-object is `invalid`.
if node.isNil: return some(newJObject())
if node.kind != JObject: return none(JsonNode)
some(node)
proc parseOpen*(node: JsonNode): Option[bool] =
## `open?`: a boolean or absent (= false).
if node.isNil: return some(false)
if node.kind != JBool: return none(bool)
some(node.getBool)
proc fieldOrNull*(env: JsonNode, key: string): JsonNode =
## `undefined` and `null` are both "field absent" for the wall payloads.
if env.isNil: return nil
result = env{key}
if not result.isNil and result.kind == JNull: result = nil
proc parseFinite(node: JsonNode): Option[float] =
## One finite JSON number (integers accepted; strings, booleans and null are not numbers).
if node.isNil: return none(float)
case node.kind
of JInt: result = some(float(node.getInt))
of JFloat:
let f = node.getFloat
if classify(f) in {fcNan, fcInf, fcNegInf}: return none(float)
result = some(f)
else: discard
proc parseScenePatch*(node: JsonNode): Option[ScenePatch] =
## `scene.set` payload (DESIGN 6.1, slice 10 / #25). At least one patch field is required and a
## present field must have its own shape: a `null` is a wrong type, not "absent", because the
## field was declared (the same reading `token.resize` gives a required `radius`).
## name: the 6.5 text rule (1..64 code points, no control characters)
## grid_size: a finite number >= 0 (0 = no grid)
## vision_radius_default, token_radius_default: a finite number > 0; no upper cap (#4, #25)
## extra: a JSON object, stored verbatim and never interpreted
if node.isNil or node.kind != JObject: return none(ScenePatch)
var p: ScenePatch
var any = false
if node.hasKey("name"):
let v = node["name"]
if v.kind != JString or not validText(v.getStr, SceneNameMaxLen): return none(ScenePatch)
p.name = some(v.getStr)
any = true
if node.hasKey("grid_size"):
let v = parseFinite(node["grid_size"])
if v.isNone or v.get < 0: return none(ScenePatch)
p.gridSize = v
any = true
if node.hasKey("vision_radius_default"):
let v = parseFinite(node["vision_radius_default"])
if v.isNone or v.get <= 0: return none(ScenePatch)
p.visionRadiusDefault = v
any = true
if node.hasKey("token_radius_default"):
let v = parseFinite(node["token_radius_default"])
if v.isNone or v.get <= 0: return none(ScenePatch)
p.tokenRadiusDefault = v
any = true
if node.hasKey("extra"):
let v = node["extra"]
if v.kind != JObject: return none(ScenePatch)
p.extra = some(v)
any = true
if not any: return none(ScenePatch)
some(p)
proc patched*(sc: SceneRec, patch: ScenePatch): SceneRec =
## The scene as `scene.set` would store it. The caller validates the result by construction: every
## patch field was already type- and range-checked by `parseScenePatch`.
result = sc
if patch.name.isSome: result.name = patch.name.get
if patch.gridSize.isSome: result.gridSize = patch.gridSize.get
if patch.visionRadiusDefault.isSome: result.visionRadiusDefault = patch.visionRadiusDefault.get
if patch.tokenRadiusDefault.isSome: result.tokenRadiusDefault = patch.tokenRadiusDefault.get
if patch.extra.isSome: result.extra = patch.extra.get
# ---------------------------------------------------------------------------------------------------
# In-memory rules (pure): validation, lookup and the id allocator
proc inBounds(sc: SceneRec, p: Vec): bool =
p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h # written so NaN fails
proc validWall*(sc: SceneRec, rec: WallRec): bool =
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds. `kind` and `flags` are
## checked by the parsers, so a `WallRec` can only carry valid ones.
(rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b)
proc normalize*(rec: WallRec): WallRec =
## A wall is never open; only a door can be, and a non-door stores no door-only settings.
result = rec
if not result.door:
result.open = false
result.secret = false
result.locked = false
if result.flags.isNil: result.flags = newJObject()
proc wallIndex*(sc: SceneRec, id: int): Option[int] =
for i, w in sc.walls:
if w.id == id: return some(i)
proc wallById*(sc: SceneRec, id: int): Option[WallRec] =
let i = wallIndex(sc, id)
if i.isSome: return some(sc.walls[i.get])
proc patched*(w: WallRec, patch: WallPatch): WallRec =
## `wall.update` candidate: the stored row with the patch applied (open untouched).
result = w
if patch.a.isSome: result.a = patch.a.get
if patch.b.isSome: result.b = patch.b.get
if patch.kind.isSome: result.kind = patch.kind.get
if patch.flags.isSome: result.flags = patch.flags.get
result = normalize(result)
# ---------------------------------------------------------------------------------------------------
# Persistence (write-through, synchronous=FULL around the transaction, Q12)
proc flagsText(node: JsonNode): string =
if node.isNil: "{}" else: $node
proc sqlLitText*(value: string): string =
## A SQL text literal (DESIGN 4.4): single quotes doubled. Used for `label`, which is nullable.
"'" & value.replace("'", "''") & "'"
proc sqlLitReal*(value: float): string =
## A fixed, locale-free SQL number literal. Used for `height`, which is nullable.
$value
proc sqlLitTextOrNull*(value: Option[string]): string =
if value.isSome: sqlLitText(value.get) else: "NULL"
proc sqlLitRealOrNull*(value: Option[float]): string =
if value.isSome: sqlLitReal(value.get) else: "NULL"
template authoringTransaction*(db: DbConn, body: untyped) =
## GM authoring durability (Q12): `synchronous=FULL` for this transaction, `NORMAL` again
## afterwards, whether the body succeeded or raised. `PRAGMA synchronous` cannot change inside a
## transaction, so it brackets BEGIN/COMMIT; a failing body rolls back completely.
db.exec(sql"PRAGMA synchronous=FULL")
try:
db.exec(sql"BEGIN")
try:
body
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
finally:
db.exec(sql"PRAGMA synchronous=NORMAL")
proc writeSceneRow*(db: DbConn, sc: SceneRec) =
## The `scene.set` columns, no transaction control: the caller owns the transaction (the scene row
## and the tokens its default radius resized commit together, #25).
db.exec(sql"""UPDATE scene SET name = ?, grid_size = ?, vision_radius_default = ?,
token_radius_default = ?, extra = ? WHERE id = ?""",
sc.name, $sc.gridSize, $sc.visionRadiusDefault, $sc.tokenRadiusDefault,
flagsText(sc.extra), sc.id)
proc storeScene*(db: DbConn, sc: SceneRec) =
## `scene.set` alone in memory (tests): one FULL authoring transaction (Q12).
authoringTransaction(db):
writeSceneRow(db, sc)
proc insertRow(db: DbConn, sceneId: int, w: WallRec) =
let height = sqlLitRealOrNull(w.height)
let label = sqlLitTextOrNull(w.label)
db.exec(sql("INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, " &
"blocks_sight, blocks_movement, sight_dir, player_marker, door, open, secret, " &
"locked, height, label, flags) " &
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " & height & ", " &
label & ", ?)"),
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags))
proc replaceRow(db: DbConn, sceneId: int, w: WallRec) =
let height = sqlLitRealOrNull(w.height)
let label = sqlLitTextOrNull(w.label)
db.exec(sql("UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, thickness = ?, position = ?, " &
"blocks_sight = ?, blocks_movement = ?, sight_dir = ?, player_marker = ?, " &
"door = ?, open = ?, secret = ?, locked = ?, height = " & height &
", label = " & label & ", flags = ? WHERE scene_id = ? AND id = ?"),
w.a.x, w.a.y, w.b.x, w.b.y, $w.thickness, $w.position,
(if w.blocksSight: 1 else: 0), (if w.blocksMovement: 1 else: 0), $w.sightDir,
(if w.playerMarker: 1 else: 0), (if w.door: 1 else: 0), (if w.open: 1 else: 0),
(if w.secret: 1 else: 0), (if w.locked: 1 else: 0), flagsText(w.flags), sceneId, w.id)
proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] =
## `wall.add`: assigns the scene's next wall id, persists and then appends to memory.
## none = invalid geometry (nothing written, nothing applied).
let candidate = normalize(rec)
if not validWall(sc, candidate): return none(int)
var stored = candidate
stored.id = max(1, sc.nextWallId)
authoringTransaction(db):
insertRow(db, sc.id, stored)
db.exec(sql"UPDATE scene SET next_wall_id = ? WHERE id = ?", stored.id + 1, sc.id)
sc.walls.add stored
sc.nextWallId = stored.id + 1
some(stored.id)
proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply =
## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules,
## which slice 5 re-evaluates). A kind change door -> wall closes the door.
let idx = wallIndex(sc, rec.id)
if idx.isNone: return waNotFound
let stored = normalize(rec)
if not validWall(sc, stored): return waInvalid
authoringTransaction(db):
replaceRow(db, sc.id, stored)
sc.walls[idx.get] = stored
waOk
proc removeWall*(db: DbConn, sc: var SceneRec, id: int): WallApply =
## `wall.remove`: the row goes, `next_wall_id` does not move (ids are never reused).
let idx = wallIndex(sc, id)
if idx.isNone: return waNotFound
authoringTransaction(db):
db.exec(sql"DELETE FROM wall WHERE scene_id = ? AND id = ?", sc.id, id)
sc.walls.delete idx.get
waOk
proc setDoor*(db: DbConn, sc: var SceneRec, id: int, open: bool): WallApply =
## `door.set`: only a door can be opened or closed (`invalid` on a plain wall).
let idx = wallIndex(sc, id)
if idx.isNone: return waNotFound
if sc.walls[idx.get].door == false: return waNotDoor
var stored = sc.walls[idx.get]
stored.open = open
authoringTransaction(db):
db.exec(sql"UPDATE wall SET open = ? WHERE scene_id = ? AND id = ?",
(if open: 1 else: 0), sc.id, id)
sc.walls[idx.get] = stored
waOk
# ---------------------------------------------------------------------------------------------------
# Loading (4.4 Startup: load everything into memory once)
proc rowToWall(row: Row): WallRec =
var flags: JsonNode
try:
flags = parseJson(row[17])
except CatchableError:
flags = newJObject()
if flags.isNil or flags.kind != JObject: flags = newJObject()
WallRec(id: parseInt(row[0]),
a: (parseFloat(row[1]), parseFloat(row[2])),
b: (parseFloat(row[3]), parseFloat(row[4])),
thickness: parseFloat(row[5]),
position: parseEnum[WallPosition](row[6]),
blocksSight: row[7] == "1",
blocksMovement: row[8] == "1",
sightDir: parseEnum[SightDir](row[9]),
playerMarker: row[10] == "1",
door: row[11] == "1",
open: row[12] == "1",
secret: row[13] == "1",
locked: row[14] == "1",
height: (if row[15].len == 0: none(float) else: some(parseFloat(row[15]))),
label: (if row[16].len == 0: none(string) else: some(row[16])),
flags: flags)
proc loadScene*(db: DbConn, sceneId = DefaultSceneId): Option[SceneRec] =
## The single scene and its walls, ordered by wall id. none = the scene row is missing (a DB that
## migration 3 did not seed): startup treats that as fatal.
for row in db.getAllRows(sql"""
SELECT id, name, w, h, tile_size, cell, grid_size, vision_radius_default,
token_radius_default, art_version, next_wall_id, extra
FROM scene WHERE id = ?""", sceneId):
var extra: JsonNode
try:
extra = parseJson(row[11])
except CatchableError:
extra = newJObject()
if extra.isNil: extra = newJObject()
result = some(SceneRec(id: parseInt(row[0]), name: row[1],
w: parseFloat(row[2]), h: parseFloat(row[3]),
tileSize: parseInt(row[4]), cell: parseInt(row[5]),
gridSize: parseFloat(row[6]),
visionRadiusDefault: parseFloat(row[7]),
tokenRadiusDefault: parseFloat(row[8]),
artVersion: parseInt(row[9]),
nextWallId: parseInt(row[10]),
extra: extra))
if result.isNone: return
var sc = result.get
for row in db.getAllRows(sql"""
SELECT id, ax, ay, bx, by, thickness, position, blocks_sight, blocks_movement, sight_dir,
player_marker, door, open, secret, locked, height, label, flags
FROM wall WHERE scene_id = ? ORDER BY id""", sceneId):
sc.walls.add rowToWall(row)
result = some(sc)
proc sceneCount*(db: DbConn): int =
parseInt(db.getValue(sql"SELECT count(*) FROM scene"))