PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
port.sh: from a disc image to a web page in one script
Samir Nuri74d4c0f21c54
diff --git a/CMakeLists.txt b/CMakeLists.txtindex ebcc91b..78197fd 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -88,7 +88,11 @@ if(PS2_GENERATED)if(EMSCRIPTEN)set(PS2_WEB_ELF "" CACHE FILEPATH "Game executable preloaded as /game/core.elf")+ set(PS2_WEB_BOOT_FILE "" CACHE FILEPATH "Text file holding the argv[0] the game sees, preloaded as /game/boot.txt")add_executable(ps2web host/web.cpp)+ if(PS2_WEB_BOOT_FILE)+ target_link_options(ps2web PRIVATE "SHELL:--preload-file ${PS2_WEB_BOOT_FILE}@/game/boot.txt")+ endif()target_link_libraries(ps2web PRIVATE ps2game ps2runtime)target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sPTHREAD_POOL_SIZE=2 -sALLOW_TABLE_GROWTH=1 -lidbfs.js -sSTACK_SIZE=16777216 -sENVIRONMENT=web-sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreteddiff --git a/host/web.cpp b/host/web.cppindex 63535b8..1d64746 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -272,6 +272,18 @@ int main(int argc, char **argv) {if (ps2::parse_press(argv[++i], press)) ps2::g_options.presses.push_back(press);}}+ if (launch.args.empty()) {+ std::string boot = "/game/core.elf";+ if (std::FILE *f = std::fopen("/game/boot.txt", "rb")) {+ char text[256] = {};+ const std::size_t n = std::fread(text, 1, sizeof text - 1, f);+ std::fclose(f);+ std::string line(text, n);+ line.erase(line.find_last_not_of(" \r\n\t") + 1);+ if (!line.empty()) boot = line;+ }+ launch.args.push_back(boot);+ }g_disc_size = static_cast<std::uint64_t>(ps2web_disc_size());g_disc_url = ps2web_disc_url();ps2::g_options.on_vblank = on_vblank;diff --git a/scripts/build_web.sh b/scripts/build_web.shindex a7cfc86..04a3cb2 100755--- a/scripts/build_web.sh+++ b/scripts/build_web.sh@@ -1,13 +1,22 @@#!/bin/bash-# Builds the web version of a recompiled game into build/web.+# Builds the web version of a recompiled game into build/web-<game>.# usage: scripts/build_web.sh <game folder under games/> [emsdk dir]set -ehere=$(cd "$(dirname "$0")/.." && pwd)game=${1:-gt4}-emsdk=${2:-${EMSDK:-$here/../webGame/tools/emsdk}}+emsdk=${2:-${EMSDK:-$here/tools/emsdk}}+out="$here/build/web-$game"+boot=$(sed -n 's/^BOOT2 *= *//p' "$here/games/$game/disc/SYSTEM.CNF" | tr -d '\r')+elf="$here/games/$game/core.elf"+if [ ! -f "$elf" ]; then+ name=${boot#*\\}+ elf="$here/games/$game/disc/${name%;*}"+fi+mkdir -p "$out"+printf '%s\n' "$boot" > "$out/boot.txt"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-gzip -kf9 "$here/build/web/ps2web.wasm" "$here/build/web/ps2web.data" "$here/build/web/ps2web.js"-echo "built $here/build/web/ps2web.html; serve it with scripts/serve.py build/web games/$game/disc.iso"+emcmake cmake -S "$here" -B "$out" -G Ninja -DCMAKE_BUILD_TYPE=Release \+ -DPS2_GENERATED="$here/generated/$game" -DPS2_WEB_ELF="$elf" -DPS2_WEB_BOOT_FILE="$out/boot.txt"+ninja -C "$out" ps2web+gzip -kf9 "$out/ps2web.wasm" "$out/ps2web.data" "$out/ps2web.js"+echo "built $out/ps2web.html; serve it with scripts/serve.py build/web-$game games/$game/disc.iso"diff --git a/scripts/port.sh b/scripts/port.shnew file mode 100755index 0000000..32f9321--- /dev/null+++ b/scripts/port.sh@@ -0,0 +1,143 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+here="$ROOT/scripts"++usage() {+ cat <<'EOF'+usage: scripts/port.sh <name> <game.iso | game.zip | game.7z> [options]++Turns a PS2 disc image you own into a browser build in build/web-<name>. It+reads the boot program named in SYSTEM.CNF, translates its machine code to+C++, runs it headless to find code the static pass missed (adding those entry+points and translating again), compiles the vector unit programs those runs+recorded and builds the page.++options:+ --frames N frames per exploring run (default 3600)+ --press F:BUTTON input for the exploring runs, repeatable; the default+ presses start at frame 300 and cross every 300 frames+ --rounds N exploring runs at most (default 8)+ --no-explore translate and build without running the game+EOF+}++[ $# -ge 2 ] || { usage; exit 2; }+name="$1"; source_path="$2"; shift 2+frames=3600; rounds=8; explore=1; presses=()+while [ $# -gt 0 ]; do+ case "$1" in+ --frames) frames="$2"; shift ;;+ --press) presses+=(--press "$2"); shift ;;+ --rounds) rounds="$2"; shift ;;+ --no-explore) explore=0 ;;+ -h|--help) usage; exit 0 ;;+ *) echo "unknown option $1" >&2; exit 2 ;;+ esac+ shift+done+if [ ${#presses[@]} -eq 0 ]; then+ presses=(--press 300:start)+ for ((f = 600; f < frames; f += 300)); do presses+=(--press "$f:cross"); done+fi++game="$ROOT/games/$name"+generated="$ROOT/generated/$name"+native="$ROOT/build/native-$name"+tools="$ROOT/build/tools"+export EMSDK="${EMSDK:-$ROOT/tools/emsdk}"+if [ ! -f "$EMSDK/emsdk_env.sh" ] || [ ! -x "$tools/eerecomp" ] || [ ! -x "$tools/vurecomp" ]; then "$here/setup.sh"; fi+mkdir -p "$game/disc" "$game/vu1" "$game/shots" "$generated"++echo "== [1/6] disc"+iso="$game/disc.iso"+if [ -e "$iso" ]; then+ echo "already in place"+else+ case "${source_path,,}" in+ *.zip)+ python3 -I - "$source_path" "$iso" <<'EOF'+import shutil, sys, zipfile+with zipfile.ZipFile(sys.argv[1]) as archive:+ images = [m for m in archive.infolist() if m.filename.lower().endswith('.iso')]+ if not images:+ sys.exit('no .iso inside the archive')+ with archive.open(max(images, key=lambda m: m.file_size)) as src, open(sys.argv[2], 'wb') as dst:+ shutil.copyfileobj(src, dst, 1 << 24)+EOF+ ;;+ *.7z) 7z e -so -r "$source_path" '*.iso' > "$iso" ;;+ *) ln -s "$(realpath "$source_path")" "$iso" ;;+ esac+fi+python3 -I "$here/disc.py" extract "$iso" "$game/disc" SYSTEM.CNF > /dev/null+boot=$(sed -n 's/^BOOT2 *= *//p' "$game/disc/SYSTEM.CNF" | tr -d '\r')+program=${boot#*\\}+program=${program%;*}+[ -n "$program" ] || { echo "SYSTEM.CNF names no BOOT2 program" >&2; exit 1; }+python3 -I "$here/disc.py" extract "$iso" "$game/disc" "$program" > /dev/null+echo "boots $boot"++echo "== [2/6] executable"+elf="$game/disc/$program"+if [ -f "$game/core.elf" ]; then+ elf="$game/core.elf"+elif python3 -I "$here/disc.py" list "$iso" | awk '{print $4}' | grep -qx CORE.GT4; then+ python3 -I "$here/disc.py" extract "$iso" "$game/disc" CORE.GT4 > /dev/null+ python3 -I "$here/gt4_core.py" "$game/disc/CORE.GT4" "$game/core.elf" > /dev/null+ elf="$game/core.elf"+fi+echo "${elf#$ROOT/}"++translate() { "$tools/eerecomp" "$elf" --entries "$game/entries.txt" --out "$generated" | tail -1; }++echo "== [3/6] machine code to C++"+touch "$game/entries.txt"+translate++echo "== [4/6] exploring"+if [ "$explore" = 1 ]; then+ if [ ! -f "$native/build.ninja" ]; then+ compilers=()+ if command -v clang++ > /dev/null; then compilers=(-DCMAKE_CXX_COMPILER=clang++); fi+ cmake -S "$ROOT" -B "$native" -G Ninja -DCMAKE_BUILD_TYPE=Release "${compilers[@]}" -DPS2_GENERATED="$generated" > /dev/null+ fi+ for ((round = 1; round <= rounds; round++)); do+ ninja -C "$native" ps2run > "$native/ninja.log" 2>&1 || { tail -30 "$native/ninja.log"; exit 1; }+ rm -f "$game/misses.txt"+ PS2_GPU_LOW_POWER=1 PS2_VU_RECORD="$game/vu1" "$native/ps2run" "$elf" --disc "$iso" --misses "$game/misses.txt" \+ --frames "$frames" "${presses[@]}" --frames-dir "$game/shots" --frame-every 300 > "$game/explore.log" 2>&1 || true+ reason=$(sed -n 's/^\[ee\] halted: //p' "$game/explore.log" | head -1)+ added=$(python3 -I - "$game/entries.txt" "$game/misses.txt" <<'EOF'+import os, sys+entries, misses = sys.argv[1], sys.argv[2]+known = {int(t, 16) for t in open(entries).read().split()}+found = [int(t, 16) for t in open(misses).read().split()] if os.path.exists(misses) else []+new = sorted({a for a in found if a not in known})+with open(entries, 'a') as out:+ for a in new:+ out.write('%x\n' % a)+print(len(new))+EOF+)+ echo "round $round: ${reason:-ran to the end}, $added new entry points"+ [ "$added" -gt 0 ] || break+ translate+ done+ echo "frames of the last run are in games/$name/shots, its log in games/$name/explore.log"+else+ echo "skipped"+fi++echo "== [5/6] vector unit programs"+if compgen -G "$game/vu1/*.bin" > /dev/null; then+ "$tools/vurecomp" "$game/vu1" "$generated" | tail -1+else+ echo "none recorded, the page compiles them on the fly"+fi++echo "== [6/6] web build"+"$here/build_web.sh" "$name" "$EMSDK"+echo+echo "Done. Serve it with: python3 scripts/serve.py build/web-$name games/$name/disc.iso"+echo "and open http://localhost:8620/"diff --git a/scripts/setup.sh b/scripts/setup.shnew file mode 100755index 0000000..695da0d--- /dev/null+++ b/scripts/setup.sh@@ -0,0 +1,24 @@+#!/usr/bin/env bash+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+EMSDK="${EMSDK:-$ROOT/tools/emsdk}"+EMSDK_VERSION="6.0.11"++if [ ! -f "$EMSDK/emsdk_env.sh" ]; then+ echo "== installing the Emscripten SDK $EMSDK_VERSION into $EMSDK"+ mkdir -p "$(dirname "$EMSDK")"+ git clone https://github.com/emscripten-core/emsdk.git "$EMSDK"+ "$EMSDK/emsdk" install "$EMSDK_VERSION"+ "$EMSDK/emsdk" activate "$EMSDK_VERSION"+fi++if [ ! -f "$ROOT/third_party/wgpu-native/lib/libwgpu_native.a" ]; then+ echo "== fetching wgpu-native for the native test runner"+ "$ROOT/scripts/fetch_wgpu.sh"+fi++compilers=()+if command -v clang++ > /dev/null; then compilers=(-DCMAKE_CXX_COMPILER=clang++); fi+cmake -S "$ROOT" -B "$ROOT/build/tools" -G Ninja -DCMAKE_BUILD_TYPE=Release "${compilers[@]}" > /dev/null+ninja -C "$ROOT/build/tools" eerecomp vurecomp+echo "== ready"diff --git a/web/shell.html b/web/shell.htmlindex 293ec67..fe85138 100644--- a/web/shell.html+++ b/web/shell.html@@ -506,7 +506,7 @@ async function chooseGpu() {let frames = 0, last = performance.now(), lastGpu = 0, lastEmuIdle = 0, lastRenderIdle = 0, lastVuIdle = 0, lastInterpreted = 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]))),+ arguments: ['/game/core.elf'].concat(params.has('arg') ? ['--arg', params.get('arg')] : [], params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),discUrl: params.get('disc') || 'disc.iso',noSurface: params.has('nosurface'),noCard: params.has('nocard'),@@ -594,7 +594,7 @@ document.getElementById('start').addEventListener('click', async () => {canvas.focus();fitCanvas();await startAudio();- statusEl.textContent = 'Running ' + Module.arguments[2] + ', ' + Module.gpuInfo;+ statusEl.textContent = 'Running, ' + Module.gpuInfo;Module.running = true;Module.callMain(Module.arguments);});