diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 56916cf6f..ed32dde1b 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -319,6 +319,7 @@ SYNC_SSH_KNOWN_HOSTS_PATH: Final[str] = _get_env( DISABLE_EMULATOR_JS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_EMULATOR_JS")) DISABLE_RUFFLE_RS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_RUFFLE_RS")) DISABLE_JSDOS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_JSDOS")) +DISABLE_PICO8: Final[bool] = safe_str_to_bool(_get_env("DISABLE_PICO8")) # FRONTEND KIOSK_MODE: Final[bool] = safe_str_to_bool(_get_env("KIOSK_MODE")) diff --git a/backend/endpoints/heartbeat.py b/backend/endpoints/heartbeat.py index 8f92a1aaa..60acc35a2 100644 --- a/backend/endpoints/heartbeat.py +++ b/backend/endpoints/heartbeat.py @@ -11,6 +11,7 @@ from config import ( DISABLE_EMULATOR_JS, DISABLE_JSDOS, DISABLE_LOGS_VIEWER, + DISABLE_PICO8, DISABLE_RUFFLE_RS, DISABLE_SETUP_WIZARD, DISABLE_USERPASS_LOGIN, @@ -157,6 +158,7 @@ async def heartbeat() -> HeartbeatResponse: "DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS, "DISABLE_RUFFLE_RS": DISABLE_RUFFLE_RS, "DISABLE_JSDOS": DISABLE_JSDOS, + "DISABLE_PICO8": DISABLE_PICO8, }, "FRONTEND": { "DISABLE_USERPASS_LOGIN": DISABLE_USERPASS_LOGIN, diff --git a/backend/endpoints/responses/heartbeat.py b/backend/endpoints/responses/heartbeat.py index b31d49f9c..6479afa51 100644 --- a/backend/endpoints/responses/heartbeat.py +++ b/backend/endpoints/responses/heartbeat.py @@ -36,6 +36,7 @@ class EmulationDict(TypedDict): DISABLE_EMULATOR_JS: bool DISABLE_RUFFLE_RS: bool DISABLE_JSDOS: bool + DISABLE_PICO8: bool class FrontendDict(TypedDict): diff --git a/backend/tests/endpoints/test_heartbeat.py b/backend/tests/endpoints/test_heartbeat.py index c121c7afc..3b46d44bb 100644 --- a/backend/tests/endpoints/test_heartbeat.py +++ b/backend/tests/endpoints/test_heartbeat.py @@ -48,6 +48,7 @@ def test_heartbeat(client): assert isinstance(emulation["DISABLE_EMULATOR_JS"], bool) assert isinstance(emulation["DISABLE_RUFFLE_RS"], bool) assert isinstance(emulation["DISABLE_JSDOS"], bool) + assert isinstance(emulation["DISABLE_PICO8"], bool) assert "FRONTEND" in heartbeat frontend = heartbeat["FRONTEND"] diff --git a/docker/Dockerfile b/docker/Dockerfile index b4346a2cf..68505cdb0 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -133,7 +133,7 @@ RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git & cp ./sigil/*.py ./sigil/_sigil.*.so /sigil-pkg/ -# FETCH EMULATORJS, RUFFLE AND JS-DOS +# FETCH EMULATORJS, RUFFLE, JS-DOS AND FAKE-08 FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS emulator-stage RUN apk add --no-cache \ @@ -170,6 +170,20 @@ RUN wget "https://github.com/caiiiycuk/js-dos/releases/download/v${JSDOS_VERSION rm -rf /jsdos/dist/index.html /jsdos/dist/emulators/types && \ find /jsdos/dist \( -name '*.map' -o -name '*.symbols' \) -exec rm -f {} + +ARG FAKE08_P3A_COMMIT=6519efd9dd1ca853e5c66f7ae9146ace0b7073dc +ARG FAKE08_JS_SHA256=fd2cd4677956037e41a91dbd40fc1a9c4f5979355d55ce3f9312400e11da463e +ARG FAKE08_WASM_SHA256=4339a77e0aa5aa6f4a5bce9fd8286053eedf7f23f2d853db7f4900f6fff4c93a +ARG FAKE08_P3A_RAW=https://raw.githubusercontent.com/fabkury/p3a/${FAKE08_P3A_COMMIT}/webui/pico8 + +# FAKE-08 (MIT, https://github.com/jtothebell/fake-08) publishes no web build, so the +# browser artifacts come from p3a (Apache-2.0, https://github.com/fabkury/p3a), which +# compiled them. Pinned by commit and checksum because that tree has no tagged releases. +RUN mkdir -p /fake08 && \ + wget "${FAKE08_P3A_RAW}/fake08.js" -O /fake08/fake08.js && \ + wget "${FAKE08_P3A_RAW}/fake08.wasm" -O /fake08/fake08.wasm && \ + echo "${FAKE08_JS_SHA256} /fake08/fake08.js" | sha256sum -c - && \ + echo "${FAKE08_WASM_SHA256} /fake08/fake08.wasm" | sha256sum -c - + # BUILD NGINX MODULE WITH MOD_ZIP FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS nginx-build @@ -302,6 +316,7 @@ ARG WEBSERVER_FOLDER=/var/www/html COPY --from=emulator-stage /emulatorjs ${WEBSERVER_FOLDER}/assets/emulatorjs COPY --from=emulator-stage /ruffle ${WEBSERVER_FOLDER}/assets/ruffle COPY --from=emulator-stage /jsdos/dist ${WEBSERVER_FOLDER}/assets/jsdos +COPY --from=emulator-stage /fake08 ${WEBSERVER_FOLDER}/assets/pico8 FROM slim-image AS dev-slim diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 5d251e83f..93f5e6830 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1621,6 +1621,7 @@ Falls back to `FakeRedis` in test mode. | `DISABLE_EMULATOR_JS` | `false` | Hide EmulatorJS player | | `DISABLE_RUFFLE_RS` | `false` | Hide Ruffle Flash player | | `DISABLE_JSDOS` | `false` | Hide js-dos player | +| `DISABLE_PICO8` | `false` | Hide PICO-8 player | #### Task Scheduling diff --git a/docs/FRONTEND_ARCHITECTURE.md b/docs/FRONTEND_ARCHITECTURE.md index 0939c96cf..199f66fcd 100644 --- a/docs/FRONTEND_ARCHITECTURE.md +++ b/docs/FRONTEND_ARCHITECTURE.md @@ -508,7 +508,7 @@ Server capability flags used throughout the UI: ```typescript METADATA_SOURCES: { IGDB, SS, MOBY, RA, STEAMGRIDDB, LAUNCHBOX, ... } -EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS, DISABLE_JSDOS } +EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS, DISABLE_JSDOS, DISABLE_PICO8 } FRONTEND: { DISABLE_USERPASS_LOGIN, DISABLE_LOGS_VIEWER, YOUTUBE_BASE_URL } OIDC: { ENABLED, AUTOLOGIN, PROVIDER, RP_INITIATED_LOGOUT } TASKS: { scheduled task configurations } diff --git a/env.template b/env.template index d45881917..2eca619de 100644 --- a/env.template +++ b/env.template @@ -115,6 +115,7 @@ SYNC_SSH_KNOWN_HOSTS_PATH= # Path to SSH known_hosts (defaults to $ROMM_BASE_PA DISABLE_EMULATOR_JS=false # Disable in-browser play via EmulatorJS DISABLE_RUFFLE_RS=false # Disable in-browser Flash playback via RuffleRS DISABLE_JSDOS=false # Disable in-browser Win3.x and Win9.x playback via js-dos +DISABLE_PICO8=false # Disable in-browser PICO-8 playback via FAKE-08 # Integrations YOUTUBE_BASE_URL=https://www.youtube.com # Base URL for alternate YouTube frontends (Piped, Invidious, etc.) diff --git a/frontend/src/__generated__/models/EmulationDict.ts b/frontend/src/__generated__/models/EmulationDict.ts index 6171be35e..ae956cd97 100644 --- a/frontend/src/__generated__/models/EmulationDict.ts +++ b/frontend/src/__generated__/models/EmulationDict.ts @@ -6,5 +6,6 @@ export type EmulationDict = { DISABLE_EMULATOR_JS: boolean; DISABLE_RUFFLE_RS: boolean; DISABLE_JSDOS: boolean; + DISABLE_PICO8: boolean; }; diff --git a/frontend/src/locales/bg_BG/platform.json b/frontend/src/locales/bg_BG/platform.json index a943ed510..b8ced4738 100644 --- a/frontend/src/locales/bg_BG/platform.json +++ b/frontend/src/locales/bg_BG/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Може да се играе в браузъра чрез DOSBox", "playable-browser-emulatorjs": "Може да се играе в браузъра чрез EmulatorJS", "playable-browser-jsdos": "Може да се играе в браузъра чрез js-dos", + "playable-browser-pico8": "Може да се играе в браузъра чрез PICO-8", "playable-browser-ruffle": "Може да се играе в браузъра чрез Ruffle", "playable-none": "Не може да се играе в браузъра или чрез стрийминг", "playable-stream": "Може да се стриймва от {label}", diff --git a/frontend/src/locales/cs_CZ/platform.json b/frontend/src/locales/cs_CZ/platform.json index 873f24af5..1a8fc7c8d 100644 --- a/frontend/src/locales/cs_CZ/platform.json +++ b/frontend/src/locales/cs_CZ/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Hratelné v prohlížeči přes DOSBox", "playable-browser-emulatorjs": "Hratelné v prohlížeči přes EmulatorJS", "playable-browser-jsdos": "Hratelné v prohlížeči přes js-dos", + "playable-browser-pico8": "Hratelné v prohlížeči přes PICO-8", "playable-browser-ruffle": "Hratelné v prohlížeči přes Ruffle", "playable-none": "Nelze hrát v prohlížeči ani streamovat", "playable-stream": "Streamovatelné z {label}", diff --git a/frontend/src/locales/de_DE/platform.json b/frontend/src/locales/de_DE/platform.json index 679dddc48..a63dc73f1 100644 --- a/frontend/src/locales/de_DE/platform.json +++ b/frontend/src/locales/de_DE/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Im Browser spielbar über DOSBox", "playable-browser-emulatorjs": "Im Browser spielbar über EmulatorJS", "playable-browser-jsdos": "Im Browser spielbar über js-dos", + "playable-browser-pico8": "Im Browser spielbar über PICO-8", "playable-browser-ruffle": "Im Browser spielbar über Ruffle", "playable-none": "Weder im Browser spielbar noch streambar", "playable-stream": "Streambar über {label}", diff --git a/frontend/src/locales/en_GB/platform.json b/frontend/src/locales/en_GB/platform.json index 10f96027a..f45a0995b 100644 --- a/frontend/src/locales/en_GB/platform.json +++ b/frontend/src/locales/en_GB/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Playable in browser through DOSBox", "playable-browser-emulatorjs": "Playable in browser through EmulatorJS", "playable-browser-jsdos": "Playable in browser through js-dos", + "playable-browser-pico8": "Playable in browser through PICO-8", "playable-browser-ruffle": "Playable in browser through Ruffle", "playable-none": "Not playable in browser or by streaming", "playable-stream": "Streamable from {label}", diff --git a/frontend/src/locales/en_US/platform.json b/frontend/src/locales/en_US/platform.json index 4d0abc967..7319a0c60 100644 --- a/frontend/src/locales/en_US/platform.json +++ b/frontend/src/locales/en_US/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Playable in browser through DOSBox", "playable-browser-emulatorjs": "Playable in browser through EmulatorJS", "playable-browser-jsdos": "Playable in browser through js-dos", + "playable-browser-pico8": "Playable in browser through PICO-8", "playable-browser-ruffle": "Playable in browser through Ruffle", "playable-none": "Not playable in browser or by streaming", "playable-stream": "Streamable from {label}", diff --git a/frontend/src/locales/es_ES/platform.json b/frontend/src/locales/es_ES/platform.json index e4913306f..095d123e4 100644 --- a/frontend/src/locales/es_ES/platform.json +++ b/frontend/src/locales/es_ES/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Jugable en el navegador mediante DOSBox", "playable-browser-emulatorjs": "Jugable en el navegador mediante EmulatorJS", "playable-browser-jsdos": "Jugable en el navegador mediante js-dos", + "playable-browser-pico8": "Jugable en el navegador mediante PICO-8", "playable-browser-ruffle": "Jugable en el navegador mediante Ruffle", "playable-none": "No jugable en el navegador ni por transmisión", "playable-stream": "Transmisible desde {label}", diff --git a/frontend/src/locales/fr_FR/platform.json b/frontend/src/locales/fr_FR/platform.json index 20ab2de9b..ed534a332 100644 --- a/frontend/src/locales/fr_FR/platform.json +++ b/frontend/src/locales/fr_FR/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Jouable dans le navigateur via DOSBox", "playable-browser-emulatorjs": "Jouable dans le navigateur via EmulatorJS", "playable-browser-jsdos": "Jouable dans le navigateur via js-dos", + "playable-browser-pico8": "Jouable dans le navigateur via PICO-8", "playable-browser-ruffle": "Jouable dans le navigateur via Ruffle", "playable-none": "Ni jouable dans le navigateur ni diffusable", "playable-stream": "Diffusable depuis {label}", diff --git a/frontend/src/locales/hu_HU/platform.json b/frontend/src/locales/hu_HU/platform.json index 297344951..4f79b77e0 100644 --- a/frontend/src/locales/hu_HU/platform.json +++ b/frontend/src/locales/hu_HU/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Böngészőben játszható DOSBox segítségével", "playable-browser-emulatorjs": "Böngészőben játszható EmulatorJS segítségével", "playable-browser-jsdos": "Böngészőben játszható js-dos segítségével", + "playable-browser-pico8": "Böngészőben játszható PICO-8 segítségével", "playable-browser-ruffle": "Böngészőben játszható Ruffle segítségével", "playable-none": "Böngészőben nem játszható és nem streamelhető", "playable-stream": "Streamelhető innen: {label}", diff --git a/frontend/src/locales/it_IT/platform.json b/frontend/src/locales/it_IT/platform.json index da40dc185..b6f083036 100644 --- a/frontend/src/locales/it_IT/platform.json +++ b/frontend/src/locales/it_IT/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Giocabile nel browser tramite DOSBox", "playable-browser-emulatorjs": "Giocabile nel browser tramite EmulatorJS", "playable-browser-jsdos": "Giocabile nel browser tramite js-dos", + "playable-browser-pico8": "Giocabile nel browser tramite PICO-8", "playable-browser-ruffle": "Giocabile nel browser tramite Ruffle", "playable-none": "Non giocabile nel browser né in streaming", "playable-stream": "Trasmissibile da {label}", diff --git a/frontend/src/locales/ja_JP/platform.json b/frontend/src/locales/ja_JP/platform.json index 418e8a462..f5d9f6cf1 100644 --- a/frontend/src/locales/ja_JP/platform.json +++ b/frontend/src/locales/ja_JP/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "DOSBox によりブラウザでプレイ可能", "playable-browser-emulatorjs": "EmulatorJS によりブラウザでプレイ可能", "playable-browser-jsdos": "js-dos によりブラウザでプレイ可能", + "playable-browser-pico8": "PICO-8 によりブラウザでプレイ可能", "playable-browser-ruffle": "Ruffle によりブラウザでプレイ可能", "playable-none": "ブラウザでもストリーミングでもプレイできません", "playable-stream": "{label} からストリーミング可能", diff --git a/frontend/src/locales/ko_KR/platform.json b/frontend/src/locales/ko_KR/platform.json index 94d08d1d5..c410adcad 100644 --- a/frontend/src/locales/ko_KR/platform.json +++ b/frontend/src/locales/ko_KR/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "DOSBox를 통해 브라우저에서 플레이 가능", "playable-browser-emulatorjs": "EmulatorJS를 통해 브라우저에서 플레이 가능", "playable-browser-jsdos": "js-dos를 통해 브라우저에서 플레이 가능", + "playable-browser-pico8": "PICO-8을 통해 브라우저에서 플레이 가능", "playable-browser-ruffle": "Ruffle을 통해 브라우저에서 플레이 가능", "playable-none": "브라우저에서도 스트리밍으로도 플레이할 수 없음", "playable-stream": "{label}에서 스트리밍 가능", diff --git a/frontend/src/locales/pl_PL/platform.json b/frontend/src/locales/pl_PL/platform.json index 7cdb5c605..e9c08acbe 100644 --- a/frontend/src/locales/pl_PL/platform.json +++ b/frontend/src/locales/pl_PL/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Grywalne w przeglądarce przez DOSBox", "playable-browser-emulatorjs": "Grywalne w przeglądarce przez EmulatorJS", "playable-browser-jsdos": "Grywalne w przeglądarce przez js-dos", + "playable-browser-pico8": "Grywalne w przeglądarce przez PICO-8", "playable-browser-ruffle": "Grywalne w przeglądarce przez Ruffle", "playable-none": "Niegrywalne w przeglądarce ani przez streaming", "playable-stream": "Dostępne w streamingu z {label}", diff --git a/frontend/src/locales/pt_BR/platform.json b/frontend/src/locales/pt_BR/platform.json index eb0409869..2ffb6967d 100644 --- a/frontend/src/locales/pt_BR/platform.json +++ b/frontend/src/locales/pt_BR/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Jogável no navegador via DOSBox", "playable-browser-emulatorjs": "Jogável no navegador via EmulatorJS", "playable-browser-jsdos": "Jogável no navegador via js-dos", + "playable-browser-pico8": "Jogável no navegador via PICO-8", "playable-browser-ruffle": "Jogável no navegador via Ruffle", "playable-none": "Não jogável no navegador nem por transmissão", "playable-stream": "Transmissível de {label}", diff --git a/frontend/src/locales/ro_RO/platform.json b/frontend/src/locales/ro_RO/platform.json index ce9532e40..2c66dfd80 100644 --- a/frontend/src/locales/ro_RO/platform.json +++ b/frontend/src/locales/ro_RO/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Se poate juca în browser prin DOSBox", "playable-browser-emulatorjs": "Se poate juca în browser prin EmulatorJS", "playable-browser-jsdos": "Se poate juca în browser prin js-dos", + "playable-browser-pico8": "Se poate juca în browser prin PICO-8", "playable-browser-ruffle": "Se poate juca în browser prin Ruffle", "playable-none": "Nu se poate juca în browser și nici prin streaming", "playable-stream": "Se poate transmite de pe {label}", diff --git a/frontend/src/locales/ru_RU/platform.json b/frontend/src/locales/ru_RU/platform.json index 1dd2edace..87f4cea8d 100644 --- a/frontend/src/locales/ru_RU/platform.json +++ b/frontend/src/locales/ru_RU/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "Запускается в браузере через DOSBox", "playable-browser-emulatorjs": "Запускается в браузере через EmulatorJS", "playable-browser-jsdos": "Запускается в браузере через js-dos", + "playable-browser-pico8": "Запускается в браузере через PICO-8", "playable-browser-ruffle": "Запускается в браузере через Ruffle", "playable-none": "Не запускается ни в браузере, ни через трансляцию", "playable-stream": "Транслируется с {label}", diff --git a/frontend/src/locales/tr_TR/platform.json b/frontend/src/locales/tr_TR/platform.json index acfe84ac8..43b2ca3d2 100644 --- a/frontend/src/locales/tr_TR/platform.json +++ b/frontend/src/locales/tr_TR/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "DOSBox ile tarayıcıda oynanabilir", "playable-browser-emulatorjs": "EmulatorJS ile tarayıcıda oynanabilir", "playable-browser-jsdos": "js-dos ile tarayıcıda oynanabilir", + "playable-browser-pico8": "PICO-8 ile tarayıcıda oynanabilir", "playable-browser-ruffle": "Ruffle ile tarayıcıda oynanabilir", "playable-none": "Tarayıcıda oynanamaz ve yayınlanamaz", "playable-stream": "{label} üzerinden yayınlanabilir", diff --git a/frontend/src/locales/zh_CN/platform.json b/frontend/src/locales/zh_CN/platform.json index e58b91edc..82ec77058 100644 --- a/frontend/src/locales/zh_CN/platform.json +++ b/frontend/src/locales/zh_CN/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "可通过 DOSBox 在浏览器中游玩", "playable-browser-emulatorjs": "可通过 EmulatorJS 在浏览器中游玩", "playable-browser-jsdos": "可通过 js-dos 在浏览器中游玩", + "playable-browser-pico8": "可通过 PICO-8 在浏览器中游玩", "playable-browser-ruffle": "可通过 Ruffle 在浏览器中游玩", "playable-none": "无法在浏览器中游玩,也无法串流", "playable-stream": "可从 {label} 串流", diff --git a/frontend/src/locales/zh_TW/platform.json b/frontend/src/locales/zh_TW/platform.json index a18c04dee..593ff7c73 100644 --- a/frontend/src/locales/zh_TW/platform.json +++ b/frontend/src/locales/zh_TW/platform.json @@ -56,6 +56,7 @@ "playable-browser-dosbox": "可透過 DOSBox 在瀏覽器中遊玩", "playable-browser-emulatorjs": "可透過 EmulatorJS 在瀏覽器中遊玩", "playable-browser-jsdos": "可透過 js-dos 在瀏覽器中遊玩", + "playable-browser-pico8": "可透過 PICO-8 在瀏覽器中遊玩", "playable-browser-ruffle": "可透過 Ruffle 在瀏覽器中遊玩", "playable-none": "無法在瀏覽器中遊玩,也無法串流", "playable-stream": "可從 {label} 串流", diff --git a/frontend/src/plugins/router.ts b/frontend/src/plugins/router.ts index 7650ea426..46c0ba164 100644 --- a/frontend/src/plugins/router.ts +++ b/frontend/src/plugins/router.ts @@ -35,6 +35,7 @@ export const ROUTES = { ROM: "rom", EMULATORJS: "emulatorjs", JSDOS: "jsdos", + PICO8: "pico8", RUFFLE: "ruffle", STREAM: "stream", STREAM_DESKTOP: "stream-desktop", @@ -274,6 +275,14 @@ const routes = [ v2: v2For(ROUTES.JSDOS), }, }, + { + path: "rom/:rom/pico8", + name: ROUTES.PICO8, + components: { + default: () => import("@/views/Home.vue"), + v2: v2For(ROUTES.PICO8), + }, + }, { path: "rom/:rom/ruffle", name: ROUTES.RUFFLE, diff --git a/frontend/src/stores/heartbeat.ts b/frontend/src/stores/heartbeat.ts index ee3deaf72..b3f2ccd4b 100644 --- a/frontend/src/stores/heartbeat.ts +++ b/frontend/src/stores/heartbeat.ts @@ -45,6 +45,7 @@ const defaultHeartbeat: Heartbeat = { DISABLE_EMULATOR_JS: false, DISABLE_RUFFLE_RS: false, DISABLE_JSDOS: false, + DISABLE_PICO8: false, }, FRONTEND: { DISABLE_USERPASS_LOGIN: false, diff --git a/frontend/src/utils/index.test.ts b/frontend/src/utils/index.test.ts index 2475efe46..905febbc8 100644 --- a/frontend/src/utils/index.test.ts +++ b/frontend/src/utils/index.test.ts @@ -6,6 +6,8 @@ import { getDownloadPath, isJsDosBundle, isJsDosEmulationSupported, + isPico8EmulationSupported, + isPico8Rom, } from "./index"; function makeRom(overrides: Partial): SimpleRom { @@ -102,6 +104,7 @@ function makeHeartbeat( DISABLE_EMULATOR_JS: false, DISABLE_RUFFLE_RS: false, DISABLE_JSDOS: false, + DISABLE_PICO8: false, ...emulation, }, } as Heartbeat; @@ -167,3 +170,32 @@ describe("isJsDosBundle", () => { expect(isJsDosBundle(undefined)).toBe(false); }); }); + +describe("PICO-8 support", () => { + const withExt = (fs_extension: string) => makeRom({ fs_extension }); + + it("supports the pico platform and configured remaps", () => { + expect(isPico8EmulationSupported("pico", makeHeartbeat())).toBe(true); + expect( + isPico8EmulationSupported( + "custom-pico", + makeHeartbeat(), + makeConfig({ "custom-pico": "pico" }), + ), + ).toBe(true); + expect(isPico8EmulationSupported("snes", makeHeartbeat())).toBe(false); + }); + + it("respects the DISABLE_PICO8 admin toggle", () => { + expect( + isPico8EmulationSupported("pico", makeHeartbeat({ DISABLE_PICO8: true })), + ).toBe(false); + }); + + it("accepts .p8 and .p8.png cartridges only", () => { + expect(isPico8Rom(withExt("p8"))).toBe(true); + expect(isPico8Rom(withExt("P8.PNG"))).toBe(true); + expect(isPico8Rom(withExt("zip"))).toBe(false); + expect(isPico8Rom(null)).toBe(false); + }); +}); diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index cf7dddf6c..f28ba4ea8 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -734,6 +734,36 @@ export function isJsDosBundle(rom: SimpleRom | null | undefined) { return rom?.fs_extension.toLowerCase() === "jsdos"; } +/** + * Check if PICO-8 emulation is supported for a given platform. + * + * @param platformSlug The platform slug. + * @param heartbeat The heartbeat object. + * @param config Optional configuration object. + * @returns True if supported, false otherwise. + */ +export function isPico8EmulationSupported( + platformSlug: string, + heartbeat: Heartbeat, + config?: Config, +) { + if (heartbeat.EMULATION.DISABLE_PICO8) return false; + + const slug = resolvePlatformSlug(platformSlug, config); + return slug.toLowerCase() === "pico"; +} + +/** + * Check if a ROM file is a PICO-8 cartridge. + * + * @param rom The ROM to check. + * @returns True if the file is a PICO-8 cartridge, false otherwise. + */ +export function isPico8Rom(rom: SimpleRom | null | undefined) { + const extension = rom?.fs_extension.toLowerCase(); + return extension === "p8" || extension === "p8.png"; +} + export type PlayingStatus = RomUserStatus | "backlogged" | "now_playing" | "hidden"; diff --git a/frontend/src/v2/composables/useCanPlay/index.test.ts b/frontend/src/v2/composables/useCanPlay/index.test.ts index cb60bc730..c15945637 100644 --- a/frontend/src/v2/composables/useCanPlay/index.test.ts +++ b/frontend/src/v2/composables/useCanPlay/index.test.ts @@ -8,6 +8,8 @@ import { useCanPlay } from "./index"; const support = vi.hoisted(() => ({ ejs: vi.fn(() => false), jsDos: vi.fn(() => false), + pico8: vi.fn(() => false), + pico8Rom: vi.fn(() => false), ruffle: vi.fn(() => false), // js-dos also demands its own bundle format; on by default so the engine // stubs stay the only variable. @@ -32,6 +34,8 @@ vi.mock("@/stores/streaming", () => ({ vi.mock("@/utils", () => ({ isEJSEmulationSupported: support.ejs, isJsDosEmulationSupported: support.jsDos, + isPico8EmulationSupported: support.pico8, + isPico8Rom: support.pico8Rom, isRuffleEmulationSupported: support.ruffle, isJsDosBundle: support.jsDosBundle, })); @@ -49,10 +53,14 @@ function makeRom(overrides: Partial = {}): SimpleRom { beforeEach(() => { support.ejs.mockReturnValue(false); support.jsDos.mockReturnValue(false); + support.pico8.mockReturnValue(false); + support.pico8Rom.mockReturnValue(false); support.ruffle.mockReturnValue(false); support.jsDosBundle.mockReturnValue(true); support.ejs.mockClear(); support.jsDos.mockClear(); + support.pico8.mockClear(); + support.pico8Rom.mockClear(); support.ruffle.mockClear(); support.jsDosBundle.mockClear(); streamContainer.value = null; @@ -62,9 +70,11 @@ 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()); expect(result[flag].value).toBe(true); @@ -73,7 +83,7 @@ describe("useCanPlay", () => { // A physical game, or one whose file vanished from the library, has nothing // to hand the emulator: every route boots from the download endpoint. - it.each(["ejs", "jsDos", "ruffle"] as const)( + it.each(["ejs", "jsDos", "pico8", "ruffle"] as const)( "refuses %s for a rom with no file on disk", (stub) => { support[stub].mockReturnValue(true); @@ -89,14 +99,23 @@ describe("useCanPlay", () => { it("refuses every route when there is no rom", () => { support.ejs.mockReturnValue(true); support.jsDos.mockReturnValue(true); + support.pico8.mockReturnValue(true); + support.pico8Rom.mockReturnValue(true); support.ruffle.mockReturnValue(true); streamContainer.value = {}; - const { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream } = - useCanPlay(() => null); + const { + canPlay, + canPlayEJS, + canPlayJsDos, + canPlayPico8, + canPlayRuffle, + canPlayStream, + } = useCanPlay(() => null); expect(canPlay.value).toBe(false); expect(canPlayEJS.value).toBe(false); expect(canPlayJsDos.value).toBe(false); + expect(canPlayPico8.value).toBe(false); expect(canPlayRuffle.value).toBe(false); expect(canPlayStream.value).toBe(false); }); @@ -134,6 +153,15 @@ describe("useCanPlay", () => { expect(canPlay.value).toBe(false); }); + it("refuses PICO-8 for a rom with another extension", () => { + support.pico8.mockReturnValue(true); + support.pico8Rom.mockReturnValue(false); + const { canPlay, canPlayPico8 } = useCanPlay(() => makeRom()); + + expect(canPlayPico8.value).toBe(false); + expect(canPlay.value).toBe(false); + }); + it("stays unplayable when no engine supports the platform", () => { const { canPlay } = useCanPlay(() => makeRom()); diff --git a/frontend/src/v2/composables/useCanPlay/index.ts b/frontend/src/v2/composables/useCanPlay/index.ts index a32340802..63ef592d2 100644 --- a/frontend/src/v2/composables/useCanPlay/index.ts +++ b/frontend/src/v2/composables/useCanPlay/index.ts @@ -3,13 +3,13 @@ // inside PlayBtn.vue; v2 lifts it to a composable so the card overlay // and the menu item agree with the details-header CTA. // -// "Playable" means EJS, js-dos, or Ruffle can run the platform on this +// "Playable" means EJS, js-dos, PICO-8, or Ruffle can run the platform on this // server (admin toggles + platform support + WebGL availability) and there // is a file to boot, or a streaming container is configured for the // platform. A physical game or one missing from the filesystem has nothing // to hand the emulator, and js-dos additionally needs the file to be one of // its own bundles. The individual flags are exposed so the play action can -// pick the right route (EJS vs js-dos vs Ruffle vs Stream). +// pick the right route (EJS vs js-dos vs PICO-8 vs Ruffle vs Stream). import { storeToRefs } from "pinia"; import { computed, type ComputedRef } from "vue"; import storeConfig from "@/stores/config"; @@ -20,6 +20,8 @@ import { isEJSEmulationSupported, isJsDosBundle, isJsDosEmulationSupported, + isPico8EmulationSupported, + isPico8Rom, isRuffleEmulationSupported, } from "@/utils"; @@ -27,6 +29,7 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): { canPlay: ComputedRef; canPlayEJS: ComputedRef; canPlayJsDos: ComputedRef; + canPlayPico8: ComputedRef; canPlayRuffle: ComputedRef; canPlayStream: ComputedRef; } { @@ -52,6 +55,11 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): { () => onJsDosPlatform.value && isJsDosBundle(getRom()), ); + const onPico8Platform = supportedBy(isPico8EmulationSupported); + const canPlayPico8 = computed( + () => onPico8Platform.value && isPico8Rom(getRom()), + ); + // The broker is handed the ROM file, so a physical game or one missing // from the filesystem has nothing to stream any more than it has to boot. const canPlayStream = computed(() => { @@ -64,9 +72,17 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): { () => canPlayEJS.value || canPlayJsDos.value || + canPlayPico8.value || canPlayRuffle.value || canPlayStream.value, ); - return { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream }; + return { + canPlay, + canPlayEJS, + canPlayJsDos, + canPlayPico8, + canPlayRuffle, + canPlayStream, + }; } diff --git a/frontend/src/v2/composables/useGalleryProvenance/index.test.ts b/frontend/src/v2/composables/useGalleryProvenance/index.test.ts index 65d05d500..ee2aa7260 100644 --- a/frontend/src/v2/composables/useGalleryProvenance/index.test.ts +++ b/frontend/src/v2/composables/useGalleryProvenance/index.test.ts @@ -19,6 +19,7 @@ function makeRouter() { { path: "/platform/:platform", name: ROUTES.PLATFORM, component: blank }, { path: "/rom/:rom", name: ROUTES.ROM, component: blank }, { path: "/play/:rom", name: ROUTES.EMULATORJS, component: blank }, + { path: "/pico/:rom", name: ROUTES.PICO8, component: blank }, ], }); } @@ -59,7 +60,7 @@ describe("useGalleryProvenance", () => { expect(mod.useGalleryProvenance().enteredFromGallery.value).toBe(false); }); - it("keeps the arming across rom → rom hops and a play session", async () => { + it("keeps the arming across rom hops and a PICO-8 session", async () => { const mod = await loadFresh(); const router = makeRouter(); mod.installGalleryProvenance(router); @@ -67,7 +68,7 @@ describe("useGalleryProvenance", () => { await router.push("/platform/1"); await router.push("/rom/10"); await router.push("/rom/11"); - await router.push("/play/11"); + await router.push("/pico/11"); await router.push("/rom/11"); expect(mod.useGalleryProvenance().enteredFromGallery.value).toBe(true); diff --git a/frontend/src/v2/composables/useGalleryProvenance/index.ts b/frontend/src/v2/composables/useGalleryProvenance/index.ts index 0f21086d8..1c8206727 100644 --- a/frontend/src/v2/composables/useGalleryProvenance/index.ts +++ b/frontend/src/v2/composables/useGalleryProvenance/index.ts @@ -29,6 +29,7 @@ const GALLERY_ROUTES: ReadonlySet = new Set([ const CHAIN_ROUTES: ReadonlySet = new Set([ ROUTES.ROM, ROUTES.EMULATORJS, + ROUTES.PICO8, ROUTES.RUFFLE, ROUTES.STREAM, ]); diff --git a/frontend/src/v2/composables/useGameActions/index.test.ts b/frontend/src/v2/composables/useGameActions/index.test.ts index 992f81d94..fe02a6696 100644 --- a/frontend/src/v2/composables/useGameActions/index.test.ts +++ b/frontend/src/v2/composables/useGameActions/index.test.ts @@ -20,6 +20,7 @@ const snackbarInfo = vi.fn(); const confirmProtectedLaunch = { value: true }; const canPlayEJS = { value: true }; const canPlayJsDos = { value: false }; +const canPlayPico8 = { value: false }; const canPlayRuffle = { value: false }; const streamContainer = { value: null as object | null }; const joinableSession = { @@ -85,6 +86,7 @@ vi.mock("@/v2/composables/useCanPlay", () => ({ useCanPlay: (getRom: () => SimpleRom | null | undefined) => ({ canPlayEJS, canPlayJsDos, + canPlayPico8, canPlayRuffle, canPlayStream: { get value() { @@ -156,6 +158,7 @@ beforeEach(() => { confirmProtectedLaunch.value = true; canPlayEJS.value = true; canPlayJsDos.value = false; + canPlayPico8.value = false; canPlayRuffle.value = false; streamContainer.value = null; joinableSession.value = null; @@ -353,6 +356,17 @@ describe("useGameActions.play — launch confirmation", () => { expect(locationAssign).not.toHaveBeenCalled(); }); + it("keeps SPA navigation for PICO-8", async () => { + canPlayEJS.value = false; + canPlayPico8.value = true; + const actions = useGameActions(() => makeRom()); + + await actions.play(); + + expect(push).toHaveBeenCalledWith("/rom/1/pico8"); + expect(locationAssign).not.toHaveBeenCalled(); + }); + it("full-loads js-dos ahead of EmulatorJS for its platforms", async () => { canPlayJsDos.value = true; const actions = useGameActions(() => makeRom()); diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index 1b761aa7d..4adce3e43 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -83,14 +83,24 @@ export function useGameActions( const canDelete = computed(() => hasDeleteGrant.value && canEdit.value); const { isFavorite, toggleFavorite } = useFavoriteToggle(emitter); const { startScan } = useScanTrigger(); - const { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream } = - useCanPlay(getRom); + const { + canPlay, + canPlayEJS, + canPlayJsDos, + canPlayPico8, + canPlayRuffle, + canPlayStream, + } = useCanPlay(getRom); const streamingStore = useStreamingStore(); // Streaming is offered as its own action rather than as the winner of a // precedence rule, so each player needs a gate of its own. const canPlayInBrowser = computed( - () => canPlayEJS.value || canPlayJsDos.value || canPlayRuffle.value, + () => + canPlayEJS.value || + canPlayJsDos.value || + canPlayPico8.value || + canPlayRuffle.value, ); // Download, the copied link and the QR code all resolve to the download @@ -332,6 +342,7 @@ export function useGameActions( // immediate here. let path: string | null = null; if (streaming && canPlayStream.value) path = `/rom/${rom.id}/stream`; + else if (inBrowser && canPlayPico8.value) path = `/rom/${rom.id}/pico8`; else if (inBrowser && canPlayRuffle.value) path = `/rom/${rom.id}/ruffle`; if (!path) return; const target = path; diff --git a/frontend/src/v2/composables/usePlatformPlayable/index.test.ts b/frontend/src/v2/composables/usePlatformPlayable/index.test.ts index ace8d8f8e..f09058872 100644 --- a/frontend/src/v2/composables/usePlatformPlayable/index.test.ts +++ b/frontend/src/v2/composables/usePlatformPlayable/index.test.ts @@ -11,12 +11,14 @@ const ejsSlugs = new Set(); const ruffleSlugs = new Set(); const dosboxSlugs = new Set(); const jsDosSlugs = new Set(); +const pico8Slugs = new Set(); const streamContainers = new Map(); const streamingEnabled = { value: true }; vi.mock("@/utils", () => ({ isEJSEmulationSupported: (slug: string) => ejsSlugs.has(slug), isJsDosEmulationSupported: (slug: string) => jsDosSlugs.has(slug), + isPico8EmulationSupported: (slug: string) => pico8Slugs.has(slug), isRuffleEmulationSupported: (slug: string) => ruffleSlugs.has(slug), getSupportedEJSCores: (slug: string) => dosboxSlugs.has(slug) ? ["dosbox_pure"] : ["snes9x"], @@ -68,6 +70,7 @@ beforeEach(() => { ruffleSlugs.clear(); dosboxSlugs.clear(); jsDosSlugs.clear(); + pico8Slugs.clear(); streamContainers.clear(); streamingEnabled.value = true; }); @@ -80,6 +83,13 @@ describe("usePlatformPlayable", () => { expect(playable.value).toBe(true); }); + it("resolves PICO-8 as a browser player", () => { + pico8Slugs.add("pico"); + const { mode, emulator } = usePlatformPlayable(() => "pico"); + expect(mode.value).toBe("browser"); + expect(emulator.value).toBe("pico8"); + }); + it("resolves streaming-only as stream and carries the container label", () => { streamContainers.set("ps2", { label: "PCSX2", emulator: "pcsx2" }); const { mode, playable, streamLabel } = usePlatformPlayable(() => "ps2"); @@ -150,6 +160,9 @@ describe("playTooltip", () => { expect(playTooltip("browser", "dosbox", null)).toBe( "platform.playable-browser-dosbox", ); + expect(playTooltip("browser", "pico8", null)).toBe( + "platform.playable-browser-pico8", + ); expect(playTooltip("browser", "emulatorjs", null)).toBe( "platform.playable-browser-emulatorjs", ); diff --git a/frontend/src/v2/composables/usePlatformPlayable/index.ts b/frontend/src/v2/composables/usePlatformPlayable/index.ts index c24e537d5..2ca20e042 100644 --- a/frontend/src/v2/composables/usePlatformPlayable/index.ts +++ b/frontend/src/v2/composables/usePlatformPlayable/index.ts @@ -9,7 +9,8 @@ // 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, "dosbox" +// 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 @@ -29,12 +30,13 @@ import { getSupportedEJSCores, isEJSEmulationSupported, isJsDosEmulationSupported, + isPico8EmulationSupported, isRuffleEmulationSupported, resolvePlatformSlug, } from "@/utils"; export type PlatformEmulator = - "emulatorjs" | "ruffle" | "jsdos" | "dosbox" | null; + "emulatorjs" | "ruffle" | "jsdos" | "pico8" | "dosbox" | null; export type PlatformPlayMode = "browser" | "stream" | "both" | null; @@ -56,6 +58,7 @@ function resolveEmulator( if (!slug) return null; if (isRuffleEmulationSupported(slug, heartbeat, config)) return "ruffle"; if (isJsDosEmulationSupported(slug, heartbeat, config)) return "jsdos"; + if (isPico8EmulationSupported(slug, heartbeat, config)) return "pico8"; if (!isEJSEmulationSupported(slug, heartbeat, config)) return null; const cores = getSupportedEJSCores(resolvePlatformSlug(slug, config)); if (cores.includes("dosbox_pure")) return "dosbox"; @@ -155,6 +158,8 @@ export function playTooltip( return t("platform.playable-browser-ruffle"); case "jsdos": return t("platform.playable-browser-jsdos"); + case "pico8": + return t("platform.playable-browser-pico8"); case "dosbox": return t("platform.playable-browser-dosbox"); default: diff --git a/frontend/src/v2/composables/useViewTransition/index.ts b/frontend/src/v2/composables/useViewTransition/index.ts index 139f1cb82..6cc234348 100644 --- a/frontend/src/v2/composables/useViewTransition/index.ts +++ b/frontend/src/v2/composables/useViewTransition/index.ts @@ -97,11 +97,15 @@ export function useViewTransition() { function morphNameForRoute(route: RouteLocationNormalized): string | null { const name = route.name; const params = route.params as Record; - // `rom` (detail) and the players (`emulatorjs` / `ruffle`) all own a + // `rom` (detail) and the players all own a // `rom-cover-` hero, so morph between any of them and the gallery / // each other. if ( - (name === "rom" || name === "emulatorjs" || name === "ruffle") && + (name === "rom" || + name === "emulatorjs" || + name === "jsdos" || + name === "pico8" || + name === "ruffle") && params.rom ) { return `rom-cover-${params.rom}`; diff --git a/frontend/src/v2/router/routes.ts b/frontend/src/v2/router/routes.ts index dad0b9fe8..45c3911b4 100644 --- a/frontend/src/v2/router/routes.ts +++ b/frontend/src/v2/router/routes.ts @@ -38,6 +38,7 @@ export const v2RouteComponents: Partial> = { // Wave 5 — Players emulatorjs: () => import("@/v2/views/Player/EmulatorJS.vue"), jsdos: () => import("@/v2/views/Player/JsDos.vue"), + pico8: () => import("@/v2/views/Player/Pico8.vue"), ruffle: () => import("@/v2/views/Player/Ruffle.vue"), stream: () => import("@/v2/views/Player/Stream.vue"), "stream-desktop": () => import("@/v2/views/Player/Desktop.vue"), diff --git a/frontend/src/v2/views/Player/Pico8.vue b/frontend/src/v2/views/Player/Pico8.vue new file mode 100644 index 000000000..1df20b9af --- /dev/null +++ b/frontend/src/v2/views/Player/Pico8.vue @@ -0,0 +1,615 @@ + + + + + diff --git a/frontend/src/v2/views/Player/pico8Runtime.test.ts b/frontend/src/v2/views/Player/pico8Runtime.test.ts new file mode 100644 index 000000000..d4c9fdea7 --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Runtime.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createPico8Runtime, 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(), +}; +const fakeModule = { + HEAPU8: heap, + _f08_init: vi.fn(), + _f08_load_cart_data: vi.fn(() => 0), + _f08_step_frame: vi.fn(), + _f08_get_framebuffer_ptr: vi.fn(() => 100), + _f08_get_palette_rgba: vi.fn((pointer: number) => { + heap[pointer + 4] = 1; + heap[pointer + 5] = 2; + heap[pointer + 6] = 3; + heap[pointer + 8] = 4; + heap[pointer + 9] = 5; + heap[pointer + 10] = 6; + }), + _f08_get_target_fps: vi.fn(() => 30), + _f08_get_last_error: vi.fn(() => 0), + _f08_set_inputs: vi.fn(), + _f08_fill_audio_buffer: vi.fn((pointer: number) => { + new Int16Array(heap.buffer, pointer, 2).set([1000, -1000]); + return 2; + }), + _f08_get_audio_sample_rate: vi.fn(() => 22050), + _malloc: vi.fn(() => 200), + _free: vi.fn(), + UTF8ToString: vi.fn(() => ""), +}; + +vi.mock("./scriptLoader", () => ({ + loadScript: vi.fn(async () => { + window.Fake08Module = vi.fn(async () => fakeModule); + }), +})); + +beforeEach(() => { + vi.clearAllMocks(); + heap[100] = 0x21; + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue( + context as unknown as CanvasRenderingContext2D, + ); +}); + +describe("createPico8Runtime", () => { + it("loads cartridges, maps frames to pixels, and exposes audio", async () => { + const runtime = await createPico8Runtime(document.createElement("canvas")); + + runtime.loadCart(new Uint8Array([1, 2, 3])); + runtime.step({ + keyDown: 0x10, + keyHeld: 0x30, + mouseX: 12, + mouseY: 34, + mouseButtons: 1, + }); + + expect(fakeModule._f08_load_cart_data).toHaveBeenCalledWith(200, 3); + expect(fakeModule._f08_set_inputs).toHaveBeenCalledWith( + 0x10, + 0x30, + 12, + 34, + 1, + ); + expect(context.putImageData).toHaveBeenCalled(); + const image = context.putImageData.mock.calls[0][0] as ImageData; + expect([...image.data.slice(0, 8)]).toEqual([1, 2, 3, 255, 4, 5, 6, 255]); + expect([...runtime.getAudioSamples()]).toEqual([1000, -1000]); + expect(runtime.frameRate).toBe(30); + expect(runtime.audioSampleRate).toBe(22050); + + runtime.dispose(); + runtime.step({ + keyDown: 0, + keyHeld: 0, + mouseX: 0, + mouseY: 0, + mouseButtons: 0, + }); + expect(fakeModule._f08_step_frame).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/v2/views/Player/pico8Runtime.ts b/frontend/src/v2/views/Player/pico8Runtime.ts new file mode 100644 index 000000000..6d17ecca3 --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Runtime.ts @@ -0,0 +1,207 @@ +import { loadScript } from "./scriptLoader"; + +export const PICO8_WIDTH = 128; +export const PICO8_HEIGHT = 128; +export const PICO8_FRAME_RATE = 30; + +export const PICO8_INPUT_BITS = { + left: 0x01, + right: 0x02, + up: 0x04, + down: 0x08, + a: 0x10, + b: 0x20, +} as const; + +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; + +interface Fake08Module { + HEAPU8: Uint8Array; + _f08_init: () => void; + _f08_load_cart_data: (pointer: number, length: number) => number; + _f08_step_frame: () => void; + _f08_get_framebuffer_ptr: () => number; + _f08_get_palette_rgba: (pointer: number) => void; + _f08_get_target_fps: () => number; + _f08_get_last_error: () => number; + _f08_set_inputs: ( + keyDown: number, + keyHeld: number, + mouseX: number, + mouseY: number, + mouseButtons: number, + ) => void; + _f08_fill_audio_buffer: (pointer: number, maxSamples: number) => number; + _f08_get_audio_sample_rate: () => number; + _malloc: (size: number) => number; + _free: (pointer: number) => void; + UTF8ToString: (pointer: number) => string; +} + +type Fake08Factory = (options: { + locateFile: (path: string) => string; +}) => Promise; + +declare global { + interface Window { + Fake08Module?: Fake08Factory; + } +} + +let scriptPromise: Promise | null = null; + +function loadPico8Script(): Promise { + if (window.Fake08Module) return Promise.resolve(); + scriptPromise ??= loadScript(PICO8_SCRIPT_PATH).catch((error) => { + scriptPromise = null; + throw error; + }); + return scriptPromise; +} + +function lastRuntimeError(module: Fake08Module): string | null { + const pointer = module._f08_get_last_error(); + if (!pointer) return null; + const message = module.UTF8ToString(pointer); + module._free(pointer); + return message || null; +} + +export interface Pico8Input { + keyDown: number; + keyHeld: number; + mouseX: number; + mouseY: number; + mouseButtons: number; +} + +export interface Pico8Runtime { + readonly frameRate: number; + readonly audioSampleRate: number; + loadCart: (bytes: Uint8Array) => void; + step: (input: Pico8Input) => void; + getAudioSamples: () => Int16Array; + dispose: () => void; +} + +export async function createPico8Runtime( + canvas: HTMLCanvasElement, +): Promise { + await loadPico8Script(); + const factory = window.Fake08Module; + if (!factory) throw new Error("PICO-8 runtime is unavailable"); + + 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; + + canvas.width = PICO8_WIDTH; + canvas.height = PICO8_HEIGHT; + renderContext.imageSmoothingEnabled = false; + module._f08_init(); + + const framebufferPointer = module._f08_get_framebuffer_ptr(); + if (!framebufferPointer) throw new Error("PICO-8 framebuffer is unavailable"); + + const palettePointer = module._malloc(PALETTE_BYTES); + const samplesPerFrame = Math.ceil( + module._f08_get_audio_sample_rate() / PICO8_FRAME_RATE, + ); + const audioPointer = module._malloc(samplesPerFrame * 2); + const imageData = renderContext.createImageData(PICO8_WIDTH, PICO8_HEIGHT); + 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, + framebufferPointer, + FRAMEBUFFER_BYTES, + ); + + 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; + } + renderContext.putImageData(imageData, 0, 0); + } + + function loadCart(bytes: Uint8Array) { + const pointer = module._malloc(bytes.byteLength); + try { + module.HEAPU8.set(bytes, pointer); + const result = module._f08_load_cart_data(pointer, bytes.byteLength); + if (result !== 0) { + throw new Error( + lastRuntimeError(module) ?? + "The PICO-8 cartridge could not be loaded", + ); + } + } finally { + module._free(pointer); + } + } + + function step(input: Pico8Input) { + if (disposed) return; + module._f08_set_inputs( + input.keyDown, + input.keyHeld, + input.mouseX, + input.mouseY, + input.mouseButtons, + ); + module._f08_step_frame(); + render(); + } + + function getAudioSamples() { + if (disposed) return new Int16Array(); + const written = module._f08_fill_audio_buffer( + audioPointer, + samplesPerFrame, + ); + if (written <= 0) return new Int16Array(); + return new Int16Array(module.HEAPU8.buffer, audioPointer, written).slice(); + } + + function dispose() { + if (disposed) return; + disposed = true; + module._free(palettePointer); + module._free(audioPointer); + } + + return { + frameRate: module._f08_get_target_fps() || PICO8_FRAME_RATE, + audioSampleRate: module._f08_get_audio_sample_rate(), + loadCart, + step, + getAudioSamples, + dispose, + }; +}