PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
web: run the recompiled game in the browser
Samir Nuri1050b99b593a
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 368d5ea..319e5e3 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -6,6 +6,11 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)set(PS2_GENERATED "" CACHE PATH "Folder with the C++ generated for a game")+if(EMSCRIPTEN)+ add_compile_options(-msimd128 -mtail-call -fwasm-exceptions)+ add_link_options(-msimd128 -mtail-call -fwasm-exceptions)+endif()+if(NOT EMSCRIPTEN)add_executable(eerecomprecomp/main.cpp@@ -76,6 +81,18 @@ if(PS2_GENERATED)target_link_libraries(ps2game PUBLIC ps2runtime)target_compile_options(ps2game PRIVATE -Wno-unused-label -Wno-unused-variable)+ if(EMSCRIPTEN)+ set(PS2_WEB_ELF "" CACHE FILEPATH "Game executable preloaded as /game/core.elf")+ add_executable(ps2web host/web.cpp)+ target_link_libraries(ps2web PRIVATE ps2game ps2runtime)+ target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=67108864 -sSTACK_SIZE=16777216 -sENVIRONMENT=web+ -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives+ -sEXPORTED_RUNTIME_METHODS=callMain,addRunDependency,removeRunDependency,HEAPU8,ENV+ --shell-file ${CMAKE_SOURCE_DIR}/web/shell.html --preload-file ${PS2_WEB_ELF}@/game/core.elf)+ set_target_properties(ps2web PROPERTIES SUFFIX ".html" LINK_DEPENDS ${CMAKE_SOURCE_DIR}/web/shell.html)+ return()+ endif()+add_executable(ps2run host/main.cpp)target_link_libraries(ps2run PRIVATE ps2game ps2runtime)if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64")diff --git a/host/main.cpp b/host/main.cppindex 19c17ff..5dd4017 100644--- a/host/main.cpp+++ b/host/main.cpp@@ -18,35 +18,6 @@ void register_generated_vu();namespace {-bool parse_press(const std::string &spec, ps2::Press &press) {- static const char *const kNames[16] = {"select", "l3", "r3", "start", "up", "right", "down", "left",- "l2", "r2", "l1", "r1", "triangle", "circle", "cross", "square"};- const auto colon = spec.find(':');- if (colon == std::string::npos) return false;- press.frame = std::strtoull(spec.c_str(), nullptr, 10);- std::string rest = spec.substr(colon + 1);- press.frames = 6;- const auto second = rest.find(':');- if (second != std::string::npos) {- press.frames = static_cast<std::uint32_t>(std::strtoul(rest.c_str() + second + 1, nullptr, 10));- rest = rest.substr(0, second);- }- press.buttons = 0;- std::size_t start = 0;- while (start <= rest.size()) {- const auto plus = rest.find('+', start);- const std::string name = rest.substr(start, plus == std::string::npos ? std::string::npos : plus - start);- int bit = -1;- for (int i = 0; i < 16; ++i)- if (name == kNames[i]) bit = i;- if (bit < 0) return false;- press.buttons |= static_cast<std::uint16_t>(1u << bit);- if (plus == std::string::npos) break;- start = plus + 1;- }- return true;-}-int usage() {std::fprintf(stderr,"usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"@@ -80,7 +51,7 @@ int main(int argc, char **argv) {else if (a == "--frames-dir" && i + 1 < argc) ps2::g_options.frames_dir = argv[++i];else if (a == "--press" && i + 1 < argc) {ps2::Press press;- if (!parse_press(argv[++i], press)) return usage();+ if (!ps2::parse_press(argv[++i], press)) return usage();ps2::g_options.presses.push_back(press);}#ifdef PS2_WINDOWdiff --git a/host/web.cpp b/host/web.cppnew file mode 100644index 0000000..57b0963--- /dev/null+++ b/host/web.cpp@@ -0,0 +1,182 @@+#include "ps2/disc.hpp"+#include "ps2/system.hpp"++#include <emscripten.h>++#include <algorithm>+#include <cstdio>+#include <cstring>+#include <list>+#include <string>+#include <unordered_map>+#include <vector>++void register_generated_code();+void register_generated_vu();++EM_ASYNC_JS(int, ps2web_fetch, (double offset, int size, void *out), {+ for (let attempt = 0; attempt < 4; ++attempt) {+ try {+ const response = await fetch(Module.discUrl, {headers: {Range: 'bytes=' + offset + '-' + (offset + size - 1)}});+ if (response.status !== 206 && response.status !== 200) continue;+ const bytes = new Uint8Array(await response.arrayBuffer());+ const length = Math.min(bytes.length, size);+ HEAPU8.set(bytes.subarray(0, length), out);+ return length;+ } catch (e) {+ console.warn('disc fetch failed', e);+ }+ }+ return 0;+});++EM_JS(double, ps2web_disc_size, (), { return Module.discSize || 0; });+EM_JS(void, ps2web_audio, (const std::int16_t *samples, int frames), { Module.pushAudio(HEAP16.subarray(samples >> 1, (samples >> 1) + frames * 2)); });+EM_JS(double, ps2web_audio_queued_ms, (), { return Module.audioQueuedMs ? Module.audioQueuedMs() : 0; });+EM_JS(void, ps2web_frame_done, (), { if (Module.onFrame) Module.onFrame(); });+EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {+ const canvas = Module.canvas;+ if (!Module.blitContext) Module.blitContext = canvas.getContext('2d');+ if (!Module.blitImage || Module.blitImage.width !== width || Module.blitImage.height !== height) {+ Module.blitImage = new ImageData(width, height);+ Module.blitSource = new OffscreenCanvas(width, height);+ }+ Module.blitImage.data.set(HEAPU8.subarray(rgba, rgba + width * height * 4));+ Module.blitSource.getContext('2d').putImageData(Module.blitImage, 0, 0);+ const ctx = Module.blitContext;+ const scale = Math.min(canvas.width / 4, canvas.height / 3);+ const w = scale * 4, h = scale * 3;+ ctx.fillStyle = '#000';+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.imageSmoothingEnabled = true;+ ctx.drawImage(Module.blitSource, (canvas.width - w) / 2, (canvas.height - h) / 2, w, h);+});++EM_JS(void, ps2web_snapshot, (const std::uint32_t *rgba, int width, int height), {+ const pixels = new Uint8ClampedArray(HEAPU8.buffer, rgba, width * height * 4).slice();+ Module.snapshot = {width: width, height: height, pixels: pixels};+ Module.wantSnapshot = false;+});++namespace {++constexpr std::size_t kChunk = 1u << 20;+constexpr std::size_t kCacheChunks = 64;++std::unordered_map<std::uint64_t, std::list<std::pair<std::uint64_t, std::vector<std::uint8_t>>>::iterator> g_chunks;+std::list<std::pair<std::uint64_t, std::vector<std::uint8_t>>> g_lru;+std::uint64_t g_disc_size = 0;++const std::vector<std::uint8_t> *chunk(std::uint64_t index) {+ auto it = g_chunks.find(index);+ if (it != g_chunks.end()) {+ g_lru.splice(g_lru.begin(), g_lru, it->second);+ return &it->second->second;+ }+ const std::uint64_t offset = index * kChunk;+ const std::size_t size = static_cast<std::size_t>(std::min<std::uint64_t>(kChunk, g_disc_size - offset));+ std::vector<std::uint8_t> data(size);+ if (ps2web_fetch(static_cast<double>(offset), static_cast<int>(size), data.data()) <= 0) return nullptr;+ if (g_lru.size() >= kCacheChunks) {+ g_chunks.erase(g_lru.back().first);+ g_lru.pop_back();+ }+ g_lru.emplace_front(index, std::move(data));+ g_chunks[index] = g_lru.begin();+ return &g_lru.front().second;+}++std::size_t read_disc(std::uint64_t offset, void *out, std::size_t size) {+ std::size_t done = 0;+ auto *to = static_cast<std::uint8_t *>(out);+ while (done < size && offset + done < g_disc_size) {+ const std::uint64_t at = offset + done;+ const std::vector<std::uint8_t> *c = chunk(at / kChunk);+ if (!c) break;+ const std::size_t within = static_cast<std::size_t>(at % kChunk);+ const std::size_t take = std::min(size - done, c->size() - within);+ std::memcpy(to + done, c->data() + within, take);+ done += take;+ }+ return done;+}++bool g_window_tried = false, g_window = false, g_copy = false;+std::vector<std::uint32_t> g_frame;++void on_vblank() {+ if (!g_window_tried) {+ g_window_tried = true;+ g_copy = EM_ASM_INT({ return Module.presentCopy ? 1 : 0; });+ if (!g_copy && !EM_ASM_INT({ return Module.noSurface ? 1 : 0; })) {+ ps2::WindowTarget target;+ target.kind = ps2::WindowTarget::Canvas;+ target.selector = "#canvas";+ target.width = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.width; }));+ target.height = static_cast<std::uint32_t>(EM_ASM_INT({ return Module.canvas.height; }));+ g_window = ps2::attach_window(target);+ }+ std::fprintf(stderr, "[web] %s\n", g_window ? "presenting through WebGPU" : g_copy ? "presenting through a 2D canvas copy" : "not presenting");+ }+ if (g_window) ps2::present_frame();+ std::uint32_t w = 0, h = 0;+ if (g_copy && ps2::display_frame(g_frame, w, h)) ps2web_blit(g_frame.data(), static_cast<int>(w), static_cast<int>(h));+ if (EM_ASM_INT({ return Module.wantSnapshot ? 1 : 0; })) {+ std::vector<std::uint32_t> rgba;+ std::uint32_t w = 0, h = 0;+ if (ps2::display_frame(rgba, w, h)) {+ ps2web_snapshot(rgba.data(), static_cast<int>(w), static_cast<int>(h));+ }+ }+ ps2web_frame_done();+ ps2::browser_yield();+ while (ps2web_audio_queued_ms() > 80.0) emscripten_sleep(2);+}++}++extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_pad(int buttons, int lx, int ly, int rx, int ry) {+ ps2::set_pad_buttons(static_cast<std::uint16_t>(buttons));+ ps2::set_pad_axis(0, static_cast<std::uint8_t>(rx));+ ps2::set_pad_axis(1, static_cast<std::uint8_t>(ry));+ ps2::set_pad_axis(2, static_cast<std::uint8_t>(lx));+ ps2::set_pad_axis(3, static_cast<std::uint8_t>(ly));+}++extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_resize(int width, int height) {+ ps2::resize_window(static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height));+}++extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_gpu_ms() { return ps2::gpu_busy_ms(); }+extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_frames() { return static_cast<double>(ps2::frames_run()); }+extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_primitives() { return static_cast<double>(ps2::primitives_drawn()); }++int main(int argc, char **argv) {+ if (argc < 2) {+ std::fprintf(stderr, "usage: ps2web <elf> [--arg text]...\n");+ return 1;+ }+ std::vector<std::string> args;+ for (int i = 2; i < argc; ++i) {+ const std::string a = argv[i];+ if (a == "--arg" && i + 1 < argc) args.push_back(argv[++i]);+ else if (a == "--frames" && i + 1 < argc) ps2::g_options.max_frames = std::strtoull(argv[++i], nullptr, 10);+ else if (a == "--press" && i + 1 < argc) {+ ps2::Press press;+ if (ps2::parse_press(argv[++i], press)) ps2::g_options.presses.push_back(press);+ }+ }+ g_disc_size = static_cast<std::uint64_t>(ps2web_disc_size());+ if (g_disc_size && !ps2::disc::open("disc", g_disc_size, read_disc)) std::fprintf(stderr, "[web] cannot read the disc image\n");+ ps2::g_options.on_vblank = on_vblank;+ ps2::set_audio_sink([](const std::int16_t *samples, std::size_t frames) { ps2web_audio(samples, static_cast<int>(frames)); });+ register_generated_code();+ register_generated_vu();+ std::uint32_t entry = 0;+ if (!ps2::load_elf(argv[1], entry)) {+ std::fprintf(stderr, "cannot load %s\n", argv[1]);+ return 1;+ }+ ps2::boot(entry, args);+ return ps2::run();+}diff --git a/runtime/include/ps2/disc.hpp b/runtime/include/ps2/disc.hppindex 49d7eb4..467623a 100644--- a/runtime/include/ps2/disc.hpp+++ b/runtime/include/ps2/disc.hpp@@ -1,6 +1,8 @@#pragma once+#include <cstddef>#include <cstdint>+#include <functional>#include <optional>#include <string>#include <vector>@@ -15,7 +17,11 @@ struct Entry {bool directory;};+// Reads up to size bytes at a byte offset of the image and returns how many it got.+using Reader = std::function<std::size_t(std::uint64_t offset, void *out, std::size_t size)>;+bool open(const std::string &path);+bool open(const std::string &name, std::uint64_t size, Reader reader);bool is_open();bool read(std::uint32_t sector, std::uint32_t count, void *out);std::optional<Entry> find(const std::string &path);diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hppindex 03ef68a..960f285 100644--- a/runtime/include/ps2/system.hpp+++ b/runtime/include/ps2/system.hpp@@ -84,8 +84,14 @@ struct WindowTarget {bool attach_window(const WindowTarget &target);void resize_window(std::uint32_t width, std::uint32_t height);bool present_frame();+// Parses "frame:button[+button][:frames]" as used by --press.+bool parse_press(const std::string &spec, Press &press);// GPU time spent on emulation so far, estimated from timestamp queries (0 when unsupported).double gpu_busy_ms();+// Returns to the browser event loop once without the 4 ms clamp of nested timers (Emscripten only).+void browser_yield();+std::uint64_t frames_run();+std::uint64_t primitives_drawn();void set_pad_buttons(std::uint16_t pressed);void set_pad_axis(int axis, std::uint8_t value);void set_audio_sink(std::function<void(const std::int16_t *samples, std::size_t frames)> sink);diff --git a/runtime/src/disc.cpp b/runtime/src/disc.cppindex c2d016b..7d1a45c 100644--- a/runtime/src/disc.cpp+++ b/runtime/src/disc.cpp@@ -11,6 +11,7 @@ namespace ps2::disc {namespace {std::FILE *g_file = nullptr;+Reader g_reader;std::uint64_t g_size = 0;std::uint32_t g_layer1 = 0;std::map<std::string, Entry> g_index;@@ -63,8 +64,27 @@ void index_layer(std::uint32_t pvd_sector, std::uint32_t base) {bool open(const std::string &path) {g_file = std::fopen(path.c_str(), "rb");if (!g_file) return false;- std::fseek(g_file, 0, SEEK_END);- g_size = static_cast<std::uint64_t>(std::ftell(g_file));+#if defined(_WIN32)+ _fseeki64(g_file, 0, SEEK_END);+ const std::uint64_t size = static_cast<std::uint64_t>(_ftelli64(g_file));+#else+ fseeko(g_file, 0, SEEK_END);+ const std::uint64_t size = static_cast<std::uint64_t>(ftello(g_file));+#endif+ std::FILE *file = g_file;+ return open(path, size, [file](std::uint64_t offset, void *out, std::size_t bytes) {+#if defined(_WIN32)+ _fseeki64(file, static_cast<long long>(offset), SEEK_SET);+#else+ fseeko(file, static_cast<off_t>(offset), SEEK_SET);+#endif+ return std::fread(out, 1, bytes, file);+ });+}++bool open(const std::string &name, std::uint64_t size, Reader reader) {+ g_reader = std::move(reader);+ g_size = size;g_index.clear();index_layer(16, 0);std::uint8_t pvd[kSector];@@ -78,22 +98,17 @@ bool open(const std::string &path) {break;}}- std::fprintf(stderr, "[disc] %s: %zu files, %llu sectors, layer 1 at %u\n", path.c_str(), g_index.size(),+ std::fprintf(stderr, "[disc] %s: %zu files, %llu sectors, layer 1 at %u\n", name.c_str(), g_index.size(),static_cast<unsigned long long>(g_size / kSector), g_layer1);return true;}-bool is_open() { return g_file != nullptr; }+bool is_open() { return static_cast<bool>(g_reader); }bool read(std::uint32_t sector, std::uint32_t count, void *out) {- if (!g_file) return false;-#if defined(_WIN32)- _fseeki64(g_file, static_cast<long long>(sector) * kSector, SEEK_SET);-#else- fseeko(g_file, static_cast<off_t>(sector) * kSector, SEEK_SET);-#endif+ if (!g_reader) return false;const std::size_t want = static_cast<std::size_t>(count) * kSector;- const std::size_t got = std::fread(out, 1, want, g_file);+ const std::size_t got = g_reader(static_cast<std::uint64_t>(sector) * kSector, out, want);if (got < want) std::memset(static_cast<std::uint8_t *>(out) + got, 0, want - got);return got > 0 || !count;}diff --git a/runtime/src/gs/gpu/gpu.cpp b/runtime/src/gs/gpu/gpu.cppindex fab23bd..9de7aa2 100644--- a/runtime/src/gs/gpu/gpu.cpp+++ b/runtime/src/gs/gpu/gpu.cpp@@ -1,4 +1,5 @@#include "gpu.hpp"+#include "ps2/system.hpp"#include <webgpu/webgpu.h>#ifndef __EMSCRIPTEN__@@ -380,14 +381,18 @@ void on_error(WGPUDevice const *, WGPUErrorType type, WGPUStringView message, vostd::fprintf(stderr, "[gpu] error %d: %.*s\n", static_cast<int>(type), static_cast<int>(message.length == WGPU_STRLEN ? std::strlen(message.data) : message.length), message.data);}-void wait_until(const bool &flag) {- while (!flag) {+void pump() {#ifdef __EMSCRIPTEN__- wgpuInstanceProcessEvents(g_instance);+ browser_yield();+ wgpuInstanceProcessEvents(g_instance);#else- wgpuDevicePoll(g_device, true, nullptr);+ if (g_device) wgpuDevicePoll(g_device, true, nullptr);+ else wgpuInstanceProcessEvents(g_instance);#endif- }+}++void wait_until(const bool &flag) {+ while (!flag) pump();}WGPUBuffer make_buffer(std::uint64_t size, WGPUBufferUsage usage) {@@ -433,11 +438,18 @@ void ensure_capacity() {if (changed || !g_group) rebuild_group();}+// Browsers copy writes above about 1 MiB through a slower path, so large uploads go in pieces.+void write_buffer(WGPUBuffer buffer, const void *data, std::uint64_t bytes) {+ constexpr std::uint64_t kPiece = 1u << 20;+ for (std::uint64_t at = 0; at < bytes; at += kPiece)+ wgpuQueueWriteBuffer(g_queue, buffer, at, static_cast<const std::uint8_t *>(data) + at, std::min(kPiece, bytes - at));+}+void submit(WGPUTextureView present_view = nullptr) {if (g_commands.empty() && !present_view) return;ensure_capacity();- if (!g_arena.empty()) wgpuQueueWriteBuffer(g_queue, g_data, 0, g_arena.data(), g_arena.size() * 4);- wgpuQueueWriteBuffer(g_queue, g_params, 0, g_param_records.data(), g_param_records.size() * kParamStride);+ write_buffer(g_data, g_arena.data(), g_arena.size() * 4);+ write_buffer(g_params, g_param_records.data(), g_param_records.size() * kParamStride);if (g_query_ready) {const void *mapped = wgpuBufferGetConstMappedRange(g_query_read, 0, 16);if (mapped) {@@ -633,7 +645,7 @@ bool init(Mode m) {acb.userdata1 = &adapter;acb.userdata2 = &adapter_done;wgpuInstanceRequestAdapter(g_instance, &options, acb);- while (!adapter_done) wgpuInstanceProcessEvents(g_instance);+ while (!adapter_done) pump();if (!adapter) {std::fprintf(stderr, "[gpu] no adapter\n");return false;@@ -668,7 +680,7 @@ bool init(Mode m) {dcb.userdata1 = &g_device;dcb.userdata2 = &device_done;wgpuAdapterRequestDevice(adapter, &dd, dcb);- while (!device_done) wgpuInstanceProcessEvents(g_instance);+ while (!device_done) pump();g_adapter = adapter;if (!g_device) return false;g_queue = wgpuDeviceGetQueue(g_device);diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex cbbbf7f..5f6ebd3 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -14,6 +14,10 @@#include "ps2/memory.hpp"#include "ps2/system.hpp"+#ifdef __EMSCRIPTEN__+#include <emscripten.h>+#endif+#include <algorithm>#include <cstdio>#include <cstring>@@ -277,7 +281,55 @@ bool display_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::bool attach_window(const WindowTarget &t) { return gs::attach_window(static_cast<int>(t.kind), t.display, t.window, t.surface, t.selector, t.width, t.height); }void resize_window(std::uint32_t width, std::uint32_t height) { gs::resize_window(width, height); }bool present_frame() { return gs::present(); }++bool parse_press(const std::string &spec, Press &press) {+ static const char *const kNames[16] = {"select", "l3", "r3", "start", "up", "right", "down", "left",+ "l2", "r2", "l1", "r1", "triangle", "circle", "cross", "square"};+ const auto colon = spec.find(':');+ if (colon == std::string::npos) return false;+ press.frame = std::strtoull(spec.c_str(), nullptr, 10);+ std::string rest = spec.substr(colon + 1);+ press.frames = 6;+ const auto second = rest.find(':');+ if (second != std::string::npos) {+ press.frames = static_cast<std::uint32_t>(std::strtoul(rest.c_str() + second + 1, nullptr, 10));+ rest = rest.substr(0, second);+ }+ press.buttons = 0;+ std::size_t start = 0;+ while (start <= rest.size()) {+ const auto plus = rest.find('+', start);+ const std::string name = rest.substr(start, plus == std::string::npos ? std::string::npos : plus - start);+ int bit = -1;+ for (int i = 0; i < 16; ++i)+ if (name == kNames[i]) bit = i;+ if (bit < 0) return false;+ press.buttons |= static_cast<std::uint16_t>(1u << bit);+ if (plus == std::string::npos) break;+ start = plus + 1;+ }+ return true;+}+double gpu_busy_ms() { return gs::gpu_busy_ms(); }++#ifdef __EMSCRIPTEN__+EM_ASYNC_JS(void, ps2_browser_yield, (), {+ if (!Module.yieldPort) {+ const channel = new MessageChannel();+ Module.yieldWaiters = [];+ channel.port1.onmessage = () => Module.yieldWaiters.shift()();+ Module.yieldPort = channel.port2;+ }+ await new Promise((resolve) => { Module.yieldWaiters.push(resolve); Module.yieldPort.postMessage(0); });+});+void browser_yield() { ps2_browser_yield(); }+#else+void browser_yield() {}+#endif++std::uint64_t frames_run() { return g_frames; }+std::uint64_t primitives_drawn() { return gs::primitives_drawn(); }void set_pad_buttons(std::uint16_t pressed) { iop::sio2::set_buttons(0, pressed); }void set_pad_axis(int axis, std::uint8_t value) { iop::sio2::set_axis(0, axis, value); }void set_audio_sink(std::function<void(const std::int16_t *, std::size_t)> sink) { iop::spu2::set_sink(std::move(sink)); }diff --git a/scripts/build_web.sh b/scripts/build_web.shnew file mode 100755index 0000000..68c4f08--- /dev/null+++ b/scripts/build_web.sh@@ -0,0 +1,12 @@+#!/bin/bash+# Builds the web version of a recompiled game into build/web.+# usage: scripts/build_web.sh <game folder under games/> [emsdk dir]+set -e+here=$(cd "$(dirname "$0")/.." && pwd)+game=${1:-gt4}+emsdk=${2:-${EMSDK:-$here/../webGame/tools/emsdk}}+source "$emsdk/emsdk_env.sh" > /dev/null 2>&1+emcmake cmake -S "$here" -B "$here/build/web" -G Ninja -DCMAKE_BUILD_TYPE=Release \+ -DPS2_GENERATED="$here/generated/$game" -DPS2_WEB_ELF="$here/games/$game/core.elf"+ninja -C "$here/build/web" ps2web+echo "built $here/build/web/ps2web.html; serve it with scripts/serve.py build/web games/$game/disc.iso"diff --git a/scripts/serve.py b/scripts/serve.pynew file mode 100755index 0000000..5333837--- /dev/null+++ b/scripts/serve.py@@ -0,0 +1,77 @@+#!/usr/bin/env python3+"""Serves a web build and a disc image with HTTP range requests.++usage: serve.py <build dir> <disc image> [port]+"""++import http.server+import os+import re+import sys++BUILD = os.path.abspath(sys.argv[1])+DISC = os.path.abspath(sys.argv[2])+PORT = int(sys.argv[3]) if len(sys.argv) > 3 else 8620+TYPES = {'.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.data': 'application/octet-stream'}+++class Handler(http.server.BaseHTTPRequestHandler):+ def target(self):+ path = self.path.split('?', 1)[0]+ if path in ('/', '/index.html'):+ path = '/ps2web.html'+ if path == '/disc.iso':+ return DISC+ name = os.path.normpath(path.lstrip('/'))+ if name.startswith('..') or os.sep in name:+ return None+ full = os.path.join(BUILD, name)+ return full if os.path.isfile(full) else None++ def headers_for(self, path, length):+ self.send_header('Content-Type', TYPES.get(os.path.splitext(path)[1], 'application/octet-stream'))+ self.send_header('Content-Length', str(length))+ self.send_header('Accept-Ranges', 'bytes')+ self.send_header('Cache-Control', 'no-cache')+ self.end_headers()++ def do_HEAD(self):+ path = self.target()+ if not path:+ self.send_error(404)+ return+ self.send_response(200)+ self.headers_for(path, os.path.getsize(path))++ def do_GET(self):+ path = self.target()+ if not path:+ self.send_error(404)+ return+ size = os.path.getsize(path)+ match = re.match(r'bytes=(\d+)-(\d*)', self.headers.get('Range', ''))+ start, end = 0, size - 1+ if match:+ start = int(match.group(1))+ end = min(int(match.group(2)) if match.group(2) else size - 1, size - 1)+ self.send_response(206)+ self.send_header('Content-Range', 'bytes %d-%d/%d' % (start, end, size))+ else:+ self.send_response(200)+ self.headers_for(path, end - start + 1)+ with open(path, 'rb') as f:+ f.seek(start)+ left = end - start + 1+ while left > 0:+ chunk = f.read(min(left, 1 << 20))+ if not chunk:+ break+ self.wfile.write(chunk)+ left -= len(chunk)++ def log_message(self, fmt, *args):+ pass+++print('serving %s and %s on http://127.0.0.1:%d/' % (BUILD, DISC, PORT))+http.server.ThreadingHTTPServer(('127.0.0.1', PORT), Handler).serve_forever()diff --git a/web/shell.html b/web/shell.htmlnew file mode 100644index 0000000..4885cf5--- /dev/null+++ b/web/shell.html@@ -0,0 +1,171 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>ps2-web-recomp</title>+<style>+ :root { color-scheme: dark; }+ html, body { margin: 0; height: 100%; background: #0b0b0d; color: #d8d8dc; font: 13px system-ui, sans-serif; }+ body { display: flex; flex-direction: column; }+ #stage { flex: 1; display: flex; align-items: center; justify-content: center; min-height: 0; }+ canvas { width: 100%; height: 100%; display: block; background: #000; }+ #bar { display: flex; gap: 16px; align-items: center; padding: 6px 12px; background: #141418; border-top: 1px solid #222; }+ #status { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ #stats { font-variant-numeric: tabular-nums; color: #9ad; }+ button { background: #2a3a55; color: #fff; border: 0; padding: 6px 14px; border-radius: 4px; cursor: pointer; }+ #overlay { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,.6); }+</style>+</head>+<body>+<div id="stage"><canvas id="canvas" tabindex="0"></canvas></div>+<div id="bar"><span id="status">Loading…</span><span id="stats"></span></div>+<div id="overlay"><button id="start" disabled>Loading…</button></div>+<script>+const statusEl = document.getElementById('status');+const statsEl = document.getElementById('stats');+const canvas = document.getElementById('canvas');+const params = new URLSearchParams(location.search);++function fitCanvas() {+ const ratio = window.devicePixelRatio || 1;+ const width = Math.max(1, Math.round(canvas.clientWidth * ratio));+ const height = Math.max(1, Math.round(canvas.clientHeight * ratio));+ if (canvas.width !== width || canvas.height !== height) {+ canvas.width = width;+ canvas.height = height;+ if (Module.calledRun && Module._ps2web_resize) Module._ps2web_resize(width, height);+ }+}+window.addEventListener('resize', fitCanvas);++const workletSource = `+class Output extends AudioWorkletProcessor {+ constructor() {+ super();+ this.queue = [];+ this.offset = 0;+ this.consumed = 0;+ this.port.onmessage = (e) => this.queue.push(e.data);+ }+ process(inputs, outputs) {+ const left = outputs[0][0], right = outputs[0][1];+ for (let i = 0; i < left.length; ++i) {+ if (!this.queue.length) { left[i] = right[i] = 0; continue; }+ const block = this.queue[0];+ left[i] = block[this.offset];+ right[i] = block[this.offset + 1];+ this.offset += 2;+ ++this.consumed;+ if (this.offset >= block.length) { this.queue.shift(); this.offset = 0; }+ }+ if ((currentFrame & 1023) < left.length) this.port.postMessage(this.consumed);+ return true;+ }+}+registerProcessor('ps2-output', Output);`;++let audio = null, node = null, posted = 0, consumed = 0;+async function startAudio() {+ audio = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });+ await audio.audioWorklet.addModule(URL.createObjectURL(new Blob([workletSource], { type: 'application/javascript' })));+ node = new AudioWorkletNode(audio, 'ps2-output', { outputChannelCount: [2] });+ node.port.onmessage = (e) => { consumed = e.data; };+ node.connect(audio.destination);+}++const keys = new Set();+const keyMap = { ArrowUp: 4, ArrowRight: 5, ArrowDown: 6, ArrowLeft: 7, KeyZ: 14, KeyX: 13, KeyA: 15, KeyS: 12,+ KeyQ: 10, KeyW: 11, Digit1: 8, Digit2: 9, Enter: 3, Backspace: 0 };+window.addEventListener('keydown', (e) => { if (e.code in keyMap) { keys.add(e.code); e.preventDefault(); } });+window.addEventListener('keyup', (e) => { keys.delete(e.code); });+const padButtons = [[0, 14], [1, 13], [2, 15], [3, 12], [4, 10], [5, 11], [6, 8], [7, 9], [8, 0], [9, 3], [10, 1], [11, 2],+ [12, 4], [13, 6], [14, 7], [15, 5]];+const axis = (v) => Math.max(0, Math.min(255, Math.round((v + 1) * 127.5)));+let lastPad = -1;+function pollInput() {+ let buttons = 0, lx = 128, ly = 128, rx = 128, ry = 128;+ for (const k of keys) buttons |= 1 << keyMap[k];+ if (keys.has('ArrowLeft')) lx = 0;+ if (keys.has('ArrowRight')) lx = 255;+ if (keys.has('ArrowUp')) ly = 0;+ if (keys.has('ArrowDown')) ly = 255;+ for (const pad of navigator.getGamepads ? navigator.getGamepads() : []) {+ if (!pad) continue;+ for (const [index, bit] of padButtons) if (pad.buttons[index] && pad.buttons[index].pressed) buttons |= 1 << bit;+ if (pad.axes.length >= 4) {+ if (lx === 128) lx = axis(pad.axes[0]);+ if (ly === 128) ly = axis(pad.axes[1]);+ rx = axis(pad.axes[2]);+ ry = axis(pad.axes[3]);+ }+ break;+ }+ const state = buttons + lx * 65536 + ly * 16777216 + rx * 4294967296 + ry * 1099511627776;+ if (state !== lastPad) {+ lastPad = state;+ Module._ps2web_pad(buttons, lx, ly, rx, ry);+ }+}++let frames = 0, last = performance.now(), lastGpu = 0;+var Module = {+ canvas,+ arguments: ['/game/core.elf', '--arg', params.get('arg') || 'cdrom0:\\CORE.GT4;1'].concat(params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),+ discUrl: params.get('disc') || 'disc.iso',+ noSurface: params.has('nosurface'),+ presentCopy: params.has('copy'),+ print: (text) => console.log(text),+ printErr: (text) => console.log(text),+ setStatus: (text) => { if (text) statusEl.textContent = text; },+ onRuntimeInitialized: () => {+ const start = document.getElementById('start');+ start.disabled = false;+ start.textContent = 'Start';+ },+ preRun: [() => {+ for (const [key, value] of params) if (key.startsWith('PS2_')) Module.ENV[key] = value;+ Module.addRunDependency('disc');+ fetch(Module.discUrl, { method: 'HEAD' }).then((r) => {+ Module.discSize = Number(r.headers.get('content-length')) || 0;+ statusEl.textContent = Module.discSize ? 'Disc ' + (Module.discSize / 1073741824).toFixed(2) + ' GB' : 'No disc image at ' + Module.discUrl;+ Module.removeRunDependency('disc');+ });+ }],+ pushAudio: (samples) => {+ if (!node) return;+ const block = new Float32Array(samples.length);+ for (let i = 0; i < samples.length; ++i) block[i] = samples[i] / 32768;+ node.port.postMessage(block, [block.buffer]);+ posted += samples.length / 2;+ },+ audioQueuedMs: () => (node ? (posted - consumed) / 48 : 0),+ onFrame: () => {+ pollInput();+ ++frames;+ const now = performance.now();+ if (now - last >= 1000) {+ const gpu = Module._ps2web_gpu_ms();+ const memory = (Module.HEAPU8.length / 1048576).toFixed(0);+ statsEl.textContent = 'frame ' + Module._ps2web_frames() + ' prims ' + Module._ps2web_primitives() + ' ' + (frames * 1000 / (now - last)).toFixed(1) + ' fps GPU ' + ((gpu - lastGpu) / (now - last) * 100).toFixed(0) ++ '% heap ' + memory + ' MB audio ' + Module.audioQueuedMs().toFixed(0) + ' ms';+ lastGpu = gpu;+ frames = 0;+ last = now;+ }+ },+ noInitialRun: true,+};++document.getElementById('start').addEventListener('click', async () => {+ document.getElementById('overlay').remove();+ canvas.focus();+ fitCanvas();+ await startAudio();+ statusEl.textContent = 'Running ' + Module.arguments[2];+ Module.callMain(Module.arguments);+});+</script>+{{{ SCRIPT }}}+</body>+</html>