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:
@@ -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 }
|
||||
|
||||
Reference in New Issue
Block a user