1
0
Fork 0

revert(minigames): roll back Bomperator prediction update after prod regression

Reverts 655407a (component + guide). Production HAR showed input POST
TTFB p50 87ms / p90 236ms / max 384ms (server pipeline variance, not
network). The nudges and ghost projection trusted rttAvg too tightly and
glitched under that variance; v0.12.3 behavior is restored.

Kept on purpose: bomperator/prediction.ts and the offline prediction
harness stay as test-only infrastructure for the re-fix, which will be
calibrated against the recorded production latency trace.
This commit is contained in:
Jason Fraley 2026-10-18 01:40:44 -04:00
parent 7322ee8dd0
commit a9f047f214
2 changed files with 193 additions and 152 deletions

View file

@ -6,15 +6,6 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { BomperatorView, Dir, PlayerView } from "@/lib/minigames/bomperator/types";
import { BOMB_FUSE_TICKS, FLAME_LIFETIME_TICKS, GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICK_MS, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import {
PRED_DEADZONE,
PRED_ENVELOPE_BUDGET_MS,
alignDecisionToServer,
predAdvance,
projectServerPosition,
type PredictBomb,
type RenderPos,
} from "@/lib/minigames/bomperator/prediction";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud";
import { useBomperatorSounds } from "./sounds";
@ -35,6 +26,7 @@ const KEY_DIR: Record<string, Dir> = {
KeyD: "right",
};
/** Direction unit vectors for client-side prediction. */
const POWERUP_COLORS: Record<string, string> = {
bomb: "#f87171",
range: "#fb923c",
@ -43,6 +35,162 @@ const POWERUP_COLORS: Record<string, string> = {
};
const POWERUP_GLYPH: Record<string, string> = { bomb: "●", range: "✸", speed: "»", kick: "⇥" };
interface RenderPos {
x: number;
y: number;
}
/* ----- client-side prediction: replicate the engine's grid-locked movement ----- */
const PRED_DIR_VEC: Record<Dir, readonly [number, number]> = {
up: [0, -1],
down: [0, 1],
left: [-1, 0],
right: [1, 0],
};
const PRED_EPS = 1e-6;
interface PredictBomb {
id: string;
x: number;
y: number;
/** Optimistic local charge the server has not confirmed yet. Blocks movement
* like a real one but cannot be kick-pushed (the server has not placed it). */
ghost?: boolean;
}
/**
* Correction deadzone in cells. Gaps explainable by input flight time or
* snapshot-projection bias live inside this band; pulling on them is what made
* movement feel heavy, so they are left alone.
*/
const PRED_DEADZONE = 0.4;
function predCellCentered(x: number, y: number): boolean {
return Math.abs(x - Math.round(x)) < PRED_EPS && Math.abs(y - Math.round(y)) < PRED_EPS;
}
function predApproach(current: number, target: number, step: number): number {
const delta = target - current;
if (Math.abs(delta) <= step) return target;
return current + Math.sign(delta) * step;
}
function predBombAt(bombs: readonly PredictBomb[], x: number, y: number): PredictBomb | undefined {
return bombs.find((b) => b.x === x && b.y === y);
}
function predOpen(grid: readonly number[], x: number, y: number): boolean {
return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H && grid[y * GRID_W + x] === 0;
}
function predCanStand(grid: readonly number[], bombs: readonly PredictBomb[], x: number, y: number): boolean {
return predOpen(grid, x, y) && !predBombAt(bombs, x, y);
}
/**
* One small advance step mirroring the engine's advancePlayer exactly: finish
* aligning the perpendicular axis first, then move toward the adjacent cell
* center; a charge blocks unless kick-capable (then it slides one cell forward,
* recorded into the mutable bombs list).
*/
function predStep(
grid: readonly number[],
bombs: PredictBomb[],
x0: number,
y0: number,
dir: Dir,
kick: boolean,
step: number,
): RenderPos {
const [dx, dy] = PRED_DIR_VEC[dir];
let x = x0;
let y = y0;
if (dx !== 0) {
if (Math.abs(y - Math.round(y)) > PRED_EPS) {
const ty = Math.round(y);
y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step);
if (Math.abs(ty - y) < PRED_EPS) y = ty;
return { x, y };
}
const cy = Math.round(y);
const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1;
const home = dx > 0 ? Math.floor(x + PRED_EPS) : Math.ceil(x - PRED_EPS);
const bomb = predBombAt(bombs, entering, cy);
if (bomb) {
if (kick && !bomb.ghost) {
const bx = entering + dx;
if (predOpen(grid, bx, cy) && !predBombAt(bombs, bx, cy)) {
bomb.x = bx;
bomb.y = cy;
return { x: predApproach(x, entering, step), y };
}
}
return { x: home, y };
}
if (!predCanStand(grid, bombs, entering, cy)) return { x: home, y };
return { x: predApproach(x, entering, step), y };
}
if (Math.abs(x - Math.round(x)) > PRED_EPS) {
const tx = Math.round(x);
x += Math.sign(tx - x) * Math.min(Math.abs(tx - x), step);
if (Math.abs(tx - x) < PRED_EPS) x = tx;
return { x, y };
}
const cx = Math.round(x);
const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1;
const home = dy > 0 ? Math.floor(y + PRED_EPS) : Math.ceil(y - PRED_EPS);
const bomb = predBombAt(bombs, cx, entering);
if (bomb) {
if (kick && !bomb.ghost) {
const by = entering + dy;
if (predOpen(grid, cx, by) && !predBombAt(bombs, cx, by)) {
bomb.x = cx;
bomb.y = by;
return { x, y: predApproach(y, entering, step) };
}
}
return { x, y: home };
}
if (!predCanStand(grid, bombs, cx, entering)) return { x, y: home };
return { x, y: predApproach(y, entering, step) };
}
/**
* Advance over `durationMs` in small slices, honoring the engine's slip-to-rest:
* with no active direction the technician keeps traveling in `facing` until it
* lands exactly on a cell center; a blocked cell settles it back to the one it
* was leaving, where it then stays.
*/
function predAdvance(
grid: readonly number[],
bombs: PredictBomb[],
start: RenderPos,
dir: Dir | null,
facing: Dir,
speed: number,
kick: boolean,
durationMs: number,
): RenderPos {
let { x, y } = start;
let remaining = Math.min(durationMs, 1500);
let guard = 0;
while (remaining > 0.5 && guard < 120) {
guard += 1;
const slice = Math.min(remaining, 16);
const step = (speed * slice) / 1000;
const effDir = dir ?? (predCellCentered(x, y) ? null : facing);
if (!effDir) break;
const res = predStep(grid, bombs, x, y, effDir, kick, step);
const moved = Math.abs(res.x - x) > 1e-9 || Math.abs(res.y - y) > 1e-9;
x = res.x;
y = res.y;
if (!moved) break; // settled against a blocked cell
remaining -= slice;
}
return { x, y };
}
/* ------------------------------------------------------------- draw helpers */
function drawFloor(ctx: CanvasRenderingContext2D) {
@ -233,20 +381,9 @@ export function BomperatorGame({
const lastAckedDirRef = useRef<Dir | null>(null);
const lastVersionSeenRef = useRef(-1);
const rttAvgRef = useRef(100);
/** Client time the newest snapshot version ARRIVED (stamped when React
* applies it). Input-edge projections start from it minus one-way latency
* (the snapshot's true server-side age), and skip when it has gone stale. */
const lastSnapshotAtRef = useRef(0);
useEffect(() => {
matchRef.current = match;
// Stamp each fresh snapshot version's arrival: measuring it absorbs the
// delivery cadence and React scheduling delay that a fixed age assumption
// ("now minus latency minus half a tick") systematically misses between
// reconciles, under-projecting decision positions by up to a full cadence.
if (match.version !== lastVersionSeenRef.current) {
lastSnapshotAtRef.current = performance.now();
}
}, [match]);
const isHost = match.yourSeat === 0;
@ -259,57 +396,6 @@ export function BomperatorGame({
/* ---- input: hold-to-move with a keepalive, edge-triggered drop ---- */
/**
* Project the server's copy of our technician forward to `atTime` by
* replaying every unacknowledged input from the latest snapshot (the same
* replay the reconcile runs, extended past "now" to the server's decision
* instant). Inputs still in flight are included: the previous edge may not
* have been applied server-side yet, and replaying through its receive time
* is what keeps corner turns from overshooting. Returns null when the
* snapshot in hand is too stale to project from.
*/
const projectDecisionPos = useCallback((atTime: number): RenderPos | null => {
const view = matchRef.current;
const seat = view.yourSeat;
const me = seat !== null ? (view.players[seat] ?? null) : null;
if (!me || !me.alive || view.phase !== "battle") return null;
const nowMs = performance.now();
if (nowMs - lastSnapshotAtRef.current > 300) return null;
if (atTime - nowMs > 400) return null;
const bombs: PredictBomb[] = view.bombs.map((b) => {
const to = pushOverlayRef.current.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
return projectServerPosition(
view.grid,
bombs,
{ x: me.x, y: me.y },
me.dir,
lastAckedDirRef.current,
pendingRef.current,
me.speed,
me.kick,
rttAvgRef.current,
// True server-side age: measured arrival minus one-way latency.
lastSnapshotAtRef.current - rttAvgRef.current / 2,
atTime,
).pos;
}, []);
/** The instant the server samples our position for an input sent now: one-way
* latency to arrive, then tick phase. A turn/release rounds from the position
* at the START of the first tick after arrival (= the last tick BEFORE arrival,
* about half a tick early); a charge placement happens after that tick's
* movement (about half a tick late). Sampling the wrong side of the arrival
* projects up to a full tick past the server's actual decision position. */
const decisionTime = useCallback(
(kind: "rounding" | "placement") =>
performance.now() +
rttAvgRef.current / 2 +
(kind === "placement" ? TICK_MS / 2 : -TICK_MS / 2),
[],
);
const sendDrop = useCallback(async () => {
playPlace();
// Optimistic placement: the ghost charge appears at our cell the same instant
@ -321,14 +407,7 @@ export function BomperatorGame({
const seat = view.yourSeat;
const me = seat !== null ? (view.players[seat] ?? null) : null;
if (view.phase === "battle" && me && me.alive) {
// The server places the charge at ITS position on the tick after the drop
// arrives, about one-way latency plus half a tick from now. A cell boundary
// crossed inside that window (frequent: the prediction lead is about half a
// cell) makes our displayed cell and the server's placement cell disagree.
// Ghost where the server will actually place it, so the optimistic charge
// does not visibly relocate a cell away when the real one confirms.
const at =
projectDecisionPos(decisionTime("placement")) ?? predRef.current ?? { x: me.x, y: me.y };
const at = predRef.current ?? { x: me.x, y: me.y };
const cx = Math.round(at.x);
const cy = Math.round(at.y);
const ghosts = ghostBombsRef.current;
@ -353,7 +432,7 @@ export function BomperatorGame({
} catch {
// Ignore transient failures.
}
}, [match.matchId, playPlace, projectDecisionPos, decisionTime]);
}, [match.matchId, playPlace]);
/**
* Fire a direction change immediately with a monotonic seq. The server drops
@ -382,27 +461,6 @@ export function BomperatorGame({
useEffect(() => {
if (!canControl) return;
// A turn or a release makes the engine commit to a rounding decision: the
// perpendicular alignment target (round) on a turn, the slip-to-rest target
// (floor/ceil) on a release. The server executes the same decision at the
// first tick after the input arrives, from its position at the last tick
// BEFORE arrival - a staircase position that trails our display by roughly
// half a cell, so around a third of decisions straddle a cell center and
// resolve to DIFFERENT cells in the two sims. The resulting persistent
// one-cell offsets are what the reconcile pull then fights (felt as
// rubber-banding) and what occasionally stacks past the snap threshold
// (felt as teleporting back). Nudge the predicted position across the
// boundary onto the server's side so both sims commit to the same cell; the
// nudge is bounded well under half a cell and lands exactly at the visual
// moment of the turn/stop, so it reads as part of the motion.
const applyDecisionNudge = (prev: Dir | null, next: Dir | null) => {
if (prev === next || predRef.current === null) return;
const dp = projectDecisionPos(decisionTime("rounding"));
if (!dp) return;
const res = alignDecisionToServer(predRef.current, dp, next, prev ?? facingRef.current);
if (res.nudged) predRef.current = res.pos;
};
// Level-triggered movement: the server keeps applying the last direction we
// sent until we send a different one, so we transmit on change (edge), plus
// a slow re-assert while a key is held to recover a lost packet.
@ -416,22 +474,14 @@ export function BomperatorGame({
const dir = KEY_DIR[e.code];
if (!dir) return;
e.preventDefault();
const prev = heldKeysRef.current[0] ?? null;
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
const next = heldKeysRef.current[0] ?? null;
// Nudge BEFORE the send: the decision position must not include the very
// edge being decided (the server executes it AT that instant).
applyDecisionNudge(prev, next);
sendDir(next);
sendDir(heldKeysRef.current[0] ?? null);
};
const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code];
if (!dir) return;
const prev = heldKeysRef.current[0] ?? null;
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
const next = heldKeysRef.current[0] ?? null;
applyDecisionNudge(prev, next);
sendDir(next);
sendDir(heldKeysRef.current[0] ?? null);
};
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true });
@ -449,7 +499,7 @@ export function BomperatorGame({
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, sendDrop, sendDir, projectDecisionPos, decisionTime]);
}, [canControl, match.matchId, sendDrop, sendDir]);
/* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */
@ -556,52 +606,44 @@ export function BomperatorGame({
// Estimate where the server really is NOW: start from its snapshot
// position and replay every input it has not yet acknowledged,
// timed by our send times plus the measured one-way latency.
const rtt = rttAvgRef.current;
const replayBombs: PredictBomb[] = view.bombs.map((b) => {
const to = overlay.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
const projected = projectServerPosition(
view.grid,
replayBombs,
{ x: me.x, y: me.y },
me.dir,
ackedDir,
pending,
me.speed,
me.kick,
rttAvgRef.current,
// Calibrated snapshot age: the half-tick bias lands the
// estimate on the server's quantized current position (its
// staircase lag cancels the extra forward projection).
now - rttAvgRef.current / 2 - TICK_MS / 2,
now,
let t = now - rtt / 2 - TICK_MS / 2;
let est = { x: me.x, y: me.y };
let dir = ackedDir;
let facing = me.dir;
for (const p of pending) {
const recv = p.sentAt + rtt / 2;
est = predAdvance(
view.grid, replayBombs, est, dir, facing, me.speed, me.kick,
Math.max(0, Math.min(recv - t, 1000)),
);
t = recv;
dir = p.dir;
if (p.dir) facing = p.dir;
}
est = predAdvance(
view.grid, replayBombs, est, dir, facing, me.speed, me.kick,
Math.max(0, Math.min(now - t, 1000)),
);
const est = projected.pos;
const gap = Math.hypot(est.x - pred.x, est.y - pred.y);
// Lead-aware correction envelope: a display leading the server by
// one-way flight + half a tick (+ a budget for estimator error and
// tick quantization) is healthy prediction, not divergence. The
// old policy corrected only once EVERY input was acked, so during
// sustained movement offsets accumulated silently and then
// discharged as the "teleported back to where the server saw me"
// snaps players reported. Now every snapshot trims what is beyond
// the envelope, and even large gaps close at a capped rate
// (2.5x run speed) instead of teleporting: divergence can no
// longer stack, and what remains reads as a quick reel-in. A
// genuine round reset still snaps via the ack-backwards branch.
const envelope = Math.max(
PRED_DEADZONE,
(me.speed * (rttAvgRef.current / 2 + TICK_MS / 2 + PRED_ENVELOPE_BUDGET_MS)) /
1000,
);
if (gap > 2.5) {
const maxStep = (me.speed * 2.5 * dtMs) / 1000;
const easeT = Math.min(1, maxStep / gap);
pred.x += (est.x - pred.x) * easeT;
pred.y += (est.y - pred.y) * easeT;
facingRef.current = projected.facing;
} else if (gap > envelope) {
const k = Math.min(gap - envelope, gap * 0.5) / gap;
// Teleport/respawn: snap instead of sliding across the map.
predRef.current = est;
facingRef.current = facing;
} else if (pending.length === 0 && gap > PRED_DEADZONE) {
// Correct only once EVERY sent input is acknowledged. While
// inputs are in flight the server legitimately trails the local
// sim (it has not seen the latest keys yet), so pulling toward
// it then drags the sprite backwards on every turn and key
// release; that drag is what made movement feel heavy. With
// everything acked, a gap beyond the deadzone is a genuine
// disagreement (a charge or wall the local sim missed), so
// close it firmly, leaving the deadzone band itself alone.
const k = Math.min(gap - PRED_DEADZONE, gap * 0.5) / gap;
pred.x += (est.x - pred.x) * k;
pred.y += (est.y - pred.y) * k;
}

View file

@ -11,7 +11,6 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Call for Fire (artillery observer)**: `/minigames/call-for-fire`, game rules in `src/lib/minigames/call-for-fire.ts` (patrol/checkpoint/compound difficulties, compass bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring/accuracy/XP, injected rng, pure). Components: `src/components/frontend/minigames/call-for-fire/` (`CallForFireArena`, `FireMissionBoard`, `CallForFireLeaderboard`). Action `submitCallForFireResult` validates result bounds, updates profile stats, awards XP + chips, emits `minigame:call-for-fire`, and records the ledger entry (accuracy is distance-to-target on a win, null on a loss).
- **Call for Fire: Versus (multiplayer)**: `/minigames/call-for-fire-versus`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/tables.ts`: `globalThis`-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact). `views.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`).
- **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active).
- **Prediction & correction (client)**: `BomperatorGame.tsx` runs a local copy of the movement engine between snapshots via pure module `src/lib/minigames/bomperator/prediction.ts` (`predStep`/`predAdvance` mirror the engine's `advancePlayer`; `projectServerPosition` estimates the server's current position from snapshot + RTT EMA + unacked inputs; `alignDecisionToServer` nudges pred across cell boundaries at turn/stop edges so both sims commit to the same rounding decision; ghost charges sit on the server's projected placement cell). Correction policy: lead-aware envelope `max(PRED_DEADZONE, speed*(rttAvg/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)`; gaps inside it ride untouched, gaps beyond it are trimmed on EVERY snapshot (never gated on all inputs acked; that gating let offsets stack and discharge as teleport-back snaps), and gaps past 2.5 cells ease toward est at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). Two snapshot-age models coexist deliberately: the reconcile estimate uses a calibrated bias (now - rttAvg/2 - TICK_MS/2) so it lands on the server's quantized now, while event projections use measured arrival - rttAvg/2. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame mirror of the component's reconcile): change prediction in the component and update the mirror there too. Harness traps already paid for: client frames must advance pred by real elapsed dt capped at 100ms (never gate on modulo of the substep size); scripted drops need a clear-ahead gate (two open cells ahead in the held direction) or the technician stands on its own fuse; seed 2817 has an open ring (1,1)-(11,5) for drop scenarios while seed 1234's spawn pocket is crate-choked.
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Periods, achievements & the game registry