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.
This commit is contained in:
@@ -36,6 +36,13 @@ in front of the server (the server itself stays on `127.0.0.1`), and prints:
|
||||
- the GM key (created on first run; an existing key is printed, never replaced),
|
||||
- the certificate-trust steps for Android Chrome and for a laptop (Linux/macOS/Firefox).
|
||||
|
||||
To import a map on the same first start, pass `--image` (an offline import runs before the server;
|
||||
a fresh state dir is created and migrated first):
|
||||
|
||||
```sh
|
||||
devbox run serve -- --image=run/map16384.png --tile-size=64
|
||||
```
|
||||
|
||||
Ctrl-C stops nginx and the server and releases the port; the next start works. State (`state.db`,
|
||||
`tiles/`), the GM key and the certificate live under `run/lan` and are **not** wiped, so a session
|
||||
survives a restart and a phone that trusted the certificate does not have to trust it again.
|
||||
@@ -86,7 +93,9 @@ sign-in page.
|
||||
|
||||
The map is a source image plus a tiled copy the server gates per player. One offline command slices
|
||||
the image and updates the scene; the server must be **stopped** for it (it reads the scene once at
|
||||
startup) and restarted afterwards. ImageMagick comes from the root devbox.
|
||||
startup) and restarted afterwards. The command also works on a fresh/empty state dir: it creates
|
||||
the directory, migrates the DB and seeds the scene through the same startup path as the server.
|
||||
ImageMagick comes from the root devbox.
|
||||
|
||||
```sh
|
||||
# stop the server first, then:
|
||||
@@ -99,23 +108,32 @@ devbox run -- ./run/fff-vtt import --state-dir=run --image=/path/to/map.png --ti
|
||||
| `--image=<path>` | source PNG or WebP (required); tiles are always PNG |
|
||||
| `--tile-size=<px>` | tile edge, default the scene's current tile size; must be a positive multiple of the 32 px explored cell (so 32 or the 64 px fallback) |
|
||||
| `--scene=<id>` | target scene; v1 has exactly one, id 1 |
|
||||
| `--state-dir=<path>` | the same state dir as the server (default `run`) |
|
||||
| `--state-dir=<path>` | the same state dir as the server (default `run`); created and migrated if absent |
|
||||
|
||||
Tiles land in `<state-dir>/tiles/1/v<art_version>/<x>_<y>.png`, origin at the world origin, which is
|
||||
exactly what the gate parses and nginx's internal `/_tiles/` alias serves. The command sets the
|
||||
scene's width, height and tile size from the image. Importing again grows `art_version` and writes a
|
||||
new `v` directory, so browsers never keep a stale tile; old versions stay on disk until the M6
|
||||
cleanup. Any problem exits non-zero and writes nothing: a missing/unreadable source or state dir, an
|
||||
cleanup. Any problem exits non-zero and writes no tiles: a missing/unreadable source, an
|
||||
unsupported or multi-frame image, a scene other than 1, a tile size that is not a multiple of the
|
||||
cell, or a server still holding the state-dir lock (exit 3).
|
||||
cell, a malformed state DB, or a server still holding the state-dir lock (exit 3).
|
||||
|
||||
**A 16384 px scene with 50 tokens (the phone-playtest target).**
|
||||
|
||||
1. Prepare a 16384×16384 PNG or WebP. `--tile-size=64` is the designed fallback and gives 256×256 =
|
||||
65,536 tiles (32 px would give 262,144 files); ImageMagick keeps the source in a disk-backed
|
||||
pixel cache, so allow temp space and a few minutes rather than gigabytes of RAM.
|
||||
2. Stop the server, run the import above, restart it.
|
||||
3. Create the 50 tokens with the GM token panel (or the `token.create` intent); tokens, walls and
|
||||
2. Start with the import in one step: `devbox run serve -- --image=run/map16384.png --tile-size=64`
|
||||
(or stop the server, run `fff-vtt import` as above, then restart it).
|
||||
3. Create the 50 tokens with the seeding tool, not 50 panel submits (a rerun does not double up):
|
||||
|
||||
```sh
|
||||
NODE_EXTRA_CA_CERTS=run/lan/tls/cert.pem \
|
||||
devbox run seed -- --url=https://<lan-ip>:8443 --tokens=49 --vision=1
|
||||
```
|
||||
|
||||
`--replace` clears the labelled `Seed NN` tokens first; `--seed` changes the deterministic
|
||||
layout; the GM token panel's X/Y now default to the current viewport centre. Tokens, walls and
|
||||
explored state are untouched by the import.
|
||||
4. Point nginx's `/_tiles/` alias at `<state-dir>/tiles` as shown below.
|
||||
|
||||
@@ -194,7 +212,8 @@ backup timer) exists in the repo yet; that is M6.
|
||||
only after they have explored a cell that overlaps it; the GM
|
||||
always gets every tile. Because one 32 px cell is the unit of disclosure, do not paint secret
|
||||
doors, traps or notes into map art near places players can reach — keep secrets as GM-only tokens.
|
||||
4. **Tokens.** *Create token* takes a kind, a descriptive name, an actual name, a position, a radius
|
||||
4. **Tokens.** *Create token* takes a kind, a descriptive name, an actual name, a position (X/Y
|
||||
default to the current viewport centre), a radius
|
||||
(blank = scene default), a `gm_only` flag and a controller (a player, or blank for the GM).
|
||||
*Select* a token to edit or remove it, resize it, or add and clear `stuck`/`squeezed` statuses.
|
||||
The GM may drag any token; a player only their own.
|
||||
@@ -243,6 +262,21 @@ Still missing entirely:
|
||||
5. The badge shows `connected`, `reconnecting` or `offline`. A dropped connection keeps the map on
|
||||
screen and retries; the server then resyncs everything.
|
||||
|
||||
### Measure fps on the phone
|
||||
|
||||
Open the site with `?perf=1` appended to the URL (for example
|
||||
`https://192.168.1.50:8443/?perf=1`). After sign-in a small overlay appears in the top-right:
|
||||
|
||||
```
|
||||
fps 59.8 · frame p50 16.6 p95 17.1 ms · JS p50 1.20 p95 2.40 ms · tokens 50 · zoom 1.00
|
||||
```
|
||||
|
||||
It is off by default and adds no per-frame work when off. The line is computed over the last 10 s:
|
||||
`fps` and the frame interval from the render loop, and `JS` is the main-thread time from the first
|
||||
ticker listener to after the render submission, so it is an upper bound on the app's JS cost.
|
||||
`chrome://inspect/#devices` remains the optional cross-check (Frame Rendering Stats + Performance
|
||||
panel); it needs USB debugging, the overlay does not.
|
||||
|
||||
### When something goes wrong
|
||||
|
||||
- **"Key not recognised."** — wrong or unknown key; the server deliberately says the same thing for
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// #82: the GM token form starts at the viewport centre, not the old 400,400. The scene is the
|
||||
// seeded 4096x4096 one, so the initial 1000x700 GM view centres on 2048,2048.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { launchBrowser, newPage, signIn, waitForVisible, withStack } from './stack.mjs'
|
||||
|
||||
test('GM token create defaults X/Y to the viewport centre', { timeout: 120000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey }) => {
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const { page } = await newPage(browser)
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, gmKey)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await page.waitForFunction(() => {
|
||||
const x = document.querySelector('#token-x')
|
||||
const y = document.querySelector('#token-y')
|
||||
return x?.value === '2048' && y?.value === '2048'
|
||||
}, undefined, { timeout: 20000 })
|
||||
assert.equal(await page.inputValue('#token-x'), '2048')
|
||||
assert.equal(await page.inputValue('#token-y'), '2048')
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
// #82: the opt-in perf overlay. Hidden by default (no node, no work), and with `?perf=1` it shows
|
||||
// the numbers the phone checklist records, from the real client through the real server/nginx.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
launchBrowser,
|
||||
newPage,
|
||||
signIn,
|
||||
waitForText,
|
||||
waitForVisible,
|
||||
withStack,
|
||||
} from './stack.mjs'
|
||||
|
||||
async function signInGm(browser, origin, gmKey, path = '/') {
|
||||
const view = await newPage(browser)
|
||||
await view.page.goto(`${origin}${path}`)
|
||||
await waitForVisible(view.page, '#signin')
|
||||
await signIn(view.page, gmKey)
|
||||
await waitForVisible(view.page, '#stage canvas')
|
||||
return view
|
||||
}
|
||||
|
||||
test('perf overlay: absent by default, `?perf=1` shows fps/frame/JS/tokens/zoom', { timeout: 120000 },
|
||||
async () => {
|
||||
await withStack(async ({ origin, gmKey }) => {
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const normal = await signInGm(browser, origin, gmKey)
|
||||
assert.equal(await normal.page.locator('#perf').count(), 0,
|
||||
'no overlay node without the opt-in')
|
||||
await normal.context.close()
|
||||
|
||||
const perf = await signInGm(browser, origin, gmKey, '/?perf=1')
|
||||
await waitForVisible(perf.page, '#perf')
|
||||
const text = await waitForText(perf.page, '#perf', /fps \d/)
|
||||
assert.match(text, /fps \d+\.\d/)
|
||||
assert.match(text, /frame p50 \d+\.\d p95 \d+\.\d ms/)
|
||||
assert.match(text, /JS p50 \d+\.\d\d p95 \d+\.\d\d ms/)
|
||||
assert.match(text, /tokens \d+/)
|
||||
assert.match(text, /zoom \d+\.\d\d/)
|
||||
await perf.context.close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -17,6 +17,7 @@ import { rosterOf } from '../reducer.ts'
|
||||
import type { AdminToken } from '../slices/admin.ts'
|
||||
import { adminTokens, selectedTokenId } from '../slices/admin.ts'
|
||||
import { createVisionFields, updateVisionFields } from '../tokenPanel.ts'
|
||||
import { viewport, viewportCentre } from '../viewport.ts'
|
||||
|
||||
export interface AdminPanelHandlers {
|
||||
send(t: string, fields?: Record<string, unknown>): Promise<AckFrame>
|
||||
@@ -236,6 +237,37 @@ export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers)
|
||||
let tokenSig = ''
|
||||
let populatedFor: string | null = null
|
||||
let current: RootState | null = null
|
||||
// The create form follows the viewport centre (#82) until the GM types a position: `autoPos` is
|
||||
// the pair this module last wrote, so a value the GM edited is never overwritten by a pan.
|
||||
let autoPos: [number, number] | null = null
|
||||
|
||||
function viewportDefaultPosition(): [number, number] | null {
|
||||
const scene = current?.session.scene
|
||||
if (!scene) return null
|
||||
const view = viewport.state
|
||||
if (view.scene && view.size.width > 1 && view.size.height > 1) {
|
||||
const [x, y] = viewportCentre(view.camera, view.size)
|
||||
return [Math.round(x), Math.round(y)]
|
||||
}
|
||||
return [Math.round(scene.w / 2), Math.round(scene.h / 2)]
|
||||
}
|
||||
|
||||
function applyPositionDefault(): void {
|
||||
if (!active) return
|
||||
const next = viewportDefaultPosition()
|
||||
if (!next) return
|
||||
const untouched =
|
||||
autoPos === null ||
|
||||
(xInput.node.value === String(autoPos[0]) && yInput.node.value === String(autoPos[1]))
|
||||
const busy = document.activeElement === xInput.node || document.activeElement === yInput.node
|
||||
if (untouched && !busy) {
|
||||
xInput.node.value = String(next[0])
|
||||
yInput.node.value = String(next[1])
|
||||
}
|
||||
autoPos = next
|
||||
}
|
||||
|
||||
const unsubscribeViewport = viewport.subscribe(applyPositionDefault)
|
||||
|
||||
function showSecret(entry: RosterEntry): string {
|
||||
if (!revealed.has(entry.id)) return ''
|
||||
@@ -396,6 +428,7 @@ export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers)
|
||||
}
|
||||
}
|
||||
renderControllerOptions(createController.node, players, createController.node.value || '')
|
||||
applyPositionDefault()
|
||||
}
|
||||
|
||||
function setError(text: string | null): void {
|
||||
@@ -501,8 +534,9 @@ export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers)
|
||||
const kind = kindInput.node.value.trim()
|
||||
const name = nameInput.node.value.trim()
|
||||
const actual = actualInput.node.value.trim()
|
||||
const x = Number(xInput.node.value)
|
||||
const y = Number(yInput.node.value)
|
||||
const fallback = viewportDefaultPosition()
|
||||
const x = xInput.node.value.trim() === '' && fallback ? fallback[0] : Number(xInput.node.value)
|
||||
const y = yInput.node.value.trim() === '' && fallback ? fallback[1] : Number(yInput.node.value)
|
||||
if (kind === '' || name === '' || actual === '' || !Number.isFinite(x) || !Number.isFinite(y)) {
|
||||
setError('Kind, both names and a numeric position are required.')
|
||||
return
|
||||
@@ -674,6 +708,7 @@ export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers)
|
||||
return {
|
||||
render,
|
||||
destroy() {
|
||||
unsubscribeViewport()
|
||||
keys.clear()
|
||||
revealed.clear()
|
||||
root.remove()
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// The opt-in perf overlay's pure half (#82): URL gating, the rolling frame window and the
|
||||
// percentile/format helpers. No DOM, no Pixi, no socket, so the numbers can be unit-tested.
|
||||
//
|
||||
// The overlay is off unless the page is opened with `?perf=1` (or `?perf=on`/`?perf=true`). When
|
||||
// it is off this module is still imported, but the render module installs no ticker callback and
|
||||
// creates no DOM node: zero per-frame cost (DESIGN 7.2's "keep the overlay minimal").
|
||||
|
||||
/** True when the URL explicitly asks for the overlay; absent and `0`/`false`/`off` mean off. */
|
||||
export function perfEnabled(search: string): boolean {
|
||||
let value: string | null = null
|
||||
try {
|
||||
value = new URLSearchParams(search).get('perf')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (value === null) return false
|
||||
return ['1', 'true', 'on', 'yes'].includes(value.trim().toLowerCase())
|
||||
}
|
||||
|
||||
/** Nearest-rank percentile of a sample; `null` for an empty sample. `p` is 0..1. */
|
||||
export function percentile(samples: readonly number[], p: number): number | null {
|
||||
if (samples.length === 0) return null
|
||||
const sorted = [...samples].sort((a, b) => a - b)
|
||||
const rank = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))
|
||||
return sorted[rank] ?? null
|
||||
}
|
||||
|
||||
export interface FrameSample {
|
||||
/** Wall-clock time the sample was taken (performance.now()). */
|
||||
at: number
|
||||
/** Frame interval in ms (the rAF/ticker delta). */
|
||||
frame: number
|
||||
/** Main-thread JS + render submission time for that frame, in ms. */
|
||||
js: number
|
||||
}
|
||||
|
||||
export interface PerfSnapshot {
|
||||
/** Frames per second over the window's measured span, or null before two samples. */
|
||||
fps: number | null
|
||||
frameP50: number | null
|
||||
frameP95: number | null
|
||||
jsP50: number | null
|
||||
jsP95: number | null
|
||||
/** How many frames the snapshot is based on. */
|
||||
samples: number
|
||||
}
|
||||
|
||||
/** A fixed-duration rolling window of frame samples (default: the last 10 s). */
|
||||
export class PerfWindow {
|
||||
readonly windowMs: number
|
||||
#samples: FrameSample[] = []
|
||||
|
||||
constructor(windowMs = 10_000) {
|
||||
this.windowMs = windowMs
|
||||
}
|
||||
|
||||
add(frameMs: number, jsMs: number, now = performance.now()): void {
|
||||
if (!Number.isFinite(frameMs) || frameMs <= 0) return
|
||||
this.#samples.push({ at: now, frame: frameMs, js: Number.isFinite(jsMs) ? Math.max(0, jsMs) : 0 })
|
||||
this.#prune(now)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.#samples = []
|
||||
}
|
||||
|
||||
snapshot(now = performance.now()): PerfSnapshot {
|
||||
this.#prune(now)
|
||||
const frames = this.#samples.map(s => s.frame)
|
||||
const js = this.#samples.map(s => s.js)
|
||||
const meanFrame = frames.length > 0 ? frames.reduce((a, b) => a + b, 0) / frames.length : null
|
||||
const fps = meanFrame !== null && meanFrame > 0 ? 1000 / meanFrame : null
|
||||
return {
|
||||
fps,
|
||||
frameP50: percentile(frames, 0.5),
|
||||
frameP95: percentile(frames, 0.95),
|
||||
jsP50: percentile(js, 0.5),
|
||||
jsP95: percentile(js, 0.95),
|
||||
samples: frames.length,
|
||||
}
|
||||
}
|
||||
|
||||
#prune(now: number): void {
|
||||
const cutoff = now - this.windowMs
|
||||
let drop = 0
|
||||
while (drop < this.#samples.length && this.#samples[drop]!.at < cutoff) drop += 1
|
||||
if (drop > 0) this.#samples.splice(0, drop)
|
||||
}
|
||||
}
|
||||
|
||||
function number(value: number | null, digits: number): string {
|
||||
return value === null ? '—' : value.toFixed(digits)
|
||||
}
|
||||
|
||||
/** The overlay's one line of text. Everything here is a number or a fixed label. */
|
||||
export function formatSnapshot(snapshot: PerfSnapshot, tokens: number, zoom: number): string {
|
||||
return [
|
||||
`fps ${number(snapshot.fps, 1)}`,
|
||||
`frame p50 ${number(snapshot.frameP50, 1)} p95 ${number(snapshot.frameP95, 1)} ms`,
|
||||
`JS p50 ${number(snapshot.jsP50, 2)} p95 ${number(snapshot.jsP95, 2)} ms`,
|
||||
`tokens ${tokens}`,
|
||||
`zoom ${zoom.toFixed(2)}`,
|
||||
].join(' · ')
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// The opt-in perf overlay (#82): fps, frame p50/p95, JS/render p50/p95, token count and zoom.
|
||||
// Mounted only when the URL says `?perf=1` (client/src/perf.ts). Off means no DOM node, no ticker
|
||||
// listener and no per-frame work.
|
||||
//
|
||||
// Timing comes from the real Pixi ticker, not a second rAF loop: a listener at INTERACTION runs
|
||||
// first in the frame and one at UTILITY runs after the render plugin (registered at LOW), so the
|
||||
// difference is the frame's main-thread JS + render submission time. `ticker.elapsedMS` is the raw
|
||||
// frame interval (not speed-scaled), which is what the phone's fps readout needs.
|
||||
|
||||
import { UPDATE_PRIORITY } from 'pixi.js'
|
||||
import type { Ticker } from 'pixi.js'
|
||||
import type { RenderModule } from '../stage.ts'
|
||||
import { viewport } from '../../viewport.ts'
|
||||
import { tokensOf } from '../../slices/tokens.ts'
|
||||
import { formatSnapshot, PerfWindow, perfEnabled } from '../../perf.ts'
|
||||
|
||||
const UPDATE_EVERY_MS = 1000
|
||||
|
||||
export const renderModule: RenderModule = {
|
||||
name: 'perf',
|
||||
mount({ app, store }) {
|
||||
if (!perfEnabled(window.location.search)) return
|
||||
|
||||
const node = document.createElement('div')
|
||||
node.id = 'perf'
|
||||
node.setAttribute('role', 'status')
|
||||
node.setAttribute('aria-live', 'off')
|
||||
node.style.cssText =
|
||||
'position:fixed;top:40px;right:12px;z-index:3;padding:6px 10px;border-radius:6px;' +
|
||||
'border:1px solid #777;background:rgb(0 0 0 / 80%);color:#eee;font:11px/1.5 ' +
|
||||
'ui-monospace,monospace;pointer-events:none;white-space:nowrap'
|
||||
node.textContent = 'perf: warming up…'
|
||||
const host = document.querySelector('#panels') ?? document.body
|
||||
host.append(node)
|
||||
|
||||
const windowStats = new PerfWindow(10_000)
|
||||
let frameStart = 0
|
||||
let started = false
|
||||
let lastUpdate = 0
|
||||
|
||||
const begin = (): void => {
|
||||
frameStart = performance.now()
|
||||
}
|
||||
const end = (ticker: Ticker): void => {
|
||||
const now = performance.now()
|
||||
if (started && frameStart > 0) windowStats.add(ticker.elapsedMS, now - frameStart, now)
|
||||
started = true
|
||||
if (lastUpdate === 0) lastUpdate = now
|
||||
if (now - lastUpdate < UPDATE_EVERY_MS) return
|
||||
lastUpdate = now
|
||||
const snapshot = windowStats.snapshot(now)
|
||||
node.textContent = formatSnapshot(snapshot, tokensOf(store.state).length, viewport.state.camera.zoom)
|
||||
}
|
||||
|
||||
app.ticker.add(begin, undefined, UPDATE_PRIORITY.INTERACTION)
|
||||
app.ticker.add(end, undefined, UPDATE_PRIORITY.UTILITY)
|
||||
|
||||
return () => {
|
||||
app.ticker.remove(begin)
|
||||
app.ticker.remove(end)
|
||||
node.remove()
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -71,6 +71,11 @@ export function panCamera(camera: Camera, dx: number, dy: number): Camera {
|
||||
return { ...camera, x: camera.x + dx, y: camera.y + dy }
|
||||
}
|
||||
|
||||
/** The world point at the centre of the viewport: the default position for a new token (#82). */
|
||||
export function viewportCentre(camera: Camera, size: ViewportSize): [number, number] {
|
||||
return screenToWorld(camera, size.width / 2, size.height / 2)
|
||||
}
|
||||
|
||||
/**
|
||||
* Multiply the zoom by `factor` around a screen anchor: the world point under the anchor does not
|
||||
* move, which is what a wheel over the pointer or a pinch between two fingers must feel like.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// #82 perf overlay seam: URL gating, the rolling window's percentiles and the one-line format.
|
||||
// Pure (no DOM/Pixi), so the numbers the phone reads are pinned without a browser.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { PerfWindow, formatSnapshot, percentile, perfEnabled } from '../src/perf.ts'
|
||||
|
||||
describe('URL gate', () => {
|
||||
it('is off when the query is absent, empty or explicitly false', () => {
|
||||
for (const search of ['', '?x=1', '?perf=', '?perf=0', '?perf=false', '?perf=off', '?perf=no']) {
|
||||
expect(perfEnabled(search), search).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('is on for 1/true/on/yes, case-insensitively', () => {
|
||||
for (const search of ['?perf=1', '?perf=true', '?perf=TRUE', '?perf=on', '?perf=yes', '?a=b&perf=1']) {
|
||||
expect(perfEnabled(search), search).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('percentile', () => {
|
||||
it('is null for an empty sample and nearest-rank otherwise', () => {
|
||||
expect(percentile([], 0.5)).toBeNull()
|
||||
expect(percentile([16, 17, 18, 19, 20], 0.5)).toBe(18)
|
||||
expect(percentile([20, 16, 20, 18, 16], 0.95)).toBe(20)
|
||||
expect(percentile([16], 0.95)).toBe(16)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rolling window', () => {
|
||||
it('reports fps from the mean frame interval and p50/p95 of frames and JS', () => {
|
||||
const window = new PerfWindow(1000)
|
||||
// Five 16 ms frames at exactly 1 s span: 62.5 fps, p50 16, p95 20.
|
||||
for (let i = 0; i < 5; i += 1) window.add(i === 4 ? 20 : 16, i + 0.5, 1000 + i * 16)
|
||||
const snapshot = window.snapshot(1100)
|
||||
expect(snapshot.samples).toBe(5)
|
||||
expect(snapshot.fps).toBeCloseTo(59.52, 2)
|
||||
expect(snapshot.frameP50).toBe(16)
|
||||
expect(snapshot.frameP95).toBe(20)
|
||||
expect(snapshot.jsP50).toBe(2.5)
|
||||
expect(snapshot.jsP95).toBe(4.5)
|
||||
})
|
||||
|
||||
it('drops samples older than the window and ignores a non-positive frame', () => {
|
||||
const window = new PerfWindow(1000)
|
||||
window.add(16, 1, 1000)
|
||||
window.add(0, 1, 1000)
|
||||
window.add(-1, 1, 1000)
|
||||
window.add(16, 1, 2500)
|
||||
const snapshot = window.snapshot(2600)
|
||||
expect(snapshot.samples).toBe(1)
|
||||
expect(snapshot.fps).toBeCloseTo(62.5, 5)
|
||||
})
|
||||
|
||||
it('has no fps before a sample and formats a missing JS measure as an em dash', () => {
|
||||
expect(new PerfWindow().snapshot(0).fps).toBeNull()
|
||||
const text = formatSnapshot(
|
||||
{ fps: 59.9, frameP50: 16.7, frameP95: 17.1, jsP50: null, jsP95: null, samples: 600 },
|
||||
50,
|
||||
1.25,
|
||||
)
|
||||
expect(text).toContain('fps 59.9')
|
||||
expect(text).toContain('frame p50 16.7 p95 17.1 ms')
|
||||
expect(text).toContain('JS p50 — p95 — ms')
|
||||
expect(text).toContain('tokens 50')
|
||||
expect(text).toContain('zoom 1.25')
|
||||
})
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
pinchCamera,
|
||||
screenToWorld,
|
||||
tileUrl,
|
||||
viewportCentre,
|
||||
visibleTiles,
|
||||
worldToScreen,
|
||||
zoomCamera,
|
||||
@@ -78,6 +79,11 @@ describe('camera', () => {
|
||||
expect(screen[1]).toBeCloseTo(80, 10)
|
||||
})
|
||||
|
||||
it('viewportCentre is the world point under the middle of the screen (#82)', () => {
|
||||
expect(viewportCentre(centredCamera(scene, size), size)).toEqual([2048, 2048])
|
||||
expect(viewportCentre({ x: -100, y: -200, zoom: 2 }, size)).toEqual([130, 180])
|
||||
})
|
||||
|
||||
it('zoomCamera keeps the world point under the anchor fixed and clamps', () => {
|
||||
const camera = { x: -1000, y: -800, zoom: 1 }
|
||||
const anchor = { x: 120, y: 200 }
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
"serve": [
|
||||
"tools/serve.sh"
|
||||
],
|
||||
"seed": [
|
||||
"node tools/seed.mjs"
|
||||
],
|
||||
"mutation": [
|
||||
"tools/mutation.sh"
|
||||
],
|
||||
|
||||
@@ -26,6 +26,10 @@ for the M4 run: what exists, what is proven, what is deliberately still open.
|
||||
- **#77** - the human real-phone playtest: Note 10 + laptop, 16384 px map, 50 tokens, fog active,
|
||||
LAN TLS/h2. Its comment is the checklist with commands, numbers to record and pass thresholds.
|
||||
`#63` and `#62` close only after #77.
|
||||
- **Playtest tooling (#82, closed with this note):** `?perf=1` in-app fps/frame/JS/token/zoom
|
||||
overlay (off by default), `fff-vtt import` on a fresh/empty state dir, `devbox run serve --
|
||||
--image=<file>`, `devbox run seed -- --url=...` for the 50 tokens, and the GM token form's X/Y
|
||||
default to the viewport centre.
|
||||
- **M5** - concurrency, bounded outbox/coalescing, lag tracking, SIGTERM, metrics, nginx dead-peer
|
||||
timeout, stats outside the lock. `#34` heartbeat is M5.
|
||||
- **Deferred:** `db_connector` -> thin sqlite3 binding (build item 13); per-token polygon cache and
|
||||
|
||||
+5
-3
@@ -61,9 +61,11 @@ built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built `lib
|
||||
`fff-vtt import`, checks the exact `<x>_<y>.png` set and per-tile geometry, then starts the real
|
||||
server and test nginx and proves a player with an explored overlapping cell gets `200` (and an
|
||||
unexplored tile `403`, another art version `404`). A re-import grows `art_version` and the
|
||||
restarted server serves the `v<new>` tree. Every refused import (bad/absent image, unsupported or
|
||||
multi-frame format, scene ≠ 1, `tile_size % cell ≠ 0`, absent state dir or DB, held lock) exits
|
||||
non-zero and leaves no tile tree. This is §10.3 Tiles evidence.
|
||||
restarted server serves the `v<new>` tree. The CLI also creates and migrates a fresh/empty state
|
||||
dir through the server's startup path (#82), so an import works before the first serve. Every
|
||||
refused import (bad/absent image, unsupported or multi-frame format, scene ≠ 1, `tile_size % cell
|
||||
≠ 0`, malformed DB, or a running server holding the lock) exits non-zero and leaves no tile tree;
|
||||
`serve --image` runs the import before starting the stack. This is §10.3 Tiles evidence.
|
||||
|
||||
### 3.4 Threat list
|
||||
|
||||
|
||||
@@ -347,3 +347,14 @@ proc migrate*(db: DbConn): int =
|
||||
except CatchableError: discard # the original error is the one worth reporting
|
||||
raise newException(MigrationError,
|
||||
"migration " & $m.version & " (" & m.name & ") failed: " & e.msg)
|
||||
|
||||
proc openMigratedDatabase*(path: string): tuple[db: DbConn, applied: int] =
|
||||
## The one startup path shared by the server, `gm-key` and `import` (#82): open the DB with the
|
||||
## engine settings above, then apply every pending migration. A failure closes the connection
|
||||
## before re-raising, so a caller that handles the error never leaks the handle.
|
||||
result.db = openDatabase(path)
|
||||
try:
|
||||
result.applied = migrate(result.db)
|
||||
except CatchableError:
|
||||
close(result.db)
|
||||
raise
|
||||
|
||||
+22
-12
@@ -32,8 +32,10 @@ Options:
|
||||
positive multiple of the scene's explored cell (32 px), so 64 is the
|
||||
designed fallback.
|
||||
--scene=<id> Target scene. v1 has exactly one scene, id 1.
|
||||
--state-dir=<path> Directory holding state.db and tiles (default: run). The server must be
|
||||
stopped: the state-dir lock is refused (exit 3), like gm-key --new.
|
||||
--state-dir=<path> Directory holding state.db and tiles (default: run). A missing or empty
|
||||
directory is created and migrated through the server's startup path, so
|
||||
an import works before the first serve. The server must be stopped: the
|
||||
state-dir lock is refused (exit 3), like gm-key --new.
|
||||
|
||||
Tiles land in <state-dir>/tiles/<scene>/v<art_version>/<x>_<y>.png, origin at the world origin.
|
||||
A re-import for a scene that already has art grows art_version and writes a new v directory; the
|
||||
@@ -143,13 +145,7 @@ proc runImport*(rawArgs: seq[string]): int =
|
||||
if a.scene != DefaultSceneId:
|
||||
return failImport("scene " & $a.scene & ": v1 has exactly one scene, id " & $DefaultSceneId, 2)
|
||||
|
||||
# Validate the state dir and the source before touching either one: an error changes nothing.
|
||||
if not dirExists(a.cfg.stateDir):
|
||||
return failImport("state dir \"" & a.cfg.stateDir &
|
||||
"\" does not exist or is not readable; create it by running the server or gm-key once", 1)
|
||||
if not fileExists(a.cfg.dbPath):
|
||||
return failImport("no state.db in \"" & a.cfg.stateDir &
|
||||
"\"; create it by running the server or gm-key once", 1)
|
||||
# Validate the source before touching the state dir: an error creates nothing.
|
||||
if not fileExists(a.image):
|
||||
return failImport("source image \"" & a.image & "\" does not exist", 1)
|
||||
let imagePath = expandFilename(a.image)
|
||||
@@ -175,22 +171,36 @@ proc runImport*(rawArgs: seq[string]): int =
|
||||
if imgW <= 0 or imgH <= 0:
|
||||
return failImport("image \"" & a.image & "\" has no pixels", 1)
|
||||
|
||||
# A fresh or empty state dir is the normal case (#82): create and migrate through the same
|
||||
# startup path as the server, under the same state-dir lock. The lock is taken before the DB is
|
||||
# created, so a running server can never race an import.
|
||||
if not dirExists(a.cfg.stateDir):
|
||||
try: createDir(a.cfg.stateDir)
|
||||
except OSError as e:
|
||||
return failImport("cannot create state dir \"" & a.cfg.stateDir & "\": " & e.msg, 1)
|
||||
|
||||
var lock = tryAcquire(a.cfg.stateDir)
|
||||
if not lock.held:
|
||||
return failImport("the server is running on \"" & a.cfg.stateDir &
|
||||
"\" (state-dir lock held); stop it first, then restart it after the import", 3)
|
||||
|
||||
var conn: DbConn
|
||||
var applied: int
|
||||
try:
|
||||
conn = openDatabase(a.cfg.dbPath)
|
||||
let opened = openMigratedDatabase(a.cfg.dbPath)
|
||||
conn = opened.db
|
||||
applied = opened.applied
|
||||
except CatchableError as e:
|
||||
return failImport("cannot open " & a.cfg.dbPath & ": " & e.msg, 1)
|
||||
return failImport("cannot open or migrate " & a.cfg.dbPath & ": " & e.msg, 1)
|
||||
defer: close(conn)
|
||||
if applied > 0:
|
||||
stderr.writeLine "fff-vtt import: created/migrated " & a.cfg.dbPath &
|
||||
" (" & $applied & " schema step" & (if applied == 1: "" else: "s") & ")"
|
||||
|
||||
let loaded = loadScene(conn)
|
||||
if loaded.isNone:
|
||||
return failImport("state.db has no scene " & $DefaultSceneId &
|
||||
"; start the server once to migrate and seed it", 1)
|
||||
" after migration; the database is inconsistent", 1)
|
||||
let scene = loaded.get
|
||||
|
||||
var tileSize = if a.hasTileSize: a.tileSize else: scene.tileSize
|
||||
|
||||
+11
-9
@@ -2380,7 +2380,8 @@ Commands:
|
||||
gm-key --new Rotate the GM key and revoke all GM sessions. Refused while the server
|
||||
holds the state-dir lock (stop the server first).
|
||||
import Slice a PNG/WebP map into the scene's tile tree and update the scene row.
|
||||
Stop the server first (it reads the scene at startup); restart it after.
|
||||
A fresh/empty state dir is created and migrated first. Stop the server
|
||||
first (it reads the scene at startup); restart it after.
|
||||
Run `fff-vtt import --help` for the import arguments.
|
||||
|
||||
The bind address is fixed at 127.0.0.1 and is not a key: put nginx (or another TLS proxy) in front.
|
||||
@@ -2425,13 +2426,12 @@ proc runGmKey(rawArgs: seq[string]): int =
|
||||
|
||||
var conn: DbConn
|
||||
try:
|
||||
conn = openDatabase(cfg.dbPath)
|
||||
conn = openMigratedDatabase(cfg.dbPath).db
|
||||
except CatchableError as e:
|
||||
stderr.writeLine "fff-vtt gm-key: cannot open " & cfg.dbPath & ": " & e.msg
|
||||
stderr.writeLine "fff-vtt gm-key: cannot open or migrate " & cfg.dbPath & ": " & e.msg
|
||||
return 1
|
||||
defer: close(conn)
|
||||
try:
|
||||
discard migrate(conn)
|
||||
let created = ensureGm(conn, rotate)
|
||||
if created.rotated:
|
||||
stdout.writeLine "GM key (new): " & created.key
|
||||
@@ -2466,15 +2466,17 @@ proc runServer(cfg: Config): int =
|
||||
return 1
|
||||
|
||||
var conn: DbConn
|
||||
var applied: int
|
||||
try:
|
||||
conn = openDatabase(cfg.dbPath)
|
||||
let opened = openMigratedDatabase(cfg.dbPath)
|
||||
conn = opened.db
|
||||
applied = opened.applied
|
||||
except MigrationError as e:
|
||||
lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)])
|
||||
return 1
|
||||
except CatchableError as e:
|
||||
lg.log(lvError, "db_open_failed", [("path", cfg.dbPath), ("error", e.msg)])
|
||||
return 1
|
||||
let applied = try: migrate(conn)
|
||||
except CatchableError as e:
|
||||
lg.log(lvError, "db_migrate_failed", [("path", cfg.dbPath), ("error", e.msg)])
|
||||
return 1
|
||||
lg.log(lvInfo, "db_ready", [("path", cfg.dbPath), ("schema_version", $schemaVersion(conn)),
|
||||
("applied", $applied)])
|
||||
|
||||
|
||||
+32
-14
@@ -8,7 +8,6 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createPlayer, freePort, httpsBaseUrl, namePlayer } from './lib.mjs'
|
||||
@@ -137,6 +136,38 @@ test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 th
|
||||
}
|
||||
})
|
||||
|
||||
test('map import CLI: a fresh/empty state dir is created, migrated and servable (#82)',
|
||||
async () => {
|
||||
const root = makeStateDir()
|
||||
const stateDir = path.join(root, 'fresh')
|
||||
const img = writeFixtureImage(path.join(root, 'map.png'))
|
||||
try {
|
||||
assert.equal(fs.existsSync(stateDir), false, 'the state dir starts absent')
|
||||
const imported = runImport(stateDir, [`--image=${img}`, '--tile-size=64'])
|
||||
assert.equal(imported.status, 0, imported.stderr)
|
||||
assert.match(imported.stderr, /created\/migrated .*schema step/)
|
||||
assert.match(imported.stdout, /256x192 px, tile 64 px, 4x3 tiles/)
|
||||
assert.equal(fs.existsSync(path.join(stateDir, 'state.db')), true, 'the DB is created')
|
||||
assert.equal(tileNames(path.join(stateDir, 'tiles', '1', 'v1')).length, 12,
|
||||
'the imported tile tree exists without a prior server or gm-key run')
|
||||
|
||||
const gmKey = gmKeyOf(stateDir)
|
||||
const s = await startServer({ stateDir })
|
||||
try {
|
||||
const gm = await openAs(s.origin, gmKey)
|
||||
const hello = await gm.ws.waitText('hello')
|
||||
assert.equal(hello.scene.w, 256, 'the server serves the imported scene')
|
||||
assert.equal(hello.scene.h, 192)
|
||||
assert.equal(hello.scene.tile_size, 64)
|
||||
gm.ws.close()
|
||||
} finally {
|
||||
await stopServer(s)
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('map import CLI: every refused import exits non-zero with a message and changes nothing',
|
||||
async () => {
|
||||
const stateDir = makeStateDir()
|
||||
@@ -170,19 +201,6 @@ test('map import CLI: every refused import exits non-zero with a message and cha
|
||||
assert.match(help.stdout, /--image=<path>/)
|
||||
assert.match(help.stdout, /state-dir lock is refused/)
|
||||
|
||||
const ghost = path.join(os.tmpdir(), `fffvtt-absent-${process.pid}-${Date.now()}`)
|
||||
const absent = runImport(ghost, [`--image=${img}`])
|
||||
assert.notEqual(absent.status, 0)
|
||||
assert.match(absent.stderr, /does not exist/)
|
||||
assert.equal(fs.existsSync(ghost), false, 'an absent state dir is not created')
|
||||
|
||||
const empty = makeStateDir()
|
||||
const noDb = runImport(empty, [`--image=${img}`])
|
||||
assert.notEqual(noDb.status, 0)
|
||||
assert.match(noDb.stderr, /no state\.db/)
|
||||
assert.equal(fs.existsSync(path.join(empty, 'tiles')), false)
|
||||
fs.rmSync(empty, { recursive: true, force: true })
|
||||
|
||||
// An unreadable DB (the state-dir contents cannot be opened) is a clear runtime error, not a
|
||||
// migration attempt or a partial import.
|
||||
const dbFile = path.join(stateDir, 'state.db')
|
||||
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
#!/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)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// #82: `tools/seed.mjs` over the real wire. It signs in as GM, creates deterministic NPC tokens,
|
||||
// skips labels on a rerun and `--replace` clears the labelled set first.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import path from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { projectRoot, sleep } from './lib.mjs'
|
||||
import { openAs, withGmServer } from './withserver.mjs'
|
||||
|
||||
function runSeed(args) {
|
||||
const r = spawnSync(process.execPath, [path.join(projectRoot, 'tools', 'seed.mjs'), ...args],
|
||||
{ cwd: projectRoot, encoding: 'utf8' })
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr }
|
||||
}
|
||||
|
||||
/** The GM's current token set, deduped by id from a fresh connection's resync. */
|
||||
async function collectTokens(origin, gmKey) {
|
||||
const gm = await openAs(origin, gmKey)
|
||||
const hello = await gm.ws.waitText('hello')
|
||||
await gm.ws.waitText('walls')
|
||||
await sleep(400)
|
||||
const byId = new Map()
|
||||
for (const message of gm.ws.messages) {
|
||||
if (message.t === 'token' && typeof message.id === 'string') byId.set(message.id, message)
|
||||
}
|
||||
gm.ws.close()
|
||||
await gm.ws.closed
|
||||
return { scene: hello.scene, tokens: [...byId.values()] }
|
||||
}
|
||||
|
||||
const byName = tokens => [...tokens].sort((a, b) => a.name.localeCompare(b.name))
|
||||
|
||||
test('seed: creates N deterministic NPC tokens, skips a rerun, and --replace starts over',
|
||||
{ timeout: 180000 }, async () => {
|
||||
await withGmServer(async (server, gmKey) => {
|
||||
const url = server.origin
|
||||
const args = [`--url=${url}`, `--key=${gmKey}`, '--tokens=6', '--vision=2', '--seed=7']
|
||||
const first = runSeed(args)
|
||||
assert.equal(first.status, 0, first.stderr)
|
||||
assert.match(first.stdout, /seeded 6 tokens \(6 created, 0 already present, 0 removed\)/)
|
||||
|
||||
const firstSet = await collectTokens(url, gmKey)
|
||||
assert.equal(firstSet.tokens.length, 6)
|
||||
const tokens = byName(firstSet.tokens)
|
||||
assert.deepEqual(tokens.map(t => t.name), ['Seed 01', 'Seed 02', 'Seed 03', 'Seed 04', 'Seed 05', 'Seed 06'])
|
||||
for (const token of tokens) {
|
||||
assert.equal(token.kind, 'npc')
|
||||
assert.equal(token.controller, null, 'an NPC stays GM-controlled')
|
||||
assert.equal(token.gm_only, false)
|
||||
assert.ok(token.pos[0] >= 1 && token.pos[0] < firstSet.scene.w)
|
||||
assert.ok(token.pos[1] >= 1 && token.pos[1] < firstSet.scene.h)
|
||||
}
|
||||
assert.equal(tokens[0].flags.vision, true, 'the first token has vision')
|
||||
assert.equal(tokens[0].vision_radius, 400)
|
||||
assert.equal(tokens[1].flags.vision, true)
|
||||
assert.equal(tokens[2].flags.vision, undefined, 'the rest keep the DESIGN 8 {} default')
|
||||
const positions = tokens.map(t => t.pos.join(','))
|
||||
assert.equal(new Set(positions).size, 6, 'positions are distinct')
|
||||
|
||||
// Same seed on a second fresh scene: same layout (ids differ, positions do not).
|
||||
await withGmServer(async (other, otherKey) => {
|
||||
const second = runSeed([`--url=${other.origin}`, `--key=${otherKey}`, '--tokens=6',
|
||||
'--seed=7'])
|
||||
assert.equal(second.status, 0, second.stderr)
|
||||
const otherSet = await collectTokens(other.origin, otherKey)
|
||||
assert.deepEqual(byName(otherSet.tokens).map(t => t.pos), byName(tokens).map(t => t.pos))
|
||||
})
|
||||
|
||||
// Rerun without --replace: no duplicates.
|
||||
const again = runSeed(args)
|
||||
assert.equal(again.status, 0, again.stderr)
|
||||
assert.match(again.stdout, /seeded 6 tokens \(0 created, 6 already present, 0 removed\)/)
|
||||
assert.equal((await collectTokens(url, gmKey)).tokens.length, 6)
|
||||
|
||||
// A smaller run without --replace leaves the extra labelled tokens alone; --replace clears
|
||||
// every labelled token (even one outside the new count) and rebuilds exactly N.
|
||||
const small = runSeed([`--url=${url}`, `--key=${gmKey}`, '--tokens=4', '--seed=7'])
|
||||
assert.equal(small.status, 0, small.stderr)
|
||||
assert.equal((await collectTokens(url, gmKey)).tokens.length, 6)
|
||||
|
||||
const replaced = runSeed([`--url=${url}`, `--key=${gmKey}`, '--tokens=4', '--seed=7',
|
||||
'--replace'])
|
||||
assert.equal(replaced.status, 0, replaced.stderr)
|
||||
assert.match(replaced.stdout, /4 created, 0 already present, 6 removed/)
|
||||
const after = await collectTokens(url, gmKey)
|
||||
assert.equal(after.tokens.length, 4)
|
||||
assert.deepEqual(byName(after.tokens).map(t => t.name),
|
||||
['Seed 01', 'Seed 02', 'Seed 03', 'Seed 04'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
// #82: `serve --image` is an end-to-end smoke of the playtest command: import runs first into a
|
||||
// fresh state dir, then the real server + TLS/HTTP2 nginx start and the GM sees the imported
|
||||
// scene. The internal probe is a child node with NODE_EXTRA_CA_CERTS set to the generated cert.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { freePort, projectRoot, sleep } from './lib.mjs'
|
||||
import { buildServer, makeStateDir } from './withserver.mjs'
|
||||
import { pngBytesWH } from './tilefixture.mjs'
|
||||
|
||||
const PROBE = `
|
||||
import { openAs } from './tools/withserver.mjs'
|
||||
const gm = await openAs(process.env.PROBE_URL, process.env.PROBE_KEY)
|
||||
const hello = await gm.ws.waitText('hello')
|
||||
process.stdout.write(JSON.stringify(hello.scene) + '\\n')
|
||||
gm.ws.close()
|
||||
process.exit(0)
|
||||
`
|
||||
|
||||
function waitFor(child, pattern, timeoutMs = 60000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let out = ''
|
||||
let err = ''
|
||||
const timer = setTimeout(() => {
|
||||
cleanup()
|
||||
reject(new Error(`timed out waiting for ${pattern}\n--- stdout ---\n${out}\n--- stderr ---\n${err}`))
|
||||
}, timeoutMs)
|
||||
const onData = chunk => {
|
||||
out += chunk
|
||||
const match = pattern.exec(out)
|
||||
if (match) { cleanup(); resolve({ match, out }) }
|
||||
}
|
||||
const onErr = chunk => { err += chunk }
|
||||
const onExit = code => {
|
||||
cleanup()
|
||||
reject(new Error(`serve exited (code=${code}) before ${pattern}\n--- stdout ---\n${out}\n--- stderr ---\n${err}`))
|
||||
}
|
||||
function cleanup() {
|
||||
clearTimeout(timer)
|
||||
child.stdout.off('data', onData)
|
||||
child.stderr.off('data', onErr)
|
||||
child.off('exit', onExit)
|
||||
}
|
||||
child.stdout.on('data', onData)
|
||||
child.stderr.on('data', onErr)
|
||||
child.on('exit', onExit)
|
||||
})
|
||||
}
|
||||
|
||||
test('serve --image: imports into a fresh dir, then serves the scene (#82)', { timeout: 120000 },
|
||||
async () => {
|
||||
const root = makeStateDir()
|
||||
const stateDir = path.join(root, 'lan')
|
||||
const image = path.join(root, 'map.png')
|
||||
fs.writeFileSync(image, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 128]))
|
||||
const port = await freePort()
|
||||
const bin = buildServer()
|
||||
const child = spawn(process.execPath, [
|
||||
path.join(projectRoot, 'tools', 'serve.mjs'),
|
||||
'--host=127.0.0.1', `--port=${port}`, `--state-dir=${stateDir}`,
|
||||
`--image=${image}`, '--tile-size=64', `--server-bin=${bin}`,
|
||||
], { cwd: projectRoot, stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
try {
|
||||
const { out } = await waitFor(child, /GM key:\s+([A-Z0-9-]+)/)
|
||||
assert.match(out, /importing .*map\.png before starting the server/)
|
||||
assert.match(out, /URL:\s+https:\/\/127\.0\.0\.1:\d+/)
|
||||
assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1', 'v1')).filter(n => n.endsWith('.png')).length,
|
||||
12, 'the import ran before the server and published v1 tiles')
|
||||
const url = /URL:\s+(https:\/\/\S+)/.exec(out)[1]
|
||||
const key = /GM key:\s+([A-Z0-9-]+)/.exec(out)[1]
|
||||
|
||||
const probe = spawnSync(process.execPath, ['--input-type=module', '-e', PROBE], {
|
||||
cwd: projectRoot,
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_EXTRA_CA_CERTS: path.join(stateDir, 'tls', 'cert.pem'),
|
||||
PROBE_URL: url,
|
||||
PROBE_KEY: key,
|
||||
},
|
||||
})
|
||||
assert.equal(probe.status, 0, probe.stderr)
|
||||
const scene = JSON.parse(probe.stdout.trim())
|
||||
assert.equal(scene.w, 256)
|
||||
assert.equal(scene.h, 192)
|
||||
assert.equal(scene.tile_size, 64)
|
||||
} finally {
|
||||
child.kill('SIGINT')
|
||||
const exited = await Promise.race([
|
||||
new Promise(resolve => child.once('exit', code => resolve(code))),
|
||||
sleep(15000).then(() => 'timeout'),
|
||||
])
|
||||
assert.equal(exited, 0, 'SIGINT stops nginx and the server')
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
+54
-6
@@ -10,32 +10,53 @@
|
||||
// --dist=<path> FFF_VTT_LAN_DIST default: client/dist
|
||||
// --server-bin=<path> FFF_VTT_SERVER_BIN default: run/fff-vtt
|
||||
// --server-port=<n> FFF_VTT_SERVER_PORT default: a free loopback port
|
||||
// --image=<file> FFF_VTT_LAN_IMAGE import this map before the server starts (#82);
|
||||
// the import runs offline and refuses (exit 3) if a server holds the lock
|
||||
// --tile-size=<px> FFF_VTT_LAN_TILE optional for --image (64 is the playtest fallback)
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { DEFAULT_DIST, DEFAULT_LAN_PORT, DEFAULT_SERVER_BIN, DEFAULT_STATE_DIR,
|
||||
detectLanIp, startLanServe } from './lanserve.mjs'
|
||||
|
||||
const USAGE = `usage: devbox run serve [-- --host=<ip>] [-- --port=<n>] [-- --state-dir=<path>]
|
||||
[-- --image=<file> [-- --tile-size=<px>]]
|
||||
|
||||
Starts the FFF_vtt server behind a TLS/HTTP2 nginx on the LAN. State, GM key and certificate
|
||||
persist under the state dir (default ${DEFAULT_STATE_DIR}), so a session (and a trusted phone)
|
||||
survives Ctrl-C and a restart. Env equivalents: FFF_VTT_LAN_HOST, FFF_VTT_LAN_PORT,
|
||||
FFF_VTT_STATE_DIR.
|
||||
|
||||
--image imports a PNG/WebP map before starting (a fresh state dir is created and migrated first)
|
||||
and then serves the imported scene; a server already holding the state-dir lock is refused (exit 3).
|
||||
`
|
||||
|
||||
const VALUE_OPTIONS = new Set(
|
||||
['host', 'port', 'state-dir', 'dist', 'server-bin', 'server-port', 'image', 'tile-size'],
|
||||
)
|
||||
|
||||
function parseArgs(argv) {
|
||||
const opts = {}
|
||||
for (const arg of argv) {
|
||||
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)
|
||||
const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg)
|
||||
if (!m) throw new Error(`unexpected argument ${JSON.stringify(arg)} (see --help)`)
|
||||
const [, key, value] = m
|
||||
const key = m[1]
|
||||
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 === 'host') opts.host = value
|
||||
else if (key === 'port') opts.port = Number(value)
|
||||
else if (key === 'state-dir') opts.stateDir = value
|
||||
else if (key === 'dist') opts.distDir = value
|
||||
else if (key === 'server-bin') opts.bin = value
|
||||
else if (key === 'server-port') opts.serverPort = Number(value)
|
||||
else throw new Error(`unknown option --${key} (see --help)`)
|
||||
else if (key === 'image') opts.image = value
|
||||
else if (key === 'tile-size') opts.tileSize = Number(value)
|
||||
}
|
||||
return opts
|
||||
}
|
||||
@@ -49,9 +70,34 @@ function envOptions() {
|
||||
if (env.FFF_VTT_LAN_DIST) opts.distDir = env.FFF_VTT_LAN_DIST
|
||||
if (env.FFF_VTT_SERVER_BIN) opts.bin = env.FFF_VTT_SERVER_BIN
|
||||
if (env.FFF_VTT_SERVER_PORT) opts.serverPort = Number(env.FFF_VTT_SERVER_PORT)
|
||||
if (env.FFF_VTT_LAN_IMAGE) opts.image = env.FFF_VTT_LAN_IMAGE
|
||||
if (env.FFF_VTT_LAN_TILE) opts.tileSize = Number(env.FFF_VTT_LAN_TILE)
|
||||
return opts
|
||||
}
|
||||
|
||||
/**
|
||||
* `--image`: run the offline import before the server exists. Import creates and migrates a fresh
|
||||
* state dir through the server's startup path, and refuses (exit 3) while a server holds the lock,
|
||||
* so `serve` never starts a stack on top of a half-imported scene.
|
||||
*/
|
||||
function importImage(opts, stateDir) {
|
||||
const bin = path.resolve(opts.bin ?? DEFAULT_SERVER_BIN)
|
||||
if (!fs.existsSync(bin)) {
|
||||
throw new Error(`server binary missing at ${bin}: run \`devbox run serve\` (it builds the ` +
|
||||
'server first), or pass --server-bin')
|
||||
}
|
||||
const args = ['import', `--state-dir=${stateDir}`, `--image=${path.resolve(opts.image)}`]
|
||||
if (Number.isFinite(opts.tileSize)) args.push(`--tile-size=${opts.tileSize}`)
|
||||
process.stdout.write(`serve: importing ${opts.image} before starting the server...\n`)
|
||||
const r = spawnSync(bin, args, { stdio: 'inherit', cwd: process.cwd() })
|
||||
if (r.error) throw r.error
|
||||
if (r.status !== 0) {
|
||||
const error = new Error(`map import failed (exit ${r.status}); the server was not started`)
|
||||
error.exitCode = r.status ?? 1
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function printStartup(handle) {
|
||||
const { origin, gmKey, stateDir, certPath, distDir, serverPort, certRegenerated } = handle
|
||||
const ip = handle.host
|
||||
@@ -100,8 +146,10 @@ async function main() {
|
||||
const detected = detectLanIp()
|
||||
if (detected) opts.host = detected
|
||||
}
|
||||
const stateDir = path.resolve(opts.stateDir ?? DEFAULT_STATE_DIR)
|
||||
if (opts.image) importImage(opts, stateDir)
|
||||
const handle = await startLanServe({
|
||||
stateDir: opts.stateDir ?? DEFAULT_STATE_DIR,
|
||||
stateDir,
|
||||
host: opts.host,
|
||||
port: opts.port ?? DEFAULT_LAN_PORT,
|
||||
distDir: opts.distDir ?? DEFAULT_DIST,
|
||||
@@ -134,5 +182,5 @@ async function main() {
|
||||
|
||||
main().catch(e => {
|
||||
process.stderr.write(`serve: ${e.stack ?? e}\n`)
|
||||
process.exit(1)
|
||||
process.exit(e.exitCode ?? 1)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user