server: scene and wall state, slice-4 migration (#19)

Migration step 3 ("world") creates scene and wall and seeds the single v1 scene
(id 1, 4096x4096, tile = cell 32, vision 400, token radius 20, art_version 1,
next_wall_id 1). server/world.nim holds the in-memory scene with SQLite as
write-through persistence: per-scene wall ids from next_wall_id (monotonic,
never reused, #3), 6.1 validation (a != b, in bounds, a wall is never open),
flags as an opaque JSON object, and one transaction with synchronous=FULL
around every GM authoring write (Q12); memory follows COMMIT, so a failed
write leaves both sides unchanged.

Tests: tests/tworld.nim (ids, reload, doors, validation, pragma, failed write),
tests/tdb.nim (version 3, history, a slice-2 DB migrating to slice 3).
This commit is contained in:
2026-11-15 08:49:16 +01:00
parent 2a1e2dd71c
commit bf9ab3edfd
4 changed files with 649 additions and 4 deletions
+32
View File
@@ -7,6 +7,9 @@
## - One transaction per step: DDL + history row + user_version together. A failing step leaves
## nothing behind; a fully migrated DB is not written to at all (re-open is a no-op).
## - Engine settings: WAL, synchronous=NORMAL (Q12), busy_timeout=5000, foreign_keys=ON.
## Step 3 ("world", M3 slice 4 / #19) creates `scene` and `wall` and seeds the single v1 scene
## (DESIGN 4.4, 8; Q3 FIXED: exactly one scene). Wall ids are per scene and come from
## `scene.next_wall_id`, which never decreases (#3 FIXED).
## One connection, used under the server's global lock (4.3); this module does no locking itself.
import std/[strutils, times]
import db_connector/db_sqlite
@@ -58,6 +61,35 @@ CREATE TABLE session (
last_seen TEXT NOT NULL
)""", """
CREATE INDEX session_player ON session(player_id)"""]),
Migration(version: 3, name: "world", stmts: @["""
CREATE TABLE scene (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
w REAL NOT NULL,
h REAL NOT NULL,
tile_size INTEGER NOT NULL, -- px; == cell in v1 (Q4)
cell INTEGER NOT NULL, -- explored cell px; tile_size % cell == 0
grid_size REAL NOT NULL, -- px; 0 = no grid
vision_radius_default REAL NOT NULL, -- px; also the player step cap (5.5)
token_radius_default REAL NOT NULL, -- px; token size when the token sets none (#4)
art_version INTEGER NOT NULL, -- tiles URL version; 1 in M3 (3.3)
active INTEGER NOT NULL DEFAULT 1,
next_wall_id INTEGER NOT NULL DEFAULT 1, -- monotonic, never reused (#3, 8)
extra TEXT NOT NULL DEFAULT '{}'
)""", """
CREATE TABLE wall (
scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE,
id INTEGER NOT NULL, -- per scene, from next_wall_id (#3, 8)
ax REAL NOT NULL, ay REAL NOT NULL,
bx REAL NOT NULL, by REAL NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')),
open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)),
flags TEXT NOT NULL DEFAULT '{}', -- JSON object, GM-defined, never interpreted
PRIMARY KEY (scene_id, id)
)""", """
INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default,
token_radius_default, art_version, active, next_wall_id, extra)
VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 1, '{}')"""]),
]
LatestVersion* = migrations[^1].version
## Derived, so adding a step cannot leave it stale.
+281
View File
@@ -0,0 +1,281 @@
## 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).
## - `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
type
WallKind* = enum
wkWall = "wall"
wkDoor = "door"
WallRec* = object
id*: int
a*, b*: Vec
kind*: WallKind
open*: bool
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]
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]
# ---------------------------------------------------------------------------------------------------
# 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
# ---------------------------------------------------------------------------------------------------
# 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.
result = rec
if result.kind == wkWall: result.open = 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
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 insertRow(db: DbConn, sceneId: int, w: WallRec) =
db.exec(sql"""INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
sceneId, w.id, w.a.x, w.a.y, w.b.x, w.b.y, $w.kind,
(if w.open: 1 else: 0), flagsText(w.flags))
proc replaceRow(db: DbConn, sceneId: int, w: WallRec) =
db.exec(sql"""UPDATE wall SET ax = ?, ay = ?, bx = ?, by = ?, kind = ?, open = ?, flags = ?
WHERE scene_id = ? AND id = ?""",
w.a.x, w.a.y, w.b.x, w.b.y, $w.kind, (if w.open: 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].kind != wkDoor: 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[7])
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])),
kind: parseEnum[WallKind](row[5]),
open: row[6] == "1",
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, kind, open, 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"))
+34 -4
View File
@@ -38,24 +38,29 @@ suite "migrate":
check migrate(db) == LatestVersion
check LatestVersion == migrations[^1].version
check schemaVersion(db) == LatestVersion
check LatestVersion == 2
check LatestVersion == 3
let rows = appliedMigrations(db)
check rows.len == 2
check rows.len == 3
check rows[0][0] == 1
check rows[0][1] == "meta"
check rows[1][0] == 2
check rows[1][1] == "auth"
check rows[2][0] == 3
check rows[2][1] == "world"
# the steps' own DDL ran: meta and the auth tables exist and are empty
check db.getValue(sql"SELECT count(*) FROM meta") == "0"
check db.getValue(sql"SELECT count(*) FROM player") == "0"
check db.getValue(sql"SELECT count(*) FROM player_key") == "0"
check db.getValue(sql"SELECT count(*) FROM session") == "0"
# step 3 seeds the single v1 scene (Q3) and no walls
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT count(*) FROM wall") == "0"
test "re-open is a no-op: no step applied, history and timestamps untouched":
let d = tmpDir()
block:
let db = openFresh(d)
check migrate(db) == 2
check migrate(db) == 3
close(db)
let db = openFresh(d)
defer:
@@ -64,7 +69,7 @@ suite "migrate":
let before = appliedMigrations(db)
check migrate(db) == 0
check migrate(db) == 0
check schemaVersion(db) == 2
check schemaVersion(db) == 3
check appliedMigrations(db) == before
test "history and user_version must agree":
@@ -118,3 +123,28 @@ suite "migrate":
check appliedMigrations(db).len == 0
# the runner's own bookkeeping table may exist, but the failed step left nothing else
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'meta'") == "1"
test "a slice-2 DB migrates to slice 3: the scene is seeded, players and keys survive":
let d = tmpDir()
let db = openFresh(d)
defer:
close(db)
removeDir(d)
# Bring the DB to step 2 only, exactly as a slice-2 server left it.
db.exec(sql(MigrationHistoryDdl))
for m in migrations[0 ..< 2]:
db.exec(sql"BEGIN")
for stmt in m.stmts: db.exec(sql(stmt))
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, 'x')",
m.version, m.name)
db.exec(sql("PRAGMA user_version = " & $m.version))
db.exec(sql"COMMIT")
db.exec(sql"INSERT INTO player (name, role, colour, created_at) VALUES ('GM', 'gm', '#6b7280', 'x')")
check schemaVersion(db) == 2
check db.getValue(sql"SELECT count(*) FROM sqlite_master WHERE name = 'scene'") == "0"
check migrate(db) == 1 # only step 3 runs
check schemaVersion(db) == 3
check db.getValue(sql"SELECT count(*) FROM scene") == "1"
check db.getValue(sql"SELECT next_wall_id FROM scene WHERE id = 1") == "1"
check db.getValue(sql"SELECT count(*) FROM player WHERE role = 'gm'") == "1"
+302
View File
@@ -0,0 +1,302 @@
## Scene and wall state (#19, DESIGN 3.1, 4.1, 4.4, 6.1, 8): wall validation, the per-scene
## never-reused wall ids, the write-through persistence (synchronous=FULL for authoring) and the
## reload that a restart performs. The wire behaviour over a real socket lives in tools/walls.test.mjs.
import std/[json, options, os, sequtils, unittest]
import db_connector/db_sqlite
import db, world
var tmpCount = 0
proc tmpDir(): string =
inc tmpCount
result = getTempDir() / "ffftworld-" & $getCurrentProcessId() & "-" & $tmpCount
removeDir(result)
createDir(result)
proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec =
WallRec(a: (ax, ay), b: (bx, by), kind: kind, open: open, flags: newJObject())
proc freshScene(): tuple[db: DbConn, dir: string] =
## A migrated DB (the scene row comes from migration step 3) plus the scene loaded into memory.
let d = tmpDir()
let conn = openDatabase(d / "state.db")
discard migrate(conn)
(conn, d)
suite "scene (migration step 3, Q3: exactly one scene)":
test "the migration seeds scene 1 with the v1 defaults, no walls, next_wall_id 1":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
check sceneCount(conn) == 1
let sc = loadScene(conn)
check sc.isSome
let s = sc.get
check s.id == DefaultSceneId
check s.name == "Scene"
check (s.w, s.h) == (4096.0, 4096.0)
check s.tileSize == 32 and s.cell == 32 # Q4 FIXED: tile == explored cell
check s.gridSize == 0 # no grid by default
check s.visionRadiusDefault == 400 # prototype default (5.5 step cap)
check s.tokenRadiusDefault == 20 # #4: scene default token size
check s.artVersion == 1 # M3 always 1 (3.3)
check s.nextWallId == 1
check s.walls.len == 0
check s.extra.kind == JObject
test "an unknown scene id is not there (the wire answers not-found)":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
check loadScene(conn, DefaultSceneId + 1).isNone
check loadScene(conn).isSome
suite "field parsing (6.1 field notes)":
test "a point is exactly two finite numbers, ints included":
check parseVec(%*[10, 20]).get == (10.0, 20.0)
check parseVec(%*[10.5, 20.25]).get == (10.5, 20.25)
check parseVec(%*[10]).isNone
check parseVec(%*[10, 20, 30]).isNone
check parseVec(%*["10", 20]).isNone
check parseVec(%*{"x": 1}).isNone
check parseVec(newJNull()).isNone
check parseVec(nil).isNone
test "kind, open and flags accept only their own shape":
check parseKind("wall").get == wkWall
check parseKind("door").get == wkDoor
check parseKind("window").isNone
check parseKind("").isNone
check parseKind("WALL").isNone
check parseOpen(nil).get == false # omitted = closed
check parseOpen(%true).get == true
check parseOpen(%1).isNone
check parseFlags(nil).get.kind == JObject # omitted = {}
check parseFlags(%*{"a": 1}).get["a"].getInt == 1
check parseFlags(%*[1]).isNone
test "undefined and null are the same as an absent field":
check fieldOrNull(%*{"open": true}, "open").getBool
var withNull = newJObject()
withNull["open"] = newJNull()
check fieldOrNull(withNull, "open").isNil
check fieldOrNull(%*{}, "open").isNil
check fieldOrNull(nil, "open").isNil
suite "wall ids (FIXED #3: per scene, monotonic, never reused)":
test "adds count from 1 and the counter advances":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
check addWall(conn, sc, wall(10, 10, 100, 10)).get == 1
check addWall(conn, sc, wall(10, 20, 100, 20)).get == 2
check addWall(conn, sc, wall(10, 30, 100, 30)).get == 3
check sc.nextWallId == 4
check sc.walls.len == 3
check sc.walls[0].id == 1 and sc.walls[2].id == 3
test "a removal never renumbers and the next add never reuses the id":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
discard addWall(conn, sc, wall(10, 10, 100, 10))
discard addWall(conn, sc, wall(10, 20, 100, 20))
check removeWall(conn, sc, 1) == waOk
check sc.walls.len == 1
check sc.walls[0].id == 2 # no renumbering
check sc.nextWallId == 3 # no decrement
check addWall(conn, sc, wall(10, 30, 100, 30)).get == 3 # not 1
check removeWall(conn, sc, 3) == waOk
check addWall(conn, sc, wall(10, 40, 100, 40)).get == 4
test "the id counter survives a reload, even when the newest wall was removed":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
discard addWall(conn, sc, wall(10, 10, 100, 10))
discard addWall(conn, sc, wall(10, 20, 100, 20))
discard removeWall(conn, sc, 2)
let reloaded = loadScene(conn).get
check reloaded.nextWallId == 3
check reloaded.walls.len == 1
var again = reloaded
check addWall(conn, again, wall(10, 30, 100, 30)).get == 3
suite "persistence (write-through, restart-identical)":
test "add, update, door set and remove round-trip through a reload":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id1 = addWall(conn, sc, WallRec(a: (0, 0), b: (4096, 0), kind: wkWall,
flags: %*{"note": "north"})).get
let id2 = addWall(conn, sc, wall(100, 25, 300, 25, wkDoor)).get
check setDoor(conn, sc, id2, true) == waOk
let changed = WallRec(id: id1, a: (0, 0), b: (2000, 0), kind: wkDoor,
open: false, flags: %*{"note": "north wall"})
check updateWall(conn, sc, changed) == waOk
let reloaded = loadScene(conn).get
check reloaded.walls.len == 2
check reloaded.nextWallId == sc.nextWallId
check reloaded.walls[0].id == id1
check reloaded.walls[0].a == (0.0, 0.0)
check reloaded.walls[0].b == (2000.0, 0.0)
check reloaded.walls[0].kind == wkDoor # kind is updatable
check reloaded.walls[0].open == false
check reloaded.walls[0].flags["note"].getStr == "north wall"
check reloaded.walls[1].id == id2
check reloaded.walls[1].kind == wkDoor
check reloaded.walls[1].open == true # an open door stays open
check reloaded.walls[1].flags.kind == JObject # flags default to {}
check removeWall(conn, sc, id1) == waOk
check loadScene(conn).get.walls.len == 1
check loadScene(conn).get.nextWallId == 3
test "authoring runs with synchronous=FULL and leaves NORMAL behind (Q12)":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
check conn.getValue(sql"PRAGMA synchronous") == "1" # NORMAL from openDatabase
discard addWall(conn, sc, wall(10, 10, 100, 10))
check conn.getValue(sql"PRAGMA synchronous") == "1"
discard setDoor(conn, sc, 1, true) # not a door: no write at all
check conn.getValue(sql"PRAGMA synchronous") == "1"
test "a failing write leaves memory and the pragma alone":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
conn.exec(sql"DROP TABLE wall") # make the INSERT fail inside the transaction
var raised = false
try:
discard addWall(conn, sc, wall(10, 10, 100, 10))
except CatchableError:
raised = true
check raised
check sc.walls.len == 0
check sc.nextWallId == 1
check conn.getValue(sql"PRAGMA synchronous") == "1"
test "walls load in id order whatever the insertion order was":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
for i in 0 ..< 5:
discard addWall(conn, sc, wall(float(i), 0, float(i) + 1, 0))
discard removeWall(conn, sc, 2)
discard addWall(conn, sc, wall(9, 0, 10, 0))
let ids = loadScene(conn).get.walls.mapIt(it.id)
check ids == @[1, 3, 4, 5, 6]
suite "validation (DESIGN 6.1 `wall.*`)":
test "a zero-length wall is invalid and writes nothing":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
check addWall(conn, sc, wall(50, 50, 50, 50)).isNone
check addWall(conn, sc, wall(0.0, 0.0, 0.0, 0.0)).isNone
check sc.walls.len == 0
check sc.nextWallId == 1
test "both endpoints must be inside [0,w] x [0,h]; the border itself is allowed":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
check addWall(conn, sc, wall(-1, 10, 100, 10)).isNone
check addWall(conn, sc, wall(10, 10, 4097, 10)).isNone
check addWall(conn, sc, wall(10, 10.5, 100, 4097)).isNone
check addWall(conn, sc, wall(10, 4100, 100, 4100)).isNone
check addWall(conn, sc, wall(0, 0, 4096, 4096)).isSome # corners, in bounds
check addWall(conn, sc, wall(4096, 4096, 0, 0)).isSome
check sc.walls.len == 2
test "a wall is never open: the stored row normalizes it":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id = addWall(conn, sc, wall(10, 10, 100, 10, wkWall, open = true)).get
check wallById(sc, id).get.open == false
check loadScene(conn).get.walls[0].open == false
test "update keeps the row's id and open flag unless the kind changes":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id = addWall(conn, sc, wall(10, 10, 100, 10, wkDoor)).get
check setDoor(conn, sc, id, true) == waOk
var w = wallById(sc, id).get
w.a = (20.0, 20.0)
check updateWall(conn, sc, w) == waOk
check wallById(sc, id).get.open == true # untouched by update
# door -> wall closes it (a wall is never open)
var back = wallById(sc, id).get
back.kind = wkWall
check updateWall(conn, sc, back) == waOk
check wallById(sc, id).get.open == false
check loadScene(conn).get.walls[0].open == false
test "dot patching: only the given fields change":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id = addWall(conn, sc, wall(10, 10, 100, 10)).get
let before = wallById(sc, id).get
let after = patched(before, WallPatch(b: some((300.0, 400.0))))
check after.a == before.a
check after.b == (300.0, 400.0)
check after.kind == before.kind
check after.flags.kind == JObject
suite "lookup outcomes (main.nim's 6.5 mapping)":
test "unknown ids are not-found, wrong kinds are their own outcome":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
let id = addWall(conn, sc, wall(10, 10, 100, 10)).get
check removeWall(conn, sc, 99) == waNotFound
check updateWall(conn, sc, WallRec(id: 99, a: (0, 0), b: (1, 1))) == waNotFound
check setDoor(conn, sc, 99, true) == waNotFound
check setDoor(conn, sc, id, true) == waNotDoor # a plain wall has no open state
check setDoor(conn, sc, id, false) == waNotDoor
check sc.walls.len == 1
check wallById(sc, 99).isNone
check wallIndex(sc, id).get == 0
test "the first wall of a fresh scene is id 1, not 0":
let (conn, d) = freshScene()
defer:
close(conn)
removeDir(d)
var sc = loadScene(conn).get
check sc.nextWallId == 1
let id = addWall(conn, sc, wall(1, 1, 2, 2)).get
check id == 1
check wallById(sc, 0).isNone