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