feat(client): drag with prediction and rollback (#72)
Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release; the sprite follows the pointer while authoritative frames are ignored for drawing. Uniform move nacks roll back with a short tween (on release if still dragging), rate-limited acks drop quietly, and pending reqIds die with the connection. - slices/move.ts: pure drag/pending/ack state machine at the reducer seam - render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins over pan/pinch (#69); sends via the new intents bridge - tokens renderer draws the optimistic/confirmed position and tweens the rollback - intents.ts + ws.send onReqId: one reqId-keyed sender for render modules - e2e: drag persists after reload, wall refusal tween, GM move mid-drag, reconnect mid-drag dropping the pending map
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
// The one way a render module sends an intent (#72). Render modules are mounted by the stage with
|
||||
// no socket of their own; this module is the tiny, replaceable bridge to the session's protocol
|
||||
// client. `main.ts` installs the live client on connect and clears it on teardown.
|
||||
//
|
||||
// The callback exists because a `token.move` ack is matched by `reqId`, not by token id (6.1):
|
||||
// the move slice records the `reqId` the socket assigned, then the ack frame finds it. Keeping the
|
||||
// callback here means the drag module never knows the counter and the protocol client stays pure.
|
||||
|
||||
import type { AckFrame } from './protocol.ts'
|
||||
|
||||
export type IntentSender = (
|
||||
t: string,
|
||||
fields?: Record<string, unknown>,
|
||||
onReqId?: (reqId: number) => void,
|
||||
) => Promise<AckFrame>
|
||||
|
||||
let sender: IntentSender | null = null
|
||||
|
||||
export function setIntentSender(next: IntentSender | null): void {
|
||||
sender = next
|
||||
}
|
||||
|
||||
/**
|
||||
* Send one intent, or reject when there is no live session (a drag that raced a disconnect). The
|
||||
* optional `onReqId` runs only after the frame actually left the socket, so a failed send never
|
||||
* leaves a pending entry that no ack can settle.
|
||||
*/
|
||||
export function sendIntent(
|
||||
t: string,
|
||||
fields: Record<string, unknown> = {},
|
||||
onReqId?: (reqId: number) => void,
|
||||
): Promise<AckFrame> {
|
||||
if (!sender) return Promise.reject(new Error('not connected'))
|
||||
return sender(t, fields, onReqId)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { mountCastPanel } from './panels/gmcast.ts'
|
||||
import type { Stage } from './render/stage.ts'
|
||||
import { createStage } from './render/stage.ts'
|
||||
import type { RootState } from './reducer.ts'
|
||||
import { setIntentSender } from './intents.ts'
|
||||
|
||||
const KEY_REFUSED = 'Key not recognised.'
|
||||
|
||||
@@ -114,6 +115,11 @@ function connect(): void {
|
||||
store.dispatch(event)
|
||||
},
|
||||
})
|
||||
// Render modules (the drag, #72) send through this bridge; it is the same client every other
|
||||
// intent uses, so `reqId` ordering and the pending map stay in one place.
|
||||
setIntentSender((t, fields, onReqId) =>
|
||||
client ? client.send(t, fields, onReqId) : Promise.reject(new Error('not connected')),
|
||||
)
|
||||
client.connect()
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
RosterEntry,
|
||||
SceneInfo,
|
||||
ServerFrame,
|
||||
Vec2,
|
||||
} from './protocol.ts'
|
||||
import { closeOutcome, isClosing, isHello } from './protocol.ts'
|
||||
|
||||
@@ -68,6 +69,19 @@ export type ReducerEvent =
|
||||
| { type: 'signed-out' }
|
||||
/** GM token panel selection (#74); slices own the state, the core just carries the event. */
|
||||
| { type: 'admin-select'; token: string | null }
|
||||
/**
|
||||
* Drag prediction (#72). The drag render module turns pointer input into these events; the move
|
||||
* slice owns the optimistic position, the pending `reqId` map and the rollback tween. Keeping
|
||||
* them in the reducer means the token renderer only reads state, and the state machine is tested
|
||||
* without a DOM or a socket (DESIGN 7.5).
|
||||
*/
|
||||
| { type: 'drag-start'; id: string; pos: Vec2 }
|
||||
| { type: 'drag-move'; id: string; pos: Vec2 }
|
||||
| { type: 'drag-end'; id: string; pos: Vec2 }
|
||||
/** One `token.move` intent left the socket; its ack is matched by `reqId` (6.3). */
|
||||
| { type: 'move-sent'; reqId: number; id: string; pos: Vec2 }
|
||||
/** The renderer finished the cosmetic rollback tween for this token. */
|
||||
| { type: 'rollback-done'; id: string; seq: number }
|
||||
|
||||
/**
|
||||
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Drag own tokens with prediction and rollback (T9, #72; DESIGN 7.4 input, 7.5, 5.5, 6.4).
|
||||
//
|
||||
// Hand-rolled DOM pointer events on the canvas (DESIGN 7.2: Pixi federated events are off). The
|
||||
// listener sits on `window` in the capture phase and only starts a drag when the press lands on
|
||||
// the canvas *and* on a token this session may move. When it does, propagation is stopped, so the
|
||||
// camera's pan/pinch (#69), which listens at the canvas, never sees the gesture: a token drag takes
|
||||
// precedence over pan exactly when the pointer starts on a token the user controls.
|
||||
//
|
||||
// The module owns input only. Prediction lives in `slices/move.ts` (a `reqId`-keyed pending map and
|
||||
// the rollback state machine); the token renderer draws the optimistic position. Sends are capped
|
||||
// at 20 Hz (DESIGN 6.4) plus one final position on release, each through the session's protocol
|
||||
// client (`intents.ts`) so the ack can be matched by `reqId`.
|
||||
|
||||
import type { RenderContext, RenderModule } from '../stage.ts'
|
||||
import type { Vec2 } from '../../protocol.ts'
|
||||
import { sendIntent } from '../../intents.ts'
|
||||
import { dragOf, draggableAt } from '../../slices/move.ts'
|
||||
import { tokensOf } from '../../slices/tokens.ts'
|
||||
|
||||
/** 20 Hz while dragging (DESIGN 6.4, FIXED #15); the release always sends. */
|
||||
export const MOVE_SEND_INTERVAL_MS = 50
|
||||
|
||||
interface ActiveDrag {
|
||||
id: string
|
||||
pointerId: number
|
||||
/** `performance.now()` of the last intent; 0 so the first move is sent at once. */
|
||||
lastSent: number
|
||||
}
|
||||
|
||||
export const renderModule: RenderModule = {
|
||||
name: 'drag',
|
||||
mount({ app, layers, store }: RenderContext): () => void {
|
||||
const canvas = app.canvas
|
||||
let active: ActiveDrag | null = null
|
||||
|
||||
/** Canvas CSS pixels -> the tokens layer's world coordinates (the camera's inverse, #69). */
|
||||
function worldPointOf(event: PointerEvent): Vec2 {
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const local = layers.tokens.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
|
||||
return [local.x, local.y]
|
||||
}
|
||||
|
||||
function send(id: string, pos: Vec2): void {
|
||||
try {
|
||||
const pending = sendIntent('token.move', { id, pos: [pos[0], pos[1]] }, reqId => {
|
||||
// The slice records the intent first; the ack frame that follows finds it by `reqId`.
|
||||
store.dispatch({ type: 'move-sent', reqId, id, pos })
|
||||
})
|
||||
// A refused/unreachable send has no pending entry (onReqId never ran) and nothing to undo.
|
||||
pending.catch(() => undefined)
|
||||
} catch {
|
||||
// `sendIntent` rejects rather than throws, but a drag must never break the render loop.
|
||||
}
|
||||
}
|
||||
|
||||
function detach(): void {
|
||||
window.removeEventListener('pointermove', onMove, true)
|
||||
window.removeEventListener('pointerup', onUp, true)
|
||||
window.removeEventListener('pointercancel', onCancel, true)
|
||||
window.removeEventListener('blur', onCancel)
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
active = null
|
||||
detach()
|
||||
}
|
||||
|
||||
function onDown(event: PointerEvent): void {
|
||||
if (active !== null) return
|
||||
// Only the primary pointer over the canvas itself; DOM panels keep their clicks.
|
||||
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
|
||||
const state = store.state
|
||||
if (state.connection.phase !== 'live') return
|
||||
const point = worldPointOf(event)
|
||||
const token = draggableAt(tokensOf(state), state.session.role, point)
|
||||
if (!token) return
|
||||
|
||||
// A token drag wins over pan/pinch (#69): the camera's listener never sees this gesture.
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
|
||||
active = { id: token.id, pointerId: event.pointerId, lastSent: 0 }
|
||||
store.dispatch({ type: 'drag-start', id: token.id, pos: token.pos })
|
||||
window.addEventListener('pointermove', onMove, true)
|
||||
window.addEventListener('pointerup', onUp, true)
|
||||
window.addEventListener('pointercancel', onCancel, true)
|
||||
window.addEventListener('blur', onCancel)
|
||||
}
|
||||
|
||||
function onMove(event: PointerEvent): void {
|
||||
const drag = active
|
||||
if (drag === null || event.pointerId !== drag.pointerId) return
|
||||
// A reconnect (`hello`/`close`) reset the slice under us: stop sending stale intents.
|
||||
if (dragOf(store.state)?.id !== drag.id) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
const pos = worldPointOf(event)
|
||||
store.dispatch({ type: 'drag-move', id: drag.id, pos })
|
||||
const now = performance.now()
|
||||
if (now - drag.lastSent >= MOVE_SEND_INTERVAL_MS) {
|
||||
drag.lastSent = now
|
||||
send(drag.id, pos)
|
||||
}
|
||||
}
|
||||
|
||||
function onUp(event: PointerEvent): void {
|
||||
const drag = active
|
||||
if (drag === null || event.pointerId !== drag.pointerId) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
// A reconnect (or the server dropping the token) already ended this drag: do not send a
|
||||
// final intent that belongs to the dead connection (6.3).
|
||||
if (dragOf(store.state)?.id !== drag.id) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
const pos = worldPointOf(event)
|
||||
store.dispatch({ type: 'drag-end', id: drag.id, pos })
|
||||
stop()
|
||||
// The final position always goes out (6.4); a dud has its own ack and may rate-limit.
|
||||
send(drag.id, pos)
|
||||
}
|
||||
|
||||
function onCancel(event: Event): void {
|
||||
const drag = active
|
||||
if (drag === null) return
|
||||
if (event.type === 'pointercancel') {
|
||||
const pointer = event as PointerEvent
|
||||
if (pointer.pointerId !== drag.pointerId) return
|
||||
}
|
||||
const current = dragOf(store.state)
|
||||
if (current?.id === drag.id) {
|
||||
store.dispatch({ type: 'drag-end', id: drag.id, pos: current.pos })
|
||||
}
|
||||
stop()
|
||||
}
|
||||
|
||||
// Capture on `window` beats every listener attached to the canvas (#69's pan included).
|
||||
window.addEventListener('pointerdown', onDown, true)
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', onDown, true)
|
||||
stop()
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -12,8 +12,12 @@
|
||||
|
||||
import { BitmapFont, BitmapText, Container, Graphics, GraphicsContext } from 'pixi.js'
|
||||
import type { RenderContext, RenderModule } from '../stage.ts'
|
||||
import type { RootState } from '../../reducer.ts'
|
||||
import type { Vec2 } from '../../protocol.ts'
|
||||
import { TokenBoard } from '../tokenBoard.ts'
|
||||
import type { TokenPatch } from '../tokenBoard.ts'
|
||||
import { drawPositionOf, moveOf, rollbacksOf } from '../../slices/move.ts'
|
||||
import type { RollbackTween } from '../../slices/move.ts'
|
||||
import { tokensOf } from '../../slices/tokens.ts'
|
||||
import type { TokenView } from '../../slices/tokens.ts'
|
||||
|
||||
@@ -170,7 +174,14 @@ function applyView(
|
||||
}
|
||||
|
||||
/** Publish the renderer's own counts, so the e2e can observe "only changed entities touched". */
|
||||
function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch, labels: number): void {
|
||||
function publish(
|
||||
canvas: HTMLCanvasElement,
|
||||
board: TokenBoard,
|
||||
patch: TokenPatch,
|
||||
labels: number,
|
||||
state: RootState,
|
||||
nodes: ReadonlyMap<string, TokenNode>,
|
||||
): void {
|
||||
const datasets = canvas.dataset
|
||||
datasets['tokens'] = String(board.size)
|
||||
datasets['tokenEntered'] = String(patch.entered.length)
|
||||
@@ -181,8 +192,34 @@ function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch
|
||||
datasets['tokenStatuses'] = [...board.views.values()]
|
||||
.flatMap(view => view.statuses.map(status => `${view.id}:${status}`))
|
||||
.join(' ')
|
||||
// The drag renderer's instrumentation (#72): the drawn position (so the e2e reads what the
|
||||
// browser shows, not what the reducer predicts) plus the move state machine's counters.
|
||||
datasets['tokenPositions'] = [...nodes.entries()]
|
||||
.map(([id, node]) => `${id}:${Math.round(node.container.x)},${Math.round(node.container.y)}`)
|
||||
.join(' ')
|
||||
const move = moveOf(state)
|
||||
datasets['dragId'] = move.drag?.id ?? ''
|
||||
datasets['dragPos'] = move.drag
|
||||
? `${Math.round(move.drag.pos[0])},${Math.round(move.drag.pos[1])}`
|
||||
: ''
|
||||
datasets['dragPhase'] = move.drag !== null ? 'drag' : Object.keys(move.rollbacks).length > 0 ? 'rollback' : ''
|
||||
datasets['dragPending'] = String(move.pending.length)
|
||||
datasets['dragRefused'] = String(move.refused)
|
||||
datasets['dragRateLimited'] = String(move.rateLimited)
|
||||
datasets['dragRollbacks'] = String(move.rollbackCount)
|
||||
datasets['dragDropped'] = String(move.dropped)
|
||||
}
|
||||
|
||||
/** Cosmetic rollback tween (DESIGN 7.5: a short slide back, never a teleport). */
|
||||
const ROLLBACK_MS = 280
|
||||
|
||||
interface ActiveTween {
|
||||
rb: RollbackTween
|
||||
from: Vec2
|
||||
started: number
|
||||
}
|
||||
|
||||
|
||||
export const renderModule: RenderModule = {
|
||||
name: 'tokens',
|
||||
mount(context: RenderContext): (() => void) | void {
|
||||
@@ -193,32 +230,99 @@ export const renderModule: RenderModule = {
|
||||
const pool: TokenNode[] = []
|
||||
const nodes = new Map<string, TokenNode>()
|
||||
const stats = { labels: 0 }
|
||||
/** At most one cosmetic rollback per token; keyed by token id, replaced on a newer sequence. */
|
||||
const tweens = new Map<string, ActiveTween>()
|
||||
|
||||
function removeNode(id: string): void {
|
||||
const node = nodes.get(id)
|
||||
if (!node) return
|
||||
tweens.delete(id)
|
||||
layers.tokens.removeChild(node.container)
|
||||
node.container.visible = false
|
||||
nodes.delete(id)
|
||||
pool.push(node)
|
||||
}
|
||||
|
||||
function enterNode(view: TokenView): void {
|
||||
function atFor(state: RootState, view: TokenView, node: TokenNode): Vec2 {
|
||||
// A rollback tween owns the sprite position while it runs; a drag/pending prediction owns it
|
||||
// otherwise (7.5); with neither, the authoritative `token` frame is the truth.
|
||||
if (tweens.has(view.id)) return [node.container.x, node.container.y]
|
||||
return drawPositionOf(state, view.id) ?? view.pos
|
||||
}
|
||||
|
||||
function enterNode(view: TokenView, state: RootState): void {
|
||||
const node = pool.pop() ?? createNode(view.radius)
|
||||
node.container.visible = true
|
||||
applyView(node, view, stats)
|
||||
applyView(node, view, stats, atFor(state, view, node))
|
||||
layers.tokens.addChild(node.container)
|
||||
nodes.set(view.id, node)
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the reducer's drag/rollback state to the sprites. Touches only a dragged token and the
|
||||
* tokens with a pending tween, so a pointer move never walks the whole scene (DESIGN 7.2).
|
||||
*/
|
||||
function applyMovement(state: RootState, now: number): void {
|
||||
const move = moveOf(state)
|
||||
if (move.drag) {
|
||||
const node = nodes.get(move.drag.id)
|
||||
if (node) {
|
||||
tweens.delete(move.drag.id)
|
||||
node.container.position.set(move.drag.pos[0], move.drag.pos[1])
|
||||
}
|
||||
}
|
||||
const active = rollbacksOf(state)
|
||||
const current = new Set<string>()
|
||||
for (const rb of active) {
|
||||
current.add(rb.id)
|
||||
const node = nodes.get(rb.id)
|
||||
if (!node) continue
|
||||
const existing = tweens.get(rb.id)
|
||||
if (existing?.rb.seq === rb.seq) continue
|
||||
tweens.set(rb.id, {
|
||||
rb,
|
||||
from: [node.container.x, node.container.y],
|
||||
started: now,
|
||||
})
|
||||
}
|
||||
// A tween the reducer no longer knows about (a new drag, a reset) is done.
|
||||
for (const id of [...tweens.keys()]) {
|
||||
if (!current.has(id) || !nodes.has(id)) tweens.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
function tick(): void {
|
||||
if (tweens.size === 0) return
|
||||
const now = performance.now()
|
||||
for (const [id, tween] of tweens) {
|
||||
const node = nodes.get(id)
|
||||
if (!node) {
|
||||
tweens.delete(id)
|
||||
continue
|
||||
}
|
||||
const t = Math.min(1, (now - tween.started) / ROLLBACK_MS)
|
||||
const eased = 1 - (1 - t) * (1 - t) * (1 - t) // ease-out cubic
|
||||
node.container.position.set(
|
||||
tween.from[0] + (tween.rb.to[0] - tween.from[0]) * eased,
|
||||
tween.from[1] + (tween.rb.to[1] - tween.from[1]) * eased,
|
||||
)
|
||||
if (t >= 1) {
|
||||
tweens.delete(id)
|
||||
store.dispatch({ type: 'rollback-done', id, seq: tween.rb.seq })
|
||||
}
|
||||
}
|
||||
publish(canvas, board, { reset: false, entered: [], updated: [], left: [] }, stats.labels, store.state, nodes)
|
||||
}
|
||||
|
||||
// The stage is created only once the session is live, but `app.init` is async and the resync
|
||||
// can beat it: start from whatever the reducer already holds, then follow the event stream.
|
||||
board.seed(tokensOf(store.state))
|
||||
let patch = board.drain()
|
||||
for (const view of patch.entered) enterNode(view)
|
||||
publish(canvas, board, patch, stats.labels)
|
||||
for (const view of patch.entered) enterNode(view, store.state)
|
||||
publish(canvas, board, patch, stats.labels, store.state, nodes)
|
||||
app.ticker.add(tick)
|
||||
|
||||
const unsubscribe = store.subscribe((_state, event) => {
|
||||
const unsubscribe = store.subscribe((state, event) => {
|
||||
board.apply(event)
|
||||
patch = board.drain()
|
||||
if (patch.reset) {
|
||||
@@ -227,17 +331,17 @@ export const renderModule: RenderModule = {
|
||||
for (const id of patch.left) removeNode(id)
|
||||
for (const view of patch.updated) {
|
||||
const node = nodes.get(view.id)
|
||||
if (node) applyView(node, view, stats)
|
||||
else enterNode(view)
|
||||
}
|
||||
for (const view of patch.entered) enterNode(view)
|
||||
if (patch.reset || patch.entered.length > 0 || patch.updated.length > 0 || patch.left.length > 0) {
|
||||
publish(canvas, board, patch, stats.labels)
|
||||
if (node) applyView(node, view, stats, atFor(state, view, node))
|
||||
else enterNode(view, state)
|
||||
}
|
||||
for (const view of patch.entered) enterNode(view, state)
|
||||
applyMovement(state, performance.now())
|
||||
publish(canvas, board, patch, stats.labels, state, nodes)
|
||||
})
|
||||
|
||||
return () => {
|
||||
unsubscribe()
|
||||
app.ticker.remove(tick)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
// Move prediction and rollback (T9, #72; DESIGN 7.5, 5.5, 6.4). The pure half of the drag: pointer
|
||||
// input becomes `drag-*` events, each `token.move` intent is remembered by `reqId`, and the acks
|
||||
// decide whether the optimistic position stands or slides back. No Pixi, no DOM, no socket.
|
||||
//
|
||||
// The contract is DESIGN 7.5:
|
||||
// - while dragging, the sprite follows the pointer and authoritative positions for that token are
|
||||
// ignored for drawing (they keep arriving in the tokens slice, unmodified);
|
||||
// - `ack{ok:true}` confirms the requested position, which the server's `token` frame repeats;
|
||||
// - the uniform move nack (`ok:false` with `pos`, no `code`) rolls back: at once when idle, on
|
||||
// release when the finger is still down;
|
||||
// - `ack{ok:false, code:"rate-limited"}` is dropped quietly: the optimistic position is discarded
|
||||
// and the next authoritative frame reconciles the view (6.4);
|
||||
// - pending requests die with the connection (6.3).
|
||||
//
|
||||
// Append-only registration: adding this file was enough; the reducer's glob picked it up and
|
||||
// `hello` resets it with every other slice.
|
||||
|
||||
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
|
||||
import type { AckFrame, Vec2 } from '../protocol.ts'
|
||||
import { isAck } from '../protocol.ts'
|
||||
import type { TokenView } from './tokens.ts'
|
||||
import { tokensOf } from './tokens.ts'
|
||||
|
||||
export interface DragState {
|
||||
id: string
|
||||
/** Where the token was when the drag began (the server's last position). */
|
||||
origin: Vec2
|
||||
/** The optimistic position under the pointer; the renderer draws here. */
|
||||
pos: Vec2
|
||||
}
|
||||
|
||||
export interface MovePending {
|
||||
reqId: number
|
||||
id: string
|
||||
pos: Vec2
|
||||
}
|
||||
|
||||
/** A refused move while the finger is still down: snap there on release, never under the finger. */
|
||||
export interface MoveSnap {
|
||||
id: string
|
||||
pos: Vec2
|
||||
}
|
||||
|
||||
export interface RollbackTween {
|
||||
/** Monotonic id so the renderer can report the exact tween it finished. */
|
||||
seq: number
|
||||
id: string
|
||||
from: Vec2
|
||||
to: Vec2
|
||||
}
|
||||
|
||||
export interface MoveState {
|
||||
drag: DragState | null
|
||||
/** `token.move` intents awaiting their ack, in send order (the server acks in order). */
|
||||
pending: MovePending[]
|
||||
snap: MoveSnap | null
|
||||
/** Cosmetic rollbacks the renderer is sliding; keyed by token id, newest per token wins. */
|
||||
rollbacks: Record<string, RollbackTween>
|
||||
/** Confirmed positions kept until the matching `token` frame lands (ack precedes the frame). */
|
||||
confirmed: Record<string, Vec2>
|
||||
seq: number
|
||||
/** Counters for the browser e2e's instrumentation and for the unit tests. */
|
||||
accepted: number
|
||||
refused: number
|
||||
rateLimited: number
|
||||
/** Pending intents thrown away because the connection closed (6.3). */
|
||||
dropped: number
|
||||
rollbackCount: number
|
||||
}
|
||||
|
||||
const EMPTY: MoveState = {
|
||||
drag: null,
|
||||
pending: [],
|
||||
snap: null,
|
||||
rollbacks: {},
|
||||
confirmed: {},
|
||||
seq: 0,
|
||||
accepted: 0,
|
||||
refused: 0,
|
||||
rateLimited: 0,
|
||||
dropped: 0,
|
||||
rollbackCount: 0,
|
||||
}
|
||||
|
||||
export function initMove(): MoveState {
|
||||
return { ...EMPTY, pending: [], rollbacks: {}, confirmed: {} }
|
||||
}
|
||||
|
||||
function isVec2(value: unknown): value is Vec2 {
|
||||
return (
|
||||
Array.isArray(value) &&
|
||||
value.length === 2 &&
|
||||
typeof value[0] === 'number' &&
|
||||
Number.isFinite(value[0]) &&
|
||||
typeof value[1] === 'number' &&
|
||||
Number.isFinite(value[1])
|
||||
)
|
||||
}
|
||||
|
||||
function copy(pos: Vec2): Vec2 {
|
||||
return [pos[0], pos[1]]
|
||||
}
|
||||
|
||||
/** The newest pending intent for one token, or null. */
|
||||
function latestPending(state: MoveState, id: string): MovePending | null {
|
||||
let found: MovePending | null = null
|
||||
for (const entry of state.pending) {
|
||||
if (entry.id === id && (found === null || entry.reqId > found.reqId)) found = entry
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function hasNewerPending(state: MoveState, id: string, reqId: number): boolean {
|
||||
return state.pending.some(entry => entry.id === id && entry.reqId > reqId)
|
||||
}
|
||||
|
||||
function startRollback(state: MoveState, id: string, from: Vec2, to: Vec2): void {
|
||||
state.seq += 1
|
||||
state.rollbackCount += 1
|
||||
state.rollbacks = {
|
||||
...state.rollbacks,
|
||||
[id]: { seq: state.seq, id, from: copy(from), to: copy(to) },
|
||||
}
|
||||
}
|
||||
|
||||
export const slice: Slice<MoveState> = {
|
||||
name: 'move',
|
||||
init: initMove,
|
||||
reduce(state: MoveState, event: ReducerEvent, root: RootState): void {
|
||||
switch (event.type) {
|
||||
case 'drag-start': {
|
||||
// A new drag is a new prediction: any pending snap or tween for this token is obsolete.
|
||||
state.drag = { id: event.id, origin: copy(event.pos), pos: copy(event.pos) }
|
||||
state.snap = null
|
||||
if (state.rollbacks[event.id] !== undefined) {
|
||||
const rollbacks = { ...state.rollbacks }
|
||||
delete rollbacks[event.id]
|
||||
state.rollbacks = rollbacks
|
||||
}
|
||||
delete state.confirmed[event.id]
|
||||
return
|
||||
}
|
||||
case 'drag-move': {
|
||||
if (state.drag?.id !== event.id) return
|
||||
state.drag = { ...state.drag, pos: copy(event.pos) }
|
||||
return
|
||||
}
|
||||
case 'drag-end': {
|
||||
if (state.drag?.id !== event.id) return
|
||||
state.drag = null
|
||||
// A refusal seen during the drag is settled on release (7.5): its ack handler starts the
|
||||
// tween from the released position. Nothing to do here but keep the snap for that ack.
|
||||
return
|
||||
}
|
||||
case 'move-sent': {
|
||||
state.pending = [
|
||||
...state.pending.filter(entry => entry.reqId !== event.reqId),
|
||||
{ reqId: event.reqId, id: event.id, pos: copy(event.pos) },
|
||||
]
|
||||
return
|
||||
}
|
||||
case 'rollback-done': {
|
||||
const tween = state.rollbacks[event.id]
|
||||
if (tween?.seq !== event.seq) return
|
||||
const rollbacks = { ...state.rollbacks }
|
||||
delete rollbacks[event.id]
|
||||
state.rollbacks = rollbacks
|
||||
return
|
||||
}
|
||||
case 'close': {
|
||||
// 6.3: pending reqIds are dropped with the connection; no ack will ever arrive.
|
||||
state.dropped += state.pending.length
|
||||
state.pending = []
|
||||
state.drag = null
|
||||
state.snap = null
|
||||
state.rollbacks = {}
|
||||
state.confirmed = {}
|
||||
return
|
||||
}
|
||||
case 'frame': {
|
||||
const frame = event.frame
|
||||
if (frame.t === 'token') {
|
||||
// The server remains the judge (story 39): its frame wins for drawing once no drag or
|
||||
// pending intent covers the token. Any frame settles a confirmed position.
|
||||
const id = frame['id']
|
||||
if (typeof id !== 'string') return
|
||||
// A frame during a cosmetic rollback does not cancel the tween: the ack that produced it
|
||||
// already gave the authoritative position, and the renderer only animates the sprite.
|
||||
delete state.confirmed[id]
|
||||
return
|
||||
}
|
||||
if (frame.t === 'token_gone') {
|
||||
const id = frame['id']
|
||||
if (typeof id !== 'string') return
|
||||
if (state.drag?.id === id) state.drag = null
|
||||
if (state.snap?.id === id) state.snap = null
|
||||
state.pending = state.pending.filter(entry => entry.id !== id)
|
||||
delete state.confirmed[id]
|
||||
if (state.rollbacks[id] !== undefined) {
|
||||
const rollbacks = { ...state.rollbacks }
|
||||
delete rollbacks[id]
|
||||
state.rollbacks = rollbacks
|
||||
}
|
||||
return
|
||||
}
|
||||
if (isAck(frame)) {
|
||||
applyAck(root, state, frame)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
function applyAck(root: RootState, state: MoveState, frame: AckFrame): void {
|
||||
const index = state.pending.findIndex(entry => entry.reqId === frame.reqId)
|
||||
if (index < 0) return // an intent this slice does not own (admin, name, ...)
|
||||
const entry = state.pending[index]!
|
||||
// What the sprite shows right now, before the pending entry is removed (7.5 rollback tween).
|
||||
const shown = drawPositionOf(root, entry.id) ?? entry.pos
|
||||
const snap = state.snap?.id === entry.id ? state.snap : null
|
||||
|
||||
state.pending = state.pending.filter(item => item.reqId !== frame.reqId)
|
||||
|
||||
if (frame.ok) {
|
||||
state.accepted += 1
|
||||
if (state.snap?.id === entry.id) state.snap = null
|
||||
// Ack then the token frame (settleLocked); hold the confirmed position for the frame so the
|
||||
// sprite never blinks back to the pre-move position for one dispatch.
|
||||
state.confirmed = {
|
||||
...state.confirmed,
|
||||
[entry.id]: isVec2(frame.pos) ? copy(frame.pos) : copy(entry.pos),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (frame.code === 'rate-limited') {
|
||||
// 6.4: refused by the bucket, never applied, no position to roll back to. Drop quietly and let
|
||||
// the next frame (or the next drag sample) reconcile; dragging keeps its optimistic position.
|
||||
state.rateLimited += 1
|
||||
if (state.snap?.id === entry.id) state.snap = null
|
||||
if (state.drag?.id !== entry.id) {
|
||||
const confirmed = { ...state.confirmed }
|
||||
delete confirmed[entry.id]
|
||||
state.confirmed = confirmed
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (!isVec2(frame.pos)) return // a malformed nack cannot move the sprite
|
||||
// A newer intent is already in flight; its ack decides. Acks arrive in order, so ignore this one.
|
||||
if (hasNewerPending(state, entry.id, entry.reqId)) return
|
||||
state.refused += 1
|
||||
|
||||
if (state.drag?.id === entry.id) {
|
||||
// 7.5: do not teleport under the finger; snap on release.
|
||||
state.snap = { id: entry.id, pos: copy(frame.pos) }
|
||||
return
|
||||
}
|
||||
|
||||
// Idle: slide back from the predicted position to the server's old position (story 40).
|
||||
startRollback(state, entry.id, snap ? entry.pos : shown, frame.pos)
|
||||
if (state.snap?.id === entry.id) state.snap = null
|
||||
const confirmed = { ...state.confirmed }
|
||||
delete confirmed[entry.id]
|
||||
state.confirmed = confirmed
|
||||
}
|
||||
|
||||
/** The move slice, or an empty one before the registry has run (unit helpers stay total). */
|
||||
export function moveOf(state: RootState): MoveState {
|
||||
return (state.slices['move'] as MoveState | undefined) ?? EMPTY
|
||||
}
|
||||
|
||||
/**
|
||||
* The position the token renderer must draw at, or null when the authoritative `token` frame is
|
||||
* the truth. Precedence: under the finger, then the newest pending request, then a confirmed ack
|
||||
* whose `token` frame has not arrived yet (DESIGN 7.2's `at` parameter, 7.5).
|
||||
*/
|
||||
export function drawPositionOf(state: RootState, id: string): Vec2 | null {
|
||||
const move = moveOf(state)
|
||||
if (move.drag?.id === id) return move.drag.pos
|
||||
const pending = latestPending(move, id)
|
||||
if (pending) return pending.pos
|
||||
const confirmed = move.confirmed[id]
|
||||
if (confirmed) return confirmed
|
||||
return null
|
||||
}
|
||||
|
||||
/** True while the pointer owns this token: its authoritative frames must not move the sprite. */
|
||||
export function isDragging(state: RootState, id: string): boolean {
|
||||
return moveOf(state).drag?.id === id
|
||||
}
|
||||
|
||||
/** The rollbacks the renderer should be tweening, newest sequence first. */
|
||||
export function rollbacksOf(state: RootState): RollbackTween[] {
|
||||
return Object.values(moveOf(state).rollbacks)
|
||||
}
|
||||
|
||||
/** The active drag (the module's own state machine), if any. */
|
||||
export function dragOf(state: RootState): DragState | null {
|
||||
return moveOf(state).drag
|
||||
}
|
||||
|
||||
/**
|
||||
* O(N) hit test on press only (DESIGN 7.2): the topmost token this recipient may move whose circle
|
||||
* contains the world point. Players move only their own tokens; the GM moves any token (story 43).
|
||||
* GM frames say `mine:false`, so the role check is what makes a GM drag work.
|
||||
*/
|
||||
export function draggableAt(
|
||||
tokens: readonly TokenView[],
|
||||
role: 'gm' | 'player' | null,
|
||||
point: Vec2,
|
||||
): TokenView | null {
|
||||
if (role === null) return null
|
||||
for (let index = tokens.length - 1; index >= 0; index -= 1) {
|
||||
const token = tokens[index]
|
||||
if (!token) continue
|
||||
if (role !== 'gm' && !token.mine) continue
|
||||
const dx = point[0] - token.pos[0]
|
||||
const dy = point[1] - token.pos[1]
|
||||
if (dx * dx + dy * dy <= token.radius * token.radius) return token
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The tokens a drag may start on, for the shell/e2e; not a secrecy filter (the server already is). */
|
||||
export function draggableTokens(state: RootState): TokenView[] {
|
||||
const role = state.session.role
|
||||
if (role === null) return []
|
||||
return tokensOf(state).filter(token => role === 'gm' || token.mine)
|
||||
}
|
||||
+9
-1
@@ -187,8 +187,15 @@ export class ProtocolClient {
|
||||
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
|
||||
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
|
||||
* `hello` on a live connection does not drop them.
|
||||
*
|
||||
* `onReqId` is told the request id once the frame has left the socket, so a caller that must
|
||||
* match the ack itself (the drag's `token.move`, #72) can record it before the reply can arrive.
|
||||
*/
|
||||
send(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame> {
|
||||
send(
|
||||
t: string,
|
||||
fields: Record<string, unknown> = {},
|
||||
onReqId?: (reqId: number) => void,
|
||||
): Promise<AckFrame> {
|
||||
const socket = this.#socket
|
||||
if (this.#state !== 'open' || !socket) {
|
||||
return Promise.reject(new Error('not connected'))
|
||||
@@ -199,6 +206,7 @@ export class ProtocolClient {
|
||||
this.#pending.set(reqId, { resolve, reject })
|
||||
try {
|
||||
socket.send(frame)
|
||||
onReqId?.(reqId)
|
||||
} catch (error) {
|
||||
this.#pending.delete(reqId)
|
||||
reject(error instanceof Error ? error : new Error(String(error)))
|
||||
|
||||
Reference in New Issue
Block a user