aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit e15b3eb5874aaab313a6bfe0f7fd9fade0dd096f
parent ce26468cb5560de6cfec27d74831f026a6e13008
Author: anon <anon@example.com>
Date:   Tue, 20 Oct 2026 15:53:50 +0000

Run browser frames without JSPI

Diffstat:
MDEVELOPERS.md | 4++--
Msrc/Makefile.wasm | 20++++++++++----------
Msrc/browser/index.html | 1-
Msrc/game/Clientr.exe/lifted-0000.c | 23+++++++++++++++++++++++
Msrc/game/Clientr.exe/lifted-0001.c | 7+++++++
Msrc/runtime/browser_host.c | 19++++++++++++++++++-
Msrc/runtime/browser_host.js | 54++++++++++++++++++++++++++----------------------------
Asrc/runtime/browser_loop.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
Asrc/runtime/browser_loop.h | 7+++++++
Msrc/runtime/linux_graphics.c | 35+++++++++++++++--------------------
Msrc/tests/browser_context.c | 100+++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------
Msrc/tests/browser_context.mjs | 38+++++---------------------------------
Msrc/tests/browser_loading.mjs | 12+-----------
Asrc/tests/browser_loop.c | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/tests/browser_pacing.c | 8++++----
Msrc/tests/browser_profile.mjs | 22++++++++--------------
Msrc/tests/browser_sound_metadata.mjs | 20++++++++++++++++----
Dsrc/tests/browser_suspension.c | 28----------------------------
Mtools/client/sweep_browser.html | 4++--
19 files changed, 313 insertions(+), 193 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -54,8 +54,8 @@ go run ./server ## Browser client -Open [the game](http://127.0.0.1:8080/) in a browser supporting WebAssembly -JSPI, shared memory, OffscreenCanvas and WebGL 2. It loads automatically with a +Open [the game](http://127.0.0.1:8080/) in a browser supporting shared WebAssembly +memory, OffscreenCanvas and WebGL 2. It loads automatically with a randomized Solitus visitor near Bronto Burger in Omni-Entertainment. A persistent cookie identifies your character on later visits; no account or training is required. New visitors start in run mode with character tips disabled. diff --git a/src/Makefile.wasm b/src/Makefile.wasm @@ -1,9 +1,9 @@ CC := ../toolchains/emsdk/upstream/emscripten/emcc CPPFLAGS := -Iruntime -Igame -Idata -DRECOMP_PORTABLE -# Keep exception landing pads in Wasm so JSPI can yield through guest calls. +# Guest exception landing pads use Wasm longjmp support. CFLAGS := -Oz -flto=thin -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm PORT_FLAGS := -sUSE_SDL=2 -sUSE_FREETYPE=1 -sUSE_ZLIB=1 -RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c runtime/browser_resolution.c runtime/browser_profile.c +RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c runtime/browser_loop.c runtime/browser_resolution.c runtime/browser_profile.c GAME_SOURCES := $(wildcard game/*/*.c) game/dispatch.c DATA_SOURCES := $(wildcard data/*.c) VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c) @@ -69,18 +69,18 @@ build/wasm/browser-network-timeout.js: tests/browser_network_timeout.c game/er.d build/wasm/web/devices-test.html: tests/devices.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_profile.c runtime/browser_host.js runtime/browser_profile.js Makefile.wasm @mkdir -p $(@D) - $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sUSE_SDL=2 -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sJSPI -sEXIT_RUNTIME --js-library runtime/browser_host.js --js-library runtime/browser_profile.js -o $@ + $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sUSE_SDL=2 -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sEXIT_RUNTIME --js-library runtime/browser_host.js --js-library runtime/browser_profile.js -o $@ build/wasm/web/context-test.html: tests/browser_context.html build/wasm/web/context-test.js cp $< $@ build/wasm/web/context-test.js: tests/browser_context.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_profile.c runtime/browser_host.js runtime/browser_profile.js Makefile.wasm @mkdir -p $(@D) - $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sUSE_SDL=2 -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sJSPI -sEXIT_RUNTIME --js-library runtime/browser_host.js --js-library runtime/browser_profile.js -o $@ + $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sUSE_SDL=2 -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sEXIT_RUNTIME --js-library runtime/browser_host.js --js-library runtime/browser_profile.js -o $@ build/wasm/web/game.js build/wasm/web/game.wasm &: $(OBJECTS) runtime/browser_network.js runtime/browser_host.js runtime/browser_fetch.js runtime/browser_audio.js runtime/browser_profile.js ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a Makefile.wasm @mkdir -p $(@D) - $(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sJSPI -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=1048576 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_audio.js --js-library runtime/browser_profile.js -sBINARYEN_EXTRA_PASSES=merge-similar-functions -Wl,--thinlto-jobs=8 -Wl,--thinlto-cache-dir=build/wasm/lto-cache --emit-symbol-map -o build/wasm/web/game.js + $(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=1048576 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_audio.js --js-library runtime/browser_profile.js -sBINARYEN_EXTRA_PASSES=merge-similar-functions -Wl,--thinlto-jobs=8 -Wl,--thinlto-cache-dir=build/wasm/lto-cache --emit-symbol-map -o build/wasm/web/game.js build/wasm/web/index.html: browser/index.html @mkdir -p $(@D) @@ -101,7 +101,7 @@ build/wasm/objects/%.o: %.c build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js runtime/browser_fetch.js runtime/browser_network.js runtime/browser_profile.c runtime/browser_profile.js Makefile.wasm @mkdir -p $(@D) - $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@ --js-library runtime/browser_profile.js + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@ --js-library runtime/browser_profile.js build/wasm/socket-events.js: tests/browser_socket_events.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/guest_heap.c runtime/recomp_state.c runtime/browser_network.js Makefile.wasm @mkdir -p $(@D) @@ -113,15 +113,15 @@ build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest build/wasm/web/storage-test.html: tests/browser_storage.c runtime/browser_host.c runtime/browser_host.js runtime/browser_fetch.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js @mkdir -p $(@D) - $(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@ --js-library runtime/browser_profile.js + $(CC) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js -o $@ --js-library runtime/browser_profile.js -build/wasm/web/suspension-test.html: tests/browser_suspension.c runtime/browser_host.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js +build/wasm/web/loop-test.html: tests/browser_loop.c runtime/browser_loop.c runtime/browser_loop.h runtime/guest_memory.c runtime/recomp_state.c Makefile.wasm @mkdir -p $(@D) - $(CC) $(CFLAGS) $< --js-library runtime/browser_host.js -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@ runtime/browser_profile.c --js-library runtime/browser_profile.js + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sOFFSCREENCANVAS_SUPPORT -o $@ build/wasm/web/pacing-test.html: tests/browser_pacing.c runtime/linux_graphics.c runtime/linux_window.c runtime/gl_renderer.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/browser_host.js Makefile.wasm runtime/browser_profile.c runtime/browser_profile.js @mkdir -p $(@D) - $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) --js-library runtime/browser_host.js -sUSE_SDL=2 -sJSPI -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -Wl,--wrap=clock_nanosleep -o $@ --js-library runtime/browser_profile.js + $(CC) -sUSE_ZLIB=1 $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) --js-library runtime/browser_host.js -sUSE_SDL=2 -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -sOFFSCREENCANVAS_SUPPORT -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -Wl,--wrap=clock_nanosleep -o $@ --js-library runtime/browser_profile.js build/wasm/web/audio-output-test.html: tests/browser_audio.html build/wasm/web/audio-output-test.js build/wasm/web/audio-worklet.js cp $< $@ diff --git a/src/browser/index.html b/src/browser/index.html @@ -287,7 +287,6 @@ show(); }; async function startGame() { if (!crossOriginIsolated) { status.textContent = 'Shared memory is unavailable'; return; } - if (!WebAssembly.Suspending) { status.textContent = 'This game requires WebAssembly JSPI, which this browser does not support'; return; } if (!canvas.transferControlToOffscreen) { status.textContent = 'This game requires OffscreenCanvas, which this browser does not support'; return; } Module.audioContext = new AudioContext(); // Load immediately; browsers unlock audio on the first game interaction. diff --git a/src/game/Clientr.exe/lifted-0000.c b/src/game/Clientr.exe/lifted-0000.c @@ -1,5 +1,8 @@ #define RECOMP_GENERATED_CODE #include "recomp_types.h" +#ifdef __EMSCRIPTEN__ +#include "browser_loop.h" +#endif #include <math.h> #include <stdio.h> #include <stdlib.h> @@ -14,6 +17,9 @@ void sub_28001000(void) { uint32_t _itail_tgt = 0; RECOMP_REGS_LOCALS RECOMP_ENTER(0x28001000u); +#ifdef __EMSCRIPTEN__ + if (browser_client_stopping) goto L_28001A62; +#endif L_28001000: PUSH32(esp, ebp); /* 0x28001000: push ebp */ @@ -1581,6 +1587,7 @@ L_28001A49: PUSH32(esp, eax); /* 0x28001A5C: push eax */ RECOMP_ICALL(0x28002DA0u); /* 0x28001A5D: call 0x28002da0 */ /* not lifted */ RECOMP_FLAGS_IN(); +L_28001A62: edi = eax; /* 0x28001A62: mov edi, eax */ RECOMP_ICALL(0x28002C10u); /* 0x28001A64: call 0x28002c10 */ /* not lifted */ RECOMP_FLAGS_IN(); @@ -102848,6 +102855,10 @@ void sub_28002DA0(void) { uint32_t _itail_tgt = 0; RECOMP_REGS_LOCALS RECOMP_ENTER(0x28002DA0u); +#ifdef __EMSCRIPTEN__ + static int running; + if (running) goto L_2800324E; +#endif L_28002DA0: PUSH32(esp, ebp); /* 0x28002DA0: push ebp */ @@ -103470,6 +103481,11 @@ L_28003140: RECOMP_ICALL(esi); /* 0x28003249: call esi */ RECOMP_FLAGS_IN(); esi = ebx + 0x1C; /* 0x2800324B: lea esi, [ebx + 0x1c] */ +#ifdef __EMSCRIPTEN__ + running = 1; + RECOMP_REGS_OUT(); + browser_start_frame_loop(); +#endif L_2800324E: _flag_a = (uint32_t)(0); _flag_b = (uint32_t)(0); edi = 0; /* 0x2800324E: xor edi, edi */ @@ -103535,9 +103551,16 @@ L_280032A9: ecx = ebx; /* 0x280032A9: mov ecx, ebx */ RECOMP_ICALL(0x28002D20u); /* 0x280032AB: call 0x28002d20 */ /* not lifted */ RECOMP_FLAGS_IN(); +#ifdef __EMSCRIPTEN__ + RECOMP_REGS_OUT(); + return; +#endif RECOMP_BACKEDGE(); goto L_2800324E; /* 0x280032B0: jmp 0x2800324e */ L_280032B2: +#ifdef __EMSCRIPTEN__ + browser_client_stopping = 1; +#endif ebx = MEM32(ebx + 0x24); /* 0x280032B2: mov ebx, dword ptr [ebx + 0x24] */ ecx = ebp + (-0x5C); /* 0x280032B5: lea ecx, [ebp - 0x5c] */ MEM32(ebp + (-0x4)) = 0xFFFFFFFFu; /* 0x280032B8: mov dword ptr [ebp - 4], 0xffffffff */ diff --git a/src/game/Clientr.exe/lifted-0001.c b/src/game/Clientr.exe/lifted-0001.c @@ -1,5 +1,8 @@ #define RECOMP_GENERATED_CODE #include "recomp_types.h" +#ifdef __EMSCRIPTEN__ +#include "browser_loop.h" +#endif #include <math.h> #include <stdio.h> #include <stdlib.h> @@ -2198,6 +2201,9 @@ void sub_28005684(void) { uint32_t _itail_tgt = 0; RECOMP_REGS_LOCALS RECOMP_ENTER(0x28005684u); +#ifdef __EMSCRIPTEN__ + if (browser_client_stopping) goto L_280057B8; +#endif L_28005684: PUSH32(esp, ebp); /* 0x28005684: push ebp */ @@ -2376,6 +2382,7 @@ L_280057A8: PUSH32(esp, eax); /* 0x280057B2: push eax */ RECOMP_ICALL(0x28001000u); /* 0x280057B3: call 0x28001000 */ /* not lifted */ RECOMP_FLAGS_IN(); +L_280057B8: MEM32(ebp + (-0x68)) = eax; /* 0x280057B8: mov dword ptr [ebp - 0x68], eax */ PUSH32(esp, eax); /* 0x280057BB: push eax */ RECOMP_ICALL(MEM32(0x280060E4)); /* 0x280057BC: call dword ptr [0x280060e4] */ diff --git a/src/runtime/browser_host.c b/src/runtime/browser_host.c @@ -10,9 +10,26 @@ #include <stdint.h> #include <emscripten/proxying.h> #include <emscripten/html5.h> +#include <emscripten/threading.h> -char *ao_asset_manifest(const char *base); char *ao_asset_base_url(void); +void ao_asset_manifest_js(em_proxying_ctx *context, void *request); +char *ao_asset_manifest_parse(const char *json); + +static char *ao_asset_manifest(const char *base) +{ + /* Fetch and retry on the page thread while this worker waits without JSPI. */ + struct { const char *base; char *listing; } request = {base, NULL}; + em_proxying_queue *queue = em_proxying_queue_create(); + assert(queue); + assert(emscripten_proxy_sync_with_ctx(queue, emscripten_main_runtime_thread_id(), + ao_asset_manifest_js, &request)); + em_proxying_queue_destroy(queue); + assert(request.listing); + char *listing = ao_asset_manifest_parse(request.listing); + free(request.listing); + return listing; +} static em_proxying_queue *resource_queue; static pthread_t resource_thread; diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js @@ -33,15 +33,6 @@ addToLibrary({ _browser_graphics_lost(); }); }, - ao_graphics_wait__async: 'auto', - ao_graphics_wait__deps: ['$GL'], - ao_graphics_wait: () => { - const context = GL.currentContext.GLctx; - if (!context.isContextLost()) return; - return new Promise(resolve => { - context.canvas.addEventListener('webglcontextrestored', () => resolve(), {once: true}); - }); - }, ao_graphics_status__proxy: 'async', ao_graphics_status: (lost) => { Module.onGraphicsStatus?.(lost); }, ao_loading_complete__proxy: 'async', @@ -63,32 +54,39 @@ addToLibrary({ }); Module.onTouchRegions?.({regions, screenWidth, screenHeight}); }, - ao_present_yield__async: 'auto', - ao_present_yield__deps: ['$AOProfile', '$AOPresented', 'ao_loading_complete'], - ao_present_yield: () => { + $AOFrameWait: 0, + ao_frame_begin__deps: ['$AOProfile', '$AOFrameWait'], + ao_frame_begin: (timestamp) => { + AOProfile.end('raf wait', AOFrameWait, AOProfile.detailed ? { + frame_time_us: (performance.timeOrigin + timestamp) * 1000 + } : undefined); + AOFrameWait = 0; + }, + ao_frame_complete__deps: ['$AOProfile', '$AOPresented', '$AOFrameWait', 'ao_loading_complete'], + ao_frame_complete: () => { if (!AOPresented) { AOPresented = true; _ao_loading_complete(); } AOProfile.frame(); - const start = AOProfile.begin('raf wait'); - return new Promise(resolve => requestAnimationFrame(timestamp => { - AOProfile.end('raf wait', start, AOProfile.detailed ? { - frame_time_us: (performance.timeOrigin + timestamp) * 1000 - } : undefined); - resolve(); - })); + AOFrameWait = AOProfile.begin('raf wait'); }, $AOSoundSizes: {}, - ao_asset_manifest__async: 'auto', - ao_asset_manifest__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOSoundSizes', '$AOAssetRequest'], - ao_asset_manifest: async (base) => { - const {response, bytes} = await AOAssetRequest(new URL('/browser-manifest', UTF8ToString(base)).href, - {cache: 'no-store', headers: {Accept: 'application/json'}}); - if (!response.ok) throw new Error(`Asset manifest: HTTP ${response.status}`); - const listing = JSON.parse(new TextDecoder().decode(bytes)); - - // Use the same manifest for filesystem creation and sound cache accounting. + ao_asset_manifest_js__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOAssetRequest', 'emscripten_proxy_finish'], + ao_asset_manifest_js: (context, request) => { + const base = HEAPU32[request >> 2]; + AOAssetRequest(new URL('/browser-manifest', UTF8ToString(base)).href, + {cache: 'no-store', headers: {Accept: 'application/json'}}).then(({response, bytes}) => { + if (response.ok) + HEAPU32[(request + 4) >> 2] = stringToNewUTF8(new TextDecoder().decode(bytes)); + else console.error(`Asset manifest: HTTP ${response.status}`); + _emscripten_proxy_finish(context); + }); + }, + ao_asset_manifest_parse__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOSoundSizes'], + ao_asset_manifest_parse: (json) => { + // Keep sound metadata on the game worker alongside its filesystem listing. + const listing = JSON.parse(UTF8ToString(json)); for (const [name, metadata] of Object.entries(listing)) { if (name.toLowerCase().startsWith('cd_image/sound/')) AOSoundSizes[name.toLowerCase()] = metadata.size; diff --git a/src/runtime/browser_loop.c b/src/runtime/browser_loop.c @@ -0,0 +1,48 @@ +#include "browser_loop.h" +#include "recomp_types.h" +#include <assert.h> +#include <emscripten.h> +#include <emscripten/html5.h> + +int browser_client_stopping; +static uint32_t client_object, loop_stack, loop_frame; +void ao_frame_complete(void); +void ao_frame_begin(double timestamp); +void ao_game_closed(void); +int browser_graphics_ready(void); +void sub_28002DA0(void); +void sub_28001000(void); +void sub_28005684(void); + +static bool browser_frame(double timestamp, void *argument) +{ + (void)argument; + if (!browser_graphics_ready()) return true; + ao_frame_begin(timestamp); + g_esp = loop_stack; + g_ebp = loop_frame; + g_ebx = client_object; + g_esi = client_object + 0x1c; + + /* The original message loop returns after one frame, or completes its quit epilogue. */ + sub_28002DA0(); + if (browser_client_stopping) { + sub_28001000(); + ao_game_closed(); + sub_28005684(); + return false; + } + assert(g_esp == loop_stack); + ao_frame_complete(); + return true; +} + +void browser_start_frame_loop(void) +{ + /* Guest startup locals remain in linear memory; no host call frame survives a tick. */ + client_object = g_ebx; + loop_stack = g_esp; + loop_frame = g_ebp; + emscripten_request_animation_frame_loop(browser_frame, NULL); + emscripten_exit_with_live_runtime(); +} diff --git a/src/runtime/browser_loop.h b/src/runtime/browser_loop.h @@ -0,0 +1,7 @@ +#ifndef BROWSER_LOOP_H +#define BROWSER_LOOP_H + +extern int browser_client_stopping; +void browser_start_frame_loop(void); + +#endif diff --git a/src/runtime/linux_graphics.c b/src/runtime/linux_graphics.c @@ -24,23 +24,25 @@ static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE context; static SDL_DisplayMode browser_display; static int graphics_lost; void ao_graphics_initialize(void); -void ao_graphics_wait(void); void ao_graphics_status(int lost); EMSCRIPTEN_KEEPALIVE void browser_graphics_lost(void) { graphics_lost = 1; + ao_graphics_status(1); } -static void wait_for_graphics(void) +int browser_graphics_ready(void) { - if (!graphics_lost && (!context || !emscripten_is_webgl_context_lost(context))) return; - ao_graphics_status(1); - ao_graphics_wait(); - gl_renderer_restore(); - graphics_lost = 0; - ao_graphics_status(0); - fprintf(stderr, "[browser-graphics] WebGL resources restored\n"); + if (context && emscripten_is_webgl_context_lost(context)) return 0; + if (graphics_lost) { + gl_renderer_restore(); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximum_texture_size); + graphics_lost = 0; + ao_graphics_status(0); + fprintf(stderr, "[browser-graphics] WebGL resources restored\n"); + } + return 1; } #else static SDL_GLContext context; @@ -136,7 +138,7 @@ void linux_graphics_shutdown(void) static int initialize_graphics(void) { #ifdef __EMSCRIPTEN__ - if (context) wait_for_graphics(); + if (context) browser_graphics_ready(); #endif if (context) return 1; if (SDL_InitSubSystem(SDL_INIT_VIDEO)) goto failed; @@ -180,7 +182,7 @@ static int initialize_graphics(void) if (!gl_renderer_initialize()) { #ifdef __EMSCRIPTEN__ if (!emscripten_is_webgl_context_lost(context)) goto failed; - wait_for_graphics(); + browser_graphics_ready(); #else goto failed; #endif @@ -217,7 +219,7 @@ int linux_graphics_resize(unsigned width, unsigned height, uint32_t drawing_surf { if (!context || !width || !height || width > (unsigned)maximum_texture_size || height > (unsigned)maximum_texture_size) return 0; - wait_for_graphics(); + browser_graphics_ready(); for (struct device_object *device = devices; device; device = device->next) if (device->scene) return 0; @@ -1511,13 +1513,6 @@ static void surface_blit(void) } done: g_eax = 0; -#ifdef __EMSCRIPTEN__ - /* Commit completed pixels before yielding; hidden/clipped windows still pace. */ - if (primary) { - extern void ao_present_yield(void); - ao_present_yield(); - } -#endif } static struct device_object *find_device(uint32_t address) @@ -2558,7 +2553,7 @@ recomp_func_t linux_graphics_virtual(uint32_t address) { if (address < 0xf3000000u || address >= 0xf3000900u || (address & 3)) return NULL; #ifdef __EMSCRIPTEN__ - wait_for_graphics(); + browser_graphics_ready(); #endif current_interface = (address - 0xf3000000u) / 0x100; current_slot = (address & 0xff) / 4; diff --git a/src/tests/browser_context.c b/src/tests/browser_context.c @@ -7,34 +7,66 @@ #include <stdio.h> #include <string.h> -EM_ASYNC_JS(void, lose_context, (void), { +static struct SDL_Window *window; +static struct gl_target *image, *first, *second; +static struct gl_depth *depth; +static unsigned iteration; + +EM_JS(void, lose_context, (void), { + Module.testRestored = false; const context = GL.currentContext.GLctx; const extension = context.getExtension('WEBGL_lose_context'); if (!extension) throw new Error('WEBGL_lose_context is required for this test'); - await new Promise(resolve => { - context.canvas.addEventListener('webglcontextlost', () => { - setTimeout(() => extension.restoreContext(), 50); - resolve(); - }, {once: true}); - extension.loseContext(); - }); + context.canvas.addEventListener('webglcontextlost', () => { + setTimeout(() => extension.restoreContext(), 50); + }, {once: true}); + context.canvas.addEventListener('webglcontextrestored', () => { + Module.testRestored = true; + }, {once: true}); + extension.loseContext(); }); +static bool restored_frame(double timestamp, void *argument); + int main(void) { - struct SDL_Window *window = linux_graphics_window(); + window = linux_graphics_window(); assert(window); - struct gl_target *image = gl_target_create(2, 2, 0); - struct gl_target *first = gl_target_create(2, 2, 0); - struct gl_target *second = gl_target_create(2, 2, 0); - struct gl_depth *depth = gl_depth_create(2, 2, 16); + image = gl_target_create(2, 2, 0); + first = gl_target_create(2, 2, 0); + second = gl_target_create(2, 2, 0); + depth = gl_depth_create(2, 2, 16); gl_target_set_depth(first, depth); gl_target_set_depth(second, depth); const unsigned char pixels[] = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255}; + gl_target_write(image, pixels); + const struct gl_vertex vertices[] = { + {.position = {-1, -1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {0, 0}}, + {.position = {1, -1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {1, 0}}, + {.position = {-1, 1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {0, 1}}, + {.position = {1, 1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {1, 1}} + }; + const uint16_t indices[] = {0, 1, 2, 1, 3, 2}; + const int32_t clip[] = {0, 0, 2, 2}; + struct gl_texture_state texture = {.image = image, .alpha = 1, + .color_op = 2, .alpha_op = 2, .color_arg1 = 2, .alpha_arg1 = 2}; + gl_renderer_set_texture(0, &texture); + gl_target_clear(first, 0xff000000, 1); + gl_target_draw(first, 4, vertices, 4, indices, 6, clip); + + lose_context(); + emscripten_request_animation_frame_loop(restored_frame, NULL); + emscripten_exit_with_live_runtime(); +} + +static bool restored_frame(double timestamp, void *argument) +{ + (void)timestamp; + (void)argument; + if (!EM_ASM_INT({ return Module.testRestored; })) return true; const unsigned char expected[] = {0, 0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 0, 255, 0, 255}; - gl_target_write(image, pixels); const struct gl_vertex vertices[] = { {.position = {-1, -1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {0, 0}}, {.position = {1, -1, .5f, 1}, .color = {1, 1, 1, 1}, .uv = {1, 0}}, @@ -45,36 +77,34 @@ int main(void) const int32_t clip[] = {0, 0, 2, 2}; struct gl_texture_state texture = {.image = image, .alpha = 1, .color_op = 2, .alpha_op = 2, .color_arg1 = 2, .alpha_arg1 = 2}; + assert(linux_graphics_window() == window); + gl_renderer_set_vertex_transform(NULL); gl_renderer_set_texture(0, &texture); + gl_renderer_set_texture(1, NULL); + gl_renderer_set_alpha_test(0, 8, 0); + gl_renderer_set_blend(0, 1, 1); + gl_renderer_set_fog(0, 0); + gl_renderer_set_depth(1, 4, 0); gl_target_clear(first, 0xff000000, 1); + gl_target_clear(second, 0xff000000, 1); gl_target_draw(first, 4, vertices, 4, indices, 6, clip); + gl_target_draw(second, 4, vertices, 4, indices, 6, clip); + unsigned char actual[16]; + gl_target_read(first, actual); - for (unsigned iteration = 0; iteration < 3; ++iteration) { + assert(!memcmp(actual, expected, sizeof(expected))); + gl_target_read(second, actual); + assert(!memcmp(actual, expected, sizeof(expected))); + assert(glGetError() == GL_NO_ERROR); + if (++iteration < 3) { lose_context(); - assert(linux_graphics_window() == window); - gl_renderer_set_vertex_transform(NULL); - gl_renderer_set_texture(0, &texture); - gl_renderer_set_texture(1, NULL); - gl_renderer_set_alpha_test(0, 8, 0); - gl_renderer_set_blend(0, 1, 1); - gl_renderer_set_fog(0, 0); - gl_renderer_set_depth(1, 4, 0); - gl_target_clear(first, 0xff000000, 1); - gl_target_clear(second, 0xff000000, 1); - gl_target_draw(first, 4, vertices, 4, indices, 6, clip); - gl_target_draw(second, 4, vertices, 4, indices, 6, clip); - unsigned char actual[16]; - gl_target_read(first, actual); - - assert(!memcmp(actual, expected, sizeof(expected))); - gl_target_read(second, actual); - assert(!memcmp(actual, expected, sizeof(expected))); - assert(glGetError() == GL_NO_ERROR); + return true; } gl_target_destroy(image); gl_target_destroy(first); gl_target_destroy(second); gl_depth_destroy(depth); linux_graphics_shutdown(); - puts("PASS: repeated worker context loss restores textures, shared depth, shaders and drawing without restarting"); + puts("PASS: repeated worker context loss restores textures, shared depth, shaders and drawing without JSPI"); + return false; } diff --git a/src/tests/browser_context.mjs b/src/tests/browser_context.mjs @@ -25,44 +25,16 @@ function graphics() { }; } -test('context loss allows restoration and suspends graphics until resources can be recreated', async () => { - const game = graphics(); - let resumed = false; - - const loss = game.lose(); - const pending = game.library.ao_graphics_wait().then(() => { resumed = true; }); - await Promise.resolve(); - assert.equal(resumed, false); - game.restore(); - await pending; - - assert.equal(loss.defaultPrevented, true); - assert.equal(game.notifications(), 1); - assert.equal(resumed, true); - assert.equal(game.library.ao_graphics_wait(), undefined); -}); - -test('restoration before the game next runs does not wait for another restoration event', () => { - const game = graphics(); - - game.lose(); - game.restore(); - const result = game.library.ao_graphics_wait(); - - assert.equal(result, undefined); - assert.equal(game.notifications(), 1); -}); - -test('graphics can suspend and resume repeatedly before the first rendered frame', async () => { +test('context loss allows restoration and notifies the game on every loss', () => { const game = graphics(); + const losses = []; for (let index = 0; index < 3; ++index) { - game.lose(); - const pending = game.library.ao_graphics_wait(); + losses.push(game.lose()); game.restore(); - await pending; } + assert.ok(losses.every(event => event.defaultPrevented)); assert.equal(game.notifications(), 3); - assert.equal(game.library.ao_graphics_wait(), undefined); + assert.equal(game.library.ao_graphics_wait, undefined); }); diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs @@ -55,18 +55,9 @@ async function rejectsFailedClientDownload() { /Client download: HTTP 404/); } -async function reportsMissingJspi() { - const test = fixture(); - test.context.WebAssembly = {}; - - await test.context.startGame(); - - assert.deepEqual(test.progress, ['This game requires WebAssembly JSPI, which this browser does not support']); -} - async function reportsMissingOffscreenCanvas() { const test = fixture(); - test.context.WebAssembly = {Suspending() {}}; + test.context.WebAssembly = {}; await test.context.startGame(); @@ -75,6 +66,5 @@ async function reportsMissingOffscreenCanvas() { await streamsDecodedClientAndTracksProgress(); await rejectsFailedClientDownload(); -await reportsMissingJspi(); await reportsMissingOffscreenCanvas(); console.log('PASS: loading progress, streaming compilation, first frame, download failure and missing browser features'); diff --git a/src/tests/browser_loop.c b/src/tests/browser_loop.c @@ -0,0 +1,56 @@ +#include "browser_loop.h" +#include "recomp_types.h" +#include "guest_memory.h" +#include <assert.h> +#include <stdio.h> +#include <emscripten/threading.h> + +static unsigned ticks, frames, completed, closed; + +int browser_graphics_ready(void) +{ + ++ticks; + return ticks != 2; +} + +void ao_frame_begin(double timestamp) { assert(timestamp > 0); } +void ao_frame_complete(void) { ++completed; } +void ao_game_closed(void) { ++closed; } + +void sub_28002DA0(void) +{ + assert(g_ebx == 0x50001000 && g_ebp == 0x5000fe00 && g_esp == 0x5000fd00); + assert(g_esi == 0x5000101c); + if (frames == 3) { + browser_client_stopping = 1; + g_esp = 0x5000ff00; + g_ebp = 0x12345678; + return; + } + assert(ticks == 1 || ticks == 3 || ticks == 4); + ++frames; +} + +void sub_28001000(void) +{ + assert(browser_client_stopping && g_esp == 0x5000ff00 && g_ebp == 0x12345678); + g_ebp = 0x23456789; +} + +void sub_28005684(void) +{ + assert(g_ebp == 0x23456789); + assert(frames == 3 && completed == 3 && ticks == 5 && closed == 1); + puts("PASS: browser callbacks preserve guest frames, skip lost graphics and resume shutdown without JSPI"); +} + +int main(void) +{ + assert(!emscripten_is_main_browser_thread()); + assert(guest_map("browser loop fixture", 0x50000000, 0x10000)); + g_ebx = 0x50001000; + g_esp = 0x5000fd00; + g_ebp = 0x5000fe00; + + browser_start_frame_loop(); +} diff --git a/src/tests/browser_pacing.c b/src/tests/browser_pacing.c @@ -106,15 +106,15 @@ int main(void) checking_wait = 1; assert(!invoke(wait, 3, arguments)); checking_wait = 0; - assert(EM_ASM_INT({ return Module.refreshTimes.length; }) == i); + assert(EM_ASM_INT({ return Module.refreshTimes.length; }) == 0); assert(!invoke(virtual_method(primary, 5), 6, (uint32_t[]){primary, rectangle, source, 0, 0x200, 0})); - assert(EM_ASM_INT({ return Module.refreshTimes.length; }) == i + 1); + assert(EM_ASM_INT({ return Module.refreshTimes.length; }) == 0); } - assert(EM_ASM_INT({ return Module.refreshTimes.every((time, i, times) => !i || time > times[i - 1]); })); + assert(EM_ASM_INT({ return Module.refreshTimes.length === 0; })); arguments[1] = 0; assert(invoke(wait, 3, arguments) == 0x80070057); linux_graphics_shutdown(); - puts("PASS: hidden, visible and clipped primary blits await animation frames without an extra timer wait; guest ABI preserved"); + puts("PASS: hidden, visible and clipped primary blits return without scheduling or waiting; guest ABI preserved"); } diff --git a/src/tests/browser_profile.mjs b/src/tests/browser_profile.mjs @@ -184,7 +184,7 @@ console.log('PASS: busy and short-lived audio workers deliver aggregates without async function frameCallbackTimestampPreservesPacing() { for (const detailed of [false, true]) { - let library, callback, now = 0, callbacks = 0, firstFrames = 0; + let library, now = 0, callbacks = 0, firstFrames = 0; const sent = []; const heap = new Uint32Array(new SharedArrayBuffer(16)); heap[1] = 2; @@ -192,8 +192,8 @@ async function frameCallbackTimestampPreservesPacing() { Atomics, HEAPU32: heap, performance: {timeOrigin: 1000, now: () => now}, _browser_profile_configuration: () => `${detailed ? 1 : 0}:test:4:7`, _pthread_self: () => 7, UTF8ToString: value => value, setInterval: () => {}, - requestAnimationFrame: handler => { callback = handler; ++callbacks; }, - AOPresented: false, _ao_loading_complete: () => { ++firstFrames; }, + requestAnimationFrame: () => { ++callbacks; }, + AOPresented: false, AOFrameWait: 0, _ao_loading_complete: () => { ++firstFrames; }, BroadcastChannel: class { postMessage(value) { sent.push(value); } }, addToLibrary: value => { library = value; } }); @@ -201,18 +201,13 @@ async function frameCallbackTimestampPreservesPacing() { context.AOProfile = library.$AOProfile; vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context); - let resumed = false; - const pending = library.ao_present_yield().then(() => { resumed = true; }); - await Promise.resolve(); - assert.equal(resumed, false); + assert.equal(library.ao_frame_complete(), undefined); now = 180; - callback(20); - await pending; + library.ao_frame_begin(20); context.AOProfile.flush(); - assert.equal(callbacks, 1); + assert.equal(callbacks, 0); assert.equal(firstFrames, 1); - assert.equal(resumed, true); assert.equal(heap[1], 2); assert.equal(sent.length, 1); assert.equal(sent[0].metrics['raf wait'].ms, 180); @@ -222,9 +217,8 @@ async function frameCallbackTimestampPreservesPacing() { assert.equal(sent[0].events[0].dur, 180000); assert.equal(sent[0].events[0].args.frame_time_us, 1020000); } - const next = library.ao_present_yield(); - callback(200); - await next; + library.ao_frame_complete(); + library.ao_frame_begin(200); assert.equal(firstFrames, 1); } } diff --git a/src/tests/browser_sound_metadata.mjs b/src/tests/browser_sound_metadata.mjs @@ -2,8 +2,10 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; -let library, requests = 0; +let library, requests = 0, finished; +const heap = new Uint32Array(4); const context = vm.createContext({ + HEAPU32: heap, _emscripten_proxy_finish: () => finished(), URL, Response, TextDecoder, AbortController, TypeError, setTimeout, clearTimeout, UTF8ToString: value => value, stringToNewUTF8: value => value, addToLibrary: value => { library = value; }, @@ -26,7 +28,14 @@ vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.met context.AOSoundSizes = library.$AOSoundSizes; context.AOAssetRequest = library.$AOAssetRequest; -const listing = await library.ao_asset_manifest('http://example.test/browser-assets'); +context.UTF8ToString = value => value === 1 ? 'http://example.test/browser-assets' : value; +heap[0] = 1; +let json; +context.stringToNewUTF8 = value => { json = value; return 2; }; +await new Promise(resolve => { finished = resolve; library.ao_asset_manifest_js(7, 0); }); +assert.equal(heap[1], 2); +context.stringToNewUTF8 = value => value; +const listing = library.ao_asset_manifest_parse(json); const initializedRequests = requests; const sizes = ['cd_image/sound/Test.wav', '.\\CD_IMAGE\\SOUND\\TEST.WAV', 'cd_image/sound/missing.wav'].map(library.ao_sound_file_size); @@ -53,7 +62,10 @@ context.setTimeout = (callback, delay) => { return setTimeout(callback, 0); }; -const recovered = await library.ao_asset_manifest('http://example.test/browser-assets'); +context.stringToNewUTF8 = value => { json = value; return 2; }; +await new Promise(resolve => { finished = resolve; library.ao_asset_manifest_js(7, 0); }); +context.stringToNewUTF8 = value => value; +const recovered = library.ao_asset_manifest_parse(json); assert.equal(recovered, listing); assert.equal(library.ao_sound_file_size('cd_image/sound/Test.wav'), 1234); @@ -62,5 +74,5 @@ assert.equal(warnings, 2); assert.equal(delays.length, 2); assert.ok(delays[0] >= 500 && delays[0] < 1000); assert.ok(delays[1] >= 1000 && delays[1] < 2000); -assert.equal(library.ao_asset_manifest__async, 'auto'); +assert.equal(library.ao_asset_manifest_js__async, undefined); console.log('PASS: startup manifest recovers from HTTP and network failures before creating the file tree'); diff --git a/src/tests/browser_suspension.c b/src/tests/browser_suspension.c @@ -1,28 +0,0 @@ -#include <assert.h> -#include <emscripten.h> -#include <emscripten/threading.h> -#include <setjmp.h> -#include <stdio.h> - -static jmp_buf landing; -static int resumed; -void ao_present_yield(void); - -static void yield_and_return(void) -{ - for (unsigned i = 0; i < 3; ++i) ao_present_yield(); - resumed = 1; - longjmp(landing, 7); -} - -int main(void) -{ - assert(!emscripten_is_main_browser_thread()); - resumed = 0; - - int result = setjmp(landing); - if (!result) yield_and_return(); - - assert(result == 7 && resumed == 1); - puts("PASS: animation-frame presentation yields resume through a Wasm longjmp landing pad"); -} diff --git a/tools/client/sweep_browser.html b/tools/client/sweep_browser.html @@ -39,8 +39,8 @@ async function request(path, body) { } document.querySelector('#start').onclick = async event => { event.target.disabled = true; - if (!crossOriginIsolated || !WebAssembly.Suspending || !HTMLCanvasElement.prototype.transferControlToOffscreen) { - status.textContent = 'This browser needs shared memory, WebAssembly JSPI and OffscreenCanvas support'; + if (!crossOriginIsolated || !HTMLCanvasElement.prototype.transferControlToOffscreen) { + status.textContent = 'This browser needs shared memory and OffscreenCanvas support'; return; } window.sweepAudio = new AudioContext();