Add vpinball: a browser Visual Pinball player

Next.js app that plays real .vpx tables via @valknar/vpinball-wasm
(WebAssembly Visual Pinball). Demo mode with the bundled default
table, drag-and-drop custom table upload, a cabinet-styled UI with a
coin-door HUD (fullscreen/stats/info/eject), a custom 404 page, PWA
support (hand-rolled service worker), and a static Docker Compose
deployment behind nginx.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012hQoM3jJT1Lx7CMTciMzvD
This commit is contained in:
2026-08-23 05:25:15 +02:00
co-authored by Claude Sonnet 5
commit e493a12e68
51 changed files with 5570 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
"use client";
import { useState, type ChangeEvent, type DragEvent, type ReactNode } from "react";
export const VPX_FILE_INPUT_ID = "vpx-file-input";
export interface FileDropZoneProps {
onFile: (file: File) => void;
onError: (message: string) => void;
children: ReactNode;
className?: string;
}
function validate(file: File | undefined, onFile: (file: File) => void, onError: (m: string) => void) {
if (!file) return;
if (!file.name.toLowerCase().endsWith(".vpx")) {
onError(`"${file.name}" isn't a .vpx file.`);
return;
}
onFile(file);
}
export default function FileDropZone({ onFile, onError, children, className = "" }: FileDropZoneProps) {
const [isDragging, setIsDragging] = useState(false);
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setIsDragging(false);
validate(e.dataTransfer.files[0], onFile, onError);
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
validate(e.target.files?.[0], onFile, onError);
e.target.value = "";
};
return (
<div
onDragOver={(e) => {
e.preventDefault();
setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
onDrop={handleDrop}
className={`relative ${className}`}
>
{children}
<input
id={VPX_FILE_INPUT_ID}
type="file"
accept=".vpx"
className="sr-only"
onChange={handleInputChange}
/>
{isDragging && (
<div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-lg bg-ink/85 font-display text-3xl tracking-wide text-arc ring-2 ring-arc">
DROP TO LOAD
</div>
)}
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { formatBytes, formatDuration } from "@/lib/format";
import { KEY_BINDINGS } from "@/lib/pinball/keyBindings";
import type { TableInfo } from "@/lib/pinball/types";
export interface GameInfoPanelProps {
tableInfo: TableInfo;
loadTimeMs: number | null;
}
export default function GameInfoPanel({ tableInfo, loadTimeMs }: GameInfoPanelProps) {
return (
<div className="w-72 space-y-4 rounded border border-chrome/30 bg-ash/95 p-4 font-mono text-sm text-paper shadow-xl">
<div>
<div className="text-xs tracking-widest text-chrome">TABLE</div>
<div className="truncate text-arc">{tableInfo.name}</div>
</div>
<dl className="grid grid-cols-2 gap-x-2 gap-y-1 text-xs">
<dt className="text-chrome">Source</dt>
<dd>{tableInfo.isDemo ? "Bundled demo" : "Your upload"}</dd>
<dt className="text-chrome">Size</dt>
<dd>{tableInfo.isDemo ? "—" : formatBytes(tableInfo.sizeBytes)}</dd>
<dt className="text-chrome">Load time</dt>
<dd>{loadTimeMs !== null ? formatDuration(loadTimeMs) : "—"}</dd>
</dl>
<div>
<div className="mb-1 text-xs tracking-widest text-chrome">CONTROLS</div>
<ul className="space-y-1 text-xs">
{KEY_BINDINGS.map((binding) => (
<li key={binding.action} className="flex justify-between gap-2">
<span className="text-chrome">{binding.action}</span>
<span className="text-paper">{binding.keys}</span>
</li>
))}
</ul>
</div>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
"use client";
import { useEffect } from "react";
export default function RegisterServiceWorker() {
useEffect(() => {
if (!("serviceWorker" in navigator)) return;
navigator.serviceWorker.register("/sw.js").catch((err) => {
console.error("Service worker registration failed:", err);
});
}, []);
return null;
}
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import type { PinballInstance } from "@valknar/vpinball-wasm";
import { useIdleTimer } from "./useIdleTimer";
import StatsReadout from "./StatsReadout";
import GameInfoPanel from "@/components/GameInfoPanel";
import type { TableInfo } from "@/lib/pinball/types";
export interface CoinDoorHudProps {
instanceRef: React.RefObject<PinballInstance | null>;
tableInfo: TableInfo;
loadTimeMs: number | null;
}
function HudButton({
label,
active,
onClick,
}: {
label: string;
active?: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
aria-pressed={active}
className={`rounded-sm border px-3 py-1.5 font-mono text-xs tracking-widest transition ${
active
? "border-marquee bg-marquee/20 text-marquee"
: "border-chrome/40 bg-black/30 text-chrome hover:border-arc hover:text-arc"
}`}
>
{label}
</button>
);
}
export default function CoinDoorHud({ instanceRef, tableInfo, loadTimeMs }: CoinDoorHudProps) {
const router = useRouter();
const isIdle = useIdleTimer(3000);
const [showStats, setShowStats] = useState(false);
const [showInfo, setShowInfo] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
useEffect(() => {
const onChange = () => setIsFullscreen(Boolean(document.fullscreenElement));
document.addEventListener("fullscreenchange", onChange);
return () => document.removeEventListener("fullscreenchange", onChange);
}, []);
const handleFullscreen = () => {
instanceRef.current?.requestFullscreen();
};
const handleEject = () => {
// dispose() (called by usePinballInstance's unmount cleanup, triggered by
// this navigation) tears the instance down immediately. Calling stop()
// here too raced it — stop() defers teardown to the engine's next
// internal step, and dispose() freeing WASM memory before that step runs
// hung the tab.
router.push("/");
};
return (
<>
<div
data-hud
className={`absolute inset-x-0 top-0 z-10 flex items-center justify-between gap-3 border-b border-chrome/30 bg-ash/90 px-4 py-2 backdrop-blur transition-opacity duration-300 ${
isIdle ? "pointer-events-none opacity-0" : "opacity-100"
}`}
>
<div className="flex items-center gap-2">
<span className="font-display text-lg tracking-wide text-marquee">VPINBALL</span>
<span className="hidden truncate font-mono text-xs text-chrome sm:inline">
{tableInfo.name}
</span>
</div>
<div className="flex items-center gap-2">
{showStats && <StatsReadout />}
<HudButton label="INFO" active={showInfo} onClick={() => setShowInfo((v) => !v)} />
<HudButton label="STATS" active={showStats} onClick={() => setShowStats((v) => !v)} />
<HudButton
label={isFullscreen ? "EXIT FS" : "FULLSCREEN"}
active={isFullscreen}
onClick={handleFullscreen}
/>
<HudButton label="EJECT" onClick={handleEject} />
</div>
</div>
{showInfo && (
<div className="absolute right-4 top-16 z-10">
<GameInfoPanel tableInfo={tableInfo} loadTimeMs={loadTimeMs} />
</div>
)}
</>
);
}
+35
View File
@@ -0,0 +1,35 @@
"use client";
import { useEffect, useState } from "react";
/** Self-contained rAF-based FPS counter — the engine exposes no perf API of its own. */
export default function StatsReadout() {
const [fps, setFps] = useState<number | null>(null);
useEffect(() => {
let frameCount = 0;
let windowStart = performance.now();
let raf = 0;
const tick = (now: number) => {
frameCount += 1;
const elapsed = now - windowStart;
if (elapsed >= 500) {
setFps(Math.round((frameCount * 1000) / elapsed));
frameCount = 0;
windowStart = now;
}
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, []);
return (
<div className="flex items-baseline gap-2 rounded border border-chrome/30 bg-black/40 px-3 py-1.5 font-mono">
<span className="text-xs tracking-widest text-chrome">FPS</span>
<span className="text-lg tabular-nums text-arc">{fps ?? "--"}</span>
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useEffect, useRef, useState } from "react";
/** True once no pointer/keyboard activity has been seen for `timeoutMs`. */
export function useIdleTimer(timeoutMs = 3000): boolean {
const [isIdle, setIsIdle] = useState(false);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
const reset = () => {
setIsIdle(false);
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => setIsIdle(true), timeoutMs);
};
reset();
const events: Array<keyof WindowEventMap> = [
"mousemove",
"pointerdown",
"touchstart",
"keydown",
];
events.forEach((event) => window.addEventListener(event, reset, { passive: true }));
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
events.forEach((event) => window.removeEventListener(event, reset));
};
}, [timeoutMs]);
return isIdle;
}
+70
View File
@@ -0,0 +1,70 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import Button, { buttonClassName } from "@/components/ui/Button";
import FileDropZone, { VPX_FILE_INPUT_ID } from "@/components/FileDropZone";
import { setPendingTable } from "@/lib/pinball/tableSelectionStore";
export default function AttractHero() {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const handleFile = (file: File) => {
setError(null);
setPendingTable(file);
router.push("/play");
};
return (
<FileDropZone onFile={handleFile} onError={setError} className="w-full max-w-4xl">
<div className="relative overflow-hidden rounded-t-3xl rounded-b-lg border-2 border-chrome/40 bg-ash shadow-2xl">
{/* Backglass glow — stands in for real playfield art; GI-lamp amber + a cyan tube accent. */}
<div
aria-hidden
className="pointer-events-none absolute inset-0 opacity-70"
style={{
background:
"radial-gradient(60% 50% at 30% 20%, rgba(255,122,41,0.35), transparent 70%), radial-gradient(45% 40% at 80% 70%, rgba(76,224,210,0.25), transparent 70%)",
}}
/>
<div
aria-hidden
className="pointer-events-none absolute inset-0"
style={{
backgroundImage:
"repeating-linear-gradient(0deg, rgba(255,255,255,0.03) 0px, rgba(255,255,255,0.03) 1px, transparent 1px, transparent 3px)",
}}
/>
<div className="relative flex flex-col items-center gap-6 px-8 py-20 text-center sm:py-28">
<p className="font-mono text-xs tracking-[0.3em] text-arc">WEBASSEMBLY · WEBGL2 · REAL .VPX TABLES</p>
<h1 className="font-display text-6xl font-black leading-none tracking-wide text-paper sm:text-8xl">
VPINBALL
</h1>
<p className="max-w-md font-body text-chrome">
Real Visual Pinball tables, playing in your browser. Drop in a{" "}
<code className="font-mono text-arc">.vpx</code> file, or try the bundled demo.
</p>
<div className="mt-4 flex flex-col items-center gap-3 sm:flex-row">
<Button type="button" variant="primary" onClick={() => router.push("/play")}>
Insert Coin Play Demo
</Button>
<label htmlFor={VPX_FILE_INPUT_ID} className={buttonClassName("outline", "cursor-pointer")}>
Load Your Table
</label>
</div>
<p className="font-mono text-xs text-chrome">or drag a .vpx file anywhere onto this panel</p>
{error && (
<p role="alert" className="font-mono text-sm text-marquee">
{error}
</p>
)}
</div>
</div>
</FileDropZone>
);
}
+14
View File
@@ -0,0 +1,14 @@
"use client";
import dynamic from "next/dynamic";
import type { PinballCanvasImplProps } from "./PinballCanvasImpl";
// The engine touches window/canvas/WebGL as soon as it mounts, so it's kept
// out of the server render entirely rather than just deferring to an effect.
const PinballCanvasImpl = dynamic<PinballCanvasImplProps>(() => import("./PinballCanvasImpl"), {
ssr: false,
});
export default function PinballCanvas(props: PinballCanvasImplProps) {
return <PinballCanvasImpl {...props} />;
}
+69
View File
@@ -0,0 +1,69 @@
"use client";
import { useRef } from "react";
import { usePinballInstance } from "@/lib/pinball/usePinballInstance";
import { useTouchControls } from "@/lib/pinball/useTouchControls";
import CoinDoorHud from "@/components/hud/CoinDoorHud";
import type { TableInfo } from "@/lib/pinball/types";
export interface PinballCanvasImplProps {
tableData?: ArrayBuffer;
tableInfo: TableInfo;
}
export default function PinballCanvasImpl({ tableData, tableInfo }: PinballCanvasImplProps) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
const { status, progress, error, loadTimeMs, instanceRef, start } = usePinballInstance(
canvasRef,
tableData,
);
useTouchControls(containerRef, status === "running");
return (
<div ref={containerRef} className="relative h-full w-full overflow-hidden bg-black">
{/* SDL3's Emscripten backend resolves its own window/GL-context target via
document.querySelector("#canvas") independently of Module.canvas — the
id is required or context creation silently no-ops (findCanvasEventTarget
returns null, emscripten_webgl_create_context returns handle 0, and the
engine crashes later reading an unset GL context). */}
<canvas id="canvas" ref={canvasRef} className="h-full w-full" />
{(status === "ready" || status === "running") && (
<CoinDoorHud instanceRef={instanceRef} tableInfo={tableInfo} loadTimeMs={loadTimeMs} />
)}
{status === "loading" && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-4 bg-ink/90 text-paper">
<div className="font-display text-2xl tracking-wide text-marquee">LOADING TABLE</div>
<div className="h-2 w-64 overflow-hidden rounded-full bg-ash">
<div
className="h-full bg-marquee transition-[width]"
style={{ width: `${Math.round(progress * 100)}%` }}
/>
</div>
<div className="font-mono text-sm text-chrome">{Math.round(progress * 100)}%</div>
</div>
)}
{status === "error" && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-ink px-8 text-center text-paper">
<div className="font-display text-2xl text-marquee">TABLE NOT LOADING</div>
<p className="max-w-md font-body text-chrome">{error}</p>
</div>
)}
{status === "ready" && (
<div className="absolute inset-0 flex items-center justify-center bg-ink/80">
<button
type="button"
onClick={start}
className="rounded-full border-2 border-marquee bg-marquee/10 px-8 py-4 font-display text-2xl tracking-wide text-marquee shadow-[0_0_24px_rgba(255,122,41,0.5)] transition hover:bg-marquee/20"
>
TAP TO START
</button>
</div>
)}
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
"use client";
import { useEffect, useState } from "react";
import PinballCanvas from "./PinballCanvas";
import { takePendingTable } from "@/lib/pinball/tableSelectionStore";
import type { TableInfo } from "@/lib/pinball/types";
interface ResolvedTable {
tableData?: ArrayBuffer;
tableInfo: TableInfo;
}
export default function PlayView() {
const [resolved, setResolved] = useState<ResolvedTable | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const file = takePendingTable();
if (file) {
const tableData = await file.arrayBuffer();
if (cancelled) return;
setResolved({
tableData,
tableInfo: { name: file.name, sizeBytes: file.size, isDemo: false },
});
return;
}
// No pending upload (fresh visit, or a hard refresh of /play) — fall
// back to the bundled demo table rather than dead-ending the route.
setResolved({
tableInfo: { name: "Demo table", sizeBytes: 0, isDemo: true },
});
})();
return () => {
cancelled = true;
};
}, []);
if (!resolved) {
return (
<div className="flex h-full w-full items-center justify-center bg-ink font-mono text-chrome">
Preparing table
</div>
);
}
return (
<PinballCanvas tableData={resolved.tableData} tableInfo={resolved.tableInfo} key={resolved.tableInfo.name} />
);
}
+22
View File
@@ -0,0 +1,22 @@
import type { ButtonHTMLAttributes } from "react";
export type ButtonVariant = "primary" | "outline" | "quiet";
const variantClasses: Record<ButtonVariant, string> = {
primary:
"border-2 border-marquee bg-marquee/10 text-marquee shadow-[0_0_24px_rgba(255,122,41,0.35)] hover:bg-marquee/20",
outline: "border-2 border-chrome/50 text-paper hover:border-arc hover:text-arc",
quiet: "border border-transparent text-chrome hover:text-paper",
};
export function buttonClassName(variant: ButtonVariant = "primary", className = ""): string {
return `inline-block rounded-full px-6 py-3 font-display text-lg tracking-wide transition ${variantClasses[variant]} ${className}`;
}
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
}
export default function Button({ variant = "primary", className = "", ...props }: ButtonProps) {
return <button className={buttonClassName(variant, className)} {...props} />;
}
+10
View File
@@ -0,0 +1,10 @@
import type { HTMLAttributes } from "react";
export default function Panel({ className = "", ...props }: HTMLAttributes<HTMLDivElement>) {
return (
<div
className={`rounded-lg border border-chrome/30 bg-ash/80 shadow-lg ${className}`}
{...props}
/>
);
}