feat(walls): presets, label rule and one switch-set validation path (#55)
wall.add/wall.update now take a preset or raw switches, never both:
resolveWall expands the four 5.8 presets to switches before validating, so
a preset never touches geometry and preset+switch or preset+open is invalid.
A raw create starts from the wall defaults; a raw update patches only the
switches it names and {door:false} closes and de-secrets.
The switch-set invariants are enforced by that one path for add and update:
open/secret/locked without a door, a secret door that is open/one-way/not
opaque, open with secret or locked, and a direction with no sight to block
are all invalid. The DB gains the missing open+locked CHECK as the backstop,
and the now-redundant open/door parity test is gone from the server path.
A wall label is now the 6.5 text rule: trimmed, 1..64 code points, no control
characters, null clears, stored verbatim and GM-only. window/one_way presets
are accepted and expanded to their switch sets per DESIGN 5.8/6.1; their
player-facing behaviour stays with #57/#58.
Tests: WS black-box presets/patch semantics/every refusal/label round-trip;
Nim shape pins for expansion, invariants and the label rule.
Nim 385 / Node 117 green.
This commit is contained in:
@@ -230,6 +230,7 @@ CREATE TABLE wall (
|
||||
CHECK (secret = 0 OR (door = 1 AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1
|
||||
AND sight_dir = 'both')),
|
||||
CHECK (locked = 0 OR door = 1),
|
||||
CHECK (open = 0 OR locked = 0),
|
||||
CHECK (sight_dir = 'both' OR blocks_sight = 1)
|
||||
)""", """
|
||||
INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, blocks_sight,
|
||||
|
||||
+66
-61
@@ -520,8 +520,8 @@ proc parseWallGeometry(env: Envelope, rec: var WallRec): bool =
|
||||
|
||||
proc parseWallLabel(env: Envelope, rec: var WallRec): bool =
|
||||
## `label` absent leaves it alone on an update (the caller seeds `rec` from the stored row);
|
||||
## an explicit null clears it; anything but a string is `invalid`. The 6.5 text rule is #55,
|
||||
## but the schema's 1..64 bound is enforced by `validWall` so SQLite cannot raise.
|
||||
## an explicit null clears it; anything but a string is `invalid`. The 6.5 text rule (trimmed,
|
||||
## 1..64 code points, no control characters) is enforced by `validWall` before the write (#55).
|
||||
if not declared(env, "label"): return true
|
||||
let node = env.node{"label"}
|
||||
if node.kind == JNull:
|
||||
@@ -532,32 +532,47 @@ proc parseWallLabel(env: Envelope, rec: var WallRec): bool =
|
||||
return false
|
||||
true
|
||||
|
||||
proc parseWallSwitch(env: Envelope, key: string, dest: var bool): bool =
|
||||
## One boolean switch: absent = leave `dest`; a non-boolean is `invalid`.
|
||||
if not present(env, key): return true
|
||||
boolField(env, key, dest)
|
||||
proc parseWallPreset(env: Envelope, dest: var Option[Preset]): bool =
|
||||
## `preset` is a 5.8 name, never JSON null; anything else is `invalid`.
|
||||
if not declared(env, "preset"): return true
|
||||
let node = env.node{"preset"}
|
||||
if node.kind != JString: return false
|
||||
let p = parsePreset(node.getStr)
|
||||
if p.isNone: return false
|
||||
dest = p
|
||||
true
|
||||
|
||||
proc parseWallSwitches(env: Envelope, rec: var WallRec, allowOpen: bool): bool =
|
||||
## The raw 5.8 switches on a create: omitted switches keep the candidate's value (the `wall`
|
||||
## defaults), `open` is accepted here. A `sight_dir` outside the three words is `invalid`.
|
||||
if not parseWallSwitch(env, "blocks_sight", rec.blocksSight): return false
|
||||
if not parseWallSwitch(env, "blocks_movement", rec.blocksMovement): return false
|
||||
if not parseWallSwitch(env, "player_marker", rec.playerMarker): return false
|
||||
if not parseWallSwitch(env, "door", rec.door): return false
|
||||
if allowOpen and not parseWallSwitch(env, "open", rec.open): return false
|
||||
if not parseWallSwitch(env, "secret", rec.secret): return false
|
||||
if not parseWallSwitch(env, "locked", rec.locked): return false
|
||||
proc parseWallSwitch(env: Envelope, key: string, dest: var Option[bool]): bool =
|
||||
## One raw switch: absent = not patched; a non-boolean is `invalid`.
|
||||
if not present(env, key): return true
|
||||
var bit: bool
|
||||
if not boolField(env, key, bit): return false
|
||||
dest = some(bit)
|
||||
true
|
||||
|
||||
proc parseWallSwitches(env: Envelope, sw: var WallSwitches, allowOpen: bool): bool =
|
||||
## Collects the raw 5.8 switches the payload names. `open` is collected only on a create; in an
|
||||
## update it is an unknown field and is ignored (`door.set` owns it, DESIGN 6.1).
|
||||
if not parseWallSwitch(env, "blocks_sight", sw.blocksSight): return false
|
||||
if not parseWallSwitch(env, "blocks_movement", sw.blocksMovement): return false
|
||||
if not parseWallSwitch(env, "player_marker", sw.playerMarker): return false
|
||||
if not parseWallSwitch(env, "door", sw.door): return false
|
||||
if allowOpen and not parseWallSwitch(env, "open", sw.open): return false
|
||||
if not parseWallSwitch(env, "secret", sw.secret): return false
|
||||
if not parseWallSwitch(env, "locked", sw.locked): return false
|
||||
if present(env, "sight_dir"):
|
||||
let node = env.node{"sight_dir"}
|
||||
if node.kind != JString: return false
|
||||
let d = parseSightDir(node.getStr)
|
||||
if d.isNone: return false
|
||||
rec.sightDir = d.get
|
||||
sw.sightDir = d
|
||||
true
|
||||
|
||||
proc parseWallPatch(env: Envelope, patch: var WallPatch): bool =
|
||||
## `wall.update` names only the fields it patches. `open` and `kind` are unknown here and are
|
||||
## ignored: a door's open state changes only through `door.set` (DESIGN 6.1, #54).
|
||||
## ignored: a door's open state changes only through `door.set` (DESIGN 6.1, #54). A preset
|
||||
## replaces the whole switch set and may not appear with any raw switch, `open` included (#55).
|
||||
if not parseWallPreset(env, patch.preset): return false
|
||||
if present(env, "a"):
|
||||
let v = parseVec(env.node{"a"})
|
||||
if v.isNone: return false
|
||||
@@ -592,31 +607,11 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool =
|
||||
patch.label = some(node.getStr)
|
||||
else:
|
||||
return false
|
||||
var bit: bool
|
||||
if present(env, "blocks_sight"):
|
||||
if not boolField(env, "blocks_sight", bit): return false
|
||||
patch.blocksSight = some(bit)
|
||||
if present(env, "blocks_movement"):
|
||||
if not boolField(env, "blocks_movement", bit): return false
|
||||
patch.blocksMovement = some(bit)
|
||||
if present(env, "player_marker"):
|
||||
if not boolField(env, "player_marker", bit): return false
|
||||
patch.playerMarker = some(bit)
|
||||
if present(env, "door"):
|
||||
if not boolField(env, "door", bit): return false
|
||||
patch.door = some(bit)
|
||||
if present(env, "secret"):
|
||||
if not boolField(env, "secret", bit): return false
|
||||
patch.secret = some(bit)
|
||||
if present(env, "locked"):
|
||||
if not boolField(env, "locked", bit): return false
|
||||
patch.locked = some(bit)
|
||||
if present(env, "sight_dir"):
|
||||
let node = env.node{"sight_dir"}
|
||||
if node.kind != JString: return false
|
||||
let d = parseSightDir(node.getStr)
|
||||
if d.isNone: return false
|
||||
patch.sightDir = d
|
||||
if not parseWallSwitches(env, patch.switches, false): return false
|
||||
if patch.preset.isSome and (patch.switches.hasAnySwitch or declared(env, "open")):
|
||||
# preset xor raw switches; an `open` field alongside a preset is `invalid` even though open is
|
||||
# otherwise an ignored unknown field on an update (DESIGN 6.1, #55).
|
||||
return false
|
||||
if present(env, "flags"):
|
||||
let f = parseFlags(env.node{"flags"})
|
||||
if f.isNone: return false
|
||||
@@ -626,9 +621,7 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool =
|
||||
proc wallPatchHasField(patch: WallPatch): bool =
|
||||
patch.a.isSome or patch.b.isSome or patch.thickness.isSome or patch.position.isSome or
|
||||
patch.height.isSome or patch.clearHeight or patch.label.isSome or patch.clearLabel or
|
||||
patch.blocksSight.isSome or patch.blocksMovement.isSome or patch.sightDir.isSome or
|
||||
patch.playerMarker.isSome or patch.door.isSome or patch.secret.isSome or patch.locked.isSome or
|
||||
patch.flags.isSome
|
||||
patch.preset.isSome or patch.switches.hasAnySwitch or patch.flags.isSome
|
||||
|
||||
type
|
||||
ControllerCheck = enum
|
||||
@@ -2043,12 +2036,20 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
if a.isNone or b.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
# The raw-switch create: omitted switches keep the `wall` preset's defaults (DESIGN 6.1, #54).
|
||||
# A raw-switch create starts from the `wall` defaults; a preset replaces the switch set. Both
|
||||
# go through the same expand-and-validate path (DESIGN 6.1, #55).
|
||||
var candidate = defaultWall(a.get, b.get)
|
||||
if not parseWallGeometry(env, candidate) or not parseWallSwitches(env, candidate, true) or
|
||||
not parseWallLabel(env, candidate):
|
||||
var preset: Option[Preset]
|
||||
var switches: WallSwitches
|
||||
if not parseWallGeometry(env, candidate) or not parseWallPreset(env, preset) or
|
||||
not parseWallSwitches(env, switches, true) or not parseWallLabel(env, candidate):
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
let resolved = resolveWall(candidate, preset, switches)
|
||||
if resolved.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
return
|
||||
candidate = resolved.get
|
||||
let flags = parseFlags(fieldOrNull(env.node, "flags"))
|
||||
if flags.isNone:
|
||||
ackErr(conn, env.reqId, CodeInvalid)
|
||||
@@ -2118,18 +2119,22 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
|
||||
# `wall.update` = remove then add for the status rules (5.5): the rules run on the snapshot
|
||||
# with the patched wall at the same index, so a move away clears and a move onto a token sticks.
|
||||
let idx = wallIndex(app.scene, id).get
|
||||
var mr = moveScene(app.scene, app.tokens)
|
||||
outcome = updateWall(app.db, app.scene, patched(current.get, storedPatch))
|
||||
if outcome == waOk:
|
||||
let updated = wallById(app.scene, id)
|
||||
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
updatedKind = derivedKind(updated.get)
|
||||
# Frame and record copy both live and die inside this lock (ANALYSIS 4.1).
|
||||
settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get)))
|
||||
ok = true
|
||||
let candidate = patched(current.get, storedPatch)
|
||||
if candidate.isNone:
|
||||
outcome = waInvalid # an impossible resulting switch set (5.8)
|
||||
else:
|
||||
var mr = moveScene(app.scene, app.tokens)
|
||||
outcome = updateWall(app.db, app.scene, candidate.get)
|
||||
if outcome == waOk:
|
||||
let updated = wallById(app.scene, id)
|
||||
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
|
||||
discard applyRuleOutcome(mr)
|
||||
refreshAll()
|
||||
persistAllExplored()
|
||||
updatedKind = derivedKind(updated.get)
|
||||
# Frame and record copy both live and die inside this lock (ANALYSIS 4.1).
|
||||
settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get)))
|
||||
ok = true
|
||||
if outcome == waNotFound:
|
||||
ackErr(conn, env.reqId, CodeNotFound)
|
||||
return
|
||||
|
||||
+134
-45
@@ -16,8 +16,10 @@
|
||||
## - `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`: the geometry fields and the eight raw switches of 6.1; an omitted switch keeps
|
||||
## the `wall` default, `open` omitted = false, and a non-door never stores door-only settings.
|
||||
## - `wall.add`/`wall.update`: either a 5.8 preset or raw switches, never both; `resolveWall` is
|
||||
## the one expand-and-validate path, so a preset never touches geometry and an impossible
|
||||
## switch set is `invalid` at every entry point. A raw create starts from the `wall` defaults;
|
||||
## a raw update patches only the switches it names; `{door:false}` closes and de-secrets.
|
||||
## - `wall.update` patches only what it names (geometry, the switches except `open`, `label`,
|
||||
## `flags`); `open` belongs to `door.set`, so an `open` field here is an unknown field and is
|
||||
## ignored, and at least one patch field is required, else `invalid`.
|
||||
@@ -28,7 +30,7 @@
|
||||
## 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, unicode]
|
||||
import std/[json, math, options, strutils]
|
||||
import db_connector/db_sqlite
|
||||
import geometry, text
|
||||
|
||||
@@ -43,6 +45,23 @@ type
|
||||
sdLeft = "left"
|
||||
sdRight = "right"
|
||||
|
||||
Preset* = enum
|
||||
## The four 5.8 presets. A preset is a named switch set, never storage: `expandPreset` turns it
|
||||
## into switches before the one validation path runs (DESIGN 5.8, 6.1).
|
||||
pwWall = "wall"
|
||||
pwDoor = "door"
|
||||
pwWindow = "window"
|
||||
pwOneWay = "one_way"
|
||||
|
||||
WallSwitches* = object
|
||||
## The raw switches a payload names. A field that is `none` is not patched, which is what makes
|
||||
## a raw-switch `wall.update` patch-only and a raw-switch `wall.add` start from the `wall`
|
||||
## defaults (DESIGN 6.1). `open` is collected only for `wall.add`; on an update it is an
|
||||
## unknown field and `door.set` owns it.
|
||||
blocksSight*, blocksMovement*, playerMarker*: Option[bool]
|
||||
door*, open*, secret*, locked*: Option[bool]
|
||||
sightDir*: Option[SightDir]
|
||||
|
||||
WallRec* = object
|
||||
## The typed wall record of DESIGN 8. Every field is a column; `kind` is never stored and is
|
||||
## derived from the switches (`derivedKind`) for the GM's frames (#54).
|
||||
@@ -90,9 +109,8 @@ type
|
||||
clearHeight*: bool
|
||||
label*: Option[string]
|
||||
clearLabel*: bool
|
||||
blocksSight*, blocksMovement*: Option[bool]
|
||||
sightDir*: Option[SightDir]
|
||||
playerMarker*, door*, secret*, locked*: Option[bool]
|
||||
preset*: Option[Preset] ## replaces the whole switch set; never with a raw switch
|
||||
switches*: WallSwitches ## the raw switches present; patches only those
|
||||
flags*: Option[JsonNode]
|
||||
|
||||
ScenePatch* = object
|
||||
@@ -114,8 +132,11 @@ const
|
||||
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
|
||||
WallPositions* = [wpCenter, wpLeft, wpRight]
|
||||
SightDirs* = [sdBoth, sdLeft, sdRight]
|
||||
Presets* = [pwWall, pwDoor, pwWindow, pwOneWay]
|
||||
SceneNameMaxLen* = 64
|
||||
## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25).
|
||||
WallLabelMaxLen* = 64
|
||||
## `wall.label`: the 6.5 text rule, 1..64 code points, trimmed, no control characters (#55).
|
||||
|
||||
proc defaultWall*(a, b: Vec): WallRec =
|
||||
## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings,
|
||||
@@ -137,6 +158,87 @@ proc derivedKind*(w: WallRec): string =
|
||||
else:
|
||||
"custom"
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55)
|
||||
|
||||
proc storable*(rec: WallRec): bool =
|
||||
## The switch-set invariants of DESIGN 5.8, mirrored by the database CHECKs of db.nim step 8.
|
||||
## The caller has already resolved presets and raw patches; this is the last semantic gate
|
||||
## before SQLite (which stays the backstop for a write that bypasses the server).
|
||||
# `open` without `door` cannot survive the resolve/normalize path (a named `open:true` is refused
|
||||
# and a cleared `door` closes the row), so the parity rule lives in the DB CHECK alone.
|
||||
if rec.secret and not rec.door: return false
|
||||
if rec.locked and not rec.door: return false
|
||||
if rec.secret and (rec.open or not rec.blocksSight or not rec.blocksMovement or
|
||||
rec.sightDir != sdBoth): return false
|
||||
if rec.open and (rec.secret or rec.locked): return false
|
||||
if rec.sightDir != sdBoth and not rec.blocksSight: return false
|
||||
true
|
||||
|
||||
proc hasAnySwitch*(sw: WallSwitches): bool =
|
||||
## True when the payload named any raw switch (a preset may not appear with one).
|
||||
sw.blocksSight.isSome or sw.blocksMovement.isSome or sw.playerMarker.isSome or
|
||||
sw.door.isSome or sw.open.isSome or sw.secret.isSome or sw.locked.isSome or
|
||||
sw.sightDir.isSome
|
||||
|
||||
proc expandPreset*(base: WallRec, preset: Preset): WallRec =
|
||||
## A preset replaces the whole switch set and touches nothing else: `a`, `b`, thickness,
|
||||
## position, height, label and flags are the base's (DESIGN 5.8 table, 6.1). `window` is the
|
||||
## opening window (door set, closed) with the marker on; the fixed window is `door` turned off.
|
||||
result = base
|
||||
case preset
|
||||
of pwWall, pwDoor:
|
||||
result.blocksSight = true
|
||||
result.blocksMovement = true
|
||||
result.sightDir = sdBoth
|
||||
of pwWindow:
|
||||
result.blocksSight = false
|
||||
result.blocksMovement = true
|
||||
result.sightDir = sdBoth
|
||||
of pwOneWay:
|
||||
result.blocksSight = true
|
||||
result.blocksMovement = true
|
||||
result.sightDir = sdLeft
|
||||
result.playerMarker = preset == pwWindow
|
||||
result.door = preset in {pwDoor, pwWindow}
|
||||
result.open = false
|
||||
result.secret = false
|
||||
result.locked = false
|
||||
|
||||
proc applySwitches(base: WallRec, sw: WallSwitches): Option[WallRec] =
|
||||
## A raw-switch write patches only the switches it names. A door-only switch set to true on a
|
||||
## non-door is `invalid` (never silently dropped); when the write clears `door`, inherited
|
||||
## door-only settings are closed and de-secreted (DESIGN 5.8, 6.1).
|
||||
var r = base
|
||||
if sw.blocksSight.isSome: r.blocksSight = sw.blocksSight.get
|
||||
if sw.blocksMovement.isSome: r.blocksMovement = sw.blocksMovement.get
|
||||
if sw.playerMarker.isSome: r.playerMarker = sw.playerMarker.get
|
||||
if sw.door.isSome: r.door = sw.door.get
|
||||
if sw.open.isSome: r.open = sw.open.get
|
||||
if sw.secret.isSome: r.secret = sw.secret.get
|
||||
if sw.locked.isSome: r.locked = sw.locked.get
|
||||
if sw.sightDir.isSome: r.sightDir = sw.sightDir.get
|
||||
if not r.door:
|
||||
if sw.open == some(true) or sw.secret == some(true) or sw.locked == some(true):
|
||||
return none(WallRec)
|
||||
r.open = false
|
||||
r.secret = false
|
||||
r.locked = false
|
||||
some(r)
|
||||
|
||||
proc resolveWall*(base: WallRec, preset: Option[Preset],
|
||||
sw: WallSwitches): Option[WallRec] =
|
||||
## THE single path shared by `wall.add`, `wall.update` and the future UVTT importer: a preset is
|
||||
## expanded before validation and may not appear with any raw switch; raw switches patch the
|
||||
## base; the resulting switch set is then checked by `storable`. Geometry, height and label are
|
||||
## validated by `validWall`; a preset never touches them (DESIGN 5.8, 6.1 FIXED #49/#55).
|
||||
if preset.isSome:
|
||||
if sw.hasAnySwitch: return none(WallRec)
|
||||
result = some(expandPreset(base, preset.get))
|
||||
else:
|
||||
result = applySwitches(base, sw)
|
||||
if result.isSome and not storable(result.get): result = none(WallRec)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
|
||||
|
||||
@@ -148,6 +250,10 @@ proc parseSightDir*(raw: string): Option[SightDir] =
|
||||
for d in SightDirs:
|
||||
if $d == raw: return some(d)
|
||||
|
||||
proc parsePreset*(raw: string): Option[Preset] =
|
||||
for p in Presets:
|
||||
if $p == raw: return some(p)
|
||||
|
||||
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)
|
||||
@@ -240,27 +346,14 @@ proc patched*(sc: SceneRec, patch: ScenePatch): SceneRec =
|
||||
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 storable*(rec: WallRec): bool =
|
||||
## The subset of the switch-set invariants the database CHECKs already enforce (db.nim step 8).
|
||||
## #54 accepts and stores the raw switches; this test keeps a payload the schema cannot store from
|
||||
## reaching SQLite and raising. The full expand-and-validate path, presets and the remaining
|
||||
## switch-set rules are #55.
|
||||
if rec.open and not rec.door: return false
|
||||
if rec.secret and not rec.door: return false
|
||||
if rec.secret and (rec.open or not rec.blocksSight or not rec.blocksMovement or
|
||||
rec.sightDir != sdBoth): return false
|
||||
if rec.locked and not rec.door: return false
|
||||
if rec.sightDir != sdBoth and not rec.blocksSight: return false
|
||||
true
|
||||
|
||||
proc validWall*(sc: SceneRec, rec: WallRec): bool =
|
||||
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds, the geometry ranges and a
|
||||
## switch set the schema can store. `flags` is checked by the parser, so a `WallRec` can only
|
||||
## carry a valid one.
|
||||
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds, the geometry ranges, the
|
||||
## 6.5 text rule for `label` and a switch set the schema can store. `flags` is checked by the
|
||||
## parser, so a `WallRec` can only carry a valid one.
|
||||
(rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b) and
|
||||
rec.thickness >= 0 and rec.thickness <= 256 and
|
||||
(rec.height.isNone or (rec.height.get > 0 and rec.height.get <= 100)) and
|
||||
(rec.label.isNone or (rec.label.get.runeLen >= 1 and rec.label.get.runeLen <= 64)) and
|
||||
(rec.label.isNone or validText(rec.label.get, WallLabelMaxLen)) and
|
||||
storable(rec)
|
||||
|
||||
proc normalize*(rec: WallRec): WallRec =
|
||||
@@ -281,28 +374,24 @@ 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. A patch is absolute and only
|
||||
## touches what it names; `open` is never here (door.set owns it). `clearHeight`/`clearLabel` are
|
||||
## an explicit null, distinct from an absent field.
|
||||
result = w
|
||||
if patch.a.isSome: result.a = patch.a.get
|
||||
if patch.b.isSome: result.b = patch.b.get
|
||||
if patch.thickness.isSome: result.thickness = patch.thickness.get
|
||||
if patch.position.isSome: result.position = patch.position.get
|
||||
if patch.clearHeight: result.height = none(float)
|
||||
elif patch.height.isSome: result.height = patch.height
|
||||
if patch.clearLabel: result.label = none(string)
|
||||
elif patch.label.isSome: result.label = patch.label
|
||||
if patch.blocksSight.isSome: result.blocksSight = patch.blocksSight.get
|
||||
if patch.blocksMovement.isSome: result.blocksMovement = patch.blocksMovement.get
|
||||
if patch.sightDir.isSome: result.sightDir = patch.sightDir.get
|
||||
if patch.playerMarker.isSome: result.playerMarker = patch.playerMarker.get
|
||||
if patch.door.isSome: result.door = patch.door.get
|
||||
if patch.secret.isSome: result.secret = patch.secret.get
|
||||
if patch.locked.isSome: result.locked = patch.locked.get
|
||||
if patch.flags.isSome: result.flags = patch.flags.get
|
||||
result = normalize(result)
|
||||
proc patched*(w: WallRec, patch: WallPatch): Option[WallRec] =
|
||||
## `wall.update` candidate: the stored row with the patch applied and validated by the same path
|
||||
## as `wall.add`. A patch is absolute and only touches what it names; `open` is never here
|
||||
## (door.set owns it). `clearHeight`/`clearLabel` are an explicit null, distinct from an absent
|
||||
## field. `none` means the resulting switch set is forbidden (DESIGN 5.8, 6.1).
|
||||
var base = w
|
||||
if patch.a.isSome: base.a = patch.a.get
|
||||
if patch.b.isSome: base.b = patch.b.get
|
||||
if patch.thickness.isSome: base.thickness = patch.thickness.get
|
||||
if patch.position.isSome: base.position = patch.position.get
|
||||
if patch.clearHeight: base.height = none(float)
|
||||
elif patch.height.isSome: base.height = patch.height
|
||||
if patch.clearLabel: base.label = none(string)
|
||||
elif patch.label.isSome: base.label = patch.label
|
||||
if patch.flags.isSome: base.flags = patch.flags.get
|
||||
result = resolveWall(base, patch.preset, patch.switches)
|
||||
if result.isSome:
|
||||
result = some(normalize(result.get))
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Persistence (write-through, synchronous=FULL around the transaction, Q12)
|
||||
|
||||
+60
-1
@@ -276,6 +276,65 @@ suite "validation (DESIGN 6.1 `wall.*`)":
|
||||
check addWall(conn, sc, wall(4096, 4096, 0, 0)).isSome
|
||||
check sc.walls.len == 2
|
||||
|
||||
test "presets expand to switches only through the one resolve path (#55)":
|
||||
let base = defaultWall((0.0, 0.0), (10.0, 0.0))
|
||||
var sized = base
|
||||
sized.thickness = 12
|
||||
sized.position = wpLeft
|
||||
sized.height = some(3.0)
|
||||
sized.label = some("railing")
|
||||
check parsePreset("wall").get == pwWall
|
||||
check parsePreset("one_way").get == pwOneWay
|
||||
check parsePreset("terrain").isNone
|
||||
let window = resolveWall(sized, some(pwWindow), WallSwitches()).get
|
||||
check not window.blocksSight and window.blocksMovement
|
||||
check window.door and not window.open and window.playerMarker
|
||||
check window.thickness == 12 and window.position == wpLeft and window.height == some(3.0)
|
||||
check window.label == some("railing") # a preset never touches non-switch fields
|
||||
let oneWay = resolveWall(sized, some(pwOneWay), WallSwitches()).get
|
||||
check oneWay.sightDir == sdLeft and oneWay.blocksSight and not oneWay.door
|
||||
# preset xor raw switches: even a switch equal to the expansion is a mix
|
||||
check resolveWall(sized, some(pwDoor), WallSwitches(blocksSight: some(true))).isNone
|
||||
check resolveWall(sized, some(pwDoor), WallSwitches(open: some(true))).isNone
|
||||
|
||||
test "the switch-set invariants reject door-only settings on a non-door (#55)":
|
||||
let plain = defaultWall((0.0, 0.0), (10.0, 0.0))
|
||||
check resolveWall(plain, none(Preset), WallSwitches(open: some(true))).isNone
|
||||
check resolveWall(plain, none(Preset), WallSwitches(secret: some(true))).isNone
|
||||
check resolveWall(plain, none(Preset), WallSwitches(locked: some(true))).isNone
|
||||
check resolveWall(plain, none(Preset), WallSwitches(secret: some(false))).isSome
|
||||
# clearing door closes and de-secrets, but naming a true door-only switch with it is invalid
|
||||
var secretDoor = plain
|
||||
secretDoor.door = true
|
||||
secretDoor.secret = true
|
||||
let closed = resolveWall(secretDoor, none(Preset), WallSwitches(door: some(false))).get
|
||||
check not closed.door and not closed.open and not closed.secret and not closed.locked
|
||||
check resolveWall(secretDoor, none(Preset),
|
||||
WallSwitches(door: some(false), secret: some(true))).isNone
|
||||
# open excludes secret and locked; a direction needs sight to block
|
||||
var lockedDoor = plain
|
||||
lockedDoor.door = true
|
||||
lockedDoor.locked = true
|
||||
check resolveWall(lockedDoor, none(Preset), WallSwitches(open: some(true))).isNone
|
||||
check resolveWall(plain, none(Preset),
|
||||
WallSwitches(blocksSight: some(false), sightDir: some(sdLeft))).isNone
|
||||
|
||||
test "a label is 1..64 code points, trimmed and free of control characters (#55)":
|
||||
let (conn, d) = freshScene()
|
||||
defer:
|
||||
close(conn)
|
||||
removeDir(d)
|
||||
var sc = loadScene(conn).get
|
||||
var w = defaultWall((10.0, 10.0), (100.0, 10.0))
|
||||
w.label = some("x")
|
||||
check addWall(conn, sc, w).isSome
|
||||
w.label = some("é".repeat(64)) # code points, not bytes
|
||||
check addWall(conn, sc, w).isSome
|
||||
for bad in ["", " x", "x ", "x\ty", "x\u007fy", " ".repeat(3), "x".repeat(65)]:
|
||||
w.label = some(bad)
|
||||
check addWall(conn, sc, w).isNone
|
||||
check sc.walls.len == 2
|
||||
|
||||
test "a wall is never open: the stored row normalizes it":
|
||||
let (conn, d) = freshScene()
|
||||
defer:
|
||||
@@ -313,7 +372,7 @@ suite "validation (DESIGN 6.1 `wall.*`)":
|
||||
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))))
|
||||
let after = patched(before, WallPatch(b: some((300.0, 400.0)))).get
|
||||
check after.a == before.a
|
||||
check after.b == (300.0, 400.0)
|
||||
check after.door == before.door
|
||||
|
||||
@@ -193,6 +193,249 @@ test('wall.update: patches only what it names; open and kind are unknown fields'
|
||||
})
|
||||
})
|
||||
|
||||
test('presets expand server-side to switches only; preset xor raw switches (#55)', async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
// The four 5.8 presets: each sets only switches, and the derived kind follows the expansion.
|
||||
const cases = [
|
||||
['wall', { blocks_sight: true, blocks_movement: true, sight_dir: 'both',
|
||||
player_marker: false, door: false, open: false, secret: false, locked: false },
|
||||
'wall'],
|
||||
['door', { blocks_sight: true, blocks_movement: true, sight_dir: 'both',
|
||||
player_marker: false, door: true, open: false, secret: false, locked: false },
|
||||
'door'],
|
||||
['window', { blocks_sight: false, blocks_movement: true, sight_dir: 'both',
|
||||
player_marker: true, door: true, open: false, secret: false, locked: false },
|
||||
'window'],
|
||||
['one_way', { blocks_sight: true, blocks_movement: true, sight_dir: 'left',
|
||||
player_marker: false, door: false, open: false, secret: false, locked: false },
|
||||
'one_way'],
|
||||
]
|
||||
for (const [preset, switches, kind] of cases) {
|
||||
const ack = await addWall(gm, { a: [10, 10], b: [300, 10], preset })
|
||||
assert.equal(ack.ok, true, preset)
|
||||
const wall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === ack.id)
|
||||
for (const [key, value] of Object.entries(switches)) {
|
||||
assert.equal(wall[key], value, `${preset}: ${key}`)
|
||||
}
|
||||
assert.equal(wall.kind, kind, preset)
|
||||
}
|
||||
|
||||
// a preset never implies or resets thickness, position or height
|
||||
const thick = await addWall(gm, { a: [10, 20], b: [300, 20], preset: 'door',
|
||||
thickness: 20, position: 'left', height: 3.5,
|
||||
label: 'west door' })
|
||||
assert.equal(thick.ok, true)
|
||||
const thickWall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === thick.id)
|
||||
assert.equal(thickWall.thickness, 20)
|
||||
assert.equal(thickWall.position, 'left')
|
||||
assert.equal(thickWall.height, 3.5)
|
||||
assert.equal(thickWall.label, 'west door')
|
||||
|
||||
// preset or raw switches, never both (open counts as a raw switch)
|
||||
const both = [
|
||||
{ preset: 'door', blocks_sight: false },
|
||||
{ preset: 'wall', player_marker: true },
|
||||
{ preset: 'door', open: true },
|
||||
{ preset: 'door', open: false },
|
||||
{ preset: 'window', sight_dir: 'left' },
|
||||
]
|
||||
for (const fields of both) {
|
||||
const ack = await addWall(gm, { a: [1, 1], b: [2, 2], ...fields })
|
||||
assert.equal(ack.ok, false, JSON.stringify(fields))
|
||||
assert.equal(ack.code, 'invalid', JSON.stringify(fields))
|
||||
}
|
||||
assert.equal((await addWall(gm, { a: [1, 1], b: [2, 2], preset: 'terrain' })).code,
|
||||
'invalid', 'an unknown preset name is invalid')
|
||||
|
||||
// a raw create starts from the `wall` preset's switch defaults
|
||||
const raw = await addWall(gm, { a: [10, 40], b: [300, 40], blocks_sight: false })
|
||||
const rawWall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === raw.id)
|
||||
assert.equal(rawWall.kind, 'window')
|
||||
assert.equal(rawWall.door, false)
|
||||
assert.equal(rawWall.player_marker, false, 'only the window preset turns the marker on')
|
||||
assert.equal(rawWall.sight_dir, 'both')
|
||||
assert.equal(rawWall.blocks_movement, true)
|
||||
gm.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('wall.update presets replace the whole switch set and raw patches only named switches (#55)',
|
||||
async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
const { id } = await addWall(gm, { a: [10, 10], b: [300, 10], thickness: 16,
|
||||
position: 'right', height: 2 })
|
||||
await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id)
|
||||
|
||||
// a raw patch names one switch and leaves the rest alone
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id,
|
||||
blocks_sight: false })).ok, true)
|
||||
const rawPatched = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id &&
|
||||
m.blocks_sight === false)
|
||||
assert.equal(rawPatched.blocks_movement, true)
|
||||
assert.equal(rawPatched.door, false)
|
||||
assert.equal(rawPatched.kind, 'window')
|
||||
|
||||
// a preset replaces the whole switch set but keeps geometry
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id,
|
||||
preset: 'door' })).ok, true)
|
||||
const asDoor = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && m.door === true)
|
||||
assert.equal(asDoor.blocks_sight, true)
|
||||
assert.equal(asDoor.blocks_movement, true)
|
||||
assert.equal(asDoor.player_marker, false)
|
||||
assert.equal(asDoor.open, false)
|
||||
assert.equal(asDoor.kind, 'door')
|
||||
assert.equal(asDoor.thickness, 16, 'a preset never resets geometry')
|
||||
assert.equal(asDoor.position, 'right')
|
||||
assert.equal(asDoor.height, 2)
|
||||
|
||||
// the window preset turns its marker on and is a closed opening window
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id,
|
||||
preset: 'window' })).ok, true)
|
||||
const asWindow = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id &&
|
||||
m.blocks_sight === false &&
|
||||
m.player_marker === true)
|
||||
assert.equal(asWindow.door, true)
|
||||
assert.equal(asWindow.player_marker, true)
|
||||
assert.equal(asWindow.kind, 'window')
|
||||
|
||||
// preset xor raw switches in an update too
|
||||
for (const fields of [{ preset: 'wall', door: true },
|
||||
{ preset: 'one_way', blocks_sight: false },
|
||||
{ preset: 'door', open: true },
|
||||
{ preset: 'door', open: false }]) {
|
||||
const ack = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, ...fields })
|
||||
assert.equal(ack.ok, false, JSON.stringify(fields))
|
||||
assert.equal(ack.code, 'invalid', JSON.stringify(fields))
|
||||
}
|
||||
|
||||
// a fieldless update is invalid whatever the id, before the lookup (6.1, 6.5 steps 7 then 8)
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: 99 })).code,
|
||||
'invalid')
|
||||
gm.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('switch-set invariants: door-only settings need a door, and open excludes secret/locked (#55)',
|
||||
async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
const invalid = [
|
||||
{ open: true }, // open without door
|
||||
{ secret: true }, // secret without door
|
||||
{ locked: true }, // locked without door
|
||||
{ open: true, secret: true },
|
||||
{ open: true, locked: true, door: true }, // an open door is never locked
|
||||
{ door: true, secret: true, open: true },
|
||||
{ door: true, secret: true, sight_dir: 'left' }, // a secret door is two-way
|
||||
{ door: true, secret: true, blocks_sight: false }, // a secret door is opaque
|
||||
{ door: true, secret: true, blocks_movement: false },
|
||||
{ door: true, locked: true, open: true },
|
||||
]
|
||||
for (const fields of invalid) {
|
||||
const ack = await addWall(gm, { a: [10, 10], b: [20, 20], ...fields })
|
||||
assert.equal(ack.ok, false, JSON.stringify(fields))
|
||||
assert.equal(ack.code, 'invalid', JSON.stringify(fields))
|
||||
}
|
||||
|
||||
// valid door settings: a closed secret+locked door is allowed; so is a locked window
|
||||
const secret = await addWall(gm, { a: [40, 40], b: [80, 40], door: true, secret: true,
|
||||
locked: true })
|
||||
assert.equal(secret.ok, true)
|
||||
await wallEffect(gm.ws, m => m.t === 'wall' && m.id === secret.id)
|
||||
const windowLocked = await addWall(gm, { a: [40, 60], b: [80, 60], preset: 'window',
|
||||
locked: true })
|
||||
assert.equal(windowLocked.ok, false, 'preset xor raw: locked alongside window is refused')
|
||||
const windowLockedRaw = await addWall(gm, { a: [40, 60], b: [80, 60],
|
||||
blocks_sight: false, door: true,
|
||||
locked: true })
|
||||
assert.equal(windowLockedRaw.ok, true)
|
||||
const lockedWindow = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === windowLockedRaw.id)
|
||||
assert.equal(lockedWindow.kind, 'window')
|
||||
assert.equal(lockedWindow.locked, true)
|
||||
|
||||
// raw switches on a non-door are refused, not silently dropped
|
||||
const plain = await addWall(gm, { a: [100, 100], b: [200, 100] })
|
||||
await wallEffect(gm.ws, m => m.t === 'wall' && m.id === plain.id)
|
||||
for (const fields of [{ secret: true }, { locked: true }]) {
|
||||
const ack = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: plain.id,
|
||||
...fields })
|
||||
assert.equal(ack.ok, false, JSON.stringify(fields))
|
||||
assert.equal(ack.code, 'invalid', JSON.stringify(fields))
|
||||
}
|
||||
// clearing door closes and de-secrets; naming a true door-only switch with it is invalid
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: secret.id,
|
||||
door: false })).ok, true)
|
||||
const cleared = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === secret.id &&
|
||||
m.door === false)
|
||||
assert.equal(cleared.open, false)
|
||||
assert.equal(cleared.secret, false)
|
||||
assert.equal(cleared.locked, false)
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: secret.id,
|
||||
door: true, secret: true, blocks_sight: false })).code,
|
||||
'invalid')
|
||||
gm.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('wall label: set, change, clear and the 6.5 text rule (#55)', async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
const { id } = await addWall(gm, { a: [10, 10], b: [200, 10], label: 'railing' })
|
||||
const added = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id)
|
||||
assert.equal(added.label, 'railing')
|
||||
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id,
|
||||
label: "the king's window" })).ok, true)
|
||||
const changed = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id &&
|
||||
m.label === "the king's window")
|
||||
assert.equal(changed.label, "the king's window")
|
||||
|
||||
// one code point and 64 code points are legal; unicode counts code points, not bytes
|
||||
const one = await addWall(gm, { a: [10, 20], b: [200, 20], label: 'x' })
|
||||
assert.equal(one.ok, true)
|
||||
const exactly64 = await addWall(gm, { a: [10, 30], b: [200, 30], label: 'é'.repeat(64) })
|
||||
assert.equal(exactly64.ok, true)
|
||||
await wallEffect(gm.ws, m => m.t === 'wall' && m.id === exactly64.id)
|
||||
|
||||
const invalid = [
|
||||
'', // 0 code points
|
||||
'x'.repeat(65), // 65 code points
|
||||
' railing', // untrimmed
|
||||
'railing ', // untrimmed
|
||||
'rail\ting', // control character
|
||||
'rail\u007fing', // DEL is a control character
|
||||
' ', // whitespace is not a label
|
||||
42, // not a string
|
||||
true,
|
||||
]
|
||||
for (const label of invalid) {
|
||||
const ack = await addWall(gm, { a: [10, 40], b: [200, 40], label })
|
||||
assert.equal(ack.ok, false, JSON.stringify(label))
|
||||
assert.equal(ack.code, 'invalid', JSON.stringify(label))
|
||||
const upd = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, label })
|
||||
assert.equal(upd.ok, false, JSON.stringify(label))
|
||||
assert.equal(upd.code, 'invalid', JSON.stringify(label))
|
||||
}
|
||||
// a refused update left the stored label alone
|
||||
const stillChanged = gm.ws.messages.filter(m => m.t === 'wall' && m.id === id).pop()
|
||||
assert.equal(stillChanged.label, "the king's window")
|
||||
|
||||
// null clears it, and the clear survives a fresh snapshot
|
||||
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id,
|
||||
label: null })).ok, true)
|
||||
const cleared = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id &&
|
||||
m.label === null)
|
||||
assert.equal(cleared.label, null)
|
||||
const gm2 = await openAs(s.origin, gmKey)
|
||||
await gm2.ws.waitText('hello')
|
||||
const snap = await gm2.ws.waitText('walls')
|
||||
assert.equal(snap.walls.find(w => w.id === id).label, null)
|
||||
gm.ws.close(); gm2.ws.close()
|
||||
})
|
||||
})
|
||||
|
||||
test('wall.update {door:true} on a see-through fixed window yields a closed opening window', async () => {
|
||||
await withGmServer(async (s, gmKey) => {
|
||||
const gm = await gmConnect(s.origin, gmKey)
|
||||
|
||||
Reference in New Issue
Block a user