feat(client): GM wall editor, round-1 fields (#73)

Draw, select, edit and delete walls through the GM panel: the four 5.8
presets, raw switches (preset XOR raw, open excluded from wall.update), a
private label, the one-way arrow + flip (sight_dir names the blind side),
the player-marker switch, door open/close through door.set, secret/locked
with the locked hint and one-click unlock, delete and single-step undo.
No thickness, height or position-flip control (ADR-0012).

The pure rules and payload builders live in src/wallEditor.ts; the GM wall
slice (src/slices/walls.ts) owns the server records, selection and undo;
the render module draws on the gm layer and defines the input precedence:
token drag (#72) > armed wall draw > camera pan (#69), with a click (no
movement) selecting the nearest wall.

Shared core edits: client/src/reducer.ts gains the wall-select and
wall-record-undo events (the only new core events); style.css and the
client README document the panel and rules. Unit tests cover the slice,
presets, derived kind, arrow side, snapping, payload XOR, door intent and
undo builders; the e2e draws every preset, edits the fields, flips the
one-way wall, opens/closes a door, deletes and undoes, proves a token drag
still wins over draw mode, and probes the player's fog pixels, with the
player WS leaking no wall data.

Ref #73
This commit is contained in:
2026-11-21 11:26:45 +01:00
parent 2d9548c941
commit 91a51c706d
9 changed files with 2425 additions and 0 deletions
+649
View File
@@ -0,0 +1,649 @@
// GM wall editor panel (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4). Plain DOM and `textContent`
// only. Mounted under the shell's `#panels` host by the wall render module, so a player never gets a
// wall panel and the panel cannot outlive the live stage.
//
// The panel owns the editor's local UI state (the armed preset, the first click, the snap toggle)
// and sends `wall.add` / `wall.update` / `wall.remove` / `door.set` through the session's intent
// bridge. Every payload is built by `src/wallEditor.ts`, which enforces preset XOR raw (an
// `open:false` never rides beside a preset) and never puts `open` in a `wall.update` patch: opening
// and closing a door is the `door.set` intent.
//
// Undo (story 52) is single-step: the panel records the inverse of the last successful edit as a
// wall-slice descriptor, and the Undo button sends that inverse. A new edit replaces it.
import type { ReducerEvent, RootState } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { sendIntent } from '../intents.ts'
import type { WallView } from '../slices/walls.ts'
import { restoreOf, selectedWallOf, undoOf, wallsOf } from '../slices/walls.ts'
import type { SightDir, WallPreset, WallSwitches, WallUndo } from '../wallEditor.ts'
import {
PRESETS,
buildAddFields,
buildDoorFields,
buildUpdateFields,
flipSightDir,
presetSwitches,
snapPoint,
undoIntent,
validateLabel,
validateSwitches,
} from '../wallEditor.ts'
export interface WallPanel {
render(state: RootState): void
/** The editor is waiting for the two draw points; the renderer must take the gesture. */
readonly armed: boolean
/** The first snapped point of the wall being drawn, or null. */
readonly first: Vec2 | null
/** Snap a world point with the current grid/endpoint settings. */
snap(point: Vec2): Vec2
/** Feed one click while armed; the second one sends `wall.add`. */
drawPoint(point: Vec2): void
cancelDraw(): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
invalid: 'That combination is not valid.',
'not-found': 'That wall no longer exists.',
'not-allowed': 'The server refused that action.',
}
function describeCode(code: string | undefined): string {
if (code === undefined) return 'The server refused that action.'
return CODE_TEXT[code] ?? `The server refused that action (${code}).`
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function field<K extends keyof HTMLElementTagNameMap>(tag: K, id: string, text: string) {
const node = element(tag, id, text)
const label = element('label', undefined, text)
label.htmlFor = id
return { node, label }
}
const PRESET_LABELS: Record<WallPreset, string> = {
wall: 'Wall',
door: 'Door',
window: 'Window',
one_way: 'One-way',
}
export function mountWallPanel(
host: HTMLElement,
dispatch: (event: ReducerEvent) => void,
): WallPanel {
const root = element('section', 'gm-walls')
root.hidden = true
root.append(element('h2', undefined, 'Walls'))
// ---- draw ----------------------------------------------------------------------------------
const drawSection = element('section', 'wall-draw')
drawSection.append(element('h3', undefined, 'Draw'))
const presetRow = element('div', 'wall-presets')
const presetButtons = new Map<WallPreset, HTMLButtonElement>()
for (const preset of PRESETS) {
const button = element('button', `wall-preset-${preset}`, PRESET_LABELS[preset])
button.type = 'button'
button.dataset['preset'] = preset
button.addEventListener('click', () => arm(preset))
presetButtons.set(preset, button)
presetRow.append(button)
}
const snapWrap = field('input', 'wall-snap', 'Snap to grid and endpoints')
snapWrap.node.type = 'checkbox'
snapWrap.node.checked = true
const drawHint = element('p', 'wall-hint', 'Choose a preset, then click two points.')
const drawState = element('p', 'wall-drawing', '')
drawSection.append(presetRow, snapWrap.label, snapWrap.node, drawHint, drawState)
// ---- selected wall -------------------------------------------------------------------------
const selected = element('section', 'wall-selected')
selected.hidden = true
const selectedTitle = element('h3', 'wall-kind', 'No wall selected')
const kindHint = element('p', 'wall-kind-hint', 'Derived kind (server)')
const labelInput = field('input', 'wall-label', 'Private label')
labelInput.node.type = 'text'
labelInput.node.maxLength = 64
const labelApply = element('button', 'wall-label-apply', 'Set label')
labelApply.type = 'button'
const markerWrap = field('input', 'wall-player-marker', 'Players see a marker')
markerWrap.node.type = 'checkbox'
const doorWrap = field('input', 'wall-door', 'Door')
doorWrap.node.type = 'checkbox'
const secretWrap = field('input', 'wall-secret', 'Secret')
secretWrap.node.type = 'checkbox'
const lockedWrap = field('input', 'wall-locked', 'Locked')
lockedWrap.node.type = 'checkbox'
const openButton = element('button', 'wall-open', 'Open door')
openButton.type = 'button'
const flipButton = element('button', 'wall-flip', 'Flip direction')
flipButton.type = 'button'
flipButton.hidden = true
const hintLocked = element('p', 'wall-hint-locked', 'locked: unlock first')
hintLocked.hidden = true
const unlockButton = element('button', 'wall-unlock', 'Unlock')
unlockButton.type = 'button'
unlockButton.hidden = true
const deleteButton = element('button', 'wall-delete', 'Delete wall')
deleteButton.type = 'button'
// ---- advanced raw switches -----------------------------------------------------------------
const advancedToggle = element('button', 'wall-advanced-toggle', 'Advanced switches')
advancedToggle.type = 'button'
const advanced = element('section', 'wall-advanced')
advanced.hidden = true
const advSight = field('input', 'wall-blocks-sight', 'blocks_sight')
advSight.node.type = 'checkbox'
const advMove = field('input', 'wall-blocks-movement', 'blocks_movement')
advMove.node.type = 'checkbox'
const advDir = field('select', 'wall-sight-dir', 'sight_dir')
for (const value of ['both', 'left', 'right'] as const) {
const option = element('option', undefined, value)
option.value = value
advDir.node.append(option)
}
const advMarker = field('input', 'wall-adv-marker', 'player_marker')
advMarker.node.type = 'checkbox'
const advDoor = field('input', 'wall-adv-door', 'door')
advDoor.node.type = 'checkbox'
const advSecret = field('input', 'wall-adv-secret', 'secret')
advSecret.node.type = 'checkbox'
const advLocked = field('input', 'wall-adv-locked', 'locked')
advLocked.node.type = 'checkbox'
const advApply = element('button', 'wall-adv-apply', 'Apply switches')
advApply.type = 'button'
advanced.append(
advSight.label,
advSight.node,
advMove.label,
advMove.node,
advDir.label,
advDir.node,
advMarker.label,
advMarker.node,
advDoor.label,
advDoor.node,
advSecret.label,
advSecret.node,
advLocked.label,
advLocked.node,
advApply,
)
const error = element('p', 'wall-error')
error.hidden = true
error.setAttribute('role', 'alert')
selected.append(
selectedTitle,
kindHint,
labelInput.label,
labelInput.node,
labelApply,
markerWrap.label,
markerWrap.node,
doorWrap.label,
doorWrap.node,
openButton,
secretWrap.label,
secretWrap.node,
lockedWrap.label,
lockedWrap.node,
hintLocked,
unlockButton,
flipButton,
advancedToggle,
advanced,
deleteButton,
error,
)
// ---- undo ----------------------------------------------------------------------------------
const undoButton = element('button', 'wall-undo', 'Undo')
undoButton.type = 'button'
root.append(drawSection, selected, undoButton)
host.append(root)
let active = false
let current: RootState | null = null
let preset: WallPreset = 'wall'
let armed = false
let first: Vec2 | null = null
let snapEnabled = true
let populatedFor = -1
let advancedOpen = false
/** The last rendered wall record, so a field edit uses exactly what the GM saw. */
let shown: WallView | null = null
function setError(text: string | null): void {
error.textContent = text ?? ''
error.hidden = text === null
}
function scene(): { id: number; w: number; h: number; grid: number } | null {
const info = current?.session.scene
if (!info) return null
return { id: info.id, w: info.w, h: info.h, grid: info.grid_size }
}
function endpoints(): Vec2[] {
const out: Vec2[] = []
if (!current) return out
for (const wall of wallsOf(current)) out.push(wall.a, wall.b)
return out
}
function clamp(world: Vec2): Vec2 {
const info = scene()
if (!info) return world
return [
Math.min(info.w, Math.max(0, world[0])),
Math.min(info.h, Math.max(0, world[1])),
]
}
function snap(point: Vec2): Vec2 {
const info = scene()
return clamp(
snapPoint(point, {
enabled: snapEnabled,
gridSize: info?.grid ?? 0,
endpoints: endpoints(),
// Endpoint snap is a small pull: 12 world px at the board's 32 px grid.
threshold: 12,
}),
)
}
function updateDrawState(): void {
for (const [value, button] of presetButtons) {
button.setAttribute('aria-pressed', value === preset ? 'true' : 'false')
}
drawState.textContent = armed
? first === null
? `Drawing ${PRESET_LABELS[preset]}: click the first point.`
: `Drawing ${PRESET_LABELS[preset]}: click the second point.`
: 'Not drawing.'
}
function arm(next: WallPreset): void {
preset = next
armed = true
first = null
setError(null)
updateDrawState()
}
function cancelDraw(): void {
armed = false
first = null
updateDrawState()
}
async function send(t: string, fields: Record<string, unknown>): Promise<AckFrame | null> {
try {
const ack = await sendIntent(t, fields)
if (!ack.ok) setError(describeCode(ack.code))
return ack
} catch {
setError('Could not reach the server.')
return null
}
}
function drawPoint(point: Vec2): void {
if (!armed) return
const info = scene()
if (!info) return
const snapped = snap(point)
if (first === null) {
first = snapped
updateDrawState()
return
}
const a = first
first = null
armed = false
updateDrawState()
if (a[0] === snapped[0] && a[1] === snapped[1]) {
setError('A wall needs two different points.')
return
}
const payload = { preset, switches: presetSwitches(preset), label: null }
const fields = buildAddFields(info.id, a, snapped, payload)
void send('wall.add', fields).then(ack => {
if (ack?.ok && typeof ack.id === 'number') {
// Select the new wall so the GM can label it or open it, and make the add undoable.
dispatch({ type: 'wall-select', id: ack.id })
dispatch({ type: 'wall-record-undo', undo: { kind: 'remove', id: ack.id } })
}
})
}
async function patch(fields: Record<string, unknown>, prior: WallView): Promise<boolean> {
const info = scene()
if (!info) return false
const ack = await send('wall.update', { scene: info.id, id: prior.id, ...fields })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
setError(null)
return true
}
return false
}
function mergedSwitches(next: Partial<WallSwitches>): WallSwitches | null {
if (!shown) return null
return { ...shown.switches, ...next }
}
/** Send one checkbox/select field, validating the resulting switch set first. */
async function applySwitch<K extends keyof WallSwitches>(
key: K,
value: WallSwitches[K],
): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
// Clearing `door` is the one patch that also closes/de-secrets server-side (6.1), so it is sent
// alone rather than as a contradictory full switch set.
if (key === 'door' && value === false) {
await patch({ door: false }, prior)
return
}
const merged = mergedSwitches({ [key]: value } as Partial<WallSwitches>)
if (!merged) return
const invalid = validateSwitches(merged)
if (invalid !== null) {
setError(invalid)
return
}
const payload = buildUpdateFields(prior.id, { preset: null, switches: merged })
const info = scene()
if (!info) return
const ack = await send('wall.update', { scene: info.id, ...payload })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
}
}
// ---- listeners -----------------------------------------------------------------------------
snapWrap.node.addEventListener('change', () => {
snapEnabled = snapWrap.node.checked
})
labelApply.addEventListener('click', () => {
const prior = shown
if (!prior) return
const message = validateLabel(labelInput.node.value)
if (message !== null) {
setError(message)
return
}
const trimmed = labelInput.node.value.trim()
void patch({ label: trimmed === '' ? null : trimmed }, prior)
})
markerWrap.node.addEventListener('change', () => {
void applySwitch('playerMarker', markerWrap.node.checked)
})
doorWrap.node.addEventListener('change', () => {
void applySwitch('door', doorWrap.node.checked)
})
secretWrap.node.addEventListener('change', () => {
void applySwitch('secret', secretWrap.node.checked)
})
lockedWrap.node.addEventListener('change', () => {
void applySwitch('locked', lockedWrap.node.checked)
})
openButton.addEventListener('click', () => {
void toggleDoor()
})
unlockButton.addEventListener('click', () => {
void unlock()
})
flipButton.addEventListener('click', () => {
const prior = shown
if (!prior) return
void applySwitch('sightDir', flipSightDir(prior.switches.sightDir))
})
deleteButton.addEventListener('click', () => {
void deleteWall()
})
advanceButtonSetup()
undoButton.addEventListener('click', () => {
void runUndo()
})
function advanceButtonSetup(): void {
advancedToggle.addEventListener('click', () => {
advancedOpen = !advancedOpen
advanced.hidden = !advancedOpen
advancedToggle.setAttribute('aria-expanded', advancedOpen ? 'true' : 'false')
})
advApply.addEventListener('click', () => {
void applyAdvanced()
})
}
function populate(wall: WallView): void {
const switches = wall.switches
labelInput.node.value = wall.label ?? ''
markerWrap.node.checked = switches.playerMarker
doorWrap.node.checked = switches.door
secretWrap.node.checked = switches.secret
lockedWrap.node.checked = switches.locked
advSight.node.checked = switches.blocksSight
advMove.node.checked = switches.blocksMovement
advDir.node.value = switches.sightDir
advMarker.node.checked = switches.playerMarker
advDoor.node.checked = switches.door
advSecret.node.checked = switches.secret
advLocked.node.checked = switches.locked
}
async function applyAdvanced(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
const switches: WallSwitches = {
...prior.switches,
blocksSight: advSight.node.checked,
blocksMovement: advMove.node.checked,
sightDir: advDir.node.value as SightDir,
playerMarker: advMarker.node.checked,
door: advDoor.node.checked,
secret: advSecret.node.checked,
locked: advLocked.node.checked,
}
const invalid = validateSwitches(switches)
if (invalid !== null) {
setError(invalid)
return
}
await patch({ ...buildUpdateFields(prior.id, { preset: null, switches }) }, prior)
}
async function toggleDoor(): Promise<void> {
const prior = shown
if (!prior || !prior.switches.door) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
if (!prior.switches.open && (prior.switches.locked || prior.switches.secret)) {
// 5.8/6.1: a secret or locked door cannot open; the editor offers the one click that clears
// the block first. No intent is sent, so the server never sees a refused open.
hintLocked.textContent = prior.switches.locked
? 'locked: unlock first'
: 'secret: clear secret first'
hintLocked.hidden = false
unlockButton.textContent = prior.switches.locked ? 'Unlock' : 'Clear secret'
unlockButton.dataset['action'] = prior.switches.locked ? 'locked' : 'secret'
unlockButton.hidden = false
return
}
const info = scene()
if (!info) return
const open = !prior.switches.open
const ack = await send('door.set', buildDoorFields(info.id, prior.id, open))
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: { kind: 'door', id: prior.id, open: prior.switches.open },
})
}
}
async function unlock(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
const field = unlockButton.dataset['action'] === 'secret' ? 'secret' : 'locked'
await applySwitch(field, false)
}
async function deleteWall(): Promise<void> {
const prior = shown
const info = scene()
if (!prior || !info) return
setError(null)
const ack = await send('wall.remove', { scene: info.id, id: prior.id })
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: { kind: 'restore', wall: restoreOf(prior) } })
dispatch({ type: 'wall-select', id: null })
}
}
async function runUndo(): Promise<void> {
if (!current) return
const info = scene()
const undo = undoOf(current)
if (!info || undo === null) return
const intent = undoIntent(info.id, undo)
if (!intent) return
setError(null)
const ack = await send(intent.t, intent.fields)
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: null })
if (intent.t === 'wall.remove') dispatch({ type: 'wall-select', id: null })
}
}
function undoLabel(undo: WallUndo | null): string {
if (undo === null) return 'Undo'
switch (undo.kind) {
case 'remove':
return 'Undo draw'
case 'restore':
return 'Undo delete'
case 'update':
return 'Undo edit'
case 'door':
return 'Undo door'
}
}
function render(state: RootState): void {
current = state
const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting'
const gm = state.session.role === 'gm' && state.session.me?.name != null
const nextActive = live && gm
if (!nextActive) {
active = false
armed = false
first = null
shown = null
populatedFor = -1
root.hidden = true
selected.hidden = true
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
updateDrawState()
return
}
if (!active) {
active = true
populatedFor = -1
}
root.hidden = false
const wall = selectedWallOf(state)
shown = wall
if (wall === null) {
selected.hidden = true
populatedFor = -1
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
return
}
selected.hidden = false
selectedTitle.textContent = `${wall.kind}`
if (populatedFor !== wall.id) {
populatedFor = wall.id
advancedOpen = false
advanced.hidden = true
advancedToggle.setAttribute('aria-expanded', 'false')
hintLocked.hidden = true
unlockButton.hidden = true
setError(null)
}
// Do not overwrite a field the GM is typing in; the server's record still drives every other
// control and the derived kind.
if (document.activeElement !== labelInput.node) populate(wall)
kindHint.textContent = `Derived kind: ${wall.kind}`
openButton.textContent = wall.switches.open ? 'Close door' : 'Open door'
openButton.disabled = !wall.switches.door
flipButton.hidden = wall.switches.sightDir === 'both'
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
}
return {
render,
get armed() {
return armed
},
get first() {
return first
},
snap,
drawPoint,
cancelDraw,
destroy() {
root.remove()
},
}
}
+5
View File
@@ -16,6 +16,7 @@ import type {
Vec2,
} from './protocol.ts'
import { closeOutcome, isClosing, isHello } from './protocol.ts'
import type { WallUndo } from './wallEditor.ts'
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reconnecting' | 'reload' | 'offline'
@@ -82,6 +83,10 @@ export type ReducerEvent =
| { type: 'move-sent'; reqId: number; id: string; pos: Vec2 }
/** The renderer finished the cosmetic rollback tween for this token. */
| { type: 'rollback-done'; id: string; seq: number }
/** GM wall editor selection (#73): the id lives in the wall slice, the core just carries it. */
| { type: 'wall-select'; id: number | null }
/** The last successful wall edit's inverse, for the editor's single-step undo (#73). */
| { type: 'wall-record-undo'; undo: WallUndo | null }
/**
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
+325
View File
@@ -0,0 +1,325 @@
// GM wall layer and editor input (T10, #73; DESIGN 5.8, 7.4, 7.2). Walls are GM-only, so this module
// draws into the `gm` layer and arms nothing for a player session. It is the Pixi half of the
// editor: the panel (`src/panels/walls.ts`) owns the armed preset and sends the intents, the slice
// (`src/slices/walls.ts`) owns the server's records, and `src/wallEditor.ts` owns the pure rules.
//
// Input precedence (the thing #73 must not break):
// 1. token drag (#72) wins first: its window-capture `pointerdown` runs before this module's and
// stops immediate propagation when the press lands on a token the session may move;
// 2. wall drawing wins next, but only while a preset is armed: the two clicks are consumed and the
// camera never starts a pan;
// 3. otherwise the camera (#69) keeps pan/pinch, and a click (no movement) selects the wall under
// the pointer. A drag that moved more than a few pixels is a pan, not a selection.
// The e2e arms a preset and starts a drag on a token to prove rule 1 still wins.
//
// A one-way wall's arrow points from the seeing side toward the blind side (`sight_dir` names the
// blind side, GLOSSARY "Blind side"): `arrowVector` is the one place that direction is computed.
import { Container, Graphics } from 'pixi.js'
import type { RenderContext, RenderModule } from '../stage.ts'
import { dragOf } from '../../slices/move.ts'
import type { WallView } from '../../slices/walls.ts'
import { selectedWallId, undoOf, wallsOf } from '../../slices/walls.ts'
import { arrowVector, distanceToSegment, wallMidpoint } from '../../wallEditor.ts'
import type { Vec2 } from '../../protocol.ts'
import { mountWallPanel } from '../../panels/walls.ts'
const COLORS: Record<string, number> = {
wall: 0xb8c4d0,
door: 0xd19a51,
window: 0x54c7c9,
one_way: 0xb989e0,
custom: 0xd8d8d8,
}
interface WallNode {
container: Container
graphics: Graphics
sig: string
}
function wallSignature(wall: WallView, selected: boolean): string {
const s = wall.switches
return [
wall.id,
wall.a.join(','),
wall.b.join(','),
wall.kind,
s.blocksSight ? 1 : 0,
s.blocksMovement ? 1 : 0,
s.sightDir,
s.playerMarker ? 1 : 0,
s.door ? 1 : 0,
s.open ? 1 : 0,
s.secret ? 1 : 0,
s.locked ? 1 : 0,
selected ? 1 : 0,
].join('|')
}
/** A dashed/dotted stroke, used for an open door (nothing is there) and a secret door (GM view). */
function dashedLine(
graphics: Graphics,
a: Vec2,
b: Vec2,
width: number,
color: number,
dash: number,
gap: number,
alpha: number,
): void {
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const length = Math.hypot(dx, dy)
if (!(length > 0)) return
const ux = dx / length
const uy = dy / length
for (let start = 0; start < length; start += dash + gap) {
const end = Math.min(length, start + dash)
graphics
.moveTo(a[0] + ux * start, a[1] + uy * start)
.lineTo(a[0] + ux * end, a[1] + uy * end)
.stroke({ width, color, alpha })
}
}
function drawWall(graphics: Graphics, wall: WallView, selected: boolean): void {
graphics.clear()
const a = wall.a
const b = wall.b
const color = COLORS[wall.kind] ?? COLORS['custom']!
const width = selected ? 6 : 4
const alpha = selected ? 1 : 0.85
const open = wall.switches.door && wall.switches.open
if (selected) {
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width: width + 6, color: 0x7ee787, alpha: 0.25 })
}
if (open) {
// An open door leaves a gap; the schema keeps the record, the GM sees where it was.
dashedLine(graphics, a, b, width, color, 8, 8, 0.55)
} else if (wall.switches.secret) {
dashedLine(graphics, a, b, width, color, 3, 5, alpha)
} else {
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width, color, alpha })
}
// Endpoint handles while selected: the two authoring points, never moved in round 1.
if (selected) {
for (const point of [a, b]) {
graphics.circle(point[0], point[1], 5).fill(0x0b0b0d).stroke({ width: 2, color: 0x7ee787 })
}
}
// Story 50: the one-way arrow at the wall's middle, toward the blind side.
const direction = arrowVector(a, b, wall.switches.sightDir)
if (direction) {
const [mx, my] = wallMidpoint(a, b)
const tip: Vec2 = [mx + direction[0] * 22, my + direction[1] * 22]
const back: Vec2 = [mx - direction[0] * 8, my - direction[1] * 8]
const px = -direction[1]
const py = direction[0]
graphics
.moveTo(back[0], back[1])
.lineTo(tip[0], tip[1])
.stroke({ width: 3, color: 0xfff3c4, alpha: 0.95 })
graphics
.moveTo(tip[0], tip[1])
.lineTo(tip[0] - direction[0] * 9 + px * 6, tip[1] - direction[1] * 9 + py * 6)
.lineTo(tip[0] - direction[0] * 9 - px * 6, tip[1] - direction[1] * 9 - py * 6)
.closePath()
.fill(0xfff3c4)
}
// Story 48: the GM sees the marker switch. A marked window is the only wall a player learns about.
if (wall.switches.playerMarker) {
const [mx, my] = wallMidpoint(a, b)
if (wall.kind === 'window') {
graphics.circle(mx, my, 6).fill(0xffcc33).stroke({ width: 2, color: 0x2b1d00 })
} else {
graphics.circle(mx, my, 5).stroke({ width: 2, color: 0xffcc33, alpha: 0.7 })
}
}
}
export const renderModule: RenderModule = {
name: 'walls',
mount({ app, layers, store }: RenderContext): () => void {
const canvas = app.canvas
const host = document.querySelector<HTMLElement>('#panels')
const panel = host ? mountWallPanel(host, event => store.dispatch(event)) : null
const container = new Container()
layers.gm.addChild(container)
const preview = new Graphics()
container.addChild(preview)
const nodes = new Map<number, WallNode>()
let hover: Vec2 | null = null
let down: { x: number; y: number; pointerId: number } | null = null
function worldOf(event: PointerEvent): Vec2 {
const rect = canvas.getBoundingClientRect()
const local = layers.gm.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
return [local.x, local.y]
}
function zoom(): number {
const scale = Math.abs(layers.gm.worldTransform.a)
return scale > 0 ? scale : 1
}
function drawPreview(): void {
preview.clear()
if (!panel?.armed || panel.first === null) return
const a = panel.first
const b = hover ?? a
preview
.moveTo(a[0], a[1])
.lineTo(b[0], b[1])
.stroke({ width: 2, color: 0x7ee787, alpha: 0.8 })
preview.circle(a[0], a[1], 4).fill(0x7ee787)
preview.circle(b[0], b[1], 3).stroke({ width: 2, color: 0x7ee787 })
}
function renderWalls(): void {
const state = store.state
const selected = selectedWallId(state)
const walls = wallsOf(state)
const seen = new Set<number>()
for (const wall of walls) {
seen.add(wall.id)
const sig = wallSignature(wall, wall.id === selected)
let node = nodes.get(wall.id)
if (!node) {
const graphics = new Graphics()
const wallContainer = new Container()
wallContainer.addChild(graphics)
container.addChild(wallContainer)
node = { container: wallContainer, graphics, sig: '' }
nodes.set(wall.id, node)
}
if (node.sig !== sig) {
drawWall(node.graphics, wall, wall.id === selected)
node.sig = sig
}
}
for (const [id, node] of nodes) {
if (seen.has(id)) continue
container.removeChild(node.container)
node.container.destroy({ children: true })
nodes.delete(id)
}
}
function publish(): void {
const state = store.state
const walls = wallsOf(state)
const selected = selectedWallId(state)
const dataset = canvas.dataset
dataset['walls'] = String(walls.length)
dataset['wallKinds'] = walls.map(wall => `${wall.id}:${wall.kind}`).join(' ')
dataset['wallSelected'] = selected === null ? '' : String(selected)
dataset['wallArrows'] = walls
.filter(wall => wall.switches.sightDir !== 'both')
.map(wall => `${wall.id}:${wall.switches.sightDir}`)
.join(' ')
dataset['wallMarkers'] = walls
.filter(wall => wall.switches.playerMarker)
.map(wall => String(wall.id))
.join(' ')
dataset['wallDraw'] = panel?.armed ? (panel.first === null ? 'first' : 'second') : 'off'
dataset['wallPreview'] = panel?.first ? panel.first.join(',') : ''
dataset['wallUndo'] = undoOf(state) === null ? 'no' : 'yes'
}
function sync(): void {
renderWalls()
drawPreview()
publish()
}
function onPointerDown(event: PointerEvent): void {
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
const state = store.state
if (state.connection.phase !== 'live' || state.session.role !== 'gm' || !panel) return
if (panel.armed) {
// Drawing takes precedence over pan: consume the gesture and feed the point.
event.preventDefault()
event.stopImmediatePropagation()
hover = worldOf(event)
panel.drawPoint(hover)
sync()
return
}
down = { x: event.clientX, y: event.clientY, pointerId: event.pointerId }
}
function onPointerMove(event: PointerEvent): void {
if (!panel?.armed) return
// A token drag owns its gesture (#72); do not paint a wall preview under it.
if (dragOf(store.state) !== null) return
if (!event.isPrimary) return
hover = worldOf(event)
drawPreview()
}
function onPointerUp(event: PointerEvent): void {
const start = down
down = null
if (!panel || panel.armed) return
if (!start || start.pointerId !== event.pointerId) return
if (event.target !== canvas) return
// A moved pointer was a pan (#69), not a click on a wall.
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) return
if (store.state.session.role !== 'gm') return
const point = worldOf(event)
const tolerance = 8 / zoom()
let hit: WallView | null = null
let best = tolerance
for (const wall of wallsOf(store.state)) {
const distance = distanceToSegment(point, wall.a, wall.b)
if (distance <= best) {
best = distance
hit = wall
}
}
store.dispatch({ type: 'wall-select', id: hit?.id ?? null })
}
function onCancel(): void {
down = null
}
function onKey(event: KeyboardEvent): void {
if (event.key !== 'Escape' || !panel?.armed) return
panel.cancelDraw()
hover = null
sync()
}
const unsubscribe = store.subscribe(() => {
panel?.render(store.state)
sync()
})
panel?.render(store.state)
sync()
window.addEventListener('pointerdown', onPointerDown, true)
window.addEventListener('pointermove', onPointerMove, true)
window.addEventListener('pointerup', onPointerUp, true)
window.addEventListener('pointercancel', onCancel, true)
window.addEventListener('blur', onCancel)
window.addEventListener('keydown', onKey)
return () => {
unsubscribe()
window.removeEventListener('pointerdown', onPointerDown, true)
window.removeEventListener('pointermove', onPointerMove, true)
window.removeEventListener('pointerup', onPointerUp, true)
window.removeEventListener('pointercancel', onCancel, true)
window.removeEventListener('blur', onCancel)
window.removeEventListener('keydown', onKey)
panel?.destroy()
}
},
}
+235
View File
@@ -0,0 +1,235 @@
// GM wall slice (T10, #73; DESIGN 6.1 `walls`/`wall`/`wall_gone`, 5.8, 7.4). Append-only
// registration: adding this file was enough; the reducer's glob picked it up and `hello` resets it
// with every other slice.
//
// Wall records are GM-only on the wire (3.1). A player connection never receives these frames and a
// player-shaped frame is ignored here too, so a bug on the server side could not quietly turn this
// client into a wall-data renderer. The slice keeps the server's typed record plus the editor's
// selection and its single-step undo descriptor; it never derives or invents a wall field.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { Vec2 } from '../protocol.ts'
import type {
SightDir,
WallKind,
WallPosition,
WallRestore,
WallSwitches,
WallUndo,
} from '../wallEditor.ts'
import { deriveKind } from '../wallEditor.ts'
export interface WallView {
id: number
scene: number
a: Vec2
b: Vec2
thickness: number
position: WallPosition
height: number | null
kind: WallKind
switches: WallSwitches
label: string | null
flags: Record<string, unknown>
}
export interface WallsState {
byId: Record<number, WallView>
order: number[]
/** The wall selected in the GM editor, or null. */
selectedId: number | null
/** The inverse of the last successful edit; single-step undo (story 52). */
undo: WallUndo | null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function own(record: Record<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function isPosition(value: unknown): value is WallPosition {
return value === 'center' || value === 'left' || value === 'right'
}
function isSightDir(value: unknown): value is SightDir {
return value === 'both' || value === 'left' || value === 'right'
}
function isKind(value: unknown): value is WallKind {
return value === 'wall' || value === 'door' || value === 'window' || value === 'one_way' || value === 'custom'
}
function bool(value: unknown): boolean {
return value === true
}
function optionalLabel(value: unknown): string | null {
return typeof value === 'string' ? value : null
}
function flagObject(value: unknown): Record<string, unknown> {
return isRecord(value) ? value : {}
}
/**
* One GM `wall` frame (the same shape inside `walls`) as the editor stores it, or null when the
* frame cannot be that shape. `kind` is the server's derived label; an absent one is derived from
* the switches so an older-shaped frame still shows a label.
*/
export function wallViewFromFrame(frame: Record<string, unknown>): WallView | null {
const id = frame['id']
const scene = frame['scene']
const a = frame['a']
const b = frame['b']
const thickness = frame['thickness']
const position = frame['position']
const sightDir = frame['sight_dir']
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) return null
if (typeof scene !== 'number' || !Number.isInteger(scene)) return null
if (!isVec2(a) || !isVec2(b)) return null
if (typeof thickness !== 'number' || !Number.isFinite(thickness)) return null
if (!isPosition(position) || !isSightDir(sightDir)) return null
const switches: WallSwitches = {
blocksSight: bool(frame['blocks_sight']),
blocksMovement: bool(frame['blocks_movement']),
sightDir,
playerMarker: bool(frame['player_marker']),
door: bool(frame['door']),
open: bool(frame['open']),
secret: bool(frame['secret']),
locked: bool(frame['locked']),
}
const height = frame['height']
const kind = own(frame, 'kind')
const label = own(frame, 'label')
return {
id,
scene,
a: [a[0], a[1]],
b: [b[0], b[1]],
thickness,
position,
height: typeof height === 'number' && Number.isFinite(height) ? height : null,
kind: isKind(kind) ? kind : deriveKind(switches),
switches,
label: optionalLabel(label),
flags: flagObject(frame['flags']),
}
}
function upsert(state: WallsState, wall: WallView): void {
if (state.byId[wall.id] === undefined) state.order = [...state.order, wall.id]
state.byId = { ...state.byId, [wall.id]: wall }
}
function remove(state: WallsState, id: number): void {
if (state.byId[id] === undefined) return
const byId = { ...state.byId }
delete byId[id]
state.byId = byId
state.order = state.order.filter(entry => entry !== id)
if (state.selectedId === id) state.selectedId = null
}
/** The editor's restore payload for one wall: everything `wall.add` needs to bring it back. */
export function restoreOf(wall: WallView): WallRestore {
return {
a: [wall.a[0], wall.a[1]],
b: [wall.b[0], wall.b[1]],
thickness: wall.thickness,
position: wall.position,
height: wall.height,
switches: { ...wall.switches },
label: wall.label,
flags: { ...wall.flags },
}
}
export const slice: Slice<WallsState> = {
name: 'walls',
init: () => ({ byId: {}, order: [], selectedId: null, undo: null }),
reduce(state: WallsState, event: ReducerEvent, root: RootState): void {
if (event.type === 'wall-select') {
state.selectedId = event.id
return
}
if (event.type === 'wall-record-undo') {
state.undo = event.undo
return
}
if (event.type !== 'frame') return
const frame = event.frame
// Wall data is GM-only (DESIGN 3.1); never accept it on a player-shaped session.
if (root.session.role !== 'gm') return
if (frame.t === 'walls') {
const list = frame['walls']
if (!Array.isArray(list)) return
const byId: Record<number, WallView> = {}
const order: number[] = []
for (const entry of list) {
if (!isRecord(entry)) continue
const wall = wallViewFromFrame(entry)
if (!wall) continue
byId[wall.id] = wall
order.push(wall.id)
}
state.byId = byId
state.order = order
if (state.selectedId !== null && byId[state.selectedId] === undefined) {
state.selectedId = null
}
return
}
if (frame.t === 'wall') {
const wall = wallViewFromFrame(frame)
if (wall) upsert(state, wall)
return
}
if (frame.t === 'wall_gone') {
const id = frame['id']
if (typeof id === 'number' && Number.isInteger(id)) remove(state, id)
}
},
}
/** Every wall the GM's connection knows, in the server's id order. */
export function wallsOf(state: RootState): WallView[] {
const walls = state.slices['walls'] as WallsState | undefined
if (!walls) return []
return walls.order
.map(id => walls.byId[id])
.filter((wall): wall is WallView => wall !== undefined)
}
export function wallOf(state: RootState, id: number): WallView | null {
const walls = state.slices['walls'] as WallsState | undefined
if (!walls) return null
return walls.byId[id] ?? null
}
export function selectedWallId(state: RootState): number | null {
return (state.slices['walls'] as WallsState | undefined)?.selectedId ?? null
}
export function selectedWallOf(state: RootState): WallView | null {
const id = selectedWallId(state)
return id === null ? null : wallOf(state, id)
}
export function undoOf(state: RootState): WallUndo | null {
return (state.slices['walls'] as WallsState | undefined)?.undo ?? null
}
+107
View File
@@ -424,3 +424,110 @@ body {
#gm-seen-hint {
opacity: 0.7;
}
/* GM wall editor (T10, #73): draw presets, the selected wall's round-1 fields and single-step undo,
in the same right-hand column. Hidden and inert for players exactly like the other GM panels. */
#gm-walls {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 10px;
padding: 10px;
border-radius: 8px;
background: rgb(10 10 12 / 88%);
border: 1px solid #333;
pointer-events: auto;
font: 12px/1.4 ui-monospace, monospace;
}
#gm-walls h2,
#gm-walls h3 {
margin: 0;
font-weight: 600;
}
#gm-walls h2 {
font-size: 14px;
}
#gm-walls h3 {
font-size: 12px;
opacity: 0.8;
}
#wall-presets {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin: 4px 0;
}
#gm-walls button {
font: inherit;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid #666;
background: #222;
color: inherit;
}
#gm-walls button[aria-pressed='true'] {
outline: 1px solid #7ee787;
background: #1d3322;
}
#gm-walls button:disabled {
opacity: 0.45;
}
#gm-walls input,
#gm-walls select {
font: inherit;
padding: 3px 5px;
border-radius: 4px;
border: 1px solid #555;
background: #111;
color: inherit;
width: 100%;
box-sizing: border-box;
}
#gm-walls input[type='checkbox'] {
width: auto;
}
#wall-selected,
#wall-advanced {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
}
#wall-selected label,
#wall-advanced label {
opacity: 0.7;
}
#wall-kind {
color: #7ee787;
}
#wall-hint,
#wall-drawing,
#wall-kind-hint {
margin: 2px 0;
opacity: 0.7;
word-break: break-word;
}
#wall-hint-locked {
margin: 4px 0 0;
color: #e3b341;
}
#wall-error {
margin: 4px 0 0;
color: #ff8a8a;
word-break: break-word;
}
+344
View File
@@ -0,0 +1,344 @@
// The wall editor's pure half (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4 GM editor). No Pixi, no
// DOM, no socket: presets and derived kinds, the preset-XOR-raw payload rules, local validation
// before an intent leaves the client, grid/endpoint snapping, the one-way arrow side and the undo
// intent. `slices/walls.ts` holds the server's wall records; this module turns editor state into
// exactly the fields DESIGN 6.1 accepts.
//
// Round 1 deliberately has no thickness, height or position control (ADR-0012, spec #63 decision 3):
// the geometry fields stay at the server defaults and `open` is never a `wall.update` patch field
// (it belongs to `door.set`, 6.1 FIXED #49).
import type { Vec2 } from './protocol.ts'
export type WallPreset = 'wall' | 'door' | 'window' | 'one_way'
export type WallKind = 'wall' | 'door' | 'window' | 'one_way' | 'custom'
export type SightDir = 'both' | 'left' | 'right'
export type WallPosition = 'center' | 'left' | 'right'
/** The v1 switches (DESIGN 5.8, 6.1). `open` is a stored door state, not a switch patch. */
export interface WallSwitches {
blocksSight: boolean
blocksMovement: boolean
sightDir: SightDir
playerMarker: boolean
door: boolean
open: boolean
secret: boolean
locked: boolean
}
export const PRESETS: readonly WallPreset[] = ['wall', 'door', 'window', 'one_way']
/**
* The four preset expansions of DESIGN 5.8's table. `window` is the opening form: see-through while
* closed, passable once opened, and it is the only preset that turns `player_marker` on. A preset
* never implies thickness, position or height (6.1).
*/
export function presetSwitches(preset: WallPreset): WallSwitches {
switch (preset) {
case 'door':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'both',
playerMarker: false,
door: true,
open: false,
secret: false,
locked: false,
}
case 'window':
return {
blocksSight: false,
blocksMovement: true,
sightDir: 'both',
playerMarker: true,
door: true,
open: false,
secret: false,
locked: false,
}
case 'one_way':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'left',
playerMarker: false,
door: false,
open: false,
secret: false,
locked: false,
}
case 'wall':
return {
blocksSight: true,
blocksMovement: true,
sightDir: 'both',
playerMarker: false,
door: false,
open: false,
secret: false,
locked: false,
}
}
}
/** The 5.8 derived shape label: output only, never stored and never accepted as input. */
export function deriveKind(switches: WallSwitches): WallKind {
if (!switches.blocksSight && switches.blocksMovement) return 'window'
if (switches.blocksSight && switches.sightDir !== 'both') return 'one_way'
if (switches.blocksSight && switches.blocksMovement && switches.door) return 'door'
if (
switches.blocksSight &&
switches.blocksMovement &&
!switches.door &&
switches.sightDir === 'both'
) {
return 'wall'
}
return 'custom'
}
export function flipSightDir(sightDir: SightDir): SightDir {
if (sightDir === 'left') return 'right'
if (sightDir === 'right') return 'left'
return 'both'
}
/**
* The direction the GM's one-way arrow points: from the seeing side toward the watched (blind)
* side. `sight_dir` names the BLIND side (GLOSSARY "Blind side", DESIGN 5.8): `left` is the
* `(-dy, dx)` normal of `a -> b`. Null for a two-way wall (no arrow).
*/
export function arrowVector(a: Vec2, b: Vec2, sightDir: SightDir): Vec2 | null {
if (sightDir === 'both') return null
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const length = Math.hypot(dx, dy)
if (!(length > 0)) return null
if (sightDir === 'left') return normalize([-dy, dx])
return normalize([dy, -dx])
}
function normalize([x, y]: Vec2): Vec2 {
const length = Math.hypot(x, y)
if (!(length > 0)) return [0, 0]
return [x / length === 0 ? 0 : x / length, y / length === 0 ? 0 : y / length]
}
/** The arrow's midpoint: the wall's drawn midpoint, the same anchor a player marker uses (5.8). */
export function wallMidpoint(a: Vec2, b: Vec2): Vec2 {
return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
}
export interface SnapOptions {
enabled: boolean
gridSize: number
endpoints: readonly Vec2[]
/** Endpoint snap radius in world px; it wins over the grid when both are in reach. */
threshold: number
}
/**
* Story 45: optional grid and endpoint snap while drawing. Endpoint snap is tried first (the GM is
* extending a wall), then the grid; disabled means the raw pointer position. Values stay in world
* px and are clamped by the caller to the scene.
*/
export function snapPoint(point: Vec2, options: SnapOptions): Vec2 {
if (!options.enabled) return [point[0], point[1]]
let best: Vec2 | null = null
let bestDistance = options.threshold
for (const endpoint of options.endpoints) {
const distance = Math.hypot(endpoint[0] - point[0], endpoint[1] - point[1])
if (distance <= bestDistance) {
bestDistance = distance
best = endpoint
}
}
if (best) return [best[0], best[1]]
const size = options.gridSize
if (!(size > 0)) return [point[0], point[1]]
return [Math.round(point[0] / size) * size, Math.round(point[1] / size) * size]
}
/** Distance from a point to a segment, for choosing the wall under a click. */
export function distanceToSegment(point: Vec2, a: Vec2, b: Vec2): number {
const dx = b[0] - a[0]
const dy = b[1] - a[1]
const lengthSq = dx * dx + dy * dy
if (lengthSq <= 0) return Math.hypot(point[0] - a[0], point[1] - a[1])
let t = ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / lengthSq
t = Math.min(1, Math.max(0, t))
return Math.hypot(point[0] - (a[0] + t * dx), point[1] - (a[1] + t * dy))
}
/** DESIGN 6.5's text rule for a wall label: 1..64 code points, trimmed, no control characters. */
export function validateLabel(label: string): string | null {
const trimmed = label.trim()
if (trimmed.length === 0) return null
if ([...trimmed].length > 64) return 'The label must be at most 64 characters.'
if (/[\u0000-\u001f\u007f]/.test(trimmed)) return 'The label cannot contain control characters.'
return null
}
/**
* The server's 5.8/6.1 switch rules, checked before an intent leaves the client so the editor can
* show the reason. The server remains the validator; this is the same rule read locally.
*/
export function validateSwitches(switches: WallSwitches): string | null {
if (!switches.blocksSight && switches.sightDir !== 'both') {
return 'invalid: a sight direction needs blocks_sight.'
}
if ((switches.open || switches.secret || switches.locked) && !switches.door) {
return 'invalid: open, secret and locked need a door.'
}
if (switches.secret) {
if (switches.open) return 'invalid: a secret door is always closed.'
if (switches.sightDir !== 'both') return 'invalid: a secret door is always two-way.'
if (!switches.blocksSight || !switches.blocksMovement) {
return 'invalid: a secret door is opaque and solid.'
}
}
if (switches.open && switches.locked) return 'invalid: a locked door cannot open.'
return null
}
/** What a preset payload or a raw-switch payload carries; never both (6.1, preset XOR raw). */
export interface WallPayload {
/** A preset name, or null for the raw switches. */
preset: WallPreset | null
switches: WallSwitches
/** `undefined` leaves it alone; `null` clears it; a string sets it. */
label?: string | null
}
function labelFields(label: string | null | undefined): Record<string, unknown> {
return label === undefined ? {} : { label }
}
/**
* `wall.add` fields for the editor's one-drag default. A preset payload carries ONLY `preset` (plus
* the label): no raw switch may sit beside it, `open:false` included (DESIGN 6.1 FIXED #49). A raw
* payload names every switch; `wall.add` accepts `open` on a new door.
*/
export function buildAddFields(
scene: number,
a: Vec2,
b: Vec2,
payload: WallPayload,
): Record<string, unknown> {
const label = payload.label === null || payload.label === undefined ? {} : { label: payload.label }
if (payload.preset !== null) {
return { scene, a: [a[0], a[1]], b: [b[0], b[1]], preset: payload.preset, ...label }
}
const s = payload.switches
return {
scene,
a: [a[0], a[1]],
b: [b[0], b[1]],
blocks_sight: s.blocksSight,
blocks_movement: s.blocksMovement,
sight_dir: s.sightDir,
player_marker: s.playerMarker,
door: s.door,
open: s.open,
secret: s.secret,
locked: s.locked,
...label,
}
}
/**
* `wall.update` fields. `open` is not a patch field (it belongs to `door.set`): even an editor that
* holds a full switch set must drop it here. A preset replaces the whole switch set; a raw patch
* names every switch it holds except `open`.
*/
export function buildUpdateFields(id: number, payload: WallPayload): Record<string, unknown> {
const label = labelFields(payload.label)
if (payload.preset !== null) return { id, preset: payload.preset, ...label }
const s = payload.switches
return {
id,
blocks_sight: s.blocksSight,
blocks_movement: s.blocksMovement,
sight_dir: s.sightDir,
player_marker: s.playerMarker,
door: s.door,
secret: s.secret,
locked: s.locked,
...label,
}
}
/** `door.set` is the only way to open or close a door (6.1): `open` is a door intent, not a patch. */
export function buildDoorFields(scene: number, id: number, open: boolean): Record<string, unknown> {
return { scene, id, open }
}
/** The restore payload for undoing a delete: the whole wall, switches and label included. */
export interface WallRestore {
a: Vec2
b: Vec2
thickness: number
position: WallPosition
height: number | null
switches: WallSwitches
label: string | null
flags: Record<string, unknown>
}
export type WallUndo =
| { kind: 'remove'; id: number }
| { kind: 'restore'; wall: WallRestore }
| { kind: 'update'; id: number; switches: WallSwitches; label: string | null; flags: Record<string, unknown> }
| { kind: 'door'; id: number; open: boolean }
/** The inverse intent of the last edit, or null when there is nothing to undo. */
export function undoIntent(
scene: number,
undo: WallUndo | null,
): { t: string; fields: Record<string, unknown> } | null {
if (undo === null) return null
switch (undo.kind) {
case 'remove':
return { t: 'wall.remove', fields: { scene, id: undo.id } }
case 'restore': {
const wall = undo.wall
return {
t: 'wall.add',
fields: {
scene,
a: [wall.a[0], wall.a[1]],
b: [wall.b[0], wall.b[1]],
thickness: wall.thickness,
position: wall.position,
height: wall.height,
blocks_sight: wall.switches.blocksSight,
blocks_movement: wall.switches.blocksMovement,
sight_dir: wall.switches.sightDir,
player_marker: wall.switches.playerMarker,
door: wall.switches.door,
open: wall.switches.open,
secret: wall.switches.secret,
locked: wall.switches.locked,
label: wall.label,
flags: wall.flags,
},
}
}
case 'update':
return {
t: 'wall.update',
fields: {
...buildUpdateFields(undo.id, {
preset: null,
switches: undo.switches,
label: undo.label,
}),
flags: undo.flags,
},
}
case 'door':
return { t: 'door.set', fields: buildDoorFields(scene, undo.id, undo.open) }
}
}