client/runtime/browser_host.js (11062B)
1 addToLibrary({ 2 browser_startup_assets__deps: ['$stringToNewUTF8'], 3 browser_startup_assets__proxy: 'sync', 4 browser_startup_assets: () => Module.startupAssets ? stringToNewUTF8(JSON.stringify(Module.startupAssets)) : 0, 5 $AOTest: {enabled: false, frame: 0}, 6 ao_test_publish__deps: ['$AOTest', 'ao_test_publish_main'], 7 ao_test_publish: (json) => { 8 AOTest.enabled = true; 9 _ao_test_publish_main(json); 10 }, 11 ao_test_publish_main__deps: ['$AOTest', '$UTF8ToString'], 12 ao_test_publish_main__proxy: 'sync', 13 ao_test_publish_main: (json) => { 14 AOTest.enabled = true; 15 Module.onTestSnapshot?.(JSON.parse(UTF8ToString(json))); 16 }, 17 ao_test_input__deps: ['$AOTest', 'ao_test_event'], 18 ao_test_input: (stage, type, a, b, c, d) => { 19 if (AOTest.enabled) _ao_test_event(stage, type, a, b, c, d, AOTest.frame, 20 performance.timeOrigin + performance.now()); 21 }, 22 ao_test_event__proxy: 'async', 23 ao_test_event: (stage, type, a, b, c, d, frame, time) => { 24 const event = {kind: 'input', stage: stage ? 'consumed' : 'queued', 25 type, frame: stage ? frame : null, time}; 26 if (type === 768 || type === 769) 27 Object.assign(event, {key: a, down: !!b, repeat: !!c, modifiers: d}); 28 else if (type === 1025 || type === 1026) 29 Object.assign(event, {button: a, down: !!b, x: c, y: d}); 30 else if (type === 32769) event.character = a; 31 else Object.assign(event, {x: a, y: b}); 32 Module.onTestEvent?.(event); 33 }, 34 emscripten_request_animation_frame_loop__deps: ['$callUserCallback', '$getWasmTableEntry'], 35 emscripten_request_animation_frame_loop: (callback, userData) => { 36 // Guest shutdown can exit from a frame; let Emscripten handle its exit sentinel. 37 function tick(timestamp) { 38 callUserCallback(() => { 39 if (getWasmTableEntry(callback)(timestamp, userData)) requestAnimationFrame(tick); 40 }); 41 } 42 return requestAnimationFrame(tick); 43 }, 44 browser_preferences_directory__deps: ['$UTF8ToString', '$stringToNewUTF8'], 45 browser_preferences_directory: base => stringToNewUTF8('/persistent/' + encodeURIComponent(UTF8ToString(base))), 46 browser_storage_available__deps: ['emscripten_proxy_finish'], 47 browser_storage_available: async (context, available) => { 48 try { 49 await navigator.storage.getDirectory(); 50 HEAP32[available >> 2] = 1; 51 } catch (error) { 52 if (error.name !== 'SecurityError') throw error; 53 HEAP32[available >> 2] = 0; 54 console.warn('Browser storage denied; local preferences will last only for this page.'); 55 } finally { 56 _emscripten_proxy_finish(context); 57 } 58 }, 59 $AOAssetRequest: async (url, options) => { 60 let delay = 1000; 61 for (;;) { 62 // Bound the entire transfer, including a body stalled after its headers. 63 const controller = new AbortController(); 64 const timeout = setTimeout(() => controller.abort(), 30000); 65 try { 66 const response = await fetch(url, {...options, signal: controller.signal}); 67 if (response.status !== 408 && response.status !== 429 && response.status < 500) { 68 return {response, bytes: response.ok ? await response.arrayBuffer() : null}; 69 } 70 controller.abort(); 71 } catch (error) { 72 if (!controller.signal.aborted && !(error instanceof TypeError)) throw error; 73 } finally { 74 clearTimeout(timeout); 75 } 76 77 // Keep waiting for connectivity without synchronizing clients after an outage. 78 const wait = delay * (0.5 + Math.random() * 0.5); 79 console.warn(`Asset request failed; retrying in ${Math.round(wait)} ms`, url); 80 await new Promise(resolve => setTimeout(resolve, wait)); 81 delay = Math.min(delay * 2, 30000); 82 } 83 }, 84 $AOPresented: false, 85 $AOInitializeGraphics__deps: ['$GL', 'browser_graphics_lost'], 86 $AOInitializeGraphics: context => { 87 // Context events run on the thread that owns the actual WebGL object. 88 context.GLctx.canvas.addEventListener('webglcontextlost', event => { 89 event.preventDefault(); 90 _browser_graphics_lost(); 91 }); 92 context.GLctx.canvas.addEventListener('webglcontextrestored', () => { 93 if (context.defaultFbo) GL.createOffscreenFramebuffer(context); 94 }); 95 }, 96 ao_graphics_initialize_main__deps: ['$GL', '$AOInitializeGraphics'], 97 ao_graphics_initialize_main__proxy: 'sync', 98 ao_graphics_initialize_main: (context) => AOInitializeGraphics(GL.getContext(context)), 99 ao_graphics_initialize__deps: ['$GL', '$AOInitializeGraphics', 'ao_graphics_initialize_main'], 100 ao_graphics_initialize: () => { 101 if (GL.currentContextIsProxied) _ao_graphics_initialize_main(GL.currentContext); 102 else AOInitializeGraphics(GL.currentContext); 103 }, 104 // Context state and destruction need explicit forwarding to their owning thread. 105 ao_graphics_context_lost_main__deps: ['$GL'], 106 ao_graphics_context_lost_main__proxy: 'sync', 107 ao_graphics_context_lost_main: (context) => !GL.getContext(context) || GL.getContext(context).GLctx.isContextLost(), 108 emscripten_is_webgl_context_lost__deps: ['$GL', 'ao_graphics_context_lost_main'], 109 emscripten_is_webgl_context_lost: (context) => GL.getContext(context) 110 ? GL.getContext(context).GLctx.isContextLost() : _ao_graphics_context_lost_main(context), 111 ao_graphics_destroy_main__deps: ['$GL'], 112 ao_graphics_destroy_main__proxy: 'sync', 113 ao_graphics_destroy_main: (context) => { GL.deleteContext(context); }, 114 emscripten_webgl_destroy_context__deps: ['$GL', 'ao_graphics_destroy_main'], 115 emscripten_webgl_destroy_context: (context) => { 116 if (GL.getContext(context)) GL.deleteContext(context); 117 else _ao_graphics_destroy_main(context); 118 }, 119 ao_graphics_status__proxy: 'async', 120 ao_graphics_status: (lost) => { Module.onGraphicsStatus?.(lost); }, 121 ao_loading_complete__proxy: 'async', 122 ao_loading_complete: () => { Module.onFirstFrame?.(); }, 123 ao_game_closed__proxy: 'async', 124 ao_game_closed: () => { Module.onGameClosed?.(); }, 125 ao_chat_bounds__proxy: 'async', 126 ao_chat_bounds: (x, y, width, height, screenWidth, screenHeight, outputX, outputY, outputWidth, outputHeight) => { 127 Module.onChatBounds?.({x, y, width, height, screenWidth, screenHeight, 128 history: {x: outputX, y: outputY, width: outputWidth, height: outputHeight}}); 129 }, 130 ao_touch_regions__proxy: 'sync', 131 ao_touch_regions: (bounds, count, screenWidth, screenHeight, itemMenu) => { 132 const regions = Array.from({length: count}, (_, index) => { 133 const offset = (bounds >> 2) + index * 5; 134 return {left: HEAP32[offset], top: HEAP32[offset + 1], 135 right: HEAP32[offset + 2], bottom: HEAP32[offset + 3], 136 world: HEAP32[offset + 4] === 1, chat: HEAP32[offset + 4] === 2, 137 item: HEAP32[offset + 4] === 3, detector: HEAP32[offset + 4] === 4}; 138 }); 139 Module.onTouchRegions?.({regions, screenWidth, screenHeight, itemMenu: !!itemMenu}); 140 }, 141 ao_touch_frame__proxy: 'async', 142 ao_touch_frame: (request) => { Module.onTouchFrame?.(request); }, 143 ao_creation_state__proxy: 'sync', 144 ao_creation_state__deps: ['$UTF8ToString', '$stringToNewUTF8', 'free', 'browser_creation_finish'], 145 ao_creation_state: (bounds, name) => { 146 Module.finishCreation ||= value => { 147 const text = stringToNewUTF8(value); 148 _browser_creation_finish(text); 149 _free(text); 150 }; 151 const offset = bounds >> 2; 152 Module.onCreationState?.({active: !!HEAP32[offset], 153 name: HEAP32[offset + 3] ? {x: HEAP32[offset + 1], y: HEAP32[offset + 2], 154 width: HEAP32[offset + 3], height: HEAP32[offset + 4], value: UTF8ToString(name)} : null, 155 screenWidth: HEAP32[offset + 5], screenHeight: HEAP32[offset + 6]}); 156 }, 157 $AOFrameWait: 0, 158 ao_frame_begin__deps: ['$AOProfile', '$AOFrameWait', '$AOTest'], 159 ao_frame_begin: (timestamp) => { 160 ++AOTest.frame; 161 AOProfile.end('raf wait', AOFrameWait, AOProfile.detailed ? { 162 frame_time_us: (performance.timeOrigin + timestamp) * 1000 163 } : undefined); 164 AOFrameWait = 0; 165 }, 166 ao_frame_complete__deps: ['$AOProfile', '$AOPresented', '$AOFrameWait', 'ao_loading_complete'], 167 ao_frame_complete: () => { 168 if (!AOPresented) { 169 AOPresented = true; 170 _ao_loading_complete(); 171 } 172 AOProfile.frame(); 173 AOFrameWait = AOProfile.begin('raf wait'); 174 }, 175 $AOSoundSizes: {}, 176 ao_asset_manifest_js__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOAssetRequest', 'emscripten_proxy_finish'], 177 ao_asset_manifest_js: (context, request) => { 178 const base = HEAPU32[request >> 2]; 179 AOAssetRequest(new URL('browser-manifest', UTF8ToString(base)).href, 180 {cache: 'no-store', headers: {Accept: 'application/json'}}).then(({response, bytes}) => { 181 if (response.ok) 182 HEAPU32[(request + 4) >> 2] = stringToNewUTF8(new TextDecoder().decode(bytes)); 183 else console.error(`Asset manifest: HTTP ${response.status}`); 184 _emscripten_proxy_finish(context); 185 }); 186 }, 187 ao_asset_manifest_parse__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOSoundSizes'], 188 ao_asset_manifest_parse: (json) => { 189 // Keep sound metadata on the game worker alongside its filesystem listing. 190 const listing = JSON.parse(UTF8ToString(json)); 191 for (const [name, metadata] of Object.entries(listing)) { 192 if (name.toLowerCase().startsWith('cd_image/sound/')) 193 AOSoundSizes[name.toLowerCase()] = metadata.size; 194 } 195 return stringToNewUTF8(Object.keys(listing).sort().join('\n') + '\n'); 196 }, 197 ao_sound_file_size__deps: ['$AOSoundSizes', '$UTF8ToString'], 198 ao_sound_file_size: (filename) => { 199 // Native custom voices can resolve through Player/../other sound folders. 200 const parts = []; 201 for (const part of UTF8ToString(filename).replaceAll('\\', '/').split('/')) { 202 if (part === '..' && parts.length && parts.at(-1) !== '..') parts.pop(); 203 else if (part && part !== '.') parts.push(part); 204 } 205 return AOSoundSizes[parts.join('/').toLowerCase()] ?? -1; 206 }, 207 ao_asset_base_url__deps: ['$stringToNewUTF8'], 208 ao_asset_base_url__proxy: 'sync', 209 ao_asset_base_url: () => { 210 // SDL's browser backend has no CaptureMouse; use canvas pointer capture. 211 const canvas = Module.canvas; 212 canvas.addEventListener('contextmenu', event => event.preventDefault()); 213 canvas.addEventListener('pointerdown', event => { 214 if (!event.isPrimary) return; 215 Module.aoMousePointer = event.pointerId; 216 if (Module.aoMouseCaptured) canvas.setPointerCapture(event.pointerId); 217 }); 218 const released = event => { 219 if (Module.aoMousePointer === event.pointerId) Module.aoMousePointer = undefined; 220 }; 221 canvas.addEventListener('pointerup', released); 222 canvas.addEventListener('pointercancel', released); 223 return stringToNewUTF8(new URL('browser-assets', document.baseURI).href); 224 }, 225 ao_mouse_capture__proxy: 'sync', 226 ao_mouse_capture: (enabled) => { 227 Module.aoMouseCaptured = enabled; 228 const pointer = Module.aoMousePointer; 229 if (pointer === undefined) return; 230 if (enabled) Module.canvas.setPointerCapture(pointer); 231 else if (Module.canvas.hasPointerCapture(pointer)) Module.canvas.releasePointerCapture(pointer); 232 } 233 });