mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 10:32:57 +01:00
refactor(pico8): tighten the frame loop and reuse existing helpers
Render through a packed-RGBA palette lookup and a 32-bit pixel view, so a paint is two stores per framebuffer byte instead of eight clamped byte writes, and rebind the heap views only when wasm memory grows. Separate `advance` from `render` so a catch-up tick emulates several frames but paints once, rather than discarding up to two full frames of pixel work exactly when the machine is already behind. Load the runtime and fetch the cart in parallel, reuse one input struct instead of allocating per step, and skip disconnected gamepads, whose stale analog values press buttons on their own in Firefox (#3851). Replace the hand-rolled liveness flag with useIsAlive, take the canvas geometry and the canvas background token from their existing homes, and move the pad, axis and mouse-button mappings next to the keyboard map. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -68,18 +68,21 @@ beforeEach(() => {
|
||||
|
||||
describe("useCanPlay", () => {
|
||||
it.each([
|
||||
["EJS", "ejs", "canPlayEJS"],
|
||||
["js-dos", "jsDos", "canPlayJsDos"],
|
||||
["PICO-8", "pico8", "canPlayPico8"],
|
||||
["Ruffle", "ruffle", "canPlayRuffle"],
|
||||
] as const)("reports %s support on its own flag", (_label, stub, flag) => {
|
||||
support[stub].mockReturnValue(true);
|
||||
if (stub === "pico8") support.pico8Rom.mockReturnValue(true);
|
||||
const result = useCanPlay(() => makeRom());
|
||||
["EJS", "ejs", "canPlayEJS", []],
|
||||
["js-dos", "jsDos", "canPlayJsDos", []],
|
||||
["PICO-8", "pico8", "canPlayPico8", ["pico8Rom"]],
|
||||
["Ruffle", "ruffle", "canPlayRuffle", []],
|
||||
] as const)(
|
||||
"reports %s support on its own flag",
|
||||
(_label, stub, flag, alsoRequires) => {
|
||||
support[stub].mockReturnValue(true);
|
||||
for (const extra of alsoRequires) support[extra].mockReturnValue(true);
|
||||
const result = useCanPlay(() => makeRom());
|
||||
|
||||
expect(result[flag].value).toBe(true);
|
||||
expect(result.canPlay.value).toBe(true);
|
||||
});
|
||||
expect(result[flag].value).toBe(true);
|
||||
expect(result.canPlay.value).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
// A physical game, or one whose file vanished from the library, has nothing
|
||||
// to hand the emulator: every route boots from the download endpoint.
|
||||
|
||||
@@ -9,12 +9,10 @@
|
||||
// slugs at once (sort comparators, group-by buckets in PlatformsIndex).
|
||||
//
|
||||
// `emulator` resolves to the in-browser engine that actually drives the
|
||||
// platform: "ruffle" for Flash, "jsdos" for Windows 3.x/9x, "pico8" for
|
||||
// PICO-8, "dosbox"
|
||||
// when the EJS catalogue picks the dosbox_pure core (DOS is wrapped by
|
||||
// EJS but distinctive enough to surface by name in the UI),
|
||||
// "emulatorjs" for everything else playable, and `null` when nothing on
|
||||
// the server can run it.
|
||||
// platform: "ruffle" for Flash, "jsdos" for Windows 3.x/9x, "dosbox" when
|
||||
// the EJS catalogue picks the dosbox_pure core (DOS is wrapped by EJS but
|
||||
// distinctive enough to surface by name in the UI), "emulatorjs" for
|
||||
// everything else playable, and `null` when nothing on the server can run it.
|
||||
//
|
||||
// `mode` folds the in-browser answer together with streaming: a platform
|
||||
// served by a configured streaming container is playable too, just not in
|
||||
|
||||
@@ -24,8 +24,18 @@
|
||||
// * Browser without `document.startViewTransition` → just navigate.
|
||||
import { nextTick, ref } from "vue";
|
||||
import type { RouteLocationNormalized, Router } from "vue-router";
|
||||
import { ROUTES } from "@/plugins/router";
|
||||
import { useReducedMotion } from "@/v2/composables/useReducedMotion";
|
||||
|
||||
// Routes that paint a `rom-cover-<id>` hero, so any pair of them can morph.
|
||||
const MORPH_ROM_ROUTES: ReadonlySet<string> = new Set([
|
||||
ROUTES.ROM,
|
||||
ROUTES.EMULATORJS,
|
||||
ROUTES.JSDOS,
|
||||
ROUTES.PICO8,
|
||||
ROUTES.RUFFLE,
|
||||
]);
|
||||
|
||||
export interface MorphSource {
|
||||
el: HTMLElement;
|
||||
name: string;
|
||||
@@ -97,17 +107,9 @@ export function useViewTransition() {
|
||||
function morphNameForRoute(route: RouteLocationNormalized): string | null {
|
||||
const name = route.name;
|
||||
const params = route.params as Record<string, string | string[]>;
|
||||
// `rom` (detail) and the players all own a
|
||||
// `rom-cover-<id>` hero, so morph between any of them and the gallery /
|
||||
// each other.
|
||||
if (
|
||||
(name === "rom" ||
|
||||
name === "emulatorjs" ||
|
||||
name === "jsdos" ||
|
||||
name === "pico8" ||
|
||||
name === "ruffle") &&
|
||||
params.rom
|
||||
) {
|
||||
// `rom` (detail) and the players all own a `rom-cover-<id>` hero, so morph
|
||||
// between any of them and the gallery, or each other.
|
||||
if (MORPH_ROM_ROUTES.has(String(name)) && params.rom) {
|
||||
return `rom-cover-${params.rom}`;
|
||||
}
|
||||
if (name === "platform" && params.platform) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
// Plays PICO-8 carts through the FAKE-08 WebAssembly runtime served from
|
||||
// /assets/pico8 (provisioned by the emulator stage of docker/Dockerfile).
|
||||
import { RBtn, RSpinner, RSwitch } from "@v2/lib";
|
||||
import { useEventListener } from "@vueuse/core";
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
|
||||
@@ -10,6 +12,7 @@ import { getDownloadPath } from "@/utils";
|
||||
import PlayerShell from "@/v2/components/Player/PlayerShell.vue";
|
||||
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
import { useIsAlive } from "@/v2/composables/useIsAlive";
|
||||
import { usePlaySession } from "@/v2/composables/usePlaySession";
|
||||
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
@@ -17,7 +20,9 @@ import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import {
|
||||
createPico8Runtime,
|
||||
PICO8_FRAME_RATE,
|
||||
PICO8_HEIGHT,
|
||||
PICO8_INPUT_BITS,
|
||||
PICO8_WIDTH,
|
||||
type Pico8Runtime,
|
||||
} from "./pico8Runtime";
|
||||
|
||||
@@ -27,6 +32,7 @@ const playSession = usePlaySession();
|
||||
const snackbar = useSnackbar();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
const { modality } = useInputModality();
|
||||
const alive = useIsAlive();
|
||||
|
||||
const rom = shallowRef<DetailedRom | null>(null);
|
||||
const gameRunning = ref(false);
|
||||
@@ -49,7 +55,9 @@ let mouseButtons = 0;
|
||||
let audioContext: AudioContext | null = null;
|
||||
let audioGain: GainNode | null = null;
|
||||
let nextAudioTime = 0;
|
||||
let viewAlive = true;
|
||||
let frameDuration = 1000 / PICO8_FRAME_RATE;
|
||||
|
||||
const input = { keyDown: 0, keyHeld: 0, mouseX: 0, mouseY: 0, mouseButtons: 0 };
|
||||
|
||||
const keyboardMap: Record<string, number> = {
|
||||
ArrowLeft: PICO8_INPUT_BITS.left,
|
||||
@@ -60,29 +68,45 @@ const keyboardMap: Record<string, number> = {
|
||||
KeyX: PICO8_INPUT_BITS.b,
|
||||
};
|
||||
|
||||
// W3C standard-mapping button index to PICO-8 bit.
|
||||
const padButtonMap = [
|
||||
[0, PICO8_INPUT_BITS.a],
|
||||
[1, PICO8_INPUT_BITS.b],
|
||||
[12, PICO8_INPUT_BITS.up],
|
||||
[13, PICO8_INPUT_BITS.down],
|
||||
[14, PICO8_INPUT_BITS.left],
|
||||
[15, PICO8_INPUT_BITS.right],
|
||||
] as const;
|
||||
|
||||
// Per stick axis, the bit for a negative then a positive deflection.
|
||||
const padAxisMap = [
|
||||
[PICO8_INPUT_BITS.left, PICO8_INPUT_BITS.right],
|
||||
[PICO8_INPUT_BITS.up, PICO8_INPUT_BITS.down],
|
||||
] as const;
|
||||
const PAD_AXIS_THRESHOLD = 0.5;
|
||||
|
||||
// Pointer button number to the mask FAKE-08 expects (left, middle, right).
|
||||
const mouseButtonMap = [0x01, 0x04, 0x02];
|
||||
|
||||
const directionControls = [
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.up,
|
||||
icon: "mdi-menu-up",
|
||||
className: "r-v2-pico8__control--up",
|
||||
label: "up",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.left,
|
||||
icon: "mdi-menu-left",
|
||||
className: "r-v2-pico8__control--left",
|
||||
label: "left",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.right,
|
||||
icon: "mdi-menu-right",
|
||||
className: "r-v2-pico8__control--right",
|
||||
label: "right",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.down,
|
||||
icon: "mdi-menu-down",
|
||||
className: "r-v2-pico8__control--down",
|
||||
label: "down",
|
||||
},
|
||||
] as const;
|
||||
@@ -115,28 +139,32 @@ function onKeyUp(event: KeyboardEvent) {
|
||||
|
||||
function readGamepadMask() {
|
||||
let mask = 0;
|
||||
const gamepads = navigator.getGamepads?.() ?? [];
|
||||
for (const gamepad of gamepads) {
|
||||
if (!gamepad) continue;
|
||||
if (gamepad.buttons[14]?.pressed) mask |= PICO8_INPUT_BITS.left;
|
||||
if (gamepad.buttons[15]?.pressed) mask |= PICO8_INPUT_BITS.right;
|
||||
if (gamepad.buttons[12]?.pressed) mask |= PICO8_INPUT_BITS.up;
|
||||
if (gamepad.buttons[13]?.pressed) mask |= PICO8_INPUT_BITS.down;
|
||||
if (gamepad.buttons[0]?.pressed) mask |= PICO8_INPUT_BITS.a;
|
||||
if (gamepad.buttons[1]?.pressed) mask |= PICO8_INPUT_BITS.b;
|
||||
if ((gamepad.axes[0] ?? 0) < -0.5) mask |= PICO8_INPUT_BITS.left;
|
||||
if ((gamepad.axes[0] ?? 0) > 0.5) mask |= PICO8_INPUT_BITS.right;
|
||||
if ((gamepad.axes[1] ?? 0) < -0.5) mask |= PICO8_INPUT_BITS.up;
|
||||
if ((gamepad.axes[1] ?? 0) > 0.5) mask |= PICO8_INPUT_BITS.down;
|
||||
for (const gamepad of navigator.getGamepads?.() ?? []) {
|
||||
// Firefox keeps disconnected entries, whose stale analog values drift
|
||||
// across the threshold and press buttons on their own. #3851.
|
||||
if (!gamepad?.connected) continue;
|
||||
const { buttons, axes } = gamepad;
|
||||
for (const [index, bit] of padButtonMap) {
|
||||
if (buttons[index]?.pressed) mask |= bit;
|
||||
}
|
||||
for (let axis = 0; axis < padAxisMap.length; axis += 1) {
|
||||
const value = axes[axis] ?? 0;
|
||||
if (value < -PAD_AXIS_THRESHOLD) mask |= padAxisMap[axis][0];
|
||||
if (value > PAD_AXIS_THRESHOLD) mask |= padAxisMap[axis][1];
|
||||
}
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
function getInput() {
|
||||
function readInput() {
|
||||
const held = keyboardMask | touchMask.value | readGamepadMask();
|
||||
const keyDown = held & ~previousHeld;
|
||||
input.keyDown = held & ~previousHeld;
|
||||
input.keyHeld = held;
|
||||
input.mouseX = mouseX;
|
||||
input.mouseY = mouseY;
|
||||
input.mouseButtons = mouseButtons;
|
||||
previousHeld = held;
|
||||
return { keyDown, keyHeld: held, mouseX, mouseY, mouseButtons };
|
||||
return input;
|
||||
}
|
||||
|
||||
function updateMousePosition(event: PointerEvent) {
|
||||
@@ -144,21 +172,22 @@ function updateMousePosition(event: PointerEvent) {
|
||||
if (!element) return;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return;
|
||||
mouseX = Math.max(
|
||||
0,
|
||||
Math.min(127, Math.floor(((event.clientX - rect.left) / rect.width) * 128)),
|
||||
mouseX = clampToScreen(
|
||||
((event.clientX - rect.left) / rect.width) * PICO8_WIDTH,
|
||||
PICO8_WIDTH,
|
||||
);
|
||||
mouseY = Math.max(
|
||||
0,
|
||||
Math.min(127, Math.floor(((event.clientY - rect.top) / rect.height) * 128)),
|
||||
mouseY = clampToScreen(
|
||||
((event.clientY - rect.top) / rect.height) * PICO8_HEIGHT,
|
||||
PICO8_HEIGHT,
|
||||
);
|
||||
}
|
||||
|
||||
function clampToScreen(value: number, size: number) {
|
||||
return Math.max(0, Math.min(size - 1, Math.floor(value)));
|
||||
}
|
||||
|
||||
function getMouseButtonMask(button: number) {
|
||||
if (button === 0) return 0x01;
|
||||
if (button === 1) return 0x04;
|
||||
if (button === 2) return 0x02;
|
||||
return 0;
|
||||
return mouseButtonMap[button] ?? 0;
|
||||
}
|
||||
|
||||
function onCanvasPointerMove(event: PointerEvent) {
|
||||
@@ -210,7 +239,7 @@ function scheduleAudio(samples: Int16Array) {
|
||||
const buffer = audioContext.createBuffer(
|
||||
1,
|
||||
samples.length,
|
||||
runtime?.audioSampleRate ?? 22050,
|
||||
audioContext.sampleRate,
|
||||
);
|
||||
const channel = buffer.getChannelData(0);
|
||||
for (let index = 0; index < samples.length; index += 1) {
|
||||
@@ -226,19 +255,18 @@ function scheduleAudio(samples: Int16Array) {
|
||||
|
||||
function runFrame(timestamp: number) {
|
||||
if (!gameRunning.value || !runtime) return;
|
||||
const frameDuration = 1000 / (runtime.frameRate || PICO8_FRAME_RATE);
|
||||
const elapsed = Math.min(timestamp - lastFrameTime, 250);
|
||||
frameAccumulator += Math.min(timestamp - lastFrameTime, 250);
|
||||
lastFrameTime = timestamp;
|
||||
frameAccumulator += elapsed;
|
||||
|
||||
let steps = 0;
|
||||
try {
|
||||
while (frameAccumulator >= frameDuration && steps < 3) {
|
||||
runtime.step(getInput());
|
||||
runtime.advance(readInput());
|
||||
scheduleAudio(runtime.getAudioSamples());
|
||||
frameAccumulator -= frameDuration;
|
||||
steps += 1;
|
||||
}
|
||||
if (steps > 0) runtime.render();
|
||||
} catch (error) {
|
||||
showPlayError(error);
|
||||
return;
|
||||
@@ -247,8 +275,9 @@ function runFrame(timestamp: number) {
|
||||
}
|
||||
|
||||
function startLoop() {
|
||||
frameDuration = 1000 / (runtime?.frameRate || PICO8_FRAME_RATE);
|
||||
lastFrameTime = performance.now();
|
||||
frameAccumulator = 1000 / (runtime?.frameRate || PICO8_FRAME_RATE);
|
||||
frameAccumulator = frameDuration;
|
||||
animationFrame = requestAnimationFrame(runFrame);
|
||||
}
|
||||
|
||||
@@ -260,18 +289,22 @@ function closeAudio() {
|
||||
if (context) void context.close().catch(() => {});
|
||||
}
|
||||
|
||||
function releaseGame() {
|
||||
cancelAnimationFrame(animationFrame);
|
||||
animationFrame = 0;
|
||||
runtime?.dispose();
|
||||
runtime = null;
|
||||
closeAudio();
|
||||
function resetInput() {
|
||||
previousHeld = 0;
|
||||
keyboardMask = 0;
|
||||
mouseX = 0;
|
||||
mouseY = 0;
|
||||
mouseButtons = 0;
|
||||
touchMask.value = 0;
|
||||
}
|
||||
|
||||
function releaseGame() {
|
||||
cancelAnimationFrame(animationFrame);
|
||||
animationFrame = 0;
|
||||
runtime?.dispose();
|
||||
runtime = null;
|
||||
closeAudio();
|
||||
resetInput();
|
||||
playSession.flush();
|
||||
playingStore.setPlaying(false);
|
||||
gameRunning.value = false;
|
||||
@@ -284,6 +317,12 @@ function showPlayError(error: unknown) {
|
||||
releaseGame();
|
||||
}
|
||||
|
||||
async function fetchCartBytes(target: DetailedRom) {
|
||||
const response = await fetch(getDownloadPath({ rom: target }));
|
||||
if (!response.ok) throw new Error(`ROM request failed: ${response.status}`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
async function onPlay() {
|
||||
const currentRom = rom.value;
|
||||
if (!currentRom || gameRunning.value) return;
|
||||
@@ -293,7 +332,7 @@ async function onPlay() {
|
||||
playingStore.setPlaying(true);
|
||||
await nextTick();
|
||||
|
||||
if (!viewAlive || !gameRunning.value) return;
|
||||
if (!gameRunning.value) return;
|
||||
const canvasElement = canvas.value;
|
||||
if (!canvasElement) {
|
||||
showPlayError(new Error("PICO-8 canvas is unavailable"));
|
||||
@@ -302,16 +341,12 @@ async function onPlay() {
|
||||
|
||||
let nextRuntime: Pico8Runtime | null = null;
|
||||
try {
|
||||
nextRuntime = await createPico8Runtime(canvasElement);
|
||||
if (!viewAlive || !gameRunning.value) {
|
||||
nextRuntime.dispose();
|
||||
nextRuntime = null;
|
||||
return;
|
||||
}
|
||||
const response = await fetch(getDownloadPath({ rom: currentRom }));
|
||||
if (!response.ok) throw new Error(`ROM request failed: ${response.status}`);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (!viewAlive || !gameRunning.value) {
|
||||
const [runtimeResult, bytes] = await Promise.all([
|
||||
createPico8Runtime(canvasElement),
|
||||
fetchCartBytes(currentRom),
|
||||
]);
|
||||
nextRuntime = runtimeResult;
|
||||
if (!gameRunning.value) {
|
||||
nextRuntime.dispose();
|
||||
nextRuntime = null;
|
||||
return;
|
||||
@@ -346,7 +381,7 @@ async function onPlay() {
|
||||
startLoop();
|
||||
} catch (error) {
|
||||
nextRuntime?.dispose();
|
||||
if (!viewAlive || !gameRunning.value) return;
|
||||
if (!gameRunning.value) return;
|
||||
showPlayError(error);
|
||||
}
|
||||
}
|
||||
@@ -358,27 +393,20 @@ function onlyQuit() {
|
||||
|
||||
useEventListener(window, "keydown", onKeyDown);
|
||||
useEventListener(window, "keyup", onKeyUp);
|
||||
useEventListener(window, "blur", () => {
|
||||
keyboardMask = 0;
|
||||
mouseButtons = 0;
|
||||
touchMask.value = 0;
|
||||
});
|
||||
useEventListener(window, "blur", resetInput);
|
||||
|
||||
onMounted(async () => {
|
||||
const romResponse = await romApi.getRom({ romId });
|
||||
if (!viewAlive) return;
|
||||
if (!alive.value) return;
|
||||
rom.value = romResponse.data;
|
||||
if (modality.value === "pad" || modality.value === "key") {
|
||||
await nextTick();
|
||||
if (!viewAlive) return;
|
||||
if (!alive.value) return;
|
||||
focusPlayButton();
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
viewAlive = false;
|
||||
releaseGame();
|
||||
});
|
||||
onBeforeUnmount(releaseGame);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -409,8 +437,8 @@ onBeforeUnmount(() => {
|
||||
<canvas
|
||||
ref="canvas"
|
||||
class="r-v2-pico8__canvas"
|
||||
width="128"
|
||||
height="128"
|
||||
:width="PICO8_WIDTH"
|
||||
:height="PICO8_HEIGHT"
|
||||
aria-label="PICO-8 game"
|
||||
@pointermove="onCanvasPointerMove"
|
||||
@pointerdown="onCanvasPointerDown"
|
||||
@@ -437,7 +465,7 @@ onBeforeUnmount(() => {
|
||||
size="small"
|
||||
:class="[
|
||||
'r-v2-pico8__control',
|
||||
control.className,
|
||||
`r-v2-pico8__control--${control.label}`,
|
||||
{
|
||||
'r-v2-pico8__control--held': touchMask & control.bit,
|
||||
},
|
||||
@@ -510,7 +538,7 @@ onBeforeUnmount(() => {
|
||||
width: min(78vmin, 640px);
|
||||
aspect-ratio: 1;
|
||||
flex: 0 0 auto;
|
||||
background: #000;
|
||||
background: var(--r-color-canvas-bg);
|
||||
box-shadow: 0 18px 48px color-mix(in srgb, black 55%, transparent);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,21 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPico8Runtime, PICO8_HEIGHT, PICO8_WIDTH } from "./pico8Runtime";
|
||||
import {
|
||||
createPico8Runtime,
|
||||
type Fake08Module,
|
||||
PICO8_HEIGHT,
|
||||
PICO8_WIDTH,
|
||||
} from "./pico8Runtime";
|
||||
|
||||
const heap = new Uint8Array(new ArrayBuffer(64 * 1024));
|
||||
const context = {
|
||||
createImageData: vi.fn(() => ({
|
||||
data: new Uint8ClampedArray(PICO8_WIDTH * PICO8_HEIGHT * 4),
|
||||
})),
|
||||
imageSmoothingEnabled: true,
|
||||
putImageData: vi.fn(),
|
||||
};
|
||||
|
||||
// Hand out distinct addresses so the palette and audio buffers do not alias.
|
||||
let nextAddress = 200;
|
||||
const fakeModule = {
|
||||
HEAPU8: heap,
|
||||
_f08_init: vi.fn(),
|
||||
@@ -31,10 +38,14 @@ const fakeModule = {
|
||||
return 2;
|
||||
}),
|
||||
_f08_get_audio_sample_rate: vi.fn(() => 22050),
|
||||
_malloc: vi.fn(() => 200),
|
||||
_malloc: vi.fn((size: number) => {
|
||||
const address = nextAddress;
|
||||
nextAddress += size;
|
||||
return address;
|
||||
}),
|
||||
_free: vi.fn(),
|
||||
UTF8ToString: vi.fn(() => ""),
|
||||
};
|
||||
} satisfies Fake08Module;
|
||||
|
||||
vi.mock("./scriptLoader", () => ({
|
||||
loadScript: vi.fn(async () => {
|
||||
@@ -44,6 +55,7 @@ vi.mock("./scriptLoader", () => ({
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
nextAddress = 200;
|
||||
heap[100] = 0x21;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(
|
||||
context as unknown as CanvasRenderingContext2D,
|
||||
@@ -55,15 +67,19 @@ describe("createPico8Runtime", () => {
|
||||
const runtime = await createPico8Runtime(document.createElement("canvas"));
|
||||
|
||||
runtime.loadCart(new Uint8Array([1, 2, 3]));
|
||||
runtime.step({
|
||||
runtime.advance({
|
||||
keyDown: 0x10,
|
||||
keyHeld: 0x30,
|
||||
mouseX: 12,
|
||||
mouseY: 34,
|
||||
mouseButtons: 1,
|
||||
});
|
||||
runtime.render();
|
||||
|
||||
expect(fakeModule._f08_load_cart_data).toHaveBeenCalledWith(200, 3);
|
||||
expect(fakeModule._f08_load_cart_data).toHaveBeenCalledWith(
|
||||
expect.any(Number),
|
||||
3,
|
||||
);
|
||||
expect(fakeModule._f08_set_inputs).toHaveBeenCalledWith(
|
||||
0x10,
|
||||
0x30,
|
||||
@@ -79,7 +95,7 @@ describe("createPico8Runtime", () => {
|
||||
expect(runtime.audioSampleRate).toBe(22050);
|
||||
|
||||
runtime.dispose();
|
||||
runtime.step({
|
||||
runtime.advance({
|
||||
keyDown: 0,
|
||||
keyHeld: 0,
|
||||
mouseX: 0,
|
||||
|
||||
@@ -17,8 +17,9 @@ const PICO8_WASM_PATH = "/assets/pico8/fake08.wasm";
|
||||
const PICO8_SCRIPT_PATH = "/assets/pico8/fake08.js";
|
||||
const FRAMEBUFFER_BYTES = (PICO8_WIDTH * PICO8_HEIGHT) / 2;
|
||||
const PALETTE_BYTES = 16 * 4;
|
||||
const EMPTY_SAMPLES = new Int16Array(0);
|
||||
|
||||
interface Fake08Module {
|
||||
export interface Fake08Module {
|
||||
HEAPU8: Uint8Array;
|
||||
_f08_init: () => void;
|
||||
_f08_load_cart_data: (pointer: number, length: number) => number;
|
||||
@@ -82,7 +83,8 @@ export interface Pico8Runtime {
|
||||
readonly frameRate: number;
|
||||
readonly audioSampleRate: number;
|
||||
loadCart: (bytes: Uint8Array) => void;
|
||||
step: (input: Pico8Input) => void;
|
||||
advance: (input: Pico8Input) => void;
|
||||
render: () => void;
|
||||
getAudioSamples: () => Int16Array;
|
||||
dispose: () => void;
|
||||
}
|
||||
@@ -97,13 +99,12 @@ export async function createPico8Runtime(
|
||||
const module = await factory({
|
||||
locateFile: (path) => (path.endsWith(".wasm") ? PICO8_WASM_PATH : path),
|
||||
});
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) throw new Error("PICO-8 needs a 2D canvas");
|
||||
const renderContext = context;
|
||||
const canvasContext = canvas.getContext("2d", { alpha: false });
|
||||
if (!canvasContext) throw new Error("PICO-8 needs a 2D canvas");
|
||||
const context = canvasContext;
|
||||
|
||||
canvas.width = PICO8_WIDTH;
|
||||
canvas.height = PICO8_HEIGHT;
|
||||
renderContext.imageSmoothingEnabled = false;
|
||||
module._f08_init();
|
||||
|
||||
const framebufferPointer = module._f08_get_framebuffer_ptr();
|
||||
@@ -114,40 +115,51 @@ export async function createPico8Runtime(
|
||||
module._f08_get_audio_sample_rate() / PICO8_FRAME_RATE,
|
||||
);
|
||||
const audioPointer = module._malloc(samplesPerFrame * 2);
|
||||
const imageData = renderContext.createImageData(PICO8_WIDTH, PICO8_HEIGHT);
|
||||
const imageData = context.createImageData(PICO8_WIDTH, PICO8_HEIGHT);
|
||||
const pixels = new Uint32Array(imageData.data.buffer);
|
||||
|
||||
// Packed-RGBA lookup for the 16 palette entries, so the pixel loop is two
|
||||
// 32-bit stores per byte instead of eight clamped byte stores. Written
|
||||
// through an aliased byte view to stay correct on either endianness.
|
||||
const paletteLutBytes = new Uint8Array(PALETTE_BYTES);
|
||||
const paletteLut = new Uint32Array(paletteLutBytes.buffer);
|
||||
|
||||
let heapBuffer: ArrayBufferLike | null = null;
|
||||
let palette: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
|
||||
let framebuffer: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
|
||||
let disposed = false;
|
||||
|
||||
function render() {
|
||||
module._f08_get_palette_rgba(palettePointer);
|
||||
const palette = new Uint8Array(
|
||||
module.HEAPU8.buffer,
|
||||
palettePointer,
|
||||
PALETTE_BYTES,
|
||||
);
|
||||
const framebuffer = new Uint8Array(
|
||||
module.HEAPU8.buffer,
|
||||
// Heap growth detaches existing views, so rebind whenever the buffer changes.
|
||||
function syncHeapViews() {
|
||||
if (heapBuffer === module.HEAPU8.buffer) return;
|
||||
heapBuffer = module.HEAPU8.buffer;
|
||||
palette = new Uint8Array(heapBuffer, palettePointer, PALETTE_BYTES);
|
||||
framebuffer = new Uint8Array(
|
||||
heapBuffer,
|
||||
framebufferPointer,
|
||||
FRAMEBUFFER_BYTES,
|
||||
);
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (disposed) return;
|
||||
module._f08_get_palette_rgba(palettePointer);
|
||||
syncHeapViews();
|
||||
|
||||
// Carts remap the palette at runtime, so the lookup is rebuilt per paint.
|
||||
paletteLutBytes.set(palette);
|
||||
for (let alpha = 3; alpha < PALETTE_BYTES; alpha += 4) {
|
||||
paletteLutBytes[alpha] = 0xff;
|
||||
}
|
||||
|
||||
let target = 0;
|
||||
for (let index = 0; index < FRAMEBUFFER_BYTES; index += 1) {
|
||||
const packed = framebuffer[index];
|
||||
const firstPixel = index * 2;
|
||||
const secondPixel = firstPixel + 1;
|
||||
const firstColor = (packed & 0x0f) * 4;
|
||||
const secondColor = (packed >> 4) * 4;
|
||||
const firstTarget = firstPixel * 4;
|
||||
const secondTarget = secondPixel * 4;
|
||||
imageData.data[firstTarget] = palette[firstColor];
|
||||
imageData.data[firstTarget + 1] = palette[firstColor + 1];
|
||||
imageData.data[firstTarget + 2] = palette[firstColor + 2];
|
||||
imageData.data[firstTarget + 3] = 255;
|
||||
imageData.data[secondTarget] = palette[secondColor];
|
||||
imageData.data[secondTarget + 1] = palette[secondColor + 1];
|
||||
imageData.data[secondTarget + 2] = palette[secondColor + 2];
|
||||
imageData.data[secondTarget + 3] = 255;
|
||||
pixels[target] = paletteLut[packed & 0x0f];
|
||||
pixels[target + 1] = paletteLut[packed >> 4];
|
||||
target += 2;
|
||||
}
|
||||
renderContext.putImageData(imageData, 0, 0);
|
||||
context.putImageData(imageData, 0, 0);
|
||||
}
|
||||
|
||||
function loadCart(bytes: Uint8Array) {
|
||||
@@ -166,7 +178,7 @@ export async function createPico8Runtime(
|
||||
}
|
||||
}
|
||||
|
||||
function step(input: Pico8Input) {
|
||||
function advance(input: Pico8Input) {
|
||||
if (disposed) return;
|
||||
module._f08_set_inputs(
|
||||
input.keyDown,
|
||||
@@ -176,16 +188,15 @@ export async function createPico8Runtime(
|
||||
input.mouseButtons,
|
||||
);
|
||||
module._f08_step_frame();
|
||||
render();
|
||||
}
|
||||
|
||||
function getAudioSamples() {
|
||||
if (disposed) return new Int16Array();
|
||||
if (disposed) return EMPTY_SAMPLES;
|
||||
const written = module._f08_fill_audio_buffer(
|
||||
audioPointer,
|
||||
samplesPerFrame,
|
||||
);
|
||||
if (written <= 0) return new Int16Array();
|
||||
if (written <= 0) return EMPTY_SAMPLES;
|
||||
return new Int16Array(module.HEAPU8.buffer, audioPointer, written).slice();
|
||||
}
|
||||
|
||||
@@ -200,7 +211,8 @@ export async function createPico8Runtime(
|
||||
frameRate: module._f08_get_target_fps() || PICO8_FRAME_RATE,
|
||||
audioSampleRate: module._f08_get_audio_sample_rate(),
|
||||
loadCart,
|
||||
step,
|
||||
advance,
|
||||
render,
|
||||
getAudioSamples,
|
||||
dispose,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Shared runtime injection for the player views. EmulatorJS and js-dos serve
|
||||
// their runtime locally in the full image and fall back to a CDN without it.
|
||||
// Shared runtime injection for the player views. Runtimes are served from
|
||||
// /assets in the full image; EmulatorJS and js-dos fall back to a CDN without
|
||||
// it, FAKE-08 has none and simply fails.
|
||||
|
||||
/** Inject a <script> and resolve once it has executed. */
|
||||
export function loadScript(src: string): Promise<void> {
|
||||
|
||||
Reference in New Issue
Block a user