Files
SirStone 9c7f9de910 feat(m4): playtest friction: perf overlay, fresh import, token seed (#82)
Opt-in ?perf=1 overlay (fps, frame p50/p95, JS p50/p95, tokens, zoom; no node or ticker work when off). fff-vtt import creates and migrates a fresh/empty state dir through the shared server startup path; devbox run serve gains --image. devbox run seed creates deterministic labelled NPC tokens over the real WS (idempotent rerun, --replace), and the GM token form defaults X/Y to the viewport centre.
2026-11-21 17:20:05 +01:00

207 lines
7.9 KiB
JavaScript

#!/usr/bin/env node
// `devbox run seed` (#82): fill the playtest scene with NPC tokens over the real WebSocket,
// exactly as the GM panel does (`token.create`), instead of 49 form submits.
//
// It signs in with the GM key (or reads it from the state dir), connects to the real LAN/loopback
// URL, spreads N tokens deterministically over the scene, optionally gives the first K vision, and
// stops. Labels are `Seed 01`, `Seed 02`, … so a rerun skips what is already there; `--replace`
// removes the labelled tokens first.
//
// NODE_EXTRA_CA_CERTS=run/lan/tls/cert.pem \
// devbox run seed -- --url=https://192.168.1.50:8443 --tokens=49 --vision=1
//
// TLS is real (the playtest stack's certificate is self-signed), so the node process must trust it:
// NODE_EXTRA_CA_CERTS=<state-dir>/tls/cert.pem. Pass --key to avoid reading the state dir.
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { sleep } from './lib.mjs'
import { gmKeyOf, openAs } from './withserver.mjs'
const USAGE = `usage: devbox run seed -- --url=<origin> [--key=<gm-key>] [options]
Create N NPC tokens through the real WebSocket as the GM. The GM key is read from the state dir
when --key is absent.
--url=<origin> Server origin, e.g. https://192.168.1.50:8443 (required)
--key=<gm-key> GM key; default: read/emit it from --state-dir with fff-vtt gm-key
--state-dir=<path> State dir used for the GM key (default: run/lan)
--bin=<path> Server binary for gm-key (default: run/fff-vtt)
--tokens=<n> How many NPC tokens to have (default: 49)
--seed=<n> Deterministic position seed (default: 1)
--vision=<n> Give the first n tokens vision (default: 0)
--vision-radius=<px> Vision radius for those tokens (default: 400)
--prefix=<text> Label prefix (default: Seed)
--replace Remove the labelled tokens first, then create the full set
The playtest stack uses a self-signed certificate: run with
NODE_EXTRA_CA_CERTS=<state-dir>/tls/cert.pem, or the WebSocket upgrade fails.
`
const VALUE_OPTIONS = new Set(
['url', 'key', 'state-dir', 'bin', 'tokens', 'seed', 'vision', 'vision-radius', 'prefix'],
)
function parseArgs(argv) {
const opts = {}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]
if (arg === '-h' || arg === '--help') { process.stdout.write(USAGE); process.exit(0) }
const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg)
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
const key = m[1]
if (key === 'replace') { opts.replace = true; continue }
if (!VALUE_OPTIONS.has(key)) throw new Error(`unknown option --${key} (see --help)`)
let value = m[2]
if (value === undefined) {
if (i + 1 >= argv.length) throw new Error(`--${key}: missing value (see --help)`)
value = argv[++i]
}
if (key === 'tokens' || key === 'seed' || key === 'vision' || key === 'vision-radius') {
const number = Number(value)
if (!Number.isInteger(number) || number < 0) {
throw new Error(`--${key}: expected a whole number >= 0, got ${JSON.stringify(value)}`)
}
opts[key === 'vision-radius' ? 'visionRadius' : key] = number
} else if (key === 'state-dir') opts.stateDir = value
else if (key === 'bin') opts.bin = value
else opts[key] = value
}
return opts
}
/** mulberry32: tiny deterministic PRNG, so the same --seed gives the same layout everywhere. */
function mulberry32(seed) {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) >>> 0
let t = a
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** N positions spread on a near-square grid with seeded jitter, inset from the scene edge. */
export function seedPositions(scene, count, seed) {
if (count <= 0) return []
const cols = Math.ceil(Math.sqrt(count))
const rows = Math.ceil(count / cols)
const marginX = scene.w * 0.08
const marginY = scene.h * 0.08
const cellW = (scene.w - 2 * marginX) / cols
const cellH = (scene.h - 2 * marginY) / rows
const random = mulberry32(seed)
const points = []
for (let i = 0; i < count; i += 1) {
const col = i % cols
const row = Math.floor(i / cols)
const jitterX = (random() - 0.5) * cellW * 0.3
const jitterY = (random() - 0.5) * cellH * 0.3
const x = marginX + (col + 0.5) * cellW + jitterX
const y = marginY + (row + 0.5) * cellH + jitterY
points.push([
Math.round(Math.min(scene.w - 1, Math.max(1, x))),
Math.round(Math.min(scene.h - 1, Math.max(1, y))),
])
}
return points
}
function labelFor(prefix, index, width) {
return `${prefix} ${String(index + 1).padStart(width, '0')}`
}
function initialTokens(ws) {
const byId = new Map()
for (const message of ws.messages) {
if (message && message.t === 'token' && typeof message.id === 'string') byId.set(message.id, message)
}
return [...byId.values()]
}
async function main() {
const opts = parseArgs(process.argv.slice(2))
const url = opts.url
if (!url) throw new Error(`--url is required (see --help)\n\n${USAGE}`)
const tokens = opts.tokens ?? 49
const seed = opts.seed ?? 1
const vision = opts.vision ?? 0
const visionRadius = opts.visionRadius ?? 400
const prefix = opts.prefix ?? 'Seed'
let key = opts.key
if (!key) {
const stateDir = path.resolve(opts.stateDir ?? 'run/lan')
key = gmKeyOf(stateDir, path.resolve(opts.bin ?? 'run/fff-vtt'))
}
const conn = await openAs(url, key)
const hello = await conn.ws.waitText('hello', 10000)
if (!hello.scene) throw new Error('the GM hello carried no scene; check --url and the key')
// The GM resync is hello, roster, walls, then every token. Give the token frames a moment to
// arrive before deciding what already exists (the wire has no "resync complete" marker).
await conn.ws.waitText('walls', 10000)
await sleep(400)
const width = Math.max(2, String(tokens).length)
const labels = Array.from({ length: tokens }, (_, i) => labelFor(prefix, i, width))
const wanted = new Set(labels)
const labelPattern = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\d+$`)
const nameOf = token => token.descriptive_name ?? token.name ?? ''
const existing = initialTokens(conn.ws)
const labelled = existing.filter(token => labelPattern.test(nameOf(token)))
let removed = 0
if (opts.replace) {
for (const token of labelled) {
const ack = await conn.ws.request({ t: 'token.remove', id: token.id })
if (!ack.ok) throw new Error(`token.remove ${token.id}: ${JSON.stringify(ack)}`)
removed += 1
}
}
const present = new Set(
(opts.replace ? [] : labelled.map(nameOf)).filter(name => wanted.has(name)),
)
const positions = seedPositions(hello.scene, tokens, seed)
let created = 0
for (let i = 0; i < tokens; i += 1) {
const name = labels[i]
if (present.has(name)) continue
const fields = {
t: 'token.create',
scene: hello.scene.id,
kind: 'npc',
pos: positions[i],
descriptive_name: name,
actual_name: name,
}
if (i < vision) {
fields.flags = { vision: true }
fields.vision_radius = visionRadius
}
const ack = await conn.ws.request(fields)
if (!ack.ok) throw new Error(`token.create ${name}: ${JSON.stringify(ack)}`)
created += 1
}
const kept = tokens - created
process.stdout.write(
`seeded ${tokens} tokens (${created} created, ${kept} already present, ${removed} removed) ` +
`on ${url} scene ${hello.scene.id} ${hello.scene.w}x${hello.scene.h}, seed ${seed}` +
`${vision > 0 ? `, vision ${vision} x ${visionRadius} px` : ''}\n`,
)
conn.ws.close()
await conn.ws.closed
}
const invokedDirectly =
process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
if (invokedDirectly) {
main().catch(error => {
process.stderr.write(`seed: ${error.stack ?? error}\n`)
process.exit(1)
})
}