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
+12
View File
@@ -0,0 +1,12 @@
export function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
const value = bytes / 1024 ** exponent;
return `${exponent === 0 ? value : value.toFixed(1)} ${units[exponent]}`;
}
export function formatDuration(ms: number): string {
if (ms < 1000) return `${Math.round(ms)} ms`;
return `${(ms / 1000).toFixed(1)} s`;
}
+11
View File
@@ -0,0 +1,11 @@
export interface KeyBinding {
keys: string;
action: string;
}
export const KEY_BINDINGS: KeyBinding[] = [
{ keys: "Left Shift", action: "Left flipper" },
{ keys: "Right Shift", action: "Right flipper" },
{ keys: "Enter", action: "Plunger" },
{ keys: "1", action: "Start game" },
];
+15
View File
@@ -0,0 +1,15 @@
// In-memory handoff for a user-selected .vpx File between the landing page
// and /play — a File can't survive a URL-based navigation, and this is a
// single-shot value read once on mount, so module-level state is sufficient
// (no need for anything heavier than a plain variable).
let pendingFile: File | null = null;
export function setPendingTable(file: File): void {
pendingFile = file;
}
export function takePendingTable(): File | null {
const file = pendingFile;
pendingFile = null;
return file;
}
+5
View File
@@ -0,0 +1,5 @@
export interface TableInfo {
name: string;
sizeBytes: number;
isDemo: boolean;
}
+104
View File
@@ -0,0 +1,104 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { LoadPinballOptions, PinballInstance } from "@valknar/vpinball-wasm";
import { hasWebGL2 } from "./webglSupport";
// Served as a plain static file, not bundled — loadPinball() internally does
// a dynamic import(`${baseUrl}/vpinball.js`) with a template-literal path
// that webpack can't statically resolve, so the whole engine must stay
// outside webpack's module graph (see scripts/copy-engine-assets.mjs).
const ENGINE_BASE_URL = "/vendor/vpinball-wasm";
export type PinballStatus = "idle" | "loading" | "ready" | "running" | "error";
interface EngineModule {
loadPinball(options: LoadPinballOptions): Promise<PinballInstance>;
}
async function loadEngineModule(): Promise<EngineModule> {
return (await import(
/* webpackIgnore: true */ `${ENGINE_BASE_URL}/index.js`
)) as EngineModule;
}
export interface UsePinballInstanceResult {
status: PinballStatus;
/** 0-1 download progress, only meaningful while status is "loading". */
progress: number;
error: string | null;
loadTimeMs: number | null;
instanceRef: React.RefObject<PinballInstance | null>;
/** Call from a user-gesture handler (audio autoplay / fullscreen policy). */
start: () => void;
}
export function usePinballInstance(
canvasRef: React.RefObject<HTMLCanvasElement | null>,
tableData: ArrayBuffer | undefined,
): UsePinballInstanceResult {
// Computed once at mount (not inside the effect below) so the WebGL2-
// unsupported case is derived initial state rather than a setState call
// that an effect makes only to immediately return.
const [webgl2Supported] = useState(hasWebGL2);
const [status, setStatus] = useState<PinballStatus>(webgl2Supported ? "idle" : "error");
const [progress, setProgress] = useState(0);
const [error, setError] = useState<string | null>(
webgl2Supported ? null : "Your browser doesn't support WebGL2, which this pinball engine requires.",
);
const [loadTimeMs, setLoadTimeMs] = useState<number | null>(null);
const instanceRef = useRef<PinballInstance | null>(null);
const disposedRef = useRef(false);
useEffect(() => {
disposedRef.current = false;
const canvas = canvasRef.current;
if (!canvas || !webgl2Supported) return;
setStatus("loading");
const startedAt = performance.now();
(async () => {
try {
const { loadPinball } = await loadEngineModule();
const instance = await loadPinball({
canvas,
baseUrl: ENGINE_BASE_URL,
tableData,
onProgress: (fraction) => {
if (!disposedRef.current) setProgress(fraction);
},
});
if (disposedRef.current) {
instance.dispose();
return;
}
instanceRef.current = instance;
setLoadTimeMs(performance.now() - startedAt);
setStatus("ready");
} catch (err) {
if (!disposedRef.current) {
setStatus("error");
setError(err instanceof Error ? err.message : "Failed to load the pinball engine.");
}
}
})();
return () => {
disposedRef.current = true;
instanceRef.current?.dispose();
instanceRef.current = null;
};
// Intentionally run once: PlayView mounts a fresh PinballCanvasImpl
// (via `key`) per table rather than swapping tableData in place.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const start = useCallback(() => {
if (!instanceRef.current) return;
instanceRef.current.start();
setStatus("running");
}, []);
return { status, progress, error, loadTimeMs, instanceRef, start };
}
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { useEffect } from "react";
import type { attachTouchControls as AttachTouchControls } from "@valknar/vpinball-wasm";
const ENGINE_BASE_URL = "/vendor/vpinball-wasm";
function isTouchDevice(): boolean {
return typeof window !== "undefined" && ("ontouchstart" in window || navigator.maxTouchPoints > 0);
}
/** Attaches the engine's on-screen touch overlay to `containerRef` while `active` is true. */
export function useTouchControls(
containerRef: React.RefObject<HTMLElement | null>,
active: boolean,
): void {
useEffect(() => {
if (!active || !isTouchDevice()) return;
const container = containerRef.current;
if (!container) return;
let handle: { detach: () => void } | undefined;
let cancelled = false;
(async () => {
const { attachTouchControls } = (await import(
/* webpackIgnore: true */ `${ENGINE_BASE_URL}/index.js`
)) as { attachTouchControls: typeof AttachTouchControls };
if (cancelled) return;
handle = attachTouchControls({ container });
})();
return () => {
cancelled = true;
handle?.detach();
};
}, [containerRef, active]);
}
+9
View File
@@ -0,0 +1,9 @@
export function hasWebGL2(): boolean {
if (typeof window === "undefined") return false;
try {
const canvas = document.createElement("canvas");
return Boolean(canvas.getContext("webgl2"));
} catch {
return false;
}
}