From 5f3aa16cc6661a9aadb0767d1a7e06668d251da7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 21:36:20 +0000 Subject: [PATCH 01/65] Make guest instruction clock deterministic across JIT rewinds; idle on infinite waits - JIT: a segment resumed through RESTORE no longer re-adds its instruction count (kLocResumed), and POLL clears the flag so the branch target counts. - Infinite kernel waits with every fiber blocked advance guest idle time (up to 10 s) instead of reporting a deadlock immediately, so timer-driven threads can run. - run-title --det-every N prints a kernel-call determinism trace. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 16 +++++++++++++--- .../kernel_import_probe.cpp | 13 +++++++++++++ .../kernel_xboxkrnl_services.cpp | 18 ++++++++++++++++++ tools/run-title.mjs | 4 +++- 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 58520e39..0f2eb7cf 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -236,7 +236,8 @@ constexpr uint32_t kPollBudget = 20000; // backward branches between polls constexpr uint32_t kLocPc = 1, kLocBudget = 2, kLocResume = 3, kLocPending = 4, kLocSp = 5, kLocTmp = 6, kLocTmpB = 7, kLocTmp64 = 8, kLocTmp64B = 9, kLocTmpF64 = 10, kLocTmpV = 11, kLocAddr = 12, - kLocPage = 13, kLocHost = 14, kLocVal = 15, kFixedLocals = 16; + kLocPage = 13, kLocHost = 14, kLocVal = 15, + kLocResumed = 16, kFixedLocals = 17; class Emitter { public: @@ -1617,12 +1618,18 @@ bool Emitter::EmitSegment(uint32_t k) { if (k < real_) { const Segment& s = segments_[k]; if (s.count) { - // Total instruction counter (--max-minstr, preemption accounting). + // Total instruction counter (--max-minstr, preemption accounting, + // deterministic clock). A segment re-entered by an Asyncify rewind + // (RESTORE) was already counted when it first ran. + Get(kLocResumed); Op(oI32Eqz); + If(); I32(int32_t(counter_)); I32(int32_t(counter_)); Mem(oI64Load, 3, 0); I64(int64_t(s.count)); Op(oI64Add); Mem(oI64Store, 3, 0); + End(); } + I32(0); Set(kLocResumed); uint32_t source = 0; for (Instr* i = s.block->instr_head; i && i != s.first; i = i->next) { if (i->opcode && i->opcode->num == hir::OPCODE_SOURCE_OFFSET) source = uint32_t(i->src1.offset); @@ -1644,6 +1651,8 @@ bool Emitter::EmitSegment(uint32_t k) { UnwindCheck(k); Get(kLocTmp); Op(oI32Eqz); If(); I32(int32_t(kJitStatusFailed)); Op(oReturn); End(); + // Resumed here after a rewind: the branch target has not run yet. + I32(0); Set(kLocResumed); Get(kLocPending); Set(kLocPc); BrTo(DepthToLoop(k)); return true; @@ -1688,6 +1697,7 @@ bool Emitter::EmitSegment(uint32_t k) { } Set(i); } + I32(1); Set(kLocResumed); Get(kLocResume); Set(kLocPc); BrTo(DepthToLoop(k)); return true; @@ -1771,7 +1781,7 @@ bool Emitter::Compile(std::vector* out) { }; for (uint32_t i = 1; i < kLocTmp64; ++i) add_local(kI32); add_local(kI64); add_local(kI64); add_local(kF64); add_local(kV128); - for (int i = 0; i < 4; ++i) add_local(kI32); + for (uint32_t i = kLocAddr; i < kFixedLocals; ++i) add_local(kI32); for (uint8_t t : local_types_) add_local(t); body.u32(uint32_t(runs.size())); for (const auto& r : runs) { body.u32(r.first); body.u8(r.second); } diff --git a/src/xenia_web_bootstrap/kernel_import_probe.cpp b/src/xenia_web_bootstrap/kernel_import_probe.cpp index d4addc84..361d3a4d 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.cpp +++ b/src/xenia_web_bootstrap/kernel_import_probe.cpp @@ -86,6 +86,7 @@ KernelServiceTraceEntry* BeginKernelServiceTrace( // are logged to stderr (r360_kernel_watch_arg; tools/run-title.mjs // --watch-kernel-arg). std::array g_kernel_arg_watch{}; +uint32_t g_determinism_every = 0; void FinishKernelServiceTrace(KernelServiceTraceEntry* trace, uint32_t result, uint32_t service_status, bool handled) { @@ -93,6 +94,13 @@ void FinishKernelServiceTrace(KernelServiceTraceEntry* trace, uint32_t result, trace->result = result; trace->service_status = service_status; trace->handled = handled ? 1u : 0u; + // Determinism checkpoints: every Nth kernel call with the guest instruction + // count, so two runs can be diffed for the first divergence. + if (g_determinism_every && trace->sequence % g_determinism_every == 0) { + std::fprintf(stderr, "R360_DET seq=%u instr=%llu thread=0x%08X ord=%u.%X r3=0x%08X\n", + trace->sequence, static_cast(HIRTotalInstructions()), + r360_guest_thread_current(), trace->module_id, trace->ordinal, result); + } if (!g_kernel_arg_watch[0]) return; for (uint32_t watched : g_kernel_arg_watch) { if (!watched) continue; @@ -385,6 +393,11 @@ uint32_t r360_kernel_export_calls(uint32_t module, uint32_t ordinal) { if (module < 1 || module > 2 || ordinal >= 0x1000u) return 0; return render360::xenia_web::g_export_calls[module - 1][ordinal]; } +__attribute__((used, export_name("r360_kernel_determinism_every"))) +uint32_t r360_kernel_determinism_every(uint32_t n) { + render360::xenia_web::g_determinism_every = n; + return n; +} __attribute__((used, export_name("r360_kernel_watch_arg"))) uint32_t r360_kernel_watch_arg(uint32_t slot, uint32_t value) { if (slot >= render360::xenia_web::g_kernel_arg_watch.size()) return 0; diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 2e5526cc..22305aef 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -5345,6 +5345,7 @@ uint32_t DispatchExtendedKernelService(uint32_t module, uint32_t ordinal, // make kernel calls) while this one is suspended in a wait. const uint32_t caller_r13 = g_caller_r13, caller_lr = g_caller_lr, caller_r1 = g_caller_r1; + uint64_t idle_started_ns = 0; for (;;) { g_status = kKernelServiceSuccess; g_handled = true; @@ -5374,6 +5375,23 @@ uint32_t DispatchExtendedKernelService(uint32_t module, uint32_t ordinal, g_caller_r1 = caller_r1; continue; } + // Every guest thread is waiting (some may sleep until a deadline). On the + // console the CPU idles while vblank, audio and timers keep firing and + // eventually wake a thread: idle the guest clock, delivering interrupts, + // and retry. Ten seconds of guest time with no thread able to run is a + // real deadlock and is reported. + constexpr uint64_t kIdleStepNs = 4000000ull, kMaxIdleNs = 10000000000ull; + if (g_status == kKernelServiceWouldBlock && g_wait.reason >= 1 && + g_wait.reason <= 3 && GuestFibersActive() && !GuestInterruptActive()) { + const uint64_t now = r360_guest_clock_ns(); + if (!idle_started_ns) idle_started_ns = now; + if (now - idle_started_ns < kMaxIdleNs && GuestFiberIdle(now + kIdleStepNs)) { + g_caller_r13 = caller_r13; + g_caller_lr = caller_lr; + g_caller_r1 = caller_r1; + continue; + } + } if (g_status == kKernelServiceSuccess) { GuestFiberNoteProgress(); if (!g_thread_waits.empty()) g_thread_waits.erase(r360_guest_thread_current()); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 81eb5e0a..82b9d46c 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -47,6 +47,7 @@ function parseArgs(argv){ else if(a==='--progress')args.progress=true; else if(a==='--no-jit')args.jit=0; else if(a==='--list-files'){} + else if(a==='--det-every')args.detEvery=Number(argv[++i])>>>0; else if(a==='--xenos-trace-from')args.xenosTraceFrom=Number(argv[++i])>>>0; else if(a==='--dump-shaders')args.dumpShaders=argv[++i]; else if(a==='--deterministic')args.deterministicPs=Number(argv[++i])>>>0; @@ -88,7 +89,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; @@ -189,6 +190,7 @@ async function main(){ // Per-call/per-function stderr tracing is off by default for speed. bootstrap.exports.r360_trace_set_verbose?.(args.traceCalls?1:0); if(args.watch)bootstrap.exports.r360_debug_watch?.(args.watch); + if(args.detEvery)bootstrap.exports.r360_kernel_determinism_every?.(args.detEvery); // Guest time from executed instructions (ps per HIR instruction): replayable runs. if(args.deterministicPs)bootstrap.exports.r360_set_deterministic_clock?.(args.deterministicPs); if(args.logDraws)bootstrap.exports.r360_xenos_debug_draws?.(args.logDraws); From 4cb1e0f9c147cc419aa977108276102d15e1bf80 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 21:44:41 +0000 Subject: [PATCH 02/65] Trace ring words per WPTR kick; update progress report The CP trace now prints the ring words each kick appends, to find what D3D's command-stream worker queues ahead of the vblank-paced swaps. PROGRESS.md records the current Swap-stall findings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 51 +++++++++++-------- src/xenia_web_bootstrap/title_gpu_runtime.cpp | 10 +++- 2 files changed, 39 insertions(+), 22 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index c291264f..471599d0 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -7,29 +7,43 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie HIR executor and guest JIT. File loading finishes (`db360.textures.cmp`, ~50 MB, is read in full); 7 title threads run. - CPU: guest JIT compiles Xenia HIR to WebAssembly. Headless speed is about - 180M guest instructions/s (6B instructions in ~62 s, down from 223 s). -- Deterministic headless runs (`run-title --deterministic 1000`): identical - flags give identical results up to at least 4B instructions. + 180M guest instructions/s. +- Deterministic headless runs (`run-title --deterministic 1000`): two + identical runs match through 58.3B instructions (1098 checkpoints, same + frames, draws and GPU packets). Fixed: a JIT segment resumed after an + Asyncify rewind re-added its instruction count, which made the guest clock + depend on host timing. +- Infinite kernel waits with every thread blocked now let guest time pass + (up to 10 s) so timers and vblank can wake threads, instead of stopping as + a deadlock. - Shader path: Xenia SpirvShaderTranslator → Naga → WGSL. All shaders seen during loading compile in Chromium WebGPU (SwiftShader). -## Current blocker -At about 58B instructions the main thread blocks inside D3D `Swap` waiting -for a GPU timestamp. D3D's presentation watchdog thread then keeps -re-presenting the previous frame, and those replays rewrite older timestamps. -No new frame is presented after that (VdSwap stops at ~1540). Root cause not -yet confirmed: the open question is why the main thread's target timestamp -is never observed. Runs still diverge slightly past ~58B (kernel-call counts -differ between identical runs), which blocks exact replay of the stall. +## Current blocker (investigation, not fixed) +At about 58B instructions the main render thread blocks in D3D `Swap`, +waiting for the GPU to reach the previous frame's timestamp. Confirmed so far: +- The GPU command processor is not deadlocked. It advances one swap at a + time; each swap waits (WAIT_REG_MEM on 0xFFCF4004) for D3D's vblank handler + to release it, and that handshake works on every cycle. +- The ring has a growing backlog (~730 words pending behind the read + pointer). D3D's command-stream worker thread (0x36000201) keeps appending + small kicks faster than the vblank-paced CP drains them, so the main + thread's timestamp is never reached. +- Some replayed command buffers contain older fence values, so the fence also + moves backwards. This is what the guest wrote: the CP does not cache IBs. + +Next step: identify what the worker appends (the ring-word trace added in +this commit shows it), and why it outpaces the GPU, before changing anything. ## Tests (latest build) -- Regression runner: 59 pass, 9 fail. The 9 failures are pre-existing +- Regression runner: 59 of 68 pass. The 9 failures are pre-existing foundation tests (fpu/vmx/wasm-backend probes, guest-control, translation probe) and are unchanged by recent work. -- Xenia PPC instruction suite with JIT forced: pass (1406 functions). -- Guest JIT differential test: pass (73 instructions). -- New: `test-translation-window-consistency.mjs` fails before the window fix - and passes after it. +- Xenia PPC instruction suite with JIT forced: pass (1398 tests, 1406 + functions compiled). +- Guest JIT differential test: pass (2920 cases, 73 instructions). +- `test-translation-window-consistency.mjs` fails before the window fix and + passes after it. ## Not done yet - Interactive gameplay: not reached. @@ -37,8 +51,3 @@ differ between identical runs), which blocks exact replay of the stall. render targets, textures and resolves are not implemented. Frames come from the CPU software renderer. - Audio: XMA decoding not implemented (XMA register window only). - -## Next task -Make headless runs fully deterministic past 58B, then reproduce the Swap -stall with a watch on the fence word and dumps of the replayed indirect -buffers, and fix the earliest confirmed cause. diff --git a/src/xenia_web_bootstrap/title_gpu_runtime.cpp b/src/xenia_web_bootstrap/title_gpu_runtime.cpp index 1fc689b1..07ded2e2 100644 --- a/src/xenia_web_bootstrap/title_gpu_runtime.cpp +++ b/src/xenia_web_bootstrap/title_gpu_runtime.cpp @@ -417,8 +417,16 @@ bool WriteTitleGpuMmio(uint32_t address, uint32_t value) { switch (RegisterIndex(address)) { case kRegisterCpRbWptr: if (r360_xenos_trace_ibs(2) & 1u) { - std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X\n", + std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X words=", g_write_pointer, value, g_read_pointer, r360_guest_thread_current()); + const uint32_t capacity = RingCapacityInternal(); + for (uint32_t i = g_write_pointer, n = 0; capacity && i != value && n < 16u; + i = (i + 1u) % capacity, ++n) { + uint32_t word = 0; + ReadRingWordInternal(i, &word); + std::fprintf(stderr, "%08X ", word); + } + std::fprintf(stderr, "\n"); } g_write_pointer = value; if (g_ring_base) g_status = g_status < 2u ? 2u : g_status; From 971ad22afb61cdd8c318ef73cc158f76270108cb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 15:07:38 +0000 Subject: [PATCH 03/65] Honor PM4 type-3 predication on tiling bins Port of Xenia CommandProcessor::ExecutePacketType3: a packet with header bit 0 set runs only when (bin_select & bin_mask) != 0, and a predicated XE_SWAP never runs. D3D predicated tiling replays one IB per screen bin, so bin-specific packets (including D3D's GPU-to-CPU deferred callback requests) ran once per bin. Each extra callback queued another frame on D3D's worker thread, the ring backlog grew faster than vblank-paced swaps drained it, and Banjo-Tooie stopped presenting at ~58B instructions. With the fix Banjo-Tooie runs to 90B instructions and keeps presenting (VdSwap 2551, previously stuck at ~1542). New regression test test-xenos-predication.mjs fails before the fix and passes after. The WPTR trace also prints guest time and vblank count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../xenia-browser-bootstrap-fastlane.yml | 4 ++ .github/workflows/xenia-wasm32-bootstrap.yml | 3 + src/xenia_web_bootstrap/title_gpu_runtime.cpp | 8 ++- .../xenos_gpu_foundation.cpp | 7 +++ test-xenos-predication.mjs | 58 +++++++++++++++++++ 5 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 test-xenos-predication.mjs diff --git a/.github/workflows/xenia-browser-bootstrap-fastlane.yml b/.github/workflows/xenia-browser-bootstrap-fastlane.yml index 4d494888..c0360592 100644 --- a/.github/workflows/xenia-browser-bootstrap-fastlane.yml +++ b/.github/workflows/xenia-browser-bootstrap-fastlane.yml @@ -34,6 +34,7 @@ on: - 'test-browser-thread-scheduler.mjs' - 'test-direct-call-sparse-window.mjs' - 'test-translation-window-consistency.mjs' + - 'test-xenos-predication.mjs' - 'test-hir-load-offset-addressing.mjs' - 'test-hir-cache-control.mjs' - 'test-hir-rotate-left.mjs' @@ -268,6 +269,9 @@ jobs: - name: Verify translations do not depend on decoder-window history run: timeout 90s node ./test-translation-window-consistency.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify PM4 type-3 predication on tiling bins + run: timeout 90s node ./test-xenos-predication.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify signed PPC LOAD_OFFSET effective addresses run: timeout 90s node ./test-hir-load-offset-addressing.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm diff --git a/.github/workflows/xenia-wasm32-bootstrap.yml b/.github/workflows/xenia-wasm32-bootstrap.yml index cca776c0..057d9ce6 100644 --- a/.github/workflows/xenia-wasm32-bootstrap.yml +++ b/.github/workflows/xenia-wasm32-bootstrap.yml @@ -21,6 +21,7 @@ on: - 'test-title-gpu-runtime.mjs' - 'test-direct-call-sparse-window.mjs' - 'test-translation-window-consistency.mjs' + - 'test-xenos-predication.mjs' - 'render360-title-gpu-traffic.mjs' - 'test-xenos-semantic-foundation.mjs' - 'test-xenos-title-state-foundation.mjs' @@ -191,6 +192,8 @@ jobs: run: node ./test-direct-call-sparse-window.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm - name: Verify translations do not depend on decoder-window history run: node ./test-translation-window-consistency.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm + - name: Verify PM4 type-3 predication on tiling bins + run: node ./test-xenos-predication.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm - name: Verify locked foundations and XEX bring-up run: | node ./test-xenia-ppc-translation-probe.mjs build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm diff --git a/src/xenia_web_bootstrap/title_gpu_runtime.cpp b/src/xenia_web_bootstrap/title_gpu_runtime.cpp index 07ded2e2..60068c81 100644 --- a/src/xenia_web_bootstrap/title_gpu_runtime.cpp +++ b/src/xenia_web_bootstrap/title_gpu_runtime.cpp @@ -6,6 +6,8 @@ #include "sparse_guest_memory.h" extern "C" __attribute__((weak)) uint32_t r360_guest_thread_current() { return 0; } +extern "C" __attribute__((weak)) uint64_t r360_guest_clock_ns() { return 0; } +extern "C" __attribute__((weak)) uint32_t r360_kernel_vblank_interrupts() { return 0; } extern "C" { void r360_xenos_reset(); uint32_t r360_xenos_ring_buffer(); @@ -417,8 +419,10 @@ bool WriteTitleGpuMmio(uint32_t address, uint32_t value) { switch (RegisterIndex(address)) { case kRegisterCpRbWptr: if (r360_xenos_trace_ibs(2) & 1u) { - std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X words=", - g_write_pointer, value, g_read_pointer, r360_guest_thread_current()); + std::fprintf(stderr, "R360_XENOS_WPTR old=%u new=%u rptr=%u thread=0x%08X us=%llu vblank=%u words=", + g_write_pointer, value, g_read_pointer, r360_guest_thread_current(), + static_cast(r360_guest_clock_ns() / 1000u), + r360_kernel_vblank_interrupts()); const uint32_t capacity = RingCapacityInternal(); for (uint32_t i = g_write_pointer, n = 0; capacity && i != value && n < 16u; i = (i + 1u) % capacity, ++n) { diff --git a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp index f543d9e7..385b8d3e 100644 --- a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp +++ b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp @@ -439,6 +439,13 @@ bool ExecuteBuffer(const uint32_t* words, uint32_t word_count, uint32_t depth) { if (type != 3) { SetFault(header_index, depth, kStatusUnsupported); return false; } const uint32_t count = ((header >> 16) & 0x3FFFu) + 1u, opcode = (header >> 8) & 0x7Fu; if (count > word_count - i) { SetFault(header_index, depth, kStatusInvalid); return false; } + // CommandProcessor::ExecutePacketType3: bit 0 predicates the packet on the + // tiling bin (SET_BIN_MASK/SELECT); predicated swaps are always skipped. + // Predicated tiling replays one IB per bin, so a packet meant for a single + // bin must not run in every pass. + if ((header & 1u) && (!(g_bin_select & g_bin_mask) || opcode == kPm4XeSwap)) { + i += count; continue; + } const uint32_t* p = words + i; g_last_opcode = opcode; bool handled = true; switch (opcode) { case kPm4Nop: case kPm4MeInit: case kPm4WaitForIdle: break; diff --git a/test-xenos-predication.mjs b/test-xenos-predication.mjs new file mode 100644 index 00000000..3550e95c --- /dev/null +++ b/test-xenos-predication.mjs @@ -0,0 +1,58 @@ +// Regression: PM4 type-3 predication (Xenia CommandProcessor::ExecutePacketType3). +// A type-3 packet with header bit 0 set runs only when (bin_select & bin_mask) +// is non-zero, and a predicated XE_SWAP never runs. D3D predicated tiling +// replays one IB per screen bin; without this check every bin-specific packet +// (including D3D's GPU-to-CPU callback requests) ran once per bin. +// +// Usage: node test-xenos-predication.mjs [bootstrap.wasm] +import fs from 'node:fs'; +import { WASI } from 'node:wasi'; + +const wasmPath = process.argv[2] || 'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const module = await WebAssembly.compile(fs.readFileSync(wasmPath)); +const wasi = new WASI({ version: 'preview1', args: [], env: {}, preopens: {}, returnOnExit: true }); +const imports = wasi.getImportObject(module); +imports.env ||= {}; +imports.env.emscripten_notify_memory_growth = () => {}; +const instance = await WebAssembly.instantiate(module, imports); +wasi.initialize(instance); +const e = instance.exports; +const f = (name) => { + const fn = e[name] ?? e[`_${name}`]; + if (typeof fn !== 'function') throw new Error(`missing export ${name}`); + return fn; +}; + +const type3 = (opcode, count, predicated = false) => + ((3 << 30) | ((count - 1) << 16) | (opcode << 8) | (predicated ? 1 : 0)) >>> 0; +const kSetConstant = 0x2D, kSetBinMaskLo = 0x60, kSetBinSelectLo = 0x62, kXeSwap = 0x64; +const setConstant = (register, value, predicated) => + [type3(kSetConstant, 2, predicated), (4 << 16) | (register - 0x2000), value]; + +f('r360_xenos_reset')(); +const words = [ + type3(kSetBinMaskLo, 1), 0x1, + type3(kSetBinSelectLo, 1), 0x2, // selected bin not in mask + ...setConstant(0x2010, 0xAAAA, true), // skipped + ...setConstant(0x2011, 0xBBBB, false), // not predicated: runs + type3(kSetBinSelectLo, 1), 0x1, // selected bin in mask + ...setConstant(0x2012, 0xCCCC, true), // runs + type3(kXeSwap, 4, true), 0x50415753, 0x00123000, 1280, 720, // predicated swap: skipped +]; +const ring = new Uint32Array(e.memory.buffer, f('r360_xenos_ring_buffer')() >>> 0, words.length); +ring.set(words); +if (!(f('r360_xenos_submit')(words.length) >>> 0)) { + throw new Error(`submit failed status=${f('r360_xenos_status')() >>> 0}`); +} +const reg = (r) => f('r360_xenos_register')(r) >>> 0; +const checks = { + 'predicated packet with no matching bin is skipped': reg(0x2010) === 0, + 'unpredicated packet runs': reg(0x2011) === 0xBBBB, + 'predicated packet with a matching bin runs': reg(0x2012) === 0xCCCC, + 'predicated XE_SWAP is skipped': (f('r360_xenos_swaps')() >>> 0) === 0, +}; +for (const [name, ok] of Object.entries(checks)) { + if (!ok) throw new Error(`${name}: failed (0x2010=0x${reg(0x2010).toString(16)} 0x2011=0x${reg(0x2011).toString(16)} 0x2012=0x${reg(0x2012).toString(16)} swaps=${f('r360_xenos_swaps')() >>> 0})`); + console.log(`ok: ${name}`); +} +console.log('XENOS_PREDICATION_PASS'); From d483f05e3f3851497e5688ab0c3b43bf255db2db Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 15:57:26 +0000 Subject: [PATCH 04/65] run-title: --press to hold gamepad buttons, --frame-at to save frames mid-run --press FROM:TO:BUTTONS holds gamepad 0 buttons between two instruction counts (millions); --frame-at M1,M2:PREFIX saves PREFIX-M.png when the run passes each count. Used to verify Banjo-Tooie responds to input. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- tools/run-title.mjs | 61 +++++++++++++++++++++++++++++++-------------- 1 file changed, 42 insertions(+), 19 deletions(-) diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 82b9d46c..3ec0c4d6 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -55,6 +55,10 @@ function parseArgs(argv){ else if(a==='--watch-kernel-arg')(args.kernelWatch||=[]).push(Number(argv[++i])>>>0); else if(a==='--render-from-minstr')args.renderFrom=Number(argv[++i])>>>0; else if(a==='--frame')args.frame=argv[++i]; + // --frame-at M1,M2,...:PREFIX saves PREFIX-M.png when the run passes M million instructions. + else if(a==='--frame-at'){const v=String(argv[++i]),c=v.lastIndexOf(':');args.frameAt={at:v.slice(0,c).split(',').map(Number).sort((x,y)=>x-y),prefix:v.slice(c+1)};} + // --press FROM:TO:BUTTONS holds gamepad 0 buttons (XINPUT bits, e.g. 0x10 = START, 0x1000 = A) between FROM and TO million instructions. + else if(a==='--press'){const [from,to,buttons]=String(argv[++i]).split(':');(args.press??=[]).push({from:Number(from),to:Number(to),buttons:Number(buttons)&0xFFFF});} else if(a==='--slice-ms')args.sliceMs=Number(argv[++i])>>>0; else if(a==='--watch')args.watch=Number(argv[++i])>>>0; else if(a==='--dump-guest'){const [addr,len,file]=String(argv[++i]).split(':');(args.dumps??=[]).push({address:Number(addr)>>>0,length:Number(len)>>>0,file});} @@ -65,6 +69,39 @@ function parseArgs(argv){ return args; } + +// PNG of the last swapped frontbuffer (Xenos decode of the VdSwap fetch +// constant from guest memory), for --frame and --frame-at. +let frontbufferModule=null,runArgs={}; +const savedFrames=[]; +function saveFramePng(file){ + let frame=null; + try{frame=frontbufferModule.captureTitleFrontbuffer({bootstrap:globalThis.__r360Bootstrap});}catch(e){frame={captured:false,reason:e.message};} + if(!frame?.captured)return {file,captured:false,reason:frame?.reason}; + const {width,height,rgba}=frame; + const raw=Buffer.alloc((width*4+1)*height); + for(let y=0;y{let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;return c>>>0;}); + const crc=b=>{let c=0xFFFFFFFF;for(const x of b)c=crcTable[(c^x)&255]^(c>>>8);return (c^0xFFFFFFFF)>>>0;}; + const chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length);const td=Buffer.concat([Buffer.from(type),data]);const c=Buffer.alloc(4);c.writeUInt32BE(crc(td));return Buffer.concat([len,td,c]);}; + const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0);ihdr.writeUInt32BE(height,4);ihdr[8]=8;ihdr[9]=6; + fs.writeFileSync(file,Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',ihdr),chunk('IDAT',zlibModule.deflateSync(raw)),chunk('IEND',Buffer.alloc(0))])); + let nonBlack=0;for(let i=0;i>>0; + if(runArgs.press){ + let buttons=0;for(const p of runArgs.press)if(m>=p.from&&mat<=m&&!savedFrames.some(f=>f.at===at)); + if(pending.length){const at=pending[pending.length-1];const info=saveFramePng(`${runArgs.frameAt.prefix}-${at}.png`);for(const p of pending)savedFrames.push({at:p,actual:m,vdSwap:x.r360_title_gpu_vd_swap_calls?.()>>>0,...(p===at?info:{skipped:true})});process.stderr.write(`frame ${m}M -> ${JSON.stringify(info)}\n`);} + } +} + const hex=v=>`0x${(Number(v)>>>0).toString(16).toUpperCase().padStart(8,'0')}`; // --dump-shaders DIR: each distinct current Xenos shader as ucode and as @@ -180,6 +217,8 @@ async function main(){ } const bootstrapFile=args.bootstrap||(fs.existsSync(rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'))?rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'):rel('xenia_ppc_bootstrap.wasm')); const {instance:bootstrap,host,stderr}=await loadBootstrap(bootstrapFile,args.verbose); + runArgs=args;globalThis.__r360Bootstrap=bootstrap; + if(args.frame||args.frameAt){frontbufferModule=await import(rel('render360-title-frontbuffer.mjs'));zlibModule=await import('node:zlib');} const core=await loadCore(); const started=Date.now(); const title=await openTitle(args.input,{core,host}); @@ -211,7 +250,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined)?(s=>{const x=bootstrap.exports;if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} @@ -253,24 +292,8 @@ async function main(){ // R360_DUMP=address,bytes,file: guest bytes (sparse memory) after the run. for(const spec of (process.env.R360_DUMP||'').split(';').filter(Boolean)){const [a0,n0,file]=spec.split(',');const a=Number(a0)>>>0,n=Number(n0)>>>0,x=bootstrap.exports,out=Buffer.alloc(n); const tmp=x.r360_ppc_probe_input_buffer()>>>0;for(let i=0;i{let c=n;for(let k=0;k<8;k++)c=c&1?0xEDB88320^(c>>>1):c>>>1;return c>>>0;}); - const crc=b=>{let c=0xFFFFFFFF;for(const x of b)c=crcTable[(c^x)&255]^(c>>>8);return (c^0xFFFFFFFF)>>>0;}; - const chunk=(type,data)=>{const len=Buffer.alloc(4);len.writeUInt32BE(data.length);const td=Buffer.concat([Buffer.from(type),data]);const c=Buffer.alloc(4);c.writeUInt32BE(crc(td));return Buffer.concat([len,td,c]);}; - const ihdr=Buffer.alloc(13);ihdr.writeUInt32BE(width,0);ihdr.writeUInt32BE(height,4);ihdr[8]=8;ihdr[9]=6; - fs.writeFileSync(args.frame,Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',ihdr),chunk('IDAT',zlib.deflateSync(raw)),chunk('IEND',Buffer.alloc(0))])); - let nonBlack=0;for(let i=0;i Date: Fri, 16 Oct 2026 16:25:55 +0000 Subject: [PATCH 05/65] Progress report: Swap stall fixed, Rare intro renders Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index 471599d0..dc606518 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -19,24 +19,28 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie - Shader path: Xenia SpirvShaderTranslator → Naga → WGSL. All shaders seen during loading compile in Chromium WebGPU (SwiftShader). -## Current blocker (investigation, not fixed) -At about 58B instructions the main render thread blocks in D3D `Swap`, -waiting for the GPU to reach the previous frame's timestamp. Confirmed so far: -- The GPU command processor is not deadlocked. It advances one swap at a - time; each swap waits (WAIT_REG_MEM on 0xFFCF4004) for D3D's vblank handler - to release it, and that handshake works on every cycle. -- The ring has a growing backlog (~730 words pending behind the read - pointer). D3D's command-stream worker thread (0x36000201) keeps appending - small kicks faster than the vblank-paced CP drains them, so the main - thread's timestamp is never reached. -- Some replayed command buffers contain older fence values, so the fence also - moves backwards. This is what the guest wrote: the CP does not cache IBs. +## Fixed: Swap stall at ~58B instructions +Root cause: the command processor ignored PM4 type-3 predication. D3D +predicated tiling replays each frame's command buffer once per screen bin, +and packets meant for one bin (including D3D's GPU-to-CPU deferred callback +requests) ran in every pass. Each extra callback made D3D's worker thread +queue another frame, the ring backlog outgrew the vblank-paced swaps, and +the main thread waited forever for its frame. Ported Xenia's check +(`ExecutePacketType3`: skip predicated packets when `bin_select & bin_mask` +is 0, never run a predicated swap). -Next step: identify what the worker appends (the ring-word trace added in -this commit shows it), and why it outpaces the GPU, before changing anything. +After the fix (deterministic headless runs): +- 90B instructions: 2551 frames (VdSwap), was stuck at ~1542. +- 120B instructions: 3067 frames; the title polls the controller every + frame (XamInputGetState 4056 calls by 90B, was 20). +- Frame at 61B: the Rare logo intro renders (software renderer). + +## Current work +Verifying the title screen and that controller input changes what the game +does (`run-title --press`, `--frame-at`). ## Tests (latest build) -- Regression runner: 59 of 68 pass. The 9 failures are pre-existing +- Regression runner: 60 of 69 pass. The 9 failures are pre-existing foundation tests (fpu/vmx/wasm-backend probes, guest-control, translation probe) and are unchanged by recent work. - Xenia PPC instruction suite with JIT forced: pass (1398 tests, 1406 @@ -44,6 +48,8 @@ this commit shows it), and why it outpaces the GPU, before changing anything. - Guest JIT differential test: pass (2920 cases, 73 instructions). - `test-translation-window-consistency.mjs` fails before the window fix and passes after it. +- `test-xenos-predication.mjs` fails before the predication fix and passes + after it. ## Not done yet - Interactive gameplay: not reached. From 6a4d2f65059c7cbad13d737803b78b9b757b16e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 18:20:52 +0000 Subject: [PATCH 06/65] XAM: XamShowMessageBoxUI (Xenia headless semantics) Banjo-Tooie calls XamShowMessageBoxUI after Start is pressed on the title screen; the call was unimplemented and stopped the run. Port of Xenia xam_ui.cc headless path: the focused button is the result, bracketed by XN_SYS_UI notifications, completed synchronously or through the overlapped (ninth, stack) argument. The title, text and buttons go to the debug log and stderr (R360_MESSAGE_BOX). Kernel services test covers the synchronous and overlapped forms. (Test run pending the current rebuild.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 26 +++++++++++++++++++ test-kernel-xboxkrnl-services.mjs | 15 +++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 22305aef..cc455498 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -5145,6 +5145,32 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { BroadcastNotification(0x0Au, 1); BroadcastNotification(0x09u, 0); return X_ERROR_SUCCESS; + case xam::XamShowMessageBoxUI: { + // (user, title, text, button_count, button_ptrs, active_button, flags, + // result_ptr, overlapped): Xenia's headless path picks the focused + // button, bracketed by XN_SYS_UI. The text goes to the debug log so a + // run shows what the title asked. + uint32_t result_ptr = 0, overlapped = 0; + if (!StackArg(8, &overlapped)) return Invalid(); + result_ptr = a[7]; + std::u16string title, text; + ReadU16String(r4, &title); + ReadU16String(r5, &text); + std::string log = "XamShowMessageBoxUI \"" + Utf16ToUtf8(title) + "\": " + Utf16ToUtf8(text) + " ["; + for (uint32_t i = 0; i < a[3] && i < 8u; ++i) { + uint32_t button = 0; + std::u16string label; + if (Rd32(a[4] + i * 4u, &button)) ReadU16String(button, &label); + log += (i ? " | " : "") + Utf16ToUtf8(label); + } + log += "] -> " + std::to_string(a[5]); + DebugLog(log); + std::fprintf(stderr, "R360_MESSAGE_BOX %s\n", log.c_str()); + BroadcastNotification(0x09u, 1); + if (!result_ptr || !Wr32(result_ptr, a[5])) return Invalid(); + BroadcastNotification(0x09u, 0); + return FinishXamOverlapped(overlapped, X_ERROR_SUCCESS, 0); + } case xam::XamShowDeviceSelectorUI: { // (user, content_type, content_flags, total_requested(qword), // device_id*, overlapped): the dummy HDD, bracketed by XN_SYS_UI. diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index 616c8e1c..bb6adcc7 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -318,6 +318,21 @@ expect(k('NtWaitForSingleObjectEx',sys,1,0,P+0x8F0)===0x102,'drained listener sh const second=x('XamNotifyCreateListener',0x1,10);expect(x('XNotifyGetNext',second,0,P+0x900,P+0x904)===0&&r32(P+0x900)===0,'startup notifications must only go to the first system listener'); console.log('XAM_NOTIFY_LISTENER_XENIA=PASS'); +// --- XamShowMessageBoxUI (Xenia xam_ui.cc headless: focused button) -------------- +utf16(P+0xA00,'Title');utf16(P+0xA40,'Continue?');utf16(P+0xA80,'Yes');utf16(P+0xA90,'No'); +w32(P+0xAA0,P+0xA80);w32(P+0xAA4,P+0xA90);w32(P+0xAB0,0xFFFFFFFF); +w32(P+0xF000+0x54,0); // ninth argument (overlapped) on the caller's stack +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,1,0,P+0xAB0)===0&&status()===1,'synchronous XamShowMessageBoxUI should succeed'); +expect(r32(P+0xAB0)===1,`message box should report the focused button, got ${r32(P+0xAB0)}`); +const uiSeen=[];while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1)uiSeen.push(`${r32(P+0x900).toString(16)}:${r32(P+0x904)}`); +expect(JSON.stringify(uiSeen)===JSON.stringify(['9:1','9:0']),`message box should bracket XN_SYS_UI, got ${uiSeen}`); +w32(P+0xAB0,0xFFFFFFFF);for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===997&&status()===1,'overlapped XamShowMessageBoxUI should return ERROR_IO_PENDING'); +expect(r32(P+0xAB0)===0&&r32(P+0xAC0)===0,'overlapped message box should complete with the focused button and success'); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +w32(P+0xF000+0x54,0); +console.log('XAM_MESSAGE_BOX_XENIA=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; From 8589f712d56c6b3a4ed57abb84bc2e9cec446462 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 18:23:02 +0000 Subject: [PATCH 07/65] Kernel services test: zero the overlapped block for XamShowMessageBoxUI Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- test-kernel-xboxkrnl-services.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index bb6adcc7..ae95cef6 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -326,7 +326,7 @@ expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,1,0,P+0xAB0)===0&&sta expect(r32(P+0xAB0)===1,`message box should report the focused button, got ${r32(P+0xAB0)}`); const uiSeen=[];while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1)uiSeen.push(`${r32(P+0x900).toString(16)}:${r32(P+0x904)}`); expect(JSON.stringify(uiSeen)===JSON.stringify(['9:1','9:0']),`message box should bracket XN_SYS_UI, got ${uiSeen}`); -w32(P+0xAB0,0xFFFFFFFF);for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); +w32(P+0xAB0,0xFFFFFFFF);for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0);w32(P+0xAC0,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===997&&status()===1,'overlapped XamShowMessageBoxUI should return ERROR_IO_PENDING'); expect(r32(P+0xAB0)===0&&r32(P+0xAC0)===0,'overlapped message box should complete with the focused button and success'); while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); From ce95227b7ba294709b1b66c026a73a460a535a83 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 19:08:28 +0000 Subject: [PATCH 08/65] XamShowMessageBoxUI: let the player answer (host dialog mode) Banjo-Tooie's offline notice offers 'Connect to Xbox LIVE' (focused) and 'Continue playing offline'; Xenia's headless choice of the focused button loops back into the sign-in UI. As in Xenia's MessageBoxDialog, the player now chooses: with r360_xam_dialog_set_host_answers(1) an overlapped call returns ERROR_IO_PENDING and completes on r360_xam_dialog_answer, and a synchronous call blocks its thread (not a deadlock) until then. The browser runner shows the dialog with the title's buttons; run-title --dialog-button N answers headlessly. Kernel services test covers both forms. (Test run pending the current rebuild.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-guest-fibers.mjs | 35 +++++ .../kernel_xboxkrnl_services.cpp | 130 ++++++++++++++++-- test-kernel-xboxkrnl-services.mjs | 20 +++ tools/run-title.mjs | 10 +- 4 files changed, 182 insertions(+), 13 deletions(-) diff --git a/render360-guest-fibers.mjs b/render360-guest-fibers.mjs index 0508b899..9609eb13 100644 --- a/render360-guest-fibers.mjs +++ b/render360-guest-fibers.mjs @@ -85,8 +85,11 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,s let lastReport=0; globalThis.render360GuestRun={stop:()=>controller.abort(),signal:controller.signal}; const read=name=>{const f=bootstrap?.exports?.[name];return typeof f==='function'?(f()>>>0):0;}; + // System message boxes (XamShowMessageBoxUI) are answered by the player. + if(globalThis.document)bootstrap?.exports?.r360_xam_dialog_set_host_answers?.(1); return {guestSliceMs:sliceMs,signal:controller.signal,onGuestSlice:s=>{ pushGuestControllerState(bootstrap); + showGuestDialog(bootstrap); const t=now(); if(t-lastReport<500)return; lastReport=t; @@ -98,6 +101,38 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,s }}; } + +// Shows a pending XamShowMessageBoxUI as a page dialog (the console's system +// UI); the chosen button goes back to the title through r360_xam_dialog_answer. +let shownDialog=null; +export function showGuestDialog(bootstrap,doc=globalThis.document){ + const e=bootstrap?.exports; + if(!doc||typeof e?.r360_xam_dialog_pending!=='function')return false; + if(!(e.r360_xam_dialog_pending()>>>0)){if(shownDialog){shownDialog.remove();shownDialog=null;}return false;} + if(shownDialog)return true; + const str=w=>new TextDecoder().decode(new Uint8Array(e.memory.buffer,e.r360_xam_dialog_string_ptr(w)>>>0,e.r360_xam_dialog_string_len(w)>>>0).slice()); + const count=e.r360_xam_dialog_button_count()>>>0,focused=e.r360_xam_dialog_active_button()>>>0; + const box=doc.createElement('div'); + box.setAttribute('role','dialog');box.setAttribute('aria-modal','true'); + box.style.cssText='position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.55);z-index:9999;padding:16px'; + const panel=doc.createElement('div'); + panel.style.cssText='max-width:520px;width:100%;background:#1d1f24;color:#f2f2f2;border-radius:10px;padding:20px;font:15px/1.45 system-ui,sans-serif;box-shadow:0 10px 40px rgba(0,0,0,.5)'; + const title=doc.createElement('h2');title.textContent=str(0)||'Message';title.style.cssText='margin:0 0 8px;font-size:18px'; + const text=doc.createElement('p');text.textContent=str(1);text.style.cssText='margin:0 0 16px;white-space:pre-wrap'; + const row=doc.createElement('div');row.style.cssText='display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end'; + let focus=null; + for(let i=0;i{e.r360_xam_dialog_answer(i);box.remove();shownDialog=null;}); + if(i===focused)focus=b; + row.append(b); + } + panel.append(title,text,row);box.append(panel);doc.body.append(box); + shownDialog=box;focus?.focus(); + return true; +} + // XInput gamepad bits (XINPUT_GAMEPAD_*) for the Render360 controller keys. const XINPUT_BUTTONS={UP:0x1,DOWN:0x2,LEFT:0x4,RIGHT:0x8,START:0x10,BACK:0x20,LS:0x40,RS:0x80,LB:0x100,RB:0x200,A:0x1000,B:0x2000,X:0x4000,Y:0x8000}; diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index cc455498..df783922 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -378,6 +378,19 @@ std::vector& DebugLogEntries() { } constexpr size_t kMaxDebugLog = 64; uint32_t g_debug_log_total = 0; +// XamShowMessageBoxUI waiting for the player (host dialog mode). +struct MessageBox { + enum State { kIdle, kPending, kAnswered } state = kIdle; + uint32_t thread = 0, result_ptr = 0, overlapped = 0; + uint32_t active_button = 0, choice = 0; + std::string title, text; + std::vector buttons; +}; +MessageBox& PendingMessageBox() { + static MessageBox box; + return box; +} +bool g_dialog_host_answers = false; void DebugLog(std::string text) { if (text.size() > 512) text.resize(512); @@ -5147,29 +5160,64 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { return X_ERROR_SUCCESS; case xam::XamShowMessageBoxUI: { // (user, title, text, button_count, button_ptrs, active_button, flags, - // result_ptr, overlapped): Xenia's headless path picks the focused - // button, bracketed by XN_SYS_UI. The text goes to the debug log so a - // run shows what the title asked. - uint32_t result_ptr = 0, overlapped = 0; + // result_ptr, overlapped), bracketed by XN_SYS_UI. Without a host + // dialog this is Xenia's headless path (the focused button). With one + // (r360_xam_dialog_set_host_answers), the player chooses, as with + // Xenia's MessageBoxDialog: an overlapped call returns + // ERROR_IO_PENDING and completes on r360_xam_dialog_answer; a + // synchronous call blocks its thread until then. + uint32_t overlapped = 0; if (!StackArg(8, &overlapped)) return Invalid(); - result_ptr = a[7]; + const uint32_t result_ptr = a[7]; + if (!result_ptr) return Invalid(); + MessageBox& box = PendingMessageBox(); + if (box.state == MessageBox::kAnswered && box.thread == r360_guest_thread_current() && + !box.overlapped) { + // Retry of a blocked synchronous call: the player has answered. + const uint32_t choice = box.choice; + box = {}; + if (!Wr32(result_ptr, choice)) return Invalid(); + BroadcastNotification(0x09u, 0); + return X_ERROR_SUCCESS; + } + if (box.state != MessageBox::kIdle) { + // Another dialog is up (or this thread's is unanswered): wait. + return WouldBlock(kModuleXam, xam::XamShowMessageBoxUI, 0, 0, 1); + } std::u16string title, text; ReadU16String(r4, &title); ReadU16String(r5, &text); - std::string log = "XamShowMessageBoxUI \"" + Utf16ToUtf8(title) + "\": " + Utf16ToUtf8(text) + " ["; + box.title = Utf16ToUtf8(title); + box.text = Utf16ToUtf8(text); + box.buttons.clear(); for (uint32_t i = 0; i < a[3] && i < 8u; ++i) { uint32_t button = 0; std::u16string label; if (Rd32(a[4] + i * 4u, &button)) ReadU16String(button, &label); - log += (i ? " | " : "") + Utf16ToUtf8(label); + box.buttons.push_back(Utf16ToUtf8(label)); } - log += "] -> " + std::to_string(a[5]); + box.active_button = a[5]; + std::string log = "XamShowMessageBoxUI \"" + box.title + "\": " + box.text + " ["; + for (size_t i = 0; i < box.buttons.size(); ++i) log += (i ? " | " : "") + box.buttons[i]; + log += "] focused " + std::to_string(a[5]); DebugLog(log); std::fprintf(stderr, "R360_MESSAGE_BOX %s\n", log.c_str()); BroadcastNotification(0x09u, 1); - if (!result_ptr || !Wr32(result_ptr, a[5])) return Invalid(); - BroadcastNotification(0x09u, 0); - return FinishXamOverlapped(overlapped, X_ERROR_SUCCESS, 0); + if (!g_dialog_host_answers) { + box = {}; + if (!Wr32(result_ptr, a[5])) return Invalid(); + BroadcastNotification(0x09u, 0); + return FinishXamOverlapped(overlapped, X_ERROR_SUCCESS, 0); + } + box.state = MessageBox::kPending; + box.thread = r360_guest_thread_current(); + box.result_ptr = result_ptr; + box.overlapped = overlapped; + if (overlapped) { + if (!Wr32(overlapped, X_ERROR_IO_PENDING)) return Invalid(); + return X_ERROR_IO_PENDING; + } + return WouldBlock(kModuleXam, xam::XamShowMessageBoxUI, 0, 0, 1); } case xam::XamShowDeviceSelectorUI: { // (user, content_type, content_flags, total_requested(qword), @@ -5411,7 +5459,10 @@ uint32_t DispatchExtendedKernelService(uint32_t module, uint32_t ordinal, g_wait.reason <= 3 && GuestFibersActive() && !GuestInterruptActive()) { const uint64_t now = r360_guest_clock_ns(); if (!idle_started_ns) idle_started_ns = now; - if (now - idle_started_ns < kMaxIdleNs && GuestFiberIdle(now + kIdleStepNs)) { + // A thread waiting for the player's answer to a dialog is not + // deadlocked, however long it waits. + const bool player_wait = PendingMessageBox().state != MessageBox::kIdle; + if ((player_wait || now - idle_started_ns < kMaxIdleNs) && GuestFiberIdle(now + kIdleStepNs)) { g_caller_r13 = caller_r13; g_caller_lr = caller_lr; g_caller_r1 = caller_r1; @@ -5618,6 +5669,7 @@ void ResetExtendedKernelServices() { g_wait = {}; g_timeout_spin = {}; DebugLogEntries().clear(); + PendingMessageBox() = {}; g_debug_log_total = 0; Input() = {}; Input()[0].connected = true; @@ -5777,6 +5829,60 @@ uint32_t r360_kernel_debug_log_read(uint32_t index, uint32_t out, } // Render360 controller -> XInput gamepad state for user_index. +// Host dialog for XamShowMessageBoxUI: the page shows the pending message +// box and passes back the chosen button. +R360_WASM_EXPORT("r360_xam_dialog_set_host_answers") +uint32_t r360_xam_dialog_set_host_answers(uint32_t on) { + r360k::g_dialog_host_answers = on != 0; + return r360k::g_dialog_host_answers ? 1u : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_pending") +uint32_t r360_xam_dialog_pending() { + return r360k::PendingMessageBox().state == r360k::MessageBox::kPending ? 1u : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_button_count") +uint32_t r360_xam_dialog_button_count() { return uint32_t(r360k::PendingMessageBox().buttons.size()); } +R360_WASM_EXPORT("r360_xam_dialog_active_button") +uint32_t r360_xam_dialog_active_button() { return r360k::PendingMessageBox().active_button; } +// which: 0 title, 1 text, 2 + n button n. UTF-8, not terminated. +static const std::string* DialogString(uint32_t which) { + const auto& box = r360k::PendingMessageBox(); + if (which == 0) return &box.title; + if (which == 1) return &box.text; + if (which - 2u < box.buttons.size()) return &box.buttons[which - 2u]; + return nullptr; +} +R360_WASM_EXPORT("r360_xam_dialog_string_ptr") +uint32_t r360_xam_dialog_string_ptr(uint32_t which) { + const std::string* s = DialogString(which); + return s ? uint32_t(reinterpret_cast(s->data())) : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_string_len") +uint32_t r360_xam_dialog_string_len(uint32_t which) { + const std::string* s = DialogString(which); + return s ? uint32_t(s->size()) : 0u; +} +R360_WASM_EXPORT("r360_xam_dialog_answer") +uint32_t r360_xam_dialog_answer(uint32_t button) { + auto& box = r360k::PendingMessageBox(); + if (box.state != r360k::MessageBox::kPending || button >= box.buttons.size()) return 0; + box.choice = button; + if (box.overlapped) { + // Xenia CompleteOverlappedDeferred: result, then XN_SYS_UI off. + const uint32_t result_ptr = box.result_ptr, overlapped = box.overlapped; + box = {}; + if (!r360k::Wr32(result_ptr, button) || + !r360k::CompleteOverlappedEx(overlapped, r360k::X_ERROR_SUCCESS, 0, 0)) { + return 0; + } + r360k::BroadcastNotification(0x09u, 0); + } else { + box.state = r360k::MessageBox::kAnswered; // the blocked call's retry completes it + } + r360k::GuestFiberNoteProgress(); + return 1; +} + R360_WASM_EXPORT("r360_input_set_gamepad") uint32_t r360_input_set_gamepad(uint32_t user_index, uint32_t connected, uint32_t buttons, uint32_t triggers, diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index ae95cef6..44517e50 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -333,6 +333,26 @@ while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); w32(P+0xF000+0x54,0); console.log('XAM_MESSAGE_BOX_XENIA=PASS'); +// Host dialog mode: the player answers (Xenia MessageBoxDialog). +expect((need('r360_xam_dialog_set_host_answers')(1)>>>0)===1,'host dialog mode not enabled'); +const dlgStr=w=>Buffer.from(new Uint8Array(e.memory.buffer,need('r360_xam_dialog_string_ptr')(w)>>>0,need('r360_xam_dialog_string_len')(w)>>>0)).toString('utf8'); +for(let i=0;i<28;i+=4)w32(P+0xAC0+i,0);w32(P+0xAB0,0xFFFFFFFF);w32(P+0xF000+0x54,P+0xAC0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===997&&r32(P+0xAC0)===997,'overlapped host dialog should stay pending'); +expect((need('r360_xam_dialog_pending')()>>>0)===1&&dlgStr(0)==='Title'&&dlgStr(1)==='Continue?'&&dlgStr(3)==='No'&&(need('r360_xam_dialog_button_count')()>>>0)===2,'pending dialog not exposed to the host'); +expect(r32(P+0xAB0)===0xFFFFFFFF,'unanswered dialog must not write a result'); +expect((need('r360_xam_dialog_answer')(5)>>>0)===0,'out-of-range answer must be rejected'); +expect((need('r360_xam_dialog_answer')(1)>>>0)===1&&r32(P+0xAB0)===1&&r32(P+0xAC0)===0&&(need('r360_xam_dialog_pending')()>>>0)===0,'answer should complete the overlapped dialog with the chosen button'); +w32(P+0xF000+0x54,0);w32(P+0xAB0,0xFFFFFFFF); +x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0); +expect(status()===5&&r32(P+0xAB0)===0xFFFFFFFF,'synchronous host dialog should block until answered'); +x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0); +expect(status()===5,'retry before the answer should still block'); +expect((need('r360_xam_dialog_answer')(1)>>>0)===1,'answer to synchronous dialog rejected'); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===0&&status()===1&&r32(P+0xAB0)===1,'retry after the answer should return the chosen button'); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +need('r360_xam_dialog_set_host_answers')(0); +console.log('XAM_MESSAGE_BOX_HOST_DIALOG=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 3ec0c4d6..e7e23eb1 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -58,6 +58,8 @@ function parseArgs(argv){ // --frame-at M1,M2,...:PREFIX saves PREFIX-M.png when the run passes M million instructions. else if(a==='--frame-at'){const v=String(argv[++i]),c=v.lastIndexOf(':');args.frameAt={at:v.slice(0,c).split(',').map(Number).sort((x,y)=>x-y),prefix:v.slice(c+1)};} // --press FROM:TO:BUTTONS holds gamepad 0 buttons (XINPUT bits, e.g. 0x10 = START, 0x1000 = A) between FROM and TO million instructions. + // --dialog-button N answers every XamShowMessageBoxUI with button N (the player's choice); without it the focused button is taken (Xenia headless). + else if(a==='--dialog-button')args.dialogButton=Number(argv[++i])>>>0; else if(a==='--press'){const [from,to,buttons]=String(argv[++i]).split(':');(args.press??=[]).push({from:Number(from),to:Number(to),buttons:Number(buttons)&0xFFFF});} else if(a==='--slice-ms')args.sliceMs=Number(argv[++i])>>>0; else if(a==='--watch')args.watch=Number(argv[++i])>>>0; @@ -91,6 +93,11 @@ function saveFramePng(file){ } let zlibModule=null; function slicePressAndFrames(x){ + if(runArgs.dialogButton!==undefined&&x.r360_xam_dialog_pending?.()){ + const str=w=>Buffer.from(new Uint8Array(x.memory.buffer,x.r360_xam_dialog_string_ptr(w)>>>0,x.r360_xam_dialog_string_len(w)>>>0)).toString('utf8'); + const n=x.r360_xam_dialog_button_count()>>>0,choice=Math.min(runArgs.dialogButton,n-1); + process.stderr.write(`dialog "${str(0)}" -> ${choice} (${str(2+choice)})\n`);x.r360_xam_dialog_answer(choice); + } const m=x.r360_hir_total_instructions_millions?.()>>>0; if(runArgs.press){ let buttons=0;for(const p of runArgs.press)if(m>=p.from&&mhandoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} From e567258a2393a9e314c35a0ef562291bdfa24bbf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 19:21:49 +0000 Subject: [PATCH 09/65] Log the primary thread's exit (code, thread, caller stack) A run ends when the title's primary thread calls ExTerminateThread, as in Xenia (Emulator::WaitUntilExit). R360_PRIMARY_EXIT records why, for the Banjo-Tooie exit after 'Continue playing offline'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index df783922..94fce1ee 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -3345,6 +3345,17 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { return Terminal(kTerminalThreadExit, r3, kModuleXboxkrnl, ordinal, a); } // The primary thread leaving ends the title, as on the console. + { + uint32_t thread_id = 0, back = 0, lr = 0; + Rd32(kthread + 0x14Cu, &thread_id); + std::fprintf(stderr, "R360_PRIMARY_EXIT code=0x%08X kthread=0x%08X id=%u native=%u lr=0x%08X stack=", + r3, kthread, thread_id, native, g_caller_lr); + uint32_t fp = g_caller_r1; + for (uint32_t n = 0; n < 16 && fp && Rd32(fp, &back) && back > fp; ++n, fp = back) { + if (Rd32(back - 8u, &lr)) std::fprintf(stderr, "0x%08X ", lr); + } + std::fprintf(stderr, "\n"); + } MarkThreadExited(kthread, r3); return Terminal(kTerminalProcessExit, r3, kModuleXboxkrnl, ordinal, a); } From 87a20eced2d70cac0b3f6450278e3efaf6c6f258 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 20:31:13 +0000 Subject: [PATCH 10/65] XAM: XamUserCreateAchievementEnumerator over the title's XDBF table Banjo-Tooie creates an achievement enumerator after 'Continue playing offline'; the call was unimplemented. Port of Xenia's XStaticAchievementEnumerator: the XDBF resource named by the title id (Xenia KernelState::title_xdbf, parsed by Xenia's own xdbf_utils.cc, now in the build), English strings, X_ACHIEVEMENT_DETAILS records followed by the requested strings. XexGetModuleSection shares the resource lookup. Kernel services test covers sizing, argument checks and an empty table. (Test run pending the current rebuild.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 2 +- .../kernel_xboxkrnl_services.cpp | 139 +++++++++++++++--- test-kernel-xboxkrnl-services.mjs | 8 + 3 files changed, 126 insertions(+), 23 deletions(-) diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 043e90b8..eadcd910 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -88,7 +88,7 @@ SOURCES=( "src/xenia/cpu/compiler/compiler.cc" "src/xenia/cpu/compiler/compiler_pass.cc" "src/xenia/cpu/compiler/passes/conditional_group_pass.cc" "src/xenia/cpu/compiler/passes/conditional_group_subpass.cc" "src/xenia/cpu/compiler/passes/constant_propagation_pass.cc" "src/xenia/cpu/compiler/passes/context_promotion_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_simplification_pass.cc" "src/xenia/cpu/compiler/passes/data_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/dead_code_elimination_pass.cc" "src/xenia/cpu/compiler/passes/finalization_pass.cc" "src/xenia/cpu/compiler/passes/memory_sequence_combination_pass.cc" "src/xenia/cpu/compiler/passes/register_allocation_pass.cc" "src/xenia/cpu/compiler/passes/simplification_pass.cc" "src/xenia/cpu/compiler/passes/validation_pass.cc" "src/xenia/cpu/compiler/passes/value_reduction_pass.cc" "src/xenia/cpu/ppc/ppc_context.cc" "src/xenia/cpu/ppc/ppc_opcode_table_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_lookup_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm.cc" "src/xenia/cpu/ppc/ppc_opcode_info.cc" "src/xenia/cpu/ppc/ppc_emit_alu.cc" "src/xenia/cpu/ppc/ppc_emit_control.cc" "src/xenia/cpu/ppc/ppc_emit_memory.cc" "src/xenia/cpu/ppc/ppc_emit_fpu.cc" "src/xenia/cpu/ppc/ppc_emit_altivec.cc" "src/xenia/cpu/ppc/ppc_scanner.cc" "src/xenia/cpu/ppc/ppc_hir_builder.cc" "src/xenia/cpu/ppc/ppc_translator.cc" "src/xenia/cpu/ppc/ppc_frontend.cc" - "src/xenia/gpu/gpu_flags.cc" "src/xenia/gpu/register_file.cc" "src/xenia/gpu/ucode.cc" "src/xenia/gpu/shader.cc" "src/xenia/gpu/shader_translator.cc" "src/xenia/gpu/shader_translator_disasm.cc" "src/xenia/gpu/shader_interpreter.cc" "src/xenia/gpu/draw_util.cc" "src/xenia/gpu/registers.cc" "src/xenia/gpu/xenos.cc" "src/xenia/gpu/texture_util.cc" "src/xenia/gpu/texture_info.cc" "src/xenia/gpu/texture_info_formats.cc" "src/xenia/ui/graphics_util.cc" "src/xenia/gpu/spirv_builder.cc" "src/xenia/gpu/spirv_shader.cc" "src/xenia/gpu/spirv_shader_translator.cc" + "src/xenia/kernel/util/xdbf_utils.cc" "src/xenia/gpu/gpu_flags.cc" "src/xenia/gpu/register_file.cc" "src/xenia/gpu/ucode.cc" "src/xenia/gpu/shader.cc" "src/xenia/gpu/shader_translator.cc" "src/xenia/gpu/shader_translator_disasm.cc" "src/xenia/gpu/shader_interpreter.cc" "src/xenia/gpu/draw_util.cc" "src/xenia/gpu/registers.cc" "src/xenia/gpu/xenos.cc" "src/xenia/gpu/texture_util.cc" "src/xenia/gpu/texture_info.cc" "src/xenia/gpu/texture_info_formats.cc" "src/xenia/ui/graphics_util.cc" "src/xenia/gpu/spirv_builder.cc" "src/xenia/gpu/spirv_shader.cc" "src/xenia/gpu/spirv_shader_translator.cc" "third_party/glslang/SPIRV/SpvBuilder.cpp" ) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 94fce1ee..8155614b 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -17,6 +17,8 @@ // * Kernel pool allocations come from a sparse arena at 0x5A000000 rather than // Xenia's system heap in the 0x80000000 XEX range. +#include "xenia/kernel/util/xdbf_utils.h" +#include "xenia/base/string.h" #include "kernel_xboxkrnl_services.h" #include @@ -2406,14 +2408,60 @@ uint32_t DeleteContent(uint32_t content_type, const std::string& file_name) { return X_ERROR_FILE_NOT_FOUND; } +// XEX resource (Xenia UserModule::GetSection): name -> guest address, size. +bool FindModuleSection(const std::string& name, uint32_t* address, uint32_t* size) { + uint32_t info = 0; + if (!XexOptionalHeader(kXexHeaderResourceInfo, &info) || !info) return false; + uint32_t info_size = 0; + if (!Rd32(info, &info_size) || info_size < 4u) return false; + const uint32_t count = (info_size - 4u) / 16u; + for (uint32_t i = 0; i < count; ++i) { + const uint32_t entry = info + 4u + i * 16u; + char raw[9] = {}; + if (!Rd(entry, raw, 8) || !Rd32(entry + 8u, address) || !Rd32(entry + 12u, size)) { + return false; + } + if (name == std::string(raw)) return true; + } + return false; +} + +// Xenia KernelState::title_xdbf: the XDBF resource named by the title id. +std::vector TitleXdbf() { + uint32_t info = 0, title_id = 0; + if (!XexOptionalHeader(kXexHeaderExecutionInfo, &info) || !info || + !Rd32(info + 0x0Cu, &title_id)) { + return {}; + } + char name[9]; + std::snprintf(name, sizeof(name), "%08X", title_id); + uint32_t address = 0, size = 0; + if (!FindModuleSection(name, &address, &size) || !size || size > (16u << 20)) return {}; + std::vector data(size); + if (!Rd(address, data.data(), size)) return {}; + return data; +} + // XAM enumerators (Xenia XStaticEnumerator): fixed-size items handed out // items_per_enumerate at a time by XamEnumerate. +struct XamAchievement { + uint32_t id = 0, image_id = 0, gamerscore = 0, flags = 0; + std::u16string label, description, unachieved; +}; struct XamEnumerator { uint32_t item_size = 0; uint32_t per_enumerate = 1; uint32_t current = 0; std::vector items; - uint32_t count() const { return item_size ? uint32_t(items.size() / item_size) : 0; } + // Xenia XStaticAchievementEnumerator: X_ACHIEVEMENT_DETAILS records, then + // the strings the flags ask for (label 1, description 2, unachieved 4). + bool achievements = false; + uint32_t achievement_flags = 0; + std::vector achievement_items; + uint32_t count() const { + if (achievements) return uint32_t(achievement_items.size()); + return item_size ? uint32_t(items.size() / item_size) : 0; + } }; std::map& XamEnumerators() { static std::map enumerators; @@ -2874,27 +2922,10 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { if (!r3 || r3 != g_exe.hmodule) return X_STATUS_INVALID_HANDLE; std::string name; if (!ReadCString(r4, &name, 64)) return Invalid(); - uint32_t info = 0; - if (!XexOptionalHeader(kXexHeaderResourceInfo, &info) || !info) { - return X_STATUS_NOT_FOUND; - } - uint32_t info_size = 0; - if (!Rd32(info, &info_size) || info_size < 4u) return X_STATUS_NOT_FOUND; - const uint32_t count = (info_size - 4u) / 16u; - for (uint32_t i = 0; i < count; ++i) { - const uint32_t entry = info + 4u + i * 16u; - char raw[9] = {}; - uint32_t address = 0, size = 0; - if (!Rd(entry, raw, 8) || !Rd32(entry + 8u, &address) || - !Rd32(entry + 12u, &size)) { - return Invalid(); - } - if (name == std::string(raw)) { - if (!Wr32(r5, address) || !Wr32(r6, size)) return Invalid(); - return X_STATUS_SUCCESS; - } - } - return X_STATUS_NOT_FOUND; + uint32_t address = 0, size = 0; + if (!FindModuleSection(name, &address, &size)) return X_STATUS_NOT_FOUND; + if (!Wr32(r5, address) || !Wr32(r6, size)) return Invalid(); + return X_STATUS_SUCCESS; } // --- Time -------------------------------------------------------------- @@ -5133,6 +5164,42 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamUserCreateAchievementEnumerator: { + // (title_id, user_index, xuid, flags, offset, count, buffer_size*, + // handle*): Xenia's static enumerator over the title's XDBF + // achievement table, strings in the default user language (English). + const uint32_t flags = r6, count = a[5], size_ptr = a[6], handle_out = a[7]; + if (!count || !size_ptr || !handle_out || r4 >= 4u) return X_ERROR_INVALID_PARAMETER; + const uint32_t entry_size = 36u + ((flags & 7u) ? 464u : 0u); + if (!Wr32(size_ptr, entry_size * count)) return Invalid(); + const uint32_t handle = CreateXamEnumerator(entry_size, count, {}); + if (!handle) return X_STATUS_NO_MEMORY; + XamEnumerator& e = XamEnumerators()[handle]; + e.achievements = true; + e.achievement_flags = flags; + const std::vector xdbf = TitleXdbf(); + const xe::kernel::util::XdbfGameData db(xdbf.data(), xdbf.size()); + if (db.is_valid()) { + const auto language = db.GetExistingLanguage(xe::XLanguage::kEnglish); + auto u16 = [&](uint16_t id) { + const std::string utf8 = db.GetStringTableEntry(language, id); + return xe::to_utf16(utf8); + }; + for (const auto& entry : db.GetAchievements()) { + XamAchievement item; + item.id = entry.id; + item.label = u16(entry.label_id); + item.description = u16(entry.description_id); + item.unachieved = u16(entry.unachieved_id); + item.image_id = entry.image_id; + item.gamerscore = entry.gamerscore; + item.flags = entry.flags; + e.achievement_items.push_back(std::move(item)); + } + } + if (!Wr32(handle_out, handle)) return Invalid(); + return X_ERROR_SUCCESS; + } case xam::XamEnumerate: { // (handle, flags, buffer, buffer_length, items_returned*, overlapped) const uint32_t items_returned = a[4], overlapped = a[5]; @@ -5149,6 +5216,34 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { count = std::min(e.count() - e.current, e.per_enumerate); if (!count) { result = X_ERROR_NO_MORE_FILES; + } else if (e.achievements) { + constexpr uint32_t kDetailsSize = 36, kStringBufferSize = 464; + uint32_t string_ptr = r5 + e.per_enumerate * kDetailsSize; + uint32_t string_left = count * kStringBufferSize; + auto append = [&](const std::u16string& text) -> uint32_t { + const uint32_t bytes = uint32_t(text.size() + 1) * 2u; + if (bytes > string_left) return 0; + const uint32_t ptr = string_ptr; + for (size_t c = 0; c <= text.size(); ++c) { + if (!Wr16(ptr + uint32_t(c) * 2u, c < text.size() ? uint16_t(text[c]) : 0u)) return 0; + } + string_ptr += bytes; + string_left -= bytes; + return ptr; + }; + for (uint32_t i = 0; i < count; ++i, ++e.current) { + const XamAchievement& item = e.achievement_items[e.current]; + const uint32_t d = r5 + i * kDetailsSize; + const uint32_t f = e.achievement_flags; + if (!Wr32(d + 0, item.id) || + !Wr32(d + 4, (f & 1u) ? append(item.label) : 0u) || + !Wr32(d + 8, (f & 2u) ? append(item.description) : 0u) || + !Wr32(d + 12, (f & 4u) ? append(item.unachieved) : 0u) || + !Wr32(d + 16, item.image_id) || !Wr32(d + 20, item.gamerscore) || + !Wr32(d + 24, 0) || !Wr32(d + 28, 0) || !Wr32(d + 32, item.flags)) { + return Invalid(); + } + } } else { if (!Wr(r5, e.items.data() + size_t(e.current) * e.item_size, count * e.item_size)) { return Invalid(); diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index 44517e50..126c56a6 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -353,6 +353,14 @@ while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); need('r360_xam_dialog_set_host_answers')(0); console.log('XAM_MESSAGE_BOX_HOST_DIALOG=PASS'); +// --- XamUserCreateAchievementEnumerator (Xenia XStaticAchievementEnumerator) ------ +expect(x('XamUserCreateAchievementEnumerator',0,0,0,7,0,4,P+0xB00,P+0xB04)===0&&status()===1,'achievement enumerator not created'); +expect(r32(P+0xB00)===(36+464)*4,`achievement buffer size ${r32(P+0xB00)}`); +expect(x('XamUserCreateAchievementEnumerator',0,4,0,7,0,4,P+0xB00,P+0xB04)===0x57,'bad user index must be rejected'); +w32(P+0xB08,0xFFFFFFFF); +expect(x('XamEnumerate',r32(P+0xB04),0,P+0xC000,(36+464)*4,P+0xB08,0)===0x12&&r32(P+0xB08)===0,'title without an XDBF achievement table should enumerate nothing'); +console.log('XAM_ACHIEVEMENT_ENUMERATOR_XENIA=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; From c680146b60ffbf3a8ac56b7367c267d568808acd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 20:40:11 +0000 Subject: [PATCH 11/65] Build fix: parse XDBF in its own translation unit xenia/xbox.h defines X_STATUS_* macros that collide with the kernel service constants, so the achievement table is read by xam_xdbf.cpp (Xenia xdbf_utils) and handed over as plain structs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 1 + .../kernel_xboxkrnl_services.cpp | 31 +++++++---------- src/xenia_web_bootstrap/xam_xdbf.cpp | 33 +++++++++++++++++++ src/xenia_web_bootstrap/xam_xdbf.h | 21 ++++++++++++ 4 files changed, 66 insertions(+), 20 deletions(-) create mode 100644 src/xenia_web_bootstrap/xam_xdbf.cpp create mode 100644 src/xenia_web_bootstrap/xam_xdbf.h diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index eadcd910..ad911bbb 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -197,6 +197,7 @@ queue_cpp "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibe queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" +queue_cpp "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" queue_cpp "render360/xenos_gpu_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp" queue_cpp "render360/xenos_shader_interpreter_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp" diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 8155614b..83b94fca 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -17,8 +17,7 @@ // * Kernel pool allocations come from a sparse arena at 0x5A000000 rather than // Xenia's system heap in the 0x80000000 XEX range. -#include "xenia/kernel/util/xdbf_utils.h" -#include "xenia/base/string.h" +#include "xam_xdbf.h" #include "kernel_xboxkrnl_services.h" #include @@ -5178,24 +5177,16 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { e.achievements = true; e.achievement_flags = flags; const std::vector xdbf = TitleXdbf(); - const xe::kernel::util::XdbfGameData db(xdbf.data(), xdbf.size()); - if (db.is_valid()) { - const auto language = db.GetExistingLanguage(xe::XLanguage::kEnglish); - auto u16 = [&](uint16_t id) { - const std::string utf8 = db.GetStringTableEntry(language, id); - return xe::to_utf16(utf8); - }; - for (const auto& entry : db.GetAchievements()) { - XamAchievement item; - item.id = entry.id; - item.label = u16(entry.label_id); - item.description = u16(entry.description_id); - item.unachieved = u16(entry.unachieved_id); - item.image_id = entry.image_id; - item.gamerscore = entry.gamerscore; - item.flags = entry.flags; - e.achievement_items.push_back(std::move(item)); - } + for (auto& entry : ParseXdbfAchievements(xdbf.data(), xdbf.size())) { + XamAchievement item; + item.id = entry.id; + item.label = std::move(entry.label); + item.description = std::move(entry.description); + item.unachieved = std::move(entry.unachieved); + item.image_id = entry.image_id; + item.gamerscore = entry.gamerscore; + item.flags = entry.flags; + e.achievement_items.push_back(std::move(item)); } if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; diff --git a/src/xenia_web_bootstrap/xam_xdbf.cpp b/src/xenia_web_bootstrap/xam_xdbf.cpp new file mode 100644 index 00000000..061f6fc3 --- /dev/null +++ b/src/xenia_web_bootstrap/xam_xdbf.cpp @@ -0,0 +1,33 @@ +// Title XDBF achievement table for XamUserCreateAchievementEnumerator, +// parsed by Xenia's own xdbf_utils (kept out of kernel_xboxkrnl_services.cpp, +// whose status constants collide with xenia/xbox.h macros). +#include "xam_xdbf.h" + +#include "xenia/base/string.h" +#include "xenia/kernel/util/xdbf_utils.h" + +namespace render360::xenia_web { + +std::vector ParseXdbfAchievements(const uint8_t* data, size_t size) { + std::vector out; + const xe::kernel::util::XdbfGameData db(data, size); + if (!db.is_valid()) return out; + // Xenia xam_user.cc: cvars::user_language (default 1, English), or the + // title's default language when it has no English strings. + const auto language = db.GetExistingLanguage(xe::XLanguage::kEnglish); + auto text = [&](uint16_t id) { return xe::to_utf16(db.GetStringTableEntry(language, id)); }; + for (const auto& entry : db.GetAchievements()) { + XdbfAchievement item; + item.id = entry.id; + item.label = text(entry.label_id); + item.description = text(entry.description_id); + item.unachieved = text(entry.unachieved_id); + item.image_id = entry.image_id; + item.gamerscore = entry.gamerscore; + item.flags = entry.flags; + out.push_back(std::move(item)); + } + return out; +} + +} // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/xam_xdbf.h b/src/xenia_web_bootstrap/xam_xdbf.h new file mode 100644 index 00000000..eb947d0c --- /dev/null +++ b/src/xenia_web_bootstrap/xam_xdbf.h @@ -0,0 +1,21 @@ +#ifndef RENDER360_XAM_XDBF_H_ +#define RENDER360_XAM_XDBF_H_ + +#include +#include +#include +#include + +namespace render360::xenia_web { + +// One XDBF achievement table entry with its strings resolved. +struct XdbfAchievement { + uint32_t id = 0, image_id = 0, gamerscore = 0, flags = 0; + std::u16string label, description, unachieved; +}; + +std::vector ParseXdbfAchievements(const uint8_t* data, size_t size); + +} // namespace render360::xenia_web + +#endif // RENDER360_XAM_XDBF_H_ From 8e4c8e20a9ca8200bc49737885d432ffabaec8c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 20:42:39 +0000 Subject: [PATCH 12/65] Build fix: XamUserCreateAchievementEnumerator flags argument Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 83b94fca..94c8bd53 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -5167,7 +5167,7 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { // (title_id, user_index, xuid, flags, offset, count, buffer_size*, // handle*): Xenia's static enumerator over the title's XDBF // achievement table, strings in the default user language (English). - const uint32_t flags = r6, count = a[5], size_ptr = a[6], handle_out = a[7]; + const uint32_t flags = a[3], count = a[5], size_ptr = a[6], handle_out = a[7]; if (!count || !size_ptr || !handle_out || r4 >= 4u) return X_ERROR_INVALID_PARAMETER; const uint32_t entry_size = 36u + ((flags & 7u) ? 464u : 0u); if (!Wr32(size_ptr, entry_size * count)) return Invalid(); From 83e2241500409b781f8f068edcb96db2ed7a73b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 20:45:16 +0000 Subject: [PATCH 13/65] Build: count xam_xdbf.cpp in the expected compile results Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index ad911bbb..cbd0b4d4 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -230,7 +230,7 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 29 )) +expected=$(( ${#SOURCES[@]} + 2 + 30 )) actual=$(( passed + failed )) echo From 614a561482370ec738f75cca2607b9f54e7b0146 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 20:55:22 +0000 Subject: [PATCH 14/65] run-title: pass R360_PRIMARY_EXIT and R360_MESSAGE_BOX through Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- tools/run-title.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/run-title.mjs b/tools/run-title.mjs index e7e23eb1..fc26547d 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -133,7 +133,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; From 904612b0cf0f11ed636900308920d5670161f3a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:03:13 +0000 Subject: [PATCH 15/65] Log why a guest thread's exit ends a run (R360_FIBER_STOP) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/guest_fibers.cpp | 14 ++++++++++++-- tools/run-title.mjs | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index c29e8911..3843761f 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -1,5 +1,6 @@ #include "guest_fibers.h" +#include #include #include #include @@ -583,7 +584,12 @@ uint32_t r360_fiber_entry() { const bool returned = hir && r360_ppc_probe_correctness_status() == 3u; const bool exited = rx::FinishGuestThreadFiber( handle, returned, uint32_t(rx::GetHIRCorrectnessLastGPR(3))); - if (!exited) return hir ? hir : 1u; // stopped on a blocker: end the run + if (!exited) { + // Stopped on a blocker: end the run. + std::fprintf(stderr, "R360_FIBER_STOP fiber=%u thread=0x%08X hir=%u status=%u returned=%u\n", + rx::g_current, handle, hir, r360_ppc_probe_correctness_status(), returned ? 1u : 0u); + return hir ? hir : 1u; + } fiber.state = rx::kFiberDone; rx::GuestFiberNoteProgress(); uint32_t target = 0; @@ -593,7 +599,11 @@ uint32_t r360_fiber_entry() { target = 0; rx::g_force_fail = rx::g_fibers[0].state == rx::kFiberBlocked || rx::g_fibers[0].state == rx::kFiberReady; - if (!rx::g_force_fail) return hir ? hir : 1u; + if (!rx::g_force_fail) { + std::fprintf(stderr, "R360_FIBER_STOP no-target fiber=%u primary_state=%u\n", rx::g_current, + uint32_t(rx::g_fibers[0].state)); + return hir ? hir : 1u; + } } rx::g_target = target; rx::g_switch_pending = true; diff --git a/tools/run-title.mjs b/tools/run-title.mjs index fc26547d..406e789a 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -133,7 +133,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_STOP'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; From 517cf68fc4d1d3974d212bae2da671572633afc5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:13:13 +0000 Subject: [PATCH 16/65] Trace guest thread exits and fiber starts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/guest_fibers.cpp | 2 ++ src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp | 2 ++ tools/run-title.mjs | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index 3843761f..81318d39 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -568,6 +568,8 @@ uint32_t r360_fiber_entry() { if (rx::g_current == 0 || rx::g_current >= rx::g_fibers.size()) return 0; const uint32_t handle = rx::g_fibers[rx::g_current].thread; const uint32_t entry = r360_guest_thread_entry(handle); + std::fprintf(stderr, "R360_FIBER_START fiber=%u thread=0x%08X entry=0x%08X minstr=%llu\n", rx::g_current, + handle, entry, static_cast(rx::HIRTotalInstructions() / 1000000ull)); rx::ResetHIRCorrectnessInitialState(); rx::ClearHIRCorrectnessInitialRegisterStrings(); rx::SetHIRCorrectnessInitialGPR(1, r360_guest_thread_stack_top(handle)); diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 94c8bd53..4eaafcad 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -3370,6 +3370,8 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { const uint32_t kthread = CurrentKThread(); const uint32_t native = NativeThreadForKThread(kthread); if (native && !r360_guest_thread_external(native)) { + std::fprintf(stderr, "R360_THREAD_EXIT thread=0x%08X kthread=0x%08X code=0x%08X lr=0x%08X\n", + native, kthread, r3, g_caller_lr); MarkThreadExited(kthread, r3); r360_guest_thread_terminate(native, r3); return Terminal(kTerminalThreadExit, r3, kModuleXboxkrnl, ordinal, a); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 406e789a..a44ce40c 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -133,7 +133,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_STOP'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; From 05bc8bf9d62b6fcc118e05e4f4ed09380e0cff5c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:25:12 +0000 Subject: [PATCH 17/65] Kernel services: keep a call's state across mid-call fiber switches A service that sleeps, waits with a timeout, yields or idles switches to other guest fibers in the middle of its dispatch. Their kernel calls overwrite the shared per-call state (g_status, g_handled, g_wait, caller registers), and the resumed call returned with another thread's status. In Banjo-Tooie a thread's ExTerminateThread left g_status = terminal while another thread slept in KeDelayExecutionThread; that thread then 'stopped' and the run ended right after the offline notice. Each switch inside a service now saves and restores the call's state. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 48 +++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 4eaafcad..25024a71 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -1012,6 +1012,38 @@ void UpdateTimerByGuest(uint32_t guest) { uint32_t g_status = kKernelServiceSuccess; bool g_handled = true; +// A service that switches fibers mid-call (a timed sleep or wait, a yield, an +// idle step that runs interrupt callbacks) resumes after other guest threads +// made kernel calls of their own. The per-call state they share (status, +// handled flag, wait record, caller registers) belongs to this call again +// when it continues. +struct KernelCallState { + uint32_t status = g_status; + bool handled = g_handled; + WaitInfo wait = g_wait; + uint32_t r13 = g_caller_r13, lr = g_caller_lr, r1 = g_caller_r1; + ~KernelCallState() { + g_status = status; + g_handled = handled; + g_wait = wait; + g_caller_r13 = r13; + g_caller_lr = lr; + g_caller_r1 = r1; + } +}; +bool ServiceSleepUntil(uint64_t deadline_ns) { + KernelCallState saved; + return GuestFiberSleepUntil(deadline_ns); +} +bool ServiceIdle(uint64_t deadline_ns) { + KernelCallState saved; + return GuestFiberIdle(deadline_ns); +} +bool ServiceYield(bool blocked) { + KernelCallState saved; + return GuestFiberYield(blocked); +} + uint32_t Terminal(uint32_t kind, uint32_t code, uint32_t module, uint32_t ordinal, const uint32_t* args) { g_terminal = {}; @@ -1110,8 +1142,8 @@ uint32_t WaitObjects(uint32_t module, uint32_t ordinal, g_timeout_spin = {}; return X_STATUS_TIMEOUT; } - if (GuestFiberSleepUntil(deadline_ns)) continue; - if (GuestFiberIdle(deadline_ns)) continue; + if (ServiceSleepUntil(deadline_ns)) continue; + if (ServiceIdle(deadline_ns)) continue; } // Without guest fibers: the old synchronous model (one turn, then elapse). if (timeout && attempt == 0 && GuestFibersActive()) { @@ -1127,7 +1159,7 @@ uint32_t WaitObjects(uint32_t module, uint32_t ordinal, poll.caller_lr = g_caller_lr; ++poll.count; } - if (timeout && attempt == 0 && GuestFiberYield(false)) continue; + if (timeout && attempt == 0 && ServiceYield(false)) continue; if (timeout) { // No other guest thread can signal during this synchronous kernel call, so // a bounded wait elapses. Detect a guest spinning on the same unsignalled @@ -3317,22 +3349,22 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { if (GuestFibersActive() && !GuestInterruptActive()) { const uint64_t deadline = TimeoutDeadlineNs(interval); if (deadline <= r360_guest_clock_ns()) { - GuestFiberYield(false); + ServiceYield(false); return X_STATUS_SUCCESS; } while (r360_guest_clock_ns() < deadline) { - if (GuestFiberSleepUntil(deadline)) continue; - if (!GuestFiberIdle(deadline)) break; + if (ServiceSleepUntil(deadline)) continue; + if (!ServiceIdle(deadline)) break; } if (r360_guest_clock_ns() >= deadline) return X_STATUS_SUCCESS; } AdvanceVirtualTime(interval); - GuestFiberYield(false); + ServiceYield(false); return X_STATUS_SUCCESS; } case kx::NtYieldExecution: GuestFiberNoteProgress(); - GuestFiberYield(false); + ServiceYield(false); return X_STATUS_SUCCESS; // --- Threads ----------------------------------------------------------- From 41d25d1b2cac16b6cdc16c7954dac6e45937b86b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:31:29 +0000 Subject: [PATCH 18/65] Kernel services: per-call state is fiber-local, not save/restore wrappers The save/restore wrappers around mid-call fiber switches crashed the core (out-of-bounds access in KeDelayExecutionThread at ~51.5B). Use the fiber system's own mechanism instead: g_status, g_handled, g_wait and the caller registers are R360_FIBER_LOCAL, swapped with each fiber and saved around interrupt callbacks, so another thread's kernel calls no longer overwrite a call that is sleeping or waiting. (Banjo-Tooie verification run pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 67 ++++++------------- 1 file changed, 21 insertions(+), 46 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 25024a71..50e2c137 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -43,6 +43,7 @@ extern "C" __attribute__((weak)) uint32_t r360_guest_clock_deterministic() { ret #include #include "guest_fibers.h" +#include "hir_correctness_executor.h" #include "kernel_export_ordinals.h" // Weak defaults for builds that link the kernel services without the HIR @@ -314,9 +315,10 @@ struct ExecutableModule { }; ExecutableModule g_exe; uint32_t g_process_info_block = 0; -uint32_t g_caller_r13 = 0; -uint32_t g_caller_lr = 0; -uint32_t g_caller_r1 = 0; +// The calling guest thread's r13/LR/r1 for the current service (per fiber). +R360_FIBER_LOCAL uint32_t g_caller_r13 = 0; +R360_FIBER_LOCAL uint32_t g_caller_lr = 0; +R360_FIBER_LOCAL uint32_t g_caller_r1 = 0; uint32_t g_irql = 0; uint32_t g_next_thread_id = 2; // The primary thread is thread id 1. uint64_t g_virtual_time_100ns = 0; @@ -350,7 +352,7 @@ struct WaitInfo { uint32_t object_type = 0; uint32_t reason = 0; // 1 infinite wait, 2 spinning bounded wait, 3 lock. }; -WaitInfo g_wait; +R360_FIBER_LOCAL WaitInfo g_wait; // Last blocking wait of each guest thread suspended in a fiber yield, with // the guest return address (diagnostics: r360_kernel_thread_wait). struct ThreadWait { @@ -1009,40 +1011,13 @@ void UpdateTimerByGuest(uint32_t guest) { // --------------------------------------------------------------------------- // Service outcome plumbing. -uint32_t g_status = kKernelServiceSuccess; -bool g_handled = true; - -// A service that switches fibers mid-call (a timed sleep or wait, a yield, an -// idle step that runs interrupt callbacks) resumes after other guest threads -// made kernel calls of their own. The per-call state they share (status, -// handled flag, wait record, caller registers) belongs to this call again -// when it continues. -struct KernelCallState { - uint32_t status = g_status; - bool handled = g_handled; - WaitInfo wait = g_wait; - uint32_t r13 = g_caller_r13, lr = g_caller_lr, r1 = g_caller_r1; - ~KernelCallState() { - g_status = status; - g_handled = handled; - g_wait = wait; - g_caller_r13 = r13; - g_caller_lr = lr; - g_caller_r1 = r1; - } -}; -bool ServiceSleepUntil(uint64_t deadline_ns) { - KernelCallState saved; - return GuestFiberSleepUntil(deadline_ns); -} -bool ServiceIdle(uint64_t deadline_ns) { - KernelCallState saved; - return GuestFiberIdle(deadline_ns); -} -bool ServiceYield(bool blocked) { - KernelCallState saved; - return GuestFiberYield(blocked); -} +// Per-call service state is per guest thread: a service that sleeps, waits +// with a timeout, yields or idles switches fibers mid-call, and the other +// threads' kernel calls must not overwrite it (R360_FIBER_LOCAL: swapped +// with the fiber, saved around interrupt callbacks). +R360_FIBER_LOCAL uint32_t g_status = kKernelServiceSuccess; +R360_FIBER_LOCAL bool g_handled = true; + uint32_t Terminal(uint32_t kind, uint32_t code, uint32_t module, uint32_t ordinal, const uint32_t* args) { @@ -1142,8 +1117,8 @@ uint32_t WaitObjects(uint32_t module, uint32_t ordinal, g_timeout_spin = {}; return X_STATUS_TIMEOUT; } - if (ServiceSleepUntil(deadline_ns)) continue; - if (ServiceIdle(deadline_ns)) continue; + if (GuestFiberSleepUntil(deadline_ns)) continue; + if (GuestFiberIdle(deadline_ns)) continue; } // Without guest fibers: the old synchronous model (one turn, then elapse). if (timeout && attempt == 0 && GuestFibersActive()) { @@ -1159,7 +1134,7 @@ uint32_t WaitObjects(uint32_t module, uint32_t ordinal, poll.caller_lr = g_caller_lr; ++poll.count; } - if (timeout && attempt == 0 && ServiceYield(false)) continue; + if (timeout && attempt == 0 && GuestFiberYield(false)) continue; if (timeout) { // No other guest thread can signal during this synchronous kernel call, so // a bounded wait elapses. Detect a guest spinning on the same unsignalled @@ -3349,22 +3324,22 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { if (GuestFibersActive() && !GuestInterruptActive()) { const uint64_t deadline = TimeoutDeadlineNs(interval); if (deadline <= r360_guest_clock_ns()) { - ServiceYield(false); + GuestFiberYield(false); return X_STATUS_SUCCESS; } while (r360_guest_clock_ns() < deadline) { - if (ServiceSleepUntil(deadline)) continue; - if (!ServiceIdle(deadline)) break; + if (GuestFiberSleepUntil(deadline)) continue; + if (!GuestFiberIdle(deadline)) break; } if (r360_guest_clock_ns() >= deadline) return X_STATUS_SUCCESS; } AdvanceVirtualTime(interval); - ServiceYield(false); + GuestFiberYield(false); return X_STATUS_SUCCESS; } case kx::NtYieldExecution: GuestFiberNoteProgress(); - ServiceYield(false); + GuestFiberYield(false); return X_STATUS_SUCCESS; // --- Threads ----------------------------------------------------------- From bbcc073ed8b6e7dbf03147a2a8b71d8a02178ed0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:36:29 +0000 Subject: [PATCH 19/65] Bisect: only the service status is fiber-local The fiber-local version still crashes at ~51.6B (out-of-bounds in KeDelayExecutionThread), like the save/restore wrappers. Narrowing down which preserved field causes it: the wait record and caller registers go back to shared state for this test build. (Verification run pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 50e2c137..6c411107 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -315,10 +315,9 @@ struct ExecutableModule { }; ExecutableModule g_exe; uint32_t g_process_info_block = 0; -// The calling guest thread's r13/LR/r1 for the current service (per fiber). -R360_FIBER_LOCAL uint32_t g_caller_r13 = 0; -R360_FIBER_LOCAL uint32_t g_caller_lr = 0; -R360_FIBER_LOCAL uint32_t g_caller_r1 = 0; +uint32_t g_caller_r13 = 0; +uint32_t g_caller_lr = 0; +uint32_t g_caller_r1 = 0; uint32_t g_irql = 0; uint32_t g_next_thread_id = 2; // The primary thread is thread id 1. uint64_t g_virtual_time_100ns = 0; @@ -352,7 +351,7 @@ struct WaitInfo { uint32_t object_type = 0; uint32_t reason = 0; // 1 infinite wait, 2 spinning bounded wait, 3 lock. }; -R360_FIBER_LOCAL WaitInfo g_wait; +WaitInfo g_wait; // Last blocking wait of each guest thread suspended in a fiber yield, with // the guest return address (diagnostics: r360_kernel_thread_wait). struct ThreadWait { From 09f5d789842972dec89c2834fea20f27c57a685a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:41:43 +0000 Subject: [PATCH 20/65] Trap report: keep the wasm stack of a core trap Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-trap-report.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/render360-trap-report.mjs b/render360-trap-report.mjs index f06ee027..19208c56 100644 --- a/render360-trap-report.mjs +++ b/render360-trap-report.mjs @@ -87,7 +87,7 @@ export function wrapCoreTrap(error,bootstrap,{onPoisoned=null,context=''}={}){ const wrapped=new Error(describeTrap(report,error)+' [FAIL_CLOSED_CORE_TRAP]'); wrapped.code='R360_CORE_TRAP'; wrapped.cause=error; - wrapped.render360={kind:'core-trap',context,trap:report,original:String(error?.message||error)}; + wrapped.render360={kind:'core-trap',context,trap:report,original:String(error?.message||error),stack:String(error?.stack||'').split('\n').slice(0,40).join('\n')}; return wrapped; } From 277806595ae578abbcc61e9709fd78f1ac408541 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 21:47:17 +0000 Subject: [PATCH 21/65] Thread exit: reset the service status it leaves behind Making the per-call kernel state fiber-local (or saving and restoring it around switches) crashed Banjo-Tooie at ~51.6B inside WaitObjects, so it is shared again. The bug actually observed is narrower: a thread's ExTerminateThread leaves g_status = terminal, and the fiber that resumes next, in the middle of a sleep, returned it as its own. FinishGuestThread Fiber now resets the status and handled flag when it retires the thread. (Verification run pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 6c411107..bda877b8 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -43,7 +43,6 @@ extern "C" __attribute__((weak)) uint32_t r360_guest_clock_deterministic() { ret #include #include "guest_fibers.h" -#include "hir_correctness_executor.h" #include "kernel_export_ordinals.h" // Weak defaults for builds that link the kernel services without the HIR @@ -1010,12 +1009,8 @@ void UpdateTimerByGuest(uint32_t guest) { // --------------------------------------------------------------------------- // Service outcome plumbing. -// Per-call service state is per guest thread: a service that sleeps, waits -// with a timeout, yields or idles switches fibers mid-call, and the other -// threads' kernel calls must not overwrite it (R360_FIBER_LOCAL: swapped -// with the fiber, saved around interrupt callbacks). -R360_FIBER_LOCAL uint32_t g_status = kKernelServiceSuccess; -R360_FIBER_LOCAL bool g_handled = true; +uint32_t g_status = kKernelServiceSuccess; +bool g_handled = true; uint32_t Terminal(uint32_t kind, uint32_t code, uint32_t module, @@ -5746,8 +5741,13 @@ void DeliverGuestInterruptsNow() { bool FinishGuestThreadFiber(uint32_t native, bool returned, uint32_t exit_code) { if (g_terminal.kind == kTerminalThreadExit) { + // ExTerminateThread already marked and terminated it. The service state + // it left (terminal) is not the next fiber's: a thread resuming in the + // middle of its own call (a sleep or timed wait) must not inherit it. g_terminal = {}; - return true; // ExTerminateThread already marked and terminated it + g_status = kKernelServiceSuccess; + g_handled = true; + return true; } if (!returned) return false; MarkThreadExited(r360_guest_thread_kthread(native), exit_code); From 00d118a4781922c9437425699daccc39970cfa4f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 22:01:18 +0000 Subject: [PATCH 22/65] XexGetProcedureAddress and XamContentAggregateCreateEnumerator Banjo-Tooie looks up XamContentAggregateCreateEnumerator (XAM ordinal 0x279) at run time after the offline notice. Ports from Xenia: - XexGetProcedureAddress: for xboxkrnl/XAM, one guest trampoline per export (KernelModule::GetProcAddressByOrdinal), registered as an import thunk so calls reach the same service dispatcher as static imports; unimplemented exports still fail closed when called. Name lookups and executable exports report the entry point as not found. - XamContentAggregateCreateEnumerator: XCONTENT_AGGREGATE_DATA items for the running title's HDD packages. Kernel services test covers both. (Test and title runs pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 73 +++++++++++++++++++ test-kernel-xboxkrnl-services.mjs | 20 +++++ 2 files changed, 93 insertions(+) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index bda877b8..f4444e05 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -43,6 +43,7 @@ extern "C" __attribute__((weak)) uint32_t r360_guest_clock_deterministic() { ret #include #include "guest_fibers.h" +#include "kernel_import_probe.h" #include "kernel_export_ordinals.h" // Weak defaults for builds that link the kernel services without the HIR @@ -141,6 +142,7 @@ constexpr uint32_t X_ERROR_NOT_FOUND = 0x00000490u; constexpr uint32_t X_ERROR_NO_SUCH_USER = 0x00000525u; constexpr uint32_t X_E_SUCCESS = 0x00000000u; constexpr uint32_t X_E_INVALIDARG = 0x80070057u; +constexpr uint32_t X_STATUS_DRIVER_ENTRYPOINT_NOT_FOUND = 0xC0000263u; constexpr uint32_t X_E_NO_SUCH_USER = 0x80070525u; constexpr uint32_t X_ERROR_INSUFFICIENT_BUFFER = 0x0000007Au; constexpr uint32_t X_ERROR_IO_INCOMPLETE = 0x000003E4u; @@ -1321,6 +1323,27 @@ uint32_t KernelModuleHandle(uint32_t index) { return g_kernel_module_handles[index]; } +// Xenia KernelModule::GetProcAddressByOrdinal: one guest trampoline per +// xboxkrnl/XAM export, made on first request. Here it is a registered import +// thunk, so calls through it reach the same service dispatcher as static +// imports (an unimplemented export still fails closed when it is called). +std::map& ProcTrampolines() { // (module << 16 | ordinal) -> guest address + static std::map trampolines; + return trampolines; +} +uint32_t KernelExportTrampoline(uint32_t module_id, uint32_t ordinal) { + const uint32_t key = (module_id << 16) | (ordinal & 0xFFFFu); + auto it = ProcTrampolines().find(key); + if (it != ProcTrampolines().end()) return it->second; + const uint32_t address = PoolAlloc(8u, 8u); + if (!address || !Wr32(address, 0x4E800020u) || !Wr32(address + 4u, 0x4E800020u) || // blr + !RegisterKernelImportThunk(address, module_id, ordinal, false, 0)) { + return 0; + } + ProcTrampolines()[key] = address; + return address; +} + std::map& ThreadPriority() { static std::map priority; return priority; @@ -2918,6 +2941,28 @@ uint32_t DispatchXboxkrnl(uint32_t ordinal, const uint32_t* a) { if (r4 && !Wr32(r4, hmodule)) return Invalid(); return hmodule ? X_ERROR_SUCCESS : X_ERROR_NOT_FOUND; } + case kx::XexGetProcedureAddress: { + // (hmodule, ordinal or name, function_ptr*): Xenia + // xboxkrnl_modules.cc. Kernel modules hand out export trampolines. + if (!r5) return Invalid(); + const bool by_name = (r4 & 0xFFFF0000u) != 0; + uint32_t module_id = 0; + if (r3 && r3 == KernelModuleHandle(0)) module_id = kModuleXboxkrnl; + if (r3 && r3 == KernelModuleHandle(1)) module_id = kModuleXam; + if (!module_id && r3 && r3 != g_exe.hmodule) return X_STATUS_INVALID_HANDLE; + uint32_t address = 0; + if (module_id && !by_name) address = KernelExportTrampoline(module_id, r4); + if (!address) { + std::string name; + if (by_name) ReadCString(r4, &name, 128); + DebugLog("XexGetProcedureAddress not found: module " + std::to_string(module_id) + + (by_name ? " name " + name : " ordinal " + std::to_string(r4))); + if (!Wr32(r5, 0)) return Invalid(); + return X_STATUS_DRIVER_ENTRYPOINT_NOT_FOUND; + } + if (!Wr32(r5, address)) return Invalid(); + return X_STATUS_SUCCESS; + } case kx::XexGetModuleSection: { if (!r3 || r3 != g_exe.hmodule) return X_STATUS_INVALID_HANDLE; std::string name; @@ -5142,6 +5187,33 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { if (!Wr32(a[4], handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamContentAggregateCreateEnumerator: { + // (xuid (qword), device_id, content_type, unknown, handle*): Xenia + // xam_content_aggregate.cc. XCONTENT_AGGREGATE_DATA items (0x148: the + // content data, a zero qword, the title id) for the HDD packages of + // the running title. Xenia's ODD test adds packages under + // game:\Content\0000000000000000, which title packages do not have. + const uint32_t device_id = r4, content_type = r5, handle_out = a[4]; + if ((device_id && !FindDummyDevice(device_id)) || !handle_out) return X_E_INVALIDARG; + uint32_t info = 0, title_id = 0; + if (XexOptionalHeader(kXexHeaderExecutionInfo, &info) && info) Rd32(info + 0x0Cu, &title_id); + std::vector items; + if (!device_id || device_id == 1u) { + for (const auto& package : ContentPackages()) { + if (package.content_type != content_type) continue; + std::array item{}; + std::copy(package.data.begin(), package.data.end(), item.begin()); + item[0] = 0; item[1] = 0; item[2] = 0; item[3] = 1; // device_id = HDD + item[0x13C] = uint8_t(title_id >> 24); item[0x13D] = uint8_t(title_id >> 16); + item[0x13E] = uint8_t(title_id >> 8); item[0x13F] = uint8_t(title_id); + items.insert(items.end(), item.begin(), item.end()); + } + } + const uint32_t handle = CreateXamEnumerator(0x148u, 1u, std::move(items)); + if (!handle) return X_STATUS_NO_MEMORY; + if (!Wr32(handle_out, handle)) return Invalid(); + return X_ERROR_SUCCESS; + } case xam::XamContentCreateEnumerator: { // (user, device_id, content_type, content_flags, items_per_enumerate, // buffer_size*, handle*) @@ -5775,6 +5847,7 @@ void ResetExtendedKernelServices() { g_timeout_spin = {}; DebugLogEntries().clear(); PendingMessageBox() = {}; + ProcTrampolines().clear(); g_debug_log_total = 0; Input() = {}; Input()[0].connected = true; diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index 126c56a6..5af97560 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -361,6 +361,26 @@ w32(P+0xB08,0xFFFFFFFF); expect(x('XamEnumerate',r32(P+0xB04),0,P+0xC000,(36+464)*4,P+0xB08,0)===0x12&&r32(P+0xB08)===0,'title without an XDBF achievement table should enumerate nothing'); console.log('XAM_ACHIEVEMENT_ENUMERATOR_XENIA=PASS'); +// --- XexGetProcedureAddress (Xenia KernelModule::GetProcAddressByOrdinal) ------- +ascii(P+0xB40,'xam.xex'); +expect(k('XexGetModuleHandle',P+0xB40,P+0xB60)===0&&r32(P+0xB60)!==0,'xam.xex module handle missing'); +const xamModule=r32(P+0xB60); +expect(k('XexGetProcedureAddress',xamModule,0x279,P+0xB64)===0&&status()===1&&r32(P+0xB64)!==0,'XAM export trampoline not created'); +const trampoline=r32(P+0xB64); +expect(k('XexGetProcedureAddress',xamModule,0x279,P+0xB68)===0&&r32(P+0xB68)===trampoline,'repeated lookup should return the same trampoline'); +expect(k('XexGetProcedureAddress',xamModule,0x2CA,P+0xB68)===0&&r32(P+0xB68)!==trampoline,'another ordinal should get its own trampoline'); +expect(k('XexGetProcedureAddress',0x12345678,0x279,P+0xB68)===0xC0000008,'bad module handle must be rejected'); +ascii(P+0xB80,'XamSomething'); +expect(k('XexGetProcedureAddress',xamModule,P+0xB80,P+0xB68)===0xC0000263&&r32(P+0xB68)===0,'lookup by name should report the entry point as not found'); +console.log('XEX_GET_PROCEDURE_ADDRESS_XENIA=PASS'); + +// --- XamContentAggregateCreateEnumerator (Xenia xam_content_aggregate.cc) --------- +expect(x('XamContentAggregateCreateEnumerator',0,0,1,0,P+0xBA0)===0&&status()===1,'aggregate content enumerator not created'); +expect(x('XamContentAggregateCreateEnumerator',0,99,1,0,P+0xBA4)===0x80070057,'unknown device must be rejected'); +w32(P+0xBA8,0xFFFFFFFF); +expect(x('XamEnumerate',r32(P+0xBA0),0,P+0xC000,0x148,P+0xBA8,0)===0x12&&r32(P+0xBA8)===0,'no saved content should enumerate nothing'); +console.log('XAM_CONTENT_AGGREGATE_XENIA=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; From c5d592d796d27d4ac7b3caca932b845006580fda Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 22:13:02 +0000 Subject: [PATCH 23/65] XAM enumerators get guest X_KENUMERATOR objects Banjo-Tooie calls XamGetPrivateEnumStructureFromHandle on its aggregate content enumerator. As in Xenia XEnumerator::Initialize, every XAM enumerator now has a guest X_KENUMERATOR (app id, open/close messages, user, items per enumerate, flags) with each enumerator's Xenia values; the aggregate one carries X_KENUMERATOR_CONTENT_AGGREGATE (XEN signature, handle). XamGetPrivateEnumStructureFromHandle returns it and takes a reference. Kernel services test covers the layout. (Test and title runs pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 54 +++++++++++++++++-- test-kernel-xboxkrnl-services.mjs | 5 ++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index f4444e05..be464e69 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -2490,10 +2490,27 @@ std::map& XamEnumerators() { static std::map enumerators; return enumerators; } +// Xenia XEnumerator::Initialize: the guest-visible X_KENUMERATOR (app id, +// open/close messages, user, items per enumerate, flags), optionally followed +// by an extra block (XamGetPrivateEnumStructureFromHandle returns it). +struct XamEnumeratorInit { + uint32_t user_index = 0xFF, app_id = 0xFE, open_message = 0, close_message = 0; + uint32_t flags = 0, extra_size = 0; +}; uint32_t CreateXamEnumerator(uint32_t item_size, uint32_t per_enumerate, - std::vector items) { - const uint32_t handle = CreateObject(ObjectType::kEnumerator, 0, false); + std::vector items, const XamEnumeratorInit& init = {}, + uint32_t* guest_out = nullptr) { + const uint32_t guest = PoolAlloc(0x18u + init.extra_size, 8u); + if (!guest) return 0; + for (uint32_t i = 0; i < 0x18u + init.extra_size; i += 4) Wr32(guest + i, 0); + if (!Wr32(guest + 0x00u, init.app_id) || !Wr32(guest + 0x04u, init.open_message) || + !Wr32(guest + 0x08u, init.close_message) || !Wr32(guest + 0x0Cu, init.user_index) || + !Wr32(guest + 0x10u, per_enumerate ? per_enumerate : 1u) || !Wr32(guest + 0x14u, init.flags)) { + return 0; + } + const uint32_t handle = CreateObject(ObjectType::kEnumerator, guest, true); if (!handle) return 0; + if (guest_out) *guest_out = guest; XamEnumerator e; e.item_size = item_size; e.per_enumerate = per_enumerate ? per_enumerate : 1u; @@ -5209,11 +5226,30 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { items.insert(items.end(), item.begin(), item.end()); } } - const uint32_t handle = CreateXamEnumerator(0x148u, 1u, std::move(items)); + // Initialize(0xFF, 0xFE, 0x2000E, 0x20010, 0) with an + // X_KENUMERATOR_CONTENT_AGGREGATE (kXObjSignature 'XEN\0', handle). + XamEnumeratorInit init; + init.open_message = 0x2000Eu; + init.close_message = 0x20010u; + init.extra_size = 8u; + uint32_t guest = 0; + const uint32_t handle = CreateXamEnumerator(0x148u, 1u, std::move(items), init, &guest); if (!handle) return X_STATUS_NO_MEMORY; + if (!Wr32(guest + 0x18u, 0x58454E00u) || !Wr32(guest + 0x1Cu, handle)) return Invalid(); if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamGetPrivateEnumStructureFromHandle: { + // (handle, object_ptr*): Xenia xam_enum.cc. The caller takes a + // reference (released by ObDereferenceObject). + KernelObject* object = ResolveHandle(r3); + if (!object || object->type != ObjectType::kEnumerator || !object->guest) { + return X_STATUS_INVALID_HANDLE; + } + ++object->handle_count; + if (r4 && !Wr32(r4, object->guest)) return Invalid(); + return X_STATUS_SUCCESS; + } case xam::XamContentCreateEnumerator: { // (user, device_id, content_type, content_flags, items_per_enumerate, // buffer_size*, handle*) @@ -5233,7 +5269,10 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { items.insert(items.end(), item.begin(), item.end()); } } - const uint32_t handle = CreateXamEnumerator(0x134u, per, std::move(items)); + XamEnumeratorInit init; // Xenia xam_content.cc: Initialize(0xFF, 0xFE, 0x20005, 0x20007, 0) + init.open_message = 0x20005u; + init.close_message = 0x20007u; + const uint32_t handle = CreateXamEnumerator(0x134u, per, std::move(items), init); if (!handle) return X_STATUS_NO_MEMORY; if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; @@ -5246,7 +5285,12 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { if (!count || !size_ptr || !handle_out || r4 >= 4u) return X_ERROR_INVALID_PARAMETER; const uint32_t entry_size = 36u + ((flags & 7u) ? 464u : 0u); if (!Wr32(size_ptr, entry_size * count)) return Invalid(); - const uint32_t handle = CreateXamEnumerator(entry_size, count, {}); + XamEnumeratorInit init; // Xenia: Initialize(user_index, 0xFB, 0xB000A, 0xB000B, 0) + init.user_index = r4; + init.app_id = 0xFBu; + init.open_message = 0xB000Au; + init.close_message = 0xB000Bu; + const uint32_t handle = CreateXamEnumerator(entry_size, count, {}, init); if (!handle) return X_STATUS_NO_MEMORY; XamEnumerator& e = XamEnumerators()[handle]; e.achievements = true; diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index 5af97560..a51ae4cf 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -379,6 +379,11 @@ expect(x('XamContentAggregateCreateEnumerator',0,0,1,0,P+0xBA0)===0&&status()=== expect(x('XamContentAggregateCreateEnumerator',0,99,1,0,P+0xBA4)===0x80070057,'unknown device must be rejected'); w32(P+0xBA8,0xFFFFFFFF); expect(x('XamEnumerate',r32(P+0xBA0),0,P+0xC000,0x148,P+0xBA8,0)===0x12&&r32(P+0xBA8)===0,'no saved content should enumerate nothing'); +expect(x('XamGetPrivateEnumStructureFromHandle',r32(P+0xBA0),P+0xBAC)===0&&status()===1,'private enum structure lookup failed'); +const enumObject=r32(P+0xBAC); +expect(r32(enumObject)===0xFE&&r32(enumObject+4)===0x2000E&&r32(enumObject+8)===0x20010&&r32(enumObject+0xC)===0xFF&&r32(enumObject+0x10)===1,'X_KENUMERATOR header mismatch'); +expect(r32(enumObject+0x18)===0x58454E00&&r32(enumObject+0x1C)===r32(P+0xBA0),'aggregate extra block should hold the XEN signature and handle'); +expect(x('XamGetPrivateEnumStructureFromHandle',0x12345678,P+0xBAC)===0xC0000008,'bad enumerator handle must be rejected'); console.log('XAM_CONTENT_AGGREGATE_XENIA=PASS'); // --- Diagnostics / boundaries ------------------------------------------------------ From 88700037d5510bc887fa6d8bea05bc5f679a9c18 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 22:24:55 +0000 Subject: [PATCH 24/65] XAM: XamTaskSchedule and XamTaskShouldExit Banjo-Tooie schedules a XAM task after the offline notice. Port of Xenia xam_task.cc: the callback runs with the message on a new guest thread (executable stack size, 16 KiB minimum) and the task handle is 12345; XamTaskShouldExit returns 0. Kernel services test covers both. (Test and title runs pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 24 +++++++++++++++++++ test-kernel-xboxkrnl-services.mjs | 7 ++++++ 2 files changed, 31 insertions(+) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index be464e69..7b1cf6a3 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -5239,6 +5239,30 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { if (!Wr32(handle_out, handle)) return Invalid(); return X_ERROR_SUCCESS; } + case xam::XamTaskSchedule: { + // (callback, message, unknown, handle*): Xenia xam_task.cc runs the + // callback with the message on a new guest thread (the executable's + // stack size, 16 KiB minimum, 4 KiB aligned) and reports handle 12345. + if (!r3 || !a[3]) return X_STATUS_INVALID_PARAMETER; + if (!Wr32(a[3], 12345u)) return Invalid(); + uint32_t stack_size = ExecutableStackSize(); + stack_size = std::max(0x4000u, (stack_size + 0xFFFu) & 0xFFFFF000u); + const uint32_t native = r360_guest_thread_create(r3, r4, stack_size, 0); + if (!native) return X_STATUS_NO_MEMORY; + const uint32_t kthread = PrepareThreadObjects(native, r3, 0, 0); + if (!kthread) { + r360_guest_thread_terminate(native, 0); + return X_STATUS_NO_MEMORY; + } + const uint32_t handle = CreateObject(ObjectType::kThread, kthread, false); + if (!handle) return X_STATUS_NO_MEMORY; + uint32_t slot = 0; + SlotForHandle(handle, &slot); + Objects()[slot].thread = native; + return X_STATUS_SUCCESS; + } + case xam::XamTaskShouldExit: + return 0; // Xenia: tasks are never asked to exit early. case xam::XamGetPrivateEnumStructureFromHandle: { // (handle, object_ptr*): Xenia xam_enum.cc. The caller takes a // reference (released by ObDereferenceObject). diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index a51ae4cf..db6b3eda 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -386,6 +386,13 @@ expect(r32(enumObject+0x18)===0x58454E00&&r32(enumObject+0x1C)===r32(P+0xBA0),'a expect(x('XamGetPrivateEnumStructureFromHandle',0x12345678,P+0xBAC)===0xC0000008,'bad enumerator handle must be rejected'); console.log('XAM_CONTENT_AGGREGATE_XENIA=PASS'); +// --- XamTaskSchedule (Xenia xam_task.cc: the callback runs on a new thread) ------- +w32(P+0xC14,0); +expect(x('XamTaskSchedule',0x82400000,P+0xC00,0,P+0xC14)===0&&status()===1&&r32(P+0xC14)===12345,'XamTaskSchedule should start the task thread and report handle 12345'); +expect(x('XamTaskSchedule',0,P+0xC00,0,P+0xC14)===0xC000000D,'a task without a callback must be rejected'); +expect(x('XamTaskShouldExit',0)===0,'XamTaskShouldExit mismatch'); +console.log('XAM_TASK_SCHEDULE_XENIA=PASS'); + // --- Diagnostics / boundaries ------------------------------------------------------ ascii(P+0xD00,'Braid: hello from DbgPrint');k('DbgPrint',P+0xD00); const logOut=need('r360_kernel_pool_alloc')(64,16)>>>0; From bd608a290a3be866e5740b56455d6f2103ae80f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 22:27:14 +0000 Subject: [PATCH 25/65] Build fix: XamTaskShouldExit was already implemented Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 7b1cf6a3..b42a6a8c 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -5261,8 +5261,6 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { Objects()[slot].thread = native; return X_STATUS_SUCCESS; } - case xam::XamTaskShouldExit: - return 0; // Xenia: tasks are never asked to exit early. case xam::XamGetPrivateEnumStructureFromHandle: { // (handle, object_ptr*): Xenia xam_enum.cc. The caller takes a // reference (released by ObDereferenceObject). From 1a252431d61a1a5f1291ec8e0485fab2f63e1f3e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 22:54:42 +0000 Subject: [PATCH 26/65] Progress: Banjo-Tooie reaches its main menu with controller input Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index dc606518..5eb090d4 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -35,9 +35,30 @@ After the fix (deterministic headless runs): frame (XamInputGetState 4056 calls by 90B, was 20). - Frame at 61B: the Rare logo intro renders (software renderer). +## Verified: title screen, input and main menu +Headless deterministic run (`run-title --deterministic 1000`), software +renderer, controller input injected with `--press`: +- 61B instructions: Rare logo intro. +- 80B: title screen ("PRESS START TO PLAY") over a moving 3D flythrough. +- Start at 80B: the title asks "Gamer profile not online" (offline profile); + the player's answer is passed back (`--dialog-button 1` = "Continue + playing offline"; in the browser the page shows the dialog). +- 82B: main menu, Banjo's room, rendered in 3D. +- 85B: "Trial game" notice (the default license is trial, as in Xenia). +- 90B: "PRESS A TO PLAY THE GAME"; frames change every second and the run + reaches its instruction limit with no blocker. + +Fixed on the way (each with a kernel services test): +- XamShowMessageBoxUI (headless focused button, or the player's answer). +- XamUserCreateAchievementEnumerator (title XDBF via Xenia xdbf_utils). +- XexGetProcedureAddress (kernel export trampolines), + XamContentAggregateCreateEnumerator, XamGetPrivateEnumStructureFromHandle + (guest X_KENUMERATOR objects), XamTaskSchedule. +- A thread's exit left the kernel service status at "terminal" and the next + thread resuming mid-sleep returned it, ending the run. + ## Current work -Verifying the title screen and that controller input changes what the game -does (`run-title --press`, `--frame-at`). +Pressing A at "PRESS A TO PLAY THE GAME" to reach gameplay. ## Tests (latest build) - Regression runner: 60 of 69 pass. The 9 failures are pre-existing From 3596c9535b0d2ef9a3f76d469f9d12895cdfc833 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 16 Oct 2026 23:52:27 +0000 Subject: [PATCH 27/65] run-title: per-thread state in the JSON report Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- tools/run-title.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/run-title.mjs b/tools/run-title.mjs index a44ce40c..f37a0468 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -293,6 +293,7 @@ async function main(){ titleGpu:result.titleGpuTelemetry, debugLog:readDebugLog(bootstrap), guestVfsFetched:result.guestVfsFetched, + threads:globalThis.__r360Threads??null, }); } // --frame FILE.png saves the last swapped frontbuffer (Xenos decode of the From 14c139ab185271cd1faed13026c708da6a46a8b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 00:22:34 +0000 Subject: [PATCH 28/65] Deterministic headless dialog answers run-title --dialog-button answered the message box at the next host slice, so the other guest threads ran a wall-clock-dependent number of instructions meanwhile and runs diverged after the dialog (Banjo-Tooie's cutscene stall came and went between runs). r360_xam_dialog_set_auto_ answer gives the answer inside the call; the browser keeps the interactive dialog. Kernel services test covers it. (Test run pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- .../kernel_xboxkrnl_services.cpp | 18 ++++++++++++++++-- test-kernel-xboxkrnl-services.mjs | 6 ++++++ tools/run-title.mjs | 3 ++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index b42a6a8c..0142b48c 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -394,6 +394,9 @@ MessageBox& PendingMessageBox() { return box; } bool g_dialog_host_answers = false; +// Headless runs: a preset answer given inside the call, so the run does not +// depend on when the host gets to answer (-1: none). +int32_t g_dialog_auto_answer = -1; void DebugLog(std::string text) { if (text.size() > 512) text.resize(512); @@ -5441,9 +5444,15 @@ uint32_t DispatchXam(uint32_t ordinal, const uint32_t* a) { DebugLog(log); std::fprintf(stderr, "R360_MESSAGE_BOX %s\n", log.c_str()); BroadcastNotification(0x09u, 1); - if (!g_dialog_host_answers) { + if (!g_dialog_host_answers || g_dialog_auto_answer >= 0) { + uint32_t choice = a[5]; + if (g_dialog_auto_answer >= 0) { + choice = std::min(uint32_t(g_dialog_auto_answer), + box.buttons.empty() ? 0u : uint32_t(box.buttons.size() - 1)); + std::fprintf(stderr, "R360_MESSAGE_BOX answered %u (preset)\n", choice); + } box = {}; - if (!Wr32(result_ptr, a[5])) return Invalid(); + if (!Wr32(result_ptr, choice)) return Invalid(); BroadcastNotification(0x09u, 0); return FinishXamOverlapped(overlapped, X_ERROR_SUCCESS, 0); } @@ -6080,6 +6089,11 @@ uint32_t r360_xam_dialog_set_host_answers(uint32_t on) { r360k::g_dialog_host_answers = on != 0; return r360k::g_dialog_host_answers ? 1u : 0u; } +R360_WASM_EXPORT("r360_xam_dialog_set_auto_answer") +int32_t r360_xam_dialog_set_auto_answer(int32_t button) { + r360k::g_dialog_auto_answer = button < 0 ? -1 : button; + return r360k::g_dialog_auto_answer; +} R360_WASM_EXPORT("r360_xam_dialog_pending") uint32_t r360_xam_dialog_pending() { return r360k::PendingMessageBox().state == r360k::MessageBox::kPending ? 1u : 0u; diff --git a/test-kernel-xboxkrnl-services.mjs b/test-kernel-xboxkrnl-services.mjs index db6b3eda..de6029ed 100644 --- a/test-kernel-xboxkrnl-services.mjs +++ b/test-kernel-xboxkrnl-services.mjs @@ -352,6 +352,12 @@ expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===0&&sta while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); need('r360_xam_dialog_set_host_answers')(0); console.log('XAM_MESSAGE_BOX_HOST_DIALOG=PASS'); +expect((need('r360_xam_dialog_set_auto_answer')(1)|0)===1,'preset answer not set'); +w32(P+0xAB0,0xFFFFFFFF);w32(P+0xF000+0x54,0); +expect(x('XamShowMessageBoxUI',0,P+0xA00,P+0xA40,2,P+0xAA0,0,0,P+0xAB0)===0&&status()===1&&r32(P+0xAB0)===1,'preset answer should complete the dialog inside the call'); +need('r360_xam_dialog_set_auto_answer')(-1); +while(x('XNotifyGetNext',sys,0,P+0x900,P+0x904)===1); +console.log('XAM_MESSAGE_BOX_PRESET_ANSWER=PASS'); // --- XamUserCreateAchievementEnumerator (Xenia XStaticAchievementEnumerator) ------ expect(x('XamUserCreateAchievementEnumerator',0,0,0,7,0,4,P+0xB00,P+0xB04)===0&&status()===1,'achievement enumerator not created'); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index f37a0468..fa8f7df8 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -225,7 +225,8 @@ async function main(){ const bootstrapFile=args.bootstrap||(fs.existsSync(rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'))?rel('build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'):rel('xenia_ppc_bootstrap.wasm')); const {instance:bootstrap,host,stderr}=await loadBootstrap(bootstrapFile,args.verbose); runArgs=args;globalThis.__r360Bootstrap=bootstrap; - if(args.dialogButton!==undefined)bootstrap.exports.r360_xam_dialog_set_host_answers?.(1); + // A preset answer inside the call keeps the run deterministic. + if(args.dialogButton!==undefined)bootstrap.exports.r360_xam_dialog_set_auto_answer?.(args.dialogButton); if(args.frame||args.frameAt){frontbufferModule=await import(rel('render360-title-frontbuffer.mjs'));zlibModule=await import('node:zlib');} const core=await loadCore(); const started=Date.now(); From ebb4174eb427b26bb1c2fe75f0e807e6bd101fc3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 00:49:55 +0000 Subject: [PATCH 29/65] Guest fiber scheduler: bound how far a busy thread can fall behind PickTarget always ran the least-run eligible fiber. In Banjo-Tooie's opening cutscene a timer thread loops Sleep(0) around a critical section the main thread needs; the timer and idle worker threads stayed far below the main thread's instruction count, so every pick went to them and the main thread waited ~50B instructions for the lock (frames stop). As CFS bounds unfairness, an eligible fiber more than eight quanta ahead of the least-run one is pulled back to that bound, so a busy thread gets a turn within a bounded number of the others' instructions, as it would on its own hardware thread. (Suite and title runs pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/guest_fibers.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index 81318d39..e8b10638 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -199,14 +199,31 @@ bool PickTarget(uint32_t from, uint32_t* target, bool preempting = false) { from >= n ? 0 : g_fibers[from].vruntime + (from == g_current ? HIRTotalInstructions() - g_run_start : 0); + // Bounded lag (as CFS bounds it): a thread that has run far more than the + // others is passed over for at most kMaxLag instructions of theirs. On the + // console every thread runs on its own hardware thread, so a busy thread is + // never starved by an idle-looping one (Banjo-Tooie's main thread waited + // ~50B instructions for a lock while a timer thread spun Sleep(0)). + constexpr uint64_t kMaxLag = 8ull * kPreemptQuantum; + bool any = false; + uint64_t min_count = 0; + for (uint32_t index = 0; index < n; ++index) { + if (index == from) continue; + const Fiber& fiber = g_fibers[index]; + if (!Eligible(fiber) || (index != 0 && !ThreadRunnable(fiber.thread))) continue; + if (!any || fiber.vruntime < min_count) min_count = fiber.vruntime; + any = true; + } + if (any && from < n && from_count < min_count) min_count = from_count; bool found = false; uint32_t best = 0; for (uint32_t step = 1; step <= n; ++step) { const uint32_t index = (from + step) % n; if (index == from) continue; - const Fiber& fiber = g_fibers[index]; + Fiber& fiber = g_fibers[index]; if (!Eligible(fiber)) continue; if (index != 0 && !ThreadRunnable(fiber.thread)) continue; + if (fiber.vruntime > min_count + kMaxLag) fiber.vruntime = min_count + kMaxLag; if (!found || fiber.vruntime < g_fibers[best].vruntime) best = index; found = true; } From ea3f534f81782fb46be84bfb1b852da39b652c11 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 01:38:07 +0000 Subject: [PATCH 30/65] HIR interpreter polls for interrupts and preemption After the opening cutscene Banjo-Tooie's main thread loops over its object table until another thread clears a slot. The function had been called only once, so it ran in the HIR interpreter, which polled only at guest calls: no interrupts, no preemption and no host slices for 10B instructions, and the thread it waits for never ran. Interpreted code now polls every 4096 instructions, as the guest JIT polls on backward branches. (Suite and title runs pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/hir_correctness_executor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/xenia_web_bootstrap/hir_correctness_executor.cpp b/src/xenia_web_bootstrap/hir_correctness_executor.cpp index 8a819898..e4900c6b 100644 --- a/src/xenia_web_bootstrap/hir_correctness_executor.cpp +++ b/src/xenia_web_bootstrap/hir_correctness_executor.cpp @@ -33,6 +33,8 @@ uint32_t r360_ppc_probe_loaded_size(); namespace render360::xenia_web { +void MaybeDeliverGuestInterrupts(); // kernel_xboxkrnl_services.cpp + bool g_r360_verbose_trace = false; namespace { @@ -1637,6 +1639,11 @@ HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder, supported = false; break; } + // Interpreted code polls like the guest JIT's backward branches: a + // loop in a function that was never compiled (one call that spins + // waiting for another thread, as in Banjo-Tooie's object table) would + // otherwise never deliver interrupts, preempt or return to the host. + if ((g_total_instructions & 4095u) == 0) MaybeDeliverGuestInterrupts(); ++g_opcode_histogram[instr->opcode->num & 0xFFu]; if (ExecuteFlaggedOperation(instr, values, &supported)) { if (!supported) { From 5c32177798985eed0902da02fb6d916eb400b4d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 02:40:32 +0000 Subject: [PATCH 31/65] run-title: --stick to hold the left analog stick Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- tools/run-title.mjs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tools/run-title.mjs b/tools/run-title.mjs index fa8f7df8..1f9c04e9 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -60,6 +60,8 @@ function parseArgs(argv){ // --press FROM:TO:BUTTONS holds gamepad 0 buttons (XINPUT bits, e.g. 0x10 = START, 0x1000 = A) between FROM and TO million instructions. // --dialog-button N answers every XamShowMessageBoxUI with button N (the player's choice); without it the focused button is taken (Xenia headless). else if(a==='--dialog-button')args.dialogButton=Number(argv[++i])>>>0; + // --stick FROM:TO:X:Y holds gamepad 0's left stick at X,Y (-1..1) between FROM and TO million instructions. + else if(a==='--stick'){const [from,to,x,y]=String(argv[++i]).split(':');(args.stick??=[]).push({from:Number(from),to:Number(to),x:Number(x),y:Number(y)});} else if(a==='--press'){const [from,to,buttons]=String(argv[++i]).split(':');(args.press??=[]).push({from:Number(from),to:Number(to),buttons:Number(buttons)&0xFFFF});} else if(a==='--slice-ms')args.sliceMs=Number(argv[++i])>>>0; else if(a==='--watch')args.watch=Number(argv[++i])>>>0; @@ -99,9 +101,13 @@ function slicePressAndFrames(x){ process.stderr.write(`dialog "${str(0)}" -> ${choice} (${str(2+choice)})\n`);x.r360_xam_dialog_answer(choice); } const m=x.r360_hir_total_instructions_millions?.()>>>0; - if(runArgs.press){ - let buttons=0;for(const p of runArgs.press)if(m>=p.from&&m=p.from&&m=p.from&&mMath.max(-32768,Math.min(32767,Math.round(v*32767)))&0xFFFF; + const left=(axis(lx)|(axis(ly)<<16))>>>0,key=`${buttons}:${left}`; + if(key!==globalThis.__r360PressKey){globalThis.__r360PressKey=key;x.r360_input_set_gamepad?.(0,1,buttons,0,left,0);process.stderr.write(`press ${m}M buttons=0x${buttons.toString(16)} stick=${lx},${ly}\n`);} } if(runArgs.frameAt){ const pending=runArgs.frameAt.at.filter(at=>at<=m&&!savedFrames.some(f=>f.at===at)); @@ -259,7 +265,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} From f2f9dff15bf5d5fdb6d18e8be1ce0563288f8142 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 02:40:45 +0000 Subject: [PATCH 32/65] Progress: Banjo-Tooie reaches gameplay in Spiral Mountain Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index 5eb090d4..2e390a84 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -57,8 +57,32 @@ Fixed on the way (each with a kernel services test): - A thread's exit left the kernel service status at "terminal" and the next thread resuming mid-sleep returned it, ending the run. +## Verified: in-game in Spiral Mountain +Same headless run, continued: A at "PRESS A TO PLAY THE GAME" starts the +opening cutscene (rainy night, "B SKIP"); B skips it, and by 108B the game +is in Spiral Mountain (first level) with the HUD (health honeycombs), the +"SPIRAL MOUNTAIN" title and in-game dialogue; frames keep changing to the +115B instruction limit (3268 frames presented). + +Two scheduler bugs blocked it (single host thread running all guest +threads as fibers): +- Least-run-first scheduling starved the busy main thread: a timer thread + looping Sleep(0) around a critical section kept winning, and the main + thread waited ~50B instructions for the lock. Lag is now bounded (8 + quanta), as CFS bounds it. +- The HIR interpreter polled for interrupts and preemption only at guest + calls. A function called once that loops waiting for another thread ran + 10B instructions without letting that thread run. It now polls every 4096 + instructions, as the guest JIT polls on backward branches. +Headless message-box answers are now given inside the call +(`--dialog-button`), so runs no longer depend on host timing. + +Known visual issue: Banjo's own model renders incompletely (small, +fragmented); the level, HUD and other characters render. + ## Current work -Pressing A at "PRESS A TO PLAY THE GAME" to reach gameplay. +Proving in-game control (`--stick` for the left analog stick), then the +renderer issue above and speed. ## Tests (latest build) - Regression runner: 60 of 69 pass. The 9 failures are pre-existing @@ -73,7 +97,8 @@ Pressing A at "PRESS A TO PLAY THE GAME" to reach gameplay. after it. ## Not done yet -- Interactive gameplay: not reached. +- Interactive gameplay: in-game reached; movement under player control is + being verified. - WebGPU real-time renderer: only the shader pipeline is proven; draws, render targets, textures and resolves are not implemented. Frames come from the CPU software renderer. From 24eb7fb5b1d16c9adc91f1570c06c6a8a59e17d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 03:28:46 +0000 Subject: [PATCH 33/65] Docs: record-to-recompile as a future opt-in option Design note only (not built): record reached functions, blocks, jump tables and indirect-call targets on the interpreter path into an address/hash manifest, recompile from it, log misses at run time and grow coverage. Lists the Render360 hook points (interpreter, call resolution, guest JIT cache) and the data rules (own copy, addresses only, no game code or generated code committed). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- docs/recompile/RECORD_TO_RECOMPILE.md | 71 +++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 docs/recompile/RECORD_TO_RECOMPILE.md diff --git a/docs/recompile/RECORD_TO_RECOMPILE.md b/docs/recompile/RECORD_TO_RECOMPILE.md new file mode 100644 index 00000000..7b5eea99 --- /dev/null +++ b/docs/recompile/RECORD_TO_RECOMPILE.md @@ -0,0 +1,71 @@ +# Record-to-recompile (future, opt-in) + +Status: **planned, not built.** Current priority is getting titles working +(Banjo-Tooie first). This is an option people can turn on later so their +titles get cached/recompiled automatically instead of anyone hunting for +functions by hand. + +## Idea + +Run the game once on a path that can execute anything (interpreter or JIT), +record every piece of code it reaches, and feed that record to an +ahead-of-time recompiler. Each later session reports what it found that +was not recompiled yet, so coverage grows toward 100% without manual work. + +## Pipeline + +1. **Record.** Run the XEX on the interpreter/fallback path and log, with + hit counts: + - function entries; + - basic blocks; + - jump-table targets; + - resolved indirect calls (`bctr` / `bcctr`), including calls that + resolve to 0 (unresolved). + + Save this as a manifest in the recompiler's function-boundary format. + The manifest holds addresses and hashes only, never game code. +2. **Recompile.** Merge each new manifest into a master manifest, re-run + codegen and the build, and report: + - functions found; + - unresolved calls (target 0); + - new since the last run; + - coverage %. +3. **Run.** Fully native where the platform forbids runtime code + generation (iOS apps: no JIT). If execution reaches code that was not + recompiled, it does not crash: + - log the address to the manifest; + - show a quiet notice; + - fall back to an interpreter if one is built in, otherwise save and + exit cleanly. +4. **Grow.** Each session sends newly discovered addresses back to the + build machine; one command rebuilds and reinstalls. +5. **Persist.** Manifests are versioned in a private repo (addresses + only). The build cache lives on the build machine's drive, with a + backup copy elsewhere. + +## Rules + +- Only the player's own copy of the game. +- Game files and generated code are never committed or uploaded. Only + address/hash manifests are kept, in a private repo. +- Every run reports coverage % and the unresolved-call count. + +## What Render360 already has that this would build on + +- **Recording path:** the HIR interpreter + (`src/xenia_web_bootstrap/hir_correctness_executor.cpp`) executes any + guest function. Call resolution (`ResolveAddressCall*`, + `TranslateNestedGuestAddress` in `probe_backend.cpp`) sees every direct + and indirect call target, including unresolved ones (target 0). These + are the hook points for a manifest writer. +- **Compiled path:** the guest JIT (`hir_wasm_jit.cpp`) already compiles hot + functions to WebAssembly. In browsers runtime code generation is + allowed, so the Render360 form of "recompile" is an opt-in cache: + persist the compiled modules per function (keyed by address + code hash) + in the player's browser storage, so later sessions skip the interpreter + warm-up. Only the player's own browser holds generated code. +- **Determinism:** `run-title --deterministic` replays a run exactly, so a + recorded manifest can be checked against a replay. + +The ReXGlue / iPhone pipeline (Watch Dogs) lives outside this repository +and would follow the same manifest format and rules. From 255aaccc62eb7f395ea6c18278946eab45856d88 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 04:12:18 +0000 Subject: [PATCH 34/65] Progress: Banjo-Tooie is controllable in Spiral Mountain Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index 2e390a84..da8a077f 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -80,9 +80,19 @@ Headless message-box answers are now given inside the call Known visual issue: Banjo's own model renders incompletely (small, fragmented); the level, HUD and other characters render. -## Current work -Proving in-game control (`--stick` for the left analog stick), then the -renderer issue above and speed. +## Verified: player control in gameplay +Continuing the same run: A clears the Bottles dialogue (116-120B), then the +left stick held forward (`--stick 122000:126000:0:1`) walks Banjo along the +path in Spiral Mountain: the camera follows him past Bottles (124B) and by +127B he has reached the boulder pit, which triggers the next dialogue. +Frames keep changing to the 127.5B instruction limit (3607 frames). + +## Not yet +- Speed: reaching gameplay takes ~1 hour headless with the software + renderer; the browser needs the WebGPU renderer and faster CPU emulation + to be playable in real time. +- Audio: XMA decoding (Xenia uses FFmpeg's XMA/WMA Pro decoder). +- Banjo's model looks small and partly fragmented in some frames. ## Tests (latest build) - Regression runner: 60 of 69 pass. The 9 failures are pre-existing @@ -97,8 +107,8 @@ renderer issue above and speed. after it. ## Not done yet -- Interactive gameplay: in-game reached; movement under player control is - being verified. +- Interactive gameplay: reached and controllable headlessly; not yet at a + playable speed in the browser. - WebGPU real-time renderer: only the shader pipeline is proven; draws, render targets, textures and resolves are not implemented. Frames come from the CPU software renderer. From 2be892a5c0effdf83dc413f9fd59b521092939c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 05:19:29 +0000 Subject: [PATCH 35/65] CPU speed: per-call context fix; native vector compares in the JIT Profiling the first 15B instructions of Banjo-Tooie (274 MIPS baseline) showed only 0.2% of guest instructions interpreted, yet 17% of host time in ExecuteHIRCorrectnessProbe: it zero-filled a whole PPCContext (GPRs, FPRs, 128 vector registers) on every guest call, though only the outermost call of a thread uses it. prepare-hir-hot-path-overlay.py keeps the storage on the stack and initialises it only there. The JIT sent 7.9M vector ops per 15B instructions back to the executor one at a time; most were VECTOR_COMPARE_* (5.3M ugt on bytes), which the emitter did not handle. They now compile to wasm SIMD (i8x16/i16x8/i32x4 eq/gt/ge signed and unsigned, f32x4 eq/gt/ge, matching the executor's StoreVectorCompare/VectorCompareFloat), and EXTRACT with a dynamic index now covers 32-bit lanes. (Measurements and JIT verification pending.) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 1 + prepare-hir-hot-path-overlay.py | 31 ++++++++++++++++++++++ src/xenia_web_bootstrap/hir_wasm_jit.cpp | 33 ++++++++++++++++++++++-- 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 prepare-hir-hot-path-overlay.py diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index cbd0b4d4..53de052d 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -57,6 +57,7 @@ python3 "$ROOT/prepare-hir-stack-history-overlay.py" python3 "$ROOT/prepare-hir-tail-frame-overlay.py" python3 "$ROOT/prepare-hir-fiber-locals-overlay.py" python3 "$ROOT/prepare-hir-jit-overlay.py" +python3 "$ROOT/prepare-hir-hot-path-overlay.py" python3 "$ROOT/prepare-xenia-shader-interpreter-overlay.py" python3 "$ROOT/prepare-xenia-shader-translator-overlay.py" python3 "$ROOT/prepare-xenia-spirv-browser-overlay.py" diff --git a/prepare-hir-hot-path-overlay.py b/prepare-hir-hot-path-overlay.py new file mode 100644 index 00000000..4518103b --- /dev/null +++ b/prepare-hir-hot-path-overlay.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Hot-path fixes for the HIR executor overlay (applied after the JIT overlay). + +ExecuteHIRCorrectnessProbe runs for every guest call, compiled or not. It +declared `PPCContext local_context{}` unconditionally, zero-filling a whole +PPC register file (GPRs, FPRs, 128 vector registers) per call although only +the outermost call of a thread uses it. The storage stays on the stack (each +fiber's outermost call needs its own), but it is only initialised there. +""" +from pathlib import Path + +path = Path(__file__).resolve().parent / 'build/xenia-web-overlay/render360/hir_correctness_executor_vmx.cpp' +s = path.read_text() +marker = 'R360_HOT_PATH_OVERLAY' +if marker not in s: + old = ' xe::cpu::ppc::PPCContext local_context{};\n if (outermost) {\n' + new = (' // ' + marker + ': initialised only by the outermost call (see\n' + ' // prepare-hir-hot-path-overlay.py).\n' + ' alignas(xe::cpu::ppc::PPCContext) unsigned char\n' + ' local_context_storage[sizeof(xe::cpu::ppc::PPCContext)];\n' + ' xe::cpu::ppc::PPCContext& local_context =\n' + ' *reinterpret_cast(local_context_storage);\n' + ' if (outermost) {\n' + ' new (&local_context) xe::cpu::ppc::PPCContext{};\n') + if s.count(old) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: PPCContext anchor not found exactly once') + s = s.replace(old, new, 1) + if '#include ' not in s: + s = '#include \n' + s + path.write_text(s) +print('R360_HOT_PATH_OVERLAY applied') diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 0f2eb7cf..af8cab4a 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -775,10 +775,18 @@ bool Emitter::EmitVector(Instr* instr, uint32_t source) { return SetDest(instr); case OPCODE_EXTRACT: { if (is_vec(a) && d && b && !b->IsConstant() && IsInt(b->type) && - (d->type == INT8_TYPE || d->type == INT16_TYPE)) { + (d->type == INT8_TYPE || d->type == INT16_TYPE || d->type == INT32_TYPE)) { // Dynamic index: gather the element into lane 0 with a swizzle. Push(a); - if (d->type == INT8_TYPE) { + if (d->type == INT32_TYPE) { + // Lane index & 3, as the constant case: bytes 4*lane .. 4*lane+3. + uint8_t quad[16]; + for (int k = 0; k < 16; ++k) quad[k] = uint8_t(k & 3); + PushAs(b, Cls::kI32); I32(3); Op(oI32And); I32(2); Op(oI32Shl); + Simd(0x0F); V128Const(quad); Simd(0x6E); // splat(4*lane) + {0,1,2,3,...} + Simd(0x0E); + Simd(0x1B); code_.u8(0); + } else if (d->type == INT8_TYPE) { PushAs(b, Cls::kI32); I32(3); Op(oI32Xor); I32(0xF); Op(oI32And); Simd(0x0F); Simd(0x0E); // swizzle(v, splat(idx)) Simd(0x16); code_.u8(0); @@ -804,6 +812,27 @@ bool Emitter::EmitVector(Instr* instr, uint32_t source) { } return SetDest(instr); } + case OPCODE_VECTOR_COMPARE_EQ: case OPCODE_VECTOR_COMPARE_SGT: + case OPCODE_VECTOR_COMPARE_SGE: case OPCODE_VECTOR_COMPARE_UGT: + case OPCODE_VECTOR_COMPARE_UGE: { + // Lane-wise compare, all-ones where true (executor StoreVectorCompare / + // VectorCompareFloat: ordered float compares, so NaN lanes are false, + // as wasm f32x4.eq/gt/ge; unsigned float compares are the signed ones). + if (!is_vec(d) || !is_vec(a) || !is_vec(b)) return Reject(instr); + const bool eq = op == OPCODE_VECTOR_COMPARE_EQ; + const bool gt = op == OPCODE_VECTOR_COMPARE_SGT || op == OPCODE_VECTOR_COMPARE_UGT; + const bool uns = op == OPCODE_VECTOR_COMPARE_UGT || op == OPCODE_VECTOR_COMPARE_UGE; + uint32_t simd = 0; + switch (TypeName(instr->flags & 0xFF)) { + case INT8_TYPE: simd = eq ? 0x23 : gt ? (uns ? 0x28 : 0x27) : (uns ? 0x2C : 0x2B); break; + case INT16_TYPE: simd = eq ? 0x2D : gt ? (uns ? 0x32 : 0x31) : (uns ? 0x36 : 0x35); break; + case INT32_TYPE: simd = eq ? 0x37 : gt ? (uns ? 0x3C : 0x3B) : (uns ? 0x40 : 0x3F); break; + case FLOAT32_TYPE: simd = eq ? 0x41 : gt ? 0x44 : 0x46; break; + default: return Reject(instr); + } + Push(a); Push(b); Simd(simd); + return SetDest(instr); + } case OPCODE_SWIZZLE: { if (!is_vec(d) || !is_vec(a) || (instr->flags != INT32_TYPE && instr->flags != FLOAT32_TYPE)) { return Reject(instr); From 62dc7149144c51b4abc27e873563ff97e84413a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 05:21:34 +0000 Subject: [PATCH 36/65] FPS and frame-time overlay in the browser player render360-perf-overlay.mjs: current FPS (last second), average FPS (last 60 s), frame time, 1% low FPS, CPU emulation vs GPU rendering time per second (with the bottleneck named) and frames submitted (guest VdSwap) vs presented (drawn on the page). Toggle with the ` key. The player now presents every new guest frame instead of at most one per 500 ms progress tick (2 FPS ceiling), and times each slice: host time in the emulator, the GPU renderer's share (new r360_xenos_soft_render_us counter around draws/resolves) and page-side present time. test-perf-overlay.mjs checks the statistics (30 FPS with a 200 ms hitch: 1% low 11.2, CPU/GPU split, submitted 60/s vs presented 30/s, 60 s window). Also measured: the PPCContext per-call fix took Banjo-Tooie's first 30B instructions from 274 to 355 MIPS (110 s to 85 s headless). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-guest-fibers.mjs | 24 +++- render360-perf-overlay.mjs | 131 ++++++++++++++++++ .../xenos_soft_renderer.cpp | 19 +++ test-perf-overlay.mjs | 44 ++++++ 4 files changed, 214 insertions(+), 4 deletions(-) create mode 100644 render360-perf-overlay.mjs create mode 100644 test-perf-overlay.mjs diff --git a/render360-guest-fibers.mjs b/render360-guest-fibers.mjs index 9609eb13..10e383a1 100644 --- a/render360-guest-fibers.mjs +++ b/render360-guest-fibers.mjs @@ -4,6 +4,8 @@ // blocks in the kernel, the core snapshots it and unwinds the wasm stack back // here (Binaryen Asyncify); this loop then starts or rewinds the next guest // thread on its own C stack until the title's primary thread returns. + +import {PerfStats,createPerfOverlay} from './render360-perf-overlay.mjs'; const pick=(bootstrap,name)=>bootstrap?.exports?.[name]??bootstrap?.exports?.[`_${name}`]; export function hasGuestFibers(bootstrap){ @@ -87,15 +89,29 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,s const read=name=>{const f=bootstrap?.exports?.[name];return typeof f==='function'?(f()>>>0):0;}; // System message boxes (XamShowMessageBoxUI) are answered by the player. if(globalThis.document)bootstrap?.exports?.r360_xam_dialog_set_host_answers?.(1); + // FPS / frame-time overlay: time inside the emulator per slice, the GPU + // renderer's share of it, page-side present time, submitted vs presented. + const perf=new PerfStats(); + const overlay=globalThis.document?createPerfOverlay():null; + let sliceExit=now(),lastRenderUs=read('r360_xenos_soft_render_us'),lastOverlay=0; return {guestSliceMs:sliceMs,signal:controller.signal,onGuestSlice:s=>{ + const t=now(); + const renderUs=read('r360_xenos_soft_render_us'); + const gpuMs=((renderUs-lastRenderUs)>>>0)/1000;lastRenderUs=renderUs; pushGuestControllerState(bootstrap); showGuestDialog(bootstrap); - const t=now(); + const frames=read('r360_title_gpu_vd_swap_calls'); + perf.submitted(t,frames); + // Present every new guest frame (software Xenos backend output). + let presentMs=0; + if(onFrame&&frames!==lastFrames){lastFrames=frames;const p0=now();try{onFrame();}catch{}presentMs=now()-p0;perf.framePresented(now());} + perf.slice(t,t-sliceExit,gpuMs,presentMs); + if(overlay&&t-lastOverlay>=1000){lastOverlay=t;overlay.update(perf.snapshot(t));} + globalThis.render360Perf=perf; + sliceExit=now(); if(t-lastReport<500)return; lastReport=t; - const frames=read('r360_title_gpu_vd_swap_calls'),draws=read('r360_xenos_draws'); - // Show the newest swapped frontbuffer (software Xenos backend output). - if(onFrame&&frames!==lastFrames){lastFrames=frames;try{onFrame();}catch{}} + const draws=read('r360_xenos_draws'); const seconds=Math.max(0.001,(t-started)/1000); onProgress?.(`Running · ${frames.toLocaleString()} frames presented (${(frames/seconds).toFixed(1)}/s) · ${draws.toLocaleString()} GPU draws · ${s.threads} guest threads`,{frames,draws,slices:s.slices}); }}; diff --git a/render360-perf-overlay.mjs b/render360-perf-overlay.mjs new file mode 100644 index 00000000..c7ab98a8 --- /dev/null +++ b/render360-perf-overlay.mjs @@ -0,0 +1,131 @@ +// Render360 FPS / frame-time overlay. +// +// PerfStats is pure (testable in Node); createPerfOverlay draws it on the page. +// The player feeds it once per guest slice (see browserGuestRunOptions): +// - presented frames: frames actually drawn to the page canvas; +// - submitted frames: the guest's VdSwap count (frames the game handed to +// the GPU); +// - host time spent inside the emulator, the part of it spent in the GPU +// renderer, and the time spent presenting frames on the page. +// +// Shown: current FPS (last second), average FPS (last 60 s), frame time, 1% +// low FPS, CPU emulation vs GPU rendering time, submitted vs presented. + +const WINDOW_MS = 60000; + +export class PerfStats { + constructor({windowMs = WINDOW_MS} = {}) { + this.windowMs = windowMs; + this.presentTimes = []; // performance.now() of each presented frame + this.submitEvents = []; // [time, count] of guest submissions + this.slices = []; // [time, emulationMs, gpuMs, presentMs] + this.lastSubmitted = null; + this.totalPresented = 0; + this.totalSubmitted = 0; + } + + // One presented frame at time t (ms). + framePresented(t) { + this.presentTimes.push(t); + ++this.totalPresented; + this.trim(t); + } + + // Guest swap counter (cumulative) seen at time t. + submitted(t, cumulative) { + if (this.lastSubmitted !== null && cumulative > this.lastSubmitted) { + const n = cumulative - this.lastSubmitted; + this.submitEvents.push([t, n]); + this.totalSubmitted += n; + } + this.lastSubmitted = cumulative; + this.trim(t); + } + + // Host time of one slice: total time inside the emulator, the part of it + // spent in the GPU renderer, and the page-side present time (all ms). + slice(t, emulationMs, gpuMs, presentMs) { + this.slices.push([t, Math.max(0, emulationMs - gpuMs), gpuMs + presentMs]); + this.trim(t); + } + + trim(t) { + const old = t - this.windowMs; + while (this.presentTimes.length && this.presentTimes[0] < old) this.presentTimes.shift(); + while (this.submitEvents.length && this.submitEvents[0][0] < old) this.submitEvents.shift(); + while (this.slices.length && this.slices[0][0] < old) this.slices.shift(); + } + + snapshot(t) { + const inLast = (times, ms) => times.filter(x => x >= t - ms).length; + const current = inLast(this.presentTimes, 1000); + const span = this.presentTimes.length > 1 + ? Math.max(1, t - this.presentTimes[0]) : 0; + const average = span ? (this.presentTimes.length - 1) * 1000 / span : current; + const deltas = []; + for (let i = 1; i < this.presentTimes.length; ++i) { + deltas.push(this.presentTimes[i] - this.presentTimes[i - 1]); + } + const frameMs = deltas.length ? deltas.slice(-Math.max(1, current)).reduce((a, b) => a + b, 0) / Math.min(deltas.length, Math.max(1, current)) : 0; + // 1% low: the FPS of the slowest 1% of frames in the window. + let low1 = 0; + if (deltas.length) { + const sorted = [...deltas].sort((a, b) => b - a); + const worst = sorted.slice(0, Math.max(1, Math.ceil(sorted.length / 100))); + low1 = 1000 / (worst.reduce((a, b) => a + b, 0) / worst.length); + } + const submittedLastSecond = this.submitEvents + .filter(([time]) => time >= t - 1000).reduce((a, [, n]) => a + n, 0); + const recent = this.slices.filter(([time]) => time >= t - 1000); + const cpuMs = recent.reduce((a, s) => a + s[1], 0); + const gpuMs = recent.reduce((a, s) => a + s[2], 0); + return { + fps: current, + averageFps: average, + frameMs, + low1Fps: low1, + cpuMsPerSecond: cpuMs, + gpuMsPerSecond: gpuMs, + bottleneck: cpuMs === 0 && gpuMs === 0 ? '—' : cpuMs >= gpuMs ? 'CPU emulation' : 'GPU rendering', + submittedPerSecond: submittedLastSecond, + presentedPerSecond: current, + totalSubmitted: this.totalSubmitted, + totalPresented: this.totalPresented, + }; + } +} + +export function formatPerf(s) { + const f = (x, d = 1) => Number.isFinite(x) ? x.toFixed(d) : '—'; + return [ + `FPS ${f(s.fps, 0)} avg ${f(s.averageFps)} 1% low ${f(s.low1Fps)}`, + `Frame time ${f(s.frameMs)} ms`, + `CPU emulation ${f(s.cpuMsPerSecond, 0)} ms/s GPU rendering ${f(s.gpuMsPerSecond, 0)} ms/s`, + `Bottleneck: ${s.bottleneck}`, + `Frames submitted ${f(s.submittedPerSecond, 0)}/s presented ${f(s.presentedPerSecond, 0)}/s`, + ].join('\n'); +} + +// Overlay element, toggled with the ` key (or globalThis.render360PerfOverlay.toggle()). +export function createPerfOverlay(doc = globalThis.document) { + if (!doc) return null; + const el = doc.createElement('pre'); + el.setAttribute('aria-live', 'off'); + el.style.cssText = 'position:fixed;top:8px;left:8px;z-index:9998;margin:0;padding:8px 10px;' + + 'background:rgba(0,0,0,.66);color:#e8f5e9;font:12px/1.4 ui-monospace,Menlo,Consolas,monospace;' + + 'border-radius:6px;pointer-events:none;white-space:pre;max-width:calc(100vw - 16px);overflow:hidden'; + el.textContent = 'FPS —'; + doc.body.append(el); + let visible = true; + const toggle = () => { visible = !visible; el.style.display = visible ? '' : 'none'; }; + const onKey = e => { if (e.key === '`') toggle(); }; + doc.addEventListener('keydown', onKey); + const overlay = { + element: el, + toggle, + update(snapshot) { if (visible) el.textContent = formatPerf(snapshot); }, + remove() { doc.removeEventListener('keydown', onKey); el.remove(); }, + }; + globalThis.render360PerfOverlay = overlay; + return overlay; +} diff --git a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp index bd3f529c..3b5a70ed 100644 --- a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp +++ b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1208,7 +1209,23 @@ bool SampleXenosTexture(const xenos::xe_gpu_texture_fetch_t& fetch, return true; } +// Host time spent rendering (draws, clears, resolves), for the frame-time +// overlay's CPU-emulation vs GPU-rendering split (r360_xenos_soft_render_us). +uint64_t g_render_ns = 0; +uint64_t MonotonicNs() { + timespec ts{}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return uint64_t(ts.tv_sec) * 1000000000ull + uint64_t(ts.tv_nsec); +} +bool RenderXenosDrawUntimed(const XenosSoftDraw& draw); bool RenderXenosDraw(const XenosSoftDraw& draw) { + if (!g_rasterize) return true; + const uint64_t start = MonotonicNs(); + const bool ok = RenderXenosDrawUntimed(draw); + g_render_ns += MonotonicNs() - start; + return ok; +} +bool RenderXenosDrawUntimed(const XenosSoftDraw& draw) { // Headless fast-forward (r360_xenos_soft_set_rasterize(0)): no EDRAM // work at all; the command processor still executes every packet. if (!g_rasterize) return true; @@ -1241,6 +1258,8 @@ void ResetXenosSoftRenderer() { namespace rx = render360::xenia_web; extern "C" { uint32_t r360_xenos_soft_draws() { return rx::g_draws_rendered; } +// Cumulative host microseconds inside the GPU renderer (wraps; take deltas). +uint32_t r360_xenos_soft_render_us() { return uint32_t(rx::g_render_ns / 1000u); } uint32_t r360_xenos_soft_set_rasterize(uint32_t on) { rx::g_rasterize = on ? 1u : 0u; return rx::g_rasterize; } uint32_t r360_xenos_soft_skipped() { return rx::g_draws_skipped; } uint32_t r360_xenos_soft_resolves() { return rx::g_resolves; } diff --git a/test-perf-overlay.mjs b/test-perf-overlay.mjs new file mode 100644 index 00000000..85571e84 --- /dev/null +++ b/test-perf-overlay.mjs @@ -0,0 +1,44 @@ +// Unit test for the FPS / frame-time overlay statistics (render360-perf-overlay.mjs). +import {PerfStats, formatPerf} from './render360-perf-overlay.mjs'; + +const expect = (cond, message) => { if (!cond) throw new Error(message); }; +const near = (a, b, tol) => Math.abs(a - b) <= tol; + +const stats = new PerfStats(); +let t = 0, submitted = 0; +stats.submitted(t, submitted); +// 10 s at 30 FPS presented, 60 frames/s submitted; one 200 ms hitch at 5 s. +for (let frame = 0; frame < 300; ++frame) { + t += frame === 150 ? 200 : 1000 / 30; + submitted += 2; + stats.submitted(t, submitted); + stats.framePresented(t); + // Each 33 ms frame: 20 ms inside the emulator, 5 of them in the GPU + // renderer, plus 3 ms presenting -> CPU 15 ms, GPU 8 ms. + stats.slice(t, 20, 5, 3); +} +const s = stats.snapshot(t); +expect(near(s.fps, 30, 1), `current FPS ${s.fps}`); +expect(near(s.averageFps, 30, 2), `average FPS ${s.averageFps}`); +expect(near(s.frameMs, 1000 / 30, 1), `frame time ${s.frameMs}`); +// Slowest 1% of 299 intervals = 3 frames: the 200 ms hitch and two 33 ms ones. +expect(near(s.low1Fps, 3000 / (200 + 2000 / 30), 0.2), `1% low should reveal the 200 ms hitch, got ${s.low1Fps}`); +expect(near(s.cpuMsPerSecond, 15 * 30, 20) && near(s.gpuMsPerSecond, 8 * 30, 20), + `CPU/GPU split ${s.cpuMsPerSecond}/${s.gpuMsPerSecond}`); +expect(s.bottleneck === 'CPU emulation', `bottleneck ${s.bottleneck}`); +expect(near(s.submittedPerSecond, 60, 2) && near(s.presentedPerSecond, 30, 1), + `submitted/presented ${s.submittedPerSecond}/${s.presentedPerSecond}`); +expect(s.totalSubmitted === 600 && s.totalPresented === 300, 'totals'); +const text = formatPerf(s); +for (const label of ['FPS', 'avg', '1% low', 'Frame time', 'CPU emulation', 'GPU rendering', 'submitted', 'presented']) { + expect(text.includes(label), `overlay text missing ${label}`); +} + +// Window: older than 60 s drops out of the average. +const w = new PerfStats({windowMs: 60000}); +for (let i = 0; i <= 600; ++i) w.framePresented(i * 100); // 10 FPS for 60 s +for (let i = 1; i <= 600; ++i) w.framePresented(60000 + i * 50); // then 20 FPS for 30 s +expect(near(w.snapshot(90000).averageFps, 15, 1.5), `windowed average ${w.snapshot(90000).averageFps}`); + +console.log(text); +console.log('PERF_OVERLAY_STATS=PASS'); From a5c48e92b1f5a65c70fce8cda1ad0128a6db5dda Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 05:52:17 +0000 Subject: [PATCH 37/65] CPU: compiled-only translation tier and cheaper guest calls (387 -> 540 MIPS) - Evicted translations whose compiled code holds no HIR pointers keep that code in a second tier and run again without retranslating or recompiling (cache misses over 30B instructions: 20.6k -> 2.7k). - Translation cache budget checked against live Xenia arena bytes. - Call/stack history is a ring buffer instead of a 32-entry shift per call. - Epilogue-signature match cached per tail target and code generation. - Executable-page content generations in a flat two-level table. - Guest function object built only on a translation miss. - run-title reports wasm memory and compiled-only cache stats. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 30 +++- prepare-hir-stack-history-overlay.py | 47 +++--- prepare-xenia-arena-overlay.py | 9 ++ src/xenia_web_bootstrap/hir_wasm_jit.cpp | 5 + src/xenia_web_bootstrap/hir_wasm_jit.h | 6 + src/xenia_web_bootstrap/probe_backend.cpp | 147 +++++++++++++++--- .../sparse_guest_memory.cpp | 24 ++- tools/run-title.mjs | 4 +- 8 files changed, 220 insertions(+), 52 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index da8a077f..b8bd0fae 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -7,7 +7,7 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie HIR executor and guest JIT. File loading finishes (`db360.textures.cmp`, ~50 MB, is read in full); 7 title threads run. - CPU: guest JIT compiles Xenia HIR to WebAssembly. Headless speed is about - 180M guest instructions/s. + 540M guest instructions/s over Banjo's first 30B instructions (see Step 1). - Deterministic headless runs (`run-title --deterministic 1000`): two identical runs match through 58.3B instructions (1098 checkpoints, same frames, draws and GPU packets). Fixed: a JIT segment resumed after an @@ -87,6 +87,32 @@ path in Spiral Mountain: the camera follows him past Bottles (124B) and by 127B he has reached the boulder pit, which triggers the next dialogue. Frames keep changing to the 127.5B instruction limit (3607 frames). +## Step 1: CPU speed (in progress) +Benchmark: Banjo-Tooie, first 30B guest instructions headless +(`run-title --max-minstr 30000 --render-from-minstr 999999 --deterministic +1000`), same container, Node 22. MIPS = guest instructions per second. + +| Change | MIPS | Cache misses | +| --- | --- | --- | +| Baseline (start of step 1) | 274 | — | +| No per-call `PPCContext` zeroing | 355 | 19.6k | +| Native vector compares in the JIT | 347 | — | +| Flat executable-page generation table; guest function object only on a miss | 355 | 19.6k | +| Ring-buffer call/stack history (was a 32-entry shift per call); cached epilogue signature per tail target | 387 | 20.6k | +| Compiled-only tier: an evicted translation keeps its compiled code (when it holds no HIR pointers) and runs again without retranslating or recompiling | 503–543 | 2.7k | + +What the profile showed: 74.5M guest calls in 30B instructions. The +translation cache (192 MiB of HIR) holds ~1000 functions, fewer than one +frame touches, so per-frame functions were evicted and retranslated and +recompiled 100+ times each. The JIT's function table only grows, so every +recompile also leaked a module. The compiled-only tier fixes both. Only +0.11% of instructions are interpreted (interior entries and cold code). +The cache budget is now checked against real arena bytes (Xenia's `Arena` +chunks), not an estimate. Wasm memory at 30B: 668 MiB. + +Next: cut the per-call path (JIT → resolver → cache → executor → JIT), which +is now the largest cost. + ## Not yet - Speed: reaching gameplay takes ~1 hour headless with the software renderer; the browser needs the WebGPU renderer and faster CPU emulation @@ -95,7 +121,7 @@ Frames keep changing to the 127.5B instruction limit (3607 frames). - Banjo's model looks small and partly fragmented in some frames. ## Tests (latest build) -- Regression runner: 60 of 69 pass. The 9 failures are pre-existing +- Regression runner: 61 of 70 pass. The 9 failures are pre-existing foundation tests (fpu/vmx/wasm-backend probes, guest-control, translation probe) and are unchanged by recent work. - Xenia PPC instruction suite with JIT forced: pass (1398 tests, 1406 diff --git a/prepare-hir-stack-history-overlay.py b/prepare-hir-stack-history-overlay.py index 381b7c0f..477e90e4 100644 --- a/prepare-hir-stack-history-overlay.py +++ b/prepare-hir-stack-history-overlay.py @@ -40,19 +40,26 @@ def replace_once(old: str, new: str, label: str) -> None: g_r360_stack_call_history{}; thread_local uint32_t g_r360_stack_write_history_count = 0; thread_local uint32_t g_r360_stack_call_history_count = 0; +// Ring buffers (every guest call records one event): index of the oldest. +thread_local uint32_t g_r360_stack_write_history_head = 0; +thread_local uint32_t g_r360_stack_call_history_head = 0; thread_local uint32_t g_r360_stack_event_sequence = 0; template void PushBoundedHistory(std::array& history, uint32_t* count, - const T& event) { - if (!count) return; + uint32_t* head, const T& event) { + if (!count || !head) return; if (*count < N) { - history[*count] = event; + history[(*head + *count) % N] = event; ++(*count); return; } - for (size_t i = 1; i < N; ++i) history[i - 1] = history[i]; - history[N - 1] = event; + history[*head] = event; + *head = uint32_t((*head + 1) % N); +} +// Oldest-first index into a ring history. +inline size_t HistorySlot(uint32_t head, uint32_t index) { + return size_t((head + index) % kR360StackHistoryCapacity); } void RecordStackWriteHistory(uint32_t source, uint64_t old_r1, @@ -64,7 +71,8 @@ def replace_once(old: str, new: str, label: str) -> None: event.old_r1 = old_r1; event.new_r1 = new_r1; PushBoundedHistory(g_r360_stack_write_history, - &g_r360_stack_write_history_count, event); + &g_r360_stack_write_history_count, + &g_r360_stack_write_history_head, event); } void RecordStackCallHistory(uint32_t target, uint32_t flags) { @@ -77,7 +85,8 @@ def replace_once(old: str, new: str, label: str) -> None: event.flags = flags; event.r1 = g_active_context->r[1]; PushBoundedHistory(g_r360_stack_call_history, - &g_r360_stack_call_history_count, event); + &g_r360_stack_call_history_count, + &g_r360_stack_call_history_head, event); } ''' replace_once(state_anchor, state_replacement, 'history state') @@ -141,6 +150,8 @@ def replace_once(old: str, new: str, label: str) -> None: g_r360_stack_call_history = {}; g_r360_stack_write_history_count = 0; g_r360_stack_call_history_count = 0; + g_r360_stack_write_history_head = 0; + g_r360_stack_call_history_head = 0; g_r360_stack_event_sequence = 0; ''' replace_once(reset_anchor, reset_replacement, 'outer history reset') @@ -157,40 +168,40 @@ def replace_once(old: str, new: str, label: str) -> None: return g_r360_stack_write_history_count; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_sequence(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].sequence : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].sequence : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_address(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].source : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].source : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_old_r1(uint32_t index) { - return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[index].old_r1) : 0; + return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].old_r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_new_r1(uint32_t index) { - return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[index].new_r1) : 0; + return index < g_r360_stack_write_history_count ? static_cast(g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].new_r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_write_depth(uint32_t index) { - return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[index].depth : 0; + return index < g_r360_stack_write_history_count ? g_r360_stack_write_history[HistorySlot(g_r360_stack_write_history_head, index)].depth : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_count() { return g_r360_stack_call_history_count; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_sequence(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].sequence : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].sequence : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_source(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].source : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].source : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_target(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].target : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].target : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_r1(uint32_t index) { - return index < g_r360_stack_call_history_count ? static_cast(g_r360_stack_call_history[index].r1) : 0; + return index < g_r360_stack_call_history_count ? static_cast(g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].r1) : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_depth(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].depth : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].depth : 0; } __attribute__((visibility("default"))) uint32_t r360_ppc_probe_stack_call_flags(uint32_t index) { - return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[index].flags : 0; + return index < g_r360_stack_call_history_count ? g_r360_stack_call_history[HistorySlot(g_r360_stack_call_history_head, index)].flags : 0; } } // extern "C" ''' diff --git a/prepare-xenia-arena-overlay.py b/prepare-xenia-arena-overlay.py index ff272639..f3d80efd 100644 --- a/prepare-xenia-arena-overlay.py +++ b/prepare-xenia-arena-overlay.py @@ -51,11 +51,13 @@ assert_not_null(buffer); assert_true((reinterpret_cast(buffer) & size_t(15)) == 0, "16 byte alignment required"); + g_r360_arena_live_bytes += capacity; } Arena::Chunk::~Chunk() { if (buffer) { free(buffer); + g_r360_arena_live_bytes -= capacity; } } ''' @@ -98,6 +100,13 @@ raise SystemExit(f"Upstream Arena {name} drifted") text = text.replace(a, b, 1) +# Live bytes held by all arena chunks. Retained HIR builders are most of it, +# so the translation cache budgets against this (probe_backend.cpp). +ns_anchor = "namespace xe {\n" +if text.count(ns_anchor) != 1: + raise SystemExit("Upstream Arena namespace drifted") +text = text.replace(ns_anchor, ns_anchor + "\nsize_t g_r360_arena_live_bytes = 0;\n", 1) + DEST.parent.mkdir(parents=True, exist_ok=True) DEST.write_text(text) print(f"Generated web Arena overlay: {DEST}") diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index af8cab4a..e5b17384 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -245,6 +245,7 @@ class Emitter { bool Compile(std::vector* out); uint32_t reject_opcode() const { return reject_opcode_; } + bool uses_exec() const { return uses_exec_; } private: struct Segment { @@ -343,6 +344,7 @@ class Emitter { uint32_t real_ = 0, n_ = 0, end_ = 0, poll_ = 0, spill_ = 0, restore_ = 0; uint32_t extra_ = 0; uint32_t reject_opcode_ = 0; + bool uses_exec_ = false; uint32_t counter_ = 0, fault_ = 0, return_slot_ = 0, return_valid_ = 0, scratch_ = 0; uint32_t page_directory_ = 0; // Inline sparse page walk for an access of `size` bytes at kLocAddr: falls @@ -920,6 +922,7 @@ bool Emitter::EmitGeneric(Instr* instr, uint32_t source) { StoreClass(c, uint32_t(16 * n)); } if (instr->dest && ClassOf(instr->dest->type) == Cls::kNone) return Reject(instr); + uses_exec_ = true; // the code now points into the builder's HIR I32(int32_t(reinterpret_cast(instr))); I32(int32_t(source)); Call(kHExec); @@ -1836,6 +1839,7 @@ uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { return 0; } const uint32_t request = g_next_request++; + slot->builder_free = !emitter.uses_exec(); slot->state = 1; slot->request = request; g_pending[request] = slot; @@ -1890,6 +1894,7 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { } uint32_t JitLastDecision() { return g_last_decision; } +bool JitEnabled() { return g_mode && g_compiler; } uint32_t JitRejectOpcode(HIRBuilder* builder) { auto it = g_reject_by_builder.find(builder); return it == g_reject_by_builder.end() ? 0xFFu : it->second; diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.h b/src/xenia_web_bootstrap/hir_wasm_jit.h index 92e36bc5..bdd6eab1 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.h +++ b/src/xenia_web_bootstrap/hir_wasm_jit.h @@ -32,8 +32,14 @@ struct JitSlot { uint32_t state = 0; // 0 not compiled, 1 compile pending, 2 not compilable uint32_t runs = 0; uint32_t request = 0; // pending asynchronous compile request id + // The compiled code holds no pointer into its HIR builder (no single-op + // executor fallbacks), so it can run after the builder is freed. + bool builder_free = false; }; +// Compiled code can run (a JIT compiler is installed and enabled). +bool JitEnabled(); + // The next HIR execution of `builder` belongs to `slot` (set by the cache just // before it runs the builder). void JitSetCandidate(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot); diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index d7fa247d..19fa64d8 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -58,6 +59,9 @@ extern "C" char __stack_high; extern "C" uintptr_t emscripten_stack_get_current(void); #endif +// Defined by the Arena overlay (prepare-xenia-arena-overlay.py). +namespace xe { extern size_t g_r360_arena_live_bytes; } + namespace render360::xenia_web { namespace { enum TrapPhase : uint32_t { @@ -305,6 +309,23 @@ struct CachedTranslation { uint32_t hir_blocks = 0, hir_instructions = 0; }; std::unordered_map g_translation_cache; +// Second tier: evicted translations whose compiled code needs no HIR +// (JitSlot::builder_free) keep only that code here, so a function that +// falls out of the HIR budget runs compiled again without retranslating or +// recompiling. Entries have no builder; interior entries (which run HIR) and +// interpreter-only runs still translate afresh. +std::unordered_map g_compiled_only_cache; +constexpr size_t kCompiledOnlyCacheLimit = 65536; +uint64_t g_compiled_only_hits = 0; +// Stands in for the freed builder: ExecuteHIRCorrectnessProbe only matches it +// against the JIT candidate (JitSetCandidate) and runs the compiled code. +xe::cpu::hir::HIRBuilder* CompiledOnlyBuilder() { + static auto* stub = new xe::cpu::hir::HIRBuilder(); + return stub; +} +xe::cpu::hir::HIRBuilder* ExecutionBuilder(CachedTranslation& entry) { + return entry.builder ? entry.builder.get() : CompiledOnlyBuilder(); +} size_t g_translation_cache_bytes = 0; size_t g_translation_cache_budget = size_t(192) * 1024 * 1024; uint64_t g_translation_cache_clock = 0; @@ -324,8 +345,12 @@ uint64_t TranslationKey(uint32_t begin, uint32_t end, bool fragment) { return (uint64_t(begin) << 32) | (uint64_t(end) & ~3ull) | (fragment ? 1u : 0u); } +// Bytes held by every Xenia arena chunk (prepare-xenia-arena-overlay.py); +// retained translations are nearly all of it. +size_t TranslationCacheLiveBytes() { return xe::g_r360_arena_live_bytes; } + void EvictTranslations() { - while (g_translation_cache_bytes > g_translation_cache_budget) { + while (TranslationCacheLiveBytes() > g_translation_cache_budget) { auto victim = g_translation_cache.end(); for (auto it = g_translation_cache.begin(); it != g_translation_cache.end(); ++it) { if (it->second.pins) continue; @@ -336,6 +361,21 @@ void EvictTranslations() { } if (victim == g_translation_cache.end()) return; g_translation_cache_bytes -= victim->second.bytes; + CachedTranslation& evicted = victim->second; + auto twin = g_compiled_only_cache.find(victim->first); + if (evicted.jit.function && evicted.jit.builder_free && + g_compiled_only_cache.size() < kCompiledOnlyCacheLimit && + (twin == g_compiled_only_cache.end() || !twin->second.pins)) { + CachedTranslation code; + code.begin = evicted.begin; + code.end = evicted.end; + code.generation_begin = evicted.generation_begin; + code.generation_end = evicted.generation_end; + code.jit = evicted.jit; + code.hir_blocks = evicted.hir_blocks; + code.hir_instructions = evicted.hir_instructions; + g_compiled_only_cache.insert_or_assign(victim->first, std::move(code)); + } JitReleaseSlot(&victim->second.jit); g_translation_cache.erase(victim); } @@ -347,9 +387,33 @@ std::unordered_map g_cache_miss_debug; void NoteCacheMiss(uint64_t key, uint32_t reason) { ++g_cache_miss_debug[(uint64_t(reason) << 32) | (key >> 32)]; } -CachedTranslation* LookupTranslation(uint64_t key) { +// Compiled-only entry for `key`, or nullptr (stale ones are dropped). +CachedTranslation* LookupCompiledOnly(uint64_t key) { + auto it = g_compiled_only_cache.find(key); + if (it == g_compiled_only_cache.end()) return nullptr; + CachedTranslation& entry = it->second; + if (entry.generation_begin != GetWasmBackendExecutableContentGeneration(entry.begin) || + entry.generation_end != GetWasmBackendExecutableContentGeneration(entry.end)) { + if (entry.pins) return nullptr; + g_compiled_only_cache.erase(it); + return nullptr; + } + if (!JitEnabled()) return nullptr; + ++g_compiled_only_hits; + return &entry; +} + +// `need_builder`: the caller runs the HIR itself (an interior entry), so a +// compiled-only entry does not count. +CachedTranslation* LookupTranslation(uint64_t key, bool need_builder = false) { auto it = g_translation_cache.find(key); - if (it == g_translation_cache.end()) { NoteCacheMiss(key, 0); return nullptr; } + if (it == g_translation_cache.end()) { + if (!need_builder) { + if (CachedTranslation* code = LookupCompiledOnly(key)) return code; + } + NoteCacheMiss(key, 0); + return nullptr; + } CachedTranslation& entry = it->second; if (entry.generation_begin != GetWasmBackendExecutableContentGeneration(entry.begin) || entry.generation_end != GetWasmBackendExecutableContentGeneration(entry.end)) { @@ -373,9 +437,9 @@ bool ExecuteCachedTranslation(CachedTranslation& entry) { ++g_translation_cache_hits; ++entry.pins; NoteTrapPhase(kTrapPhaseExecute, entry.begin); - JitSetCandidate(entry.builder.get(), &entry.jit); - const HIRCorrectnessResult result = - ExecuteHIRCorrectnessProbe(entry.builder.get(), memory); + xe::cpu::hir::HIRBuilder* const builder = ExecutionBuilder(entry); + JitSetCandidate(builder, &entry.jit); + const HIRCorrectnessResult result = ExecuteHIRCorrectnessProbe(builder, memory); --entry.pins; return result.supported && result.reached_return_boundary; } @@ -383,8 +447,9 @@ bool ExecuteCachedTranslation(CachedTranslation& entry) { // DefineFunction (translate + execute), or the cached translation of the same // function. The interior entry and provenance mode are applied by the caller. bool DefineOrRunCached(xe::cpu::ppc::PPCFrontend* frontend, - xe::cpu::GuestFunction* function, uint64_t key) { - if (CachedTranslation* cached = LookupTranslation(key)) { + xe::cpu::GuestFunction* function, uint64_t key, + bool need_builder = false) { + if (CachedTranslation* cached = LookupTranslation(key, need_builder)) { return ExecuteCachedTranslation(*cached); } ++g_translation_cache_misses; @@ -502,6 +567,10 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, struct CallTargetClass { uint32_t address = 0, fn_begin = 0, fn_end = 0, prolog = 0; bool valid = false, pdata = false, epilog_meta = false; + // MatchSharedEpilogReturnSignature reads the code at `address`; cached + // per content generation of the (at most two) pages it reads. + bool signature_checked = false, signature_match = false; + uint32_t signature_first_gpr = 0, signature_generation[2] = {}; }; static std::array call_classes; if (g_call_class_generation != g_call_class_seen_generation) { @@ -520,8 +589,21 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, } const bool epilog_by_metadata = cls.epilog_meta; uint32_t signature_first_gpr = 0; - const bool epilog_by_signature = - is_tail && MatchSharedEpilogReturnSignature(address, &signature_first_gpr); + bool epilog_by_signature = false; + if (is_tail) { + // The signature spans at most 21 words from `address` (r14..r31 + 3). + const uint32_t g0 = GetWasmBackendExecutableContentGeneration(address); + const uint32_t g1 = GetWasmBackendExecutableContentGeneration(address + 20u * 4u); + if (!cls.signature_checked || cls.signature_generation[0] != g0 || + cls.signature_generation[1] != g1) { + cls.signature_match = MatchSharedEpilogReturnSignature(address, &cls.signature_first_gpr); + cls.signature_generation[0] = g0; + cls.signature_generation[1] = g1; + cls.signature_checked = true; + } + epilog_by_signature = cls.signature_match; + signature_first_gpr = cls.signature_first_gpr; + } const bool is_epilog_return = epilog_by_metadata || epilog_by_signature; if (is_tail && is_epilog_return) { @@ -593,7 +675,13 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, "depth=%u\n", address, g_trap_depth); return false; } - ProbeGuestFunction nested_function(module, fn_begin); + // Only a translation miss scans or defines the function: a cached + // translation runs without constructing the guest function object. + std::optional nested_storage; + auto nested = [&]() -> ProbeGuestFunction& { + if (!nested_storage) nested_storage.emplace(module, fn_begin); + return *nested_storage; + }; uint32_t scan_end = use_owner ? fn_end - 4 : 0u; // Decoder-window-relative scan bound, valid once the code is paged. auto set_scan_end = [&]() -> bool { @@ -601,7 +689,7 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, const uint32_t loaded_size = r360_ppc_probe_loaded_size(); if (loaded_size < 4) return false; scan_end = use_owner ? fn_end - 4 : loaded_base + loaded_size - 4; - nested_function.set_end_address(scan_end); + nested().set_end_address(scan_end); return true; }; @@ -615,19 +703,20 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, g_missing_interior_entries.count((owner_key << 0) ^ (uint64_t(interior_entry) * 0x9E3779B97F4A7C15ull)); // The PPC scan only feeds a new translation: a cached one runs as is (its // key does not depend on the scan). - CachedTranslation* const cached_owner = known_missing ? nullptr : LookupTranslation(owner_key); + CachedTranslation* const cached_owner = + known_missing ? nullptr : LookupTranslation(owner_key, interior_entry != 0); if (!cached_owner && !known_missing) { if (!page_code() || !set_scan_end()) return false; xe::cpu::ppc::PPCScanner scanner(frontend); - if (!scanner.Scan(&nested_function, nullptr)) { + if (!scanner.Scan(&nested(), nullptr)) { std::fprintf(stderr, "R360_CALL_RESOLVE scan failed target=0x%08X function=0x%08X " "owner=%u\n", address, fn_begin, use_owner ? 1u : 0u); return false; } - if (use_owner && nested_function.end_address() < address) { - nested_function.set_end_address(scan_end); + if (use_owner && nested().end_address() < address) { + nested().set_end_address(scan_end); } } if (interior_entry) { @@ -643,7 +732,8 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, NoteTrapPhase(kTrapPhaseTranslate, address); ++g_trap_depth; translated = cached_owner ? ExecuteCachedTranslation(*cached_owner) - : DefineOrRunCached(frontend, &nested_function, owner_key); + : DefineOrRunCached(frontend, &nested(), owner_key, + interior_entry != 0); --g_trap_depth; SetHIRCorrectnessExecutionEntry(0u); missing_entry = interior_entry ? ConsumeHIRCorrectnessInteriorEntryMissing() : 0u; @@ -654,7 +744,7 @@ bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, R360_VERBOSE_TRACE( "R360_CALL_RESOLVE translated target=0x%08X function=0x%08X " "end=0x%08X flags=0x%X owner=%u interior=0x%08X result=%u\n", - address, fn_begin, nested_function.end_address(), call_flags, + address, fn_begin, nested().end_address(), call_flags, use_owner ? 1u : 0u, interior_entry, translated ? 1u : 0u); // A compiler tail target may be a valid PPC instruction without surviving as @@ -731,18 +821,23 @@ void RetainTranslatedBuilder(std::unique_ptr builder) JitReleaseSlot(&it->second.jit); g_translation_cache.erase(it); } + if (auto code = g_compiled_only_cache.find(g_retain_key); + code != g_compiled_only_cache.end() && !code->second.pins) { + g_compiled_only_cache.erase(code); + } CachedTranslation entry; entry.begin = g_retain_begin; entry.end = g_retain_end ? g_retain_end : g_retain_begin; entry.generation_begin = GetWasmBackendExecutableContentGeneration(entry.begin); entry.generation_end = GetWasmBackendExecutableContentGeneration(entry.end); - // Arena use is private to Xenia; an HIR instruction plus its result value - // and operand uses is about 192 bytes, plus the 64 KiB first arena chunk. + // Per-entry estimate (an HIR instruction with its value and uses is about + // 192 bytes, plus a part-used 64 KiB arena chunk); the budget itself is + // checked against the real arena bytes (EvictTranslations). size_t instructions = 0; for (auto* block = builder->first_block(); block; block = block->next) { for (auto* instr = block->instr_head; instr; instr = instr->next) ++instructions; } - entry.bytes = instructions * 192 + 64 * 1024; + entry.bytes = instructions * 192 + 32 * 1024; entry.hir_instructions = uint32_t(instructions); for (auto* block = builder->first_block(); block; block = block->next) ++entry.hir_blocks; entry.last_use = ++g_translation_cache_clock; @@ -758,7 +853,11 @@ void ResetTranslationCache() { JitReleaseSlot(&it->second.jit); it = g_translation_cache.erase(it); } + for (auto it = g_compiled_only_cache.begin(); it != g_compiled_only_cache.end();) { + it = it->second.pins ? std::next(it) : g_compiled_only_cache.erase(it); + } g_translation_cache_hits = g_translation_cache_misses = 0; + g_compiled_only_hits = 0; g_missing_interior_entries.clear(); ++g_call_class_generation; g_retain_pending = false; @@ -787,7 +886,7 @@ bool DefineTopLevelCached(xe::cpu::ppc::PPCFrontend* frontend, ? g_probe_backend->processor()->memory() : nullptr; if (memory && GetProbeExecuteCorrectnessOnAssemble() && !IsHIRCorrectnessExecutionActive()) { - if (CachedTranslation* cached = LookupTranslation(key)) { + if (CachedTranslation* cached = LookupTranslation(key, true)) { ++g_translation_cache_hits; ++cached->pins; NoteTrapPhase(kTrapPhaseExecute, cached->begin); @@ -1021,7 +1120,9 @@ extern "C" { uint32_t r360_hir_cache_hits() { return uint32_t(render360::xenia_web::g_translation_cache_hits); } uint32_t r360_hir_cache_misses() { return uint32_t(render360::xenia_web::g_translation_cache_misses); } uint32_t r360_hir_cache_entries() { return uint32_t(render360::xenia_web::g_translation_cache.size()); } -uint32_t r360_hir_cache_kilobytes() { return uint32_t(render360::xenia_web::g_translation_cache_bytes / 1024); } +uint32_t r360_hir_cache_compiled_only_entries() { return uint32_t(render360::xenia_web::g_compiled_only_cache.size()); } +uint32_t r360_hir_cache_compiled_only_hits() { return uint32_t(render360::xenia_web::g_compiled_only_hits); } +uint32_t r360_hir_cache_kilobytes() { return uint32_t(render360::xenia_web::TranslationCacheLiveBytes() / 1024); } uint32_t r360_hir_cache_set_budget_mb(uint32_t megabytes) { if (megabytes) render360::xenia_web::g_translation_cache_budget = size_t(megabytes) * 1024 * 1024; render360::xenia_web::EvictTranslations(); diff --git a/src/xenia_web_bootstrap/sparse_guest_memory.cpp b/src/xenia_web_bootstrap/sparse_guest_memory.cpp index c2aca660..985ccbcc 100644 --- a/src/xenia_web_bootstrap/sparse_guest_memory.cpp +++ b/src/xenia_web_bootstrap/sparse_guest_memory.cpp @@ -83,7 +83,10 @@ std::map, std::set> g_executable_aliases // This is the authoritative executable-byte content generation. It is sparse // across the full 32-bit Xbox virtual address space and is intentionally // independent of permission/mapping invalidation and the legacy backend epoch. -std::map g_executable_content_generations; +// Two-level table (same split as g_page_directory): translation-cache lookups +// read two generations per guest call, so this must be a couple of loads. +// A zero entry means the default generation 1. +std::array g_executable_content_generations{}; uint32_t g_last_fault_address = 0; uint32_t g_last_fault_code = kFaultNone; @@ -108,14 +111,18 @@ bool PageRangeValid(uint32_t address, uint32_t page_count) { uint32_t ContentGeneration(uint32_t address) { const uint32_t page = address >> kPageShift; - auto it = g_executable_content_generations.find(page); - return it == g_executable_content_generations.end() ? 1u : it->second; + const uint32_t* table = g_executable_content_generations[page >> kTableBits]; + if (!table) return 1u; + const uint32_t generation = table[page & (kTableEntries - 1u)]; + return generation ? generation : 1u; } void BumpContentGeneration(uint32_t page) { - auto [it, inserted] = g_executable_content_generations.emplace(page, 1u); - ++it->second; - if (it->second == 0) it->second = 1u; + uint32_t*& table = g_executable_content_generations[page >> kTableBits]; + if (!table) table = new uint32_t[kTableEntries](); + uint32_t& generation = table[page & (kTableEntries - 1u)]; + generation = (generation ? generation : 1u) + 1u; + if (generation == 0) generation = 1u; } Backing* GetBacking(uint32_t backing_id) { @@ -242,7 +249,10 @@ void ResetSparseGuestMemory() { g_mapped_pages = 0; g_backings.clear(); g_executable_aliases.clear(); - g_executable_content_generations.clear(); + for (uint32_t*& table : g_executable_content_generations) { + delete[] table; + table = nullptr; + } ClearFault(); } diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 1f9c04e9..a293cdbf 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -275,7 +275,7 @@ async function main(){ const elapsedMs=Date.now()-started; const report={ - input:path.resolve(args.input),kind:title.kind,bootstrap:bootstrapFile,elapsedMs,instructionBudget:budget||null, + input:path.resolve(args.input),kind:title.kind,bootstrap:bootstrapFile,elapsedMs,wasmMemoryMiB:Math.round(bootstrap.exports.memory.buffer.byteLength/1048576),instructionBudget:budget||null, vfs:{files:title.files.filter(f=>!f.directory).length,directories:title.files.filter(f=>f.directory).length,registered:vfs.registered,reads:bootstrap.exports.r360_vfs_reads?.()>>>0,pending:pendingGuestVfsRead(bootstrap)}, error:error?{message:error.message,details:error.render360??null}:null, }; @@ -289,7 +289,7 @@ async function main(){ memoryFault:result.memoryFaultCode?{code:result.memoryFaultCode,address:hex(result.memoryFaultAddress)}:null, guestFibers:result.guestFibers??null, guestThreadWaits:globalThis.__r360Threads??null, - framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), + framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), mainThread:result.mainThreadContext?{stackBytes:result.mainThreadContext.stackBytes,tlsBytes:result.mainThreadContext.tlsBytes,tlsTemplate:result.mainThreadContext.tlsTemplate}:null, kernelVariables:{relocated:result.kernelVariableRegistration?.relocated?.map(v=>v.name),placeholders:result.kernelVariableRegistration?.placeholders?.map(v=>kernelExportName(v.module,v.ordinal))}, importedKernelFunctions:result.kernelImports?.plan?.filter(i=>i.isKernelModule&&i.kind==='function').length, From 1e7e769c5ddf17815a9de06ccd536316f6881d19 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 06:01:10 +0000 Subject: [PATCH 38/65] CPU: fast path for cached plain calls (543 -> 642 MIPS) - Non-tail calls that hit the translation cache skip the owner/epilogue classification; the full resolver is out of line. - The HIR interpreter (ExecuteBuilder) is no longer inlined into the per-call executor entry. - __restgprlr register restores read the save area in one access. - Translation cache maps use a cheap 64-bit key hash (libc++ hashed the key byte-wise on wasm32). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 3 +- prepare-hir-hot-path-overlay.py | 13 +++++ .../kernel_import_probe.cpp | 4 ++ src/xenia_web_bootstrap/kernel_import_probe.h | 2 + src/xenia_web_bootstrap/probe_backend.cpp | 51 ++++++++++++++++++- 5 files changed, 70 insertions(+), 3 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index b8bd0fae..d79763f8 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -7,7 +7,7 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie HIR executor and guest JIT. File loading finishes (`db360.textures.cmp`, ~50 MB, is read in full); 7 title threads run. - CPU: guest JIT compiles Xenia HIR to WebAssembly. Headless speed is about - 540M guest instructions/s over Banjo's first 30B instructions (see Step 1). + 640M guest instructions/s over Banjo's first 30B instructions (see Step 1). - Deterministic headless runs (`run-title --deterministic 1000`): two identical runs match through 58.3B instructions (1098 checkpoints, same frames, draws and GPU packets). Fixed: a JIT segment resumed after an @@ -100,6 +100,7 @@ Benchmark: Banjo-Tooie, first 30B guest instructions headless | Flat executable-page generation table; guest function object only on a miss | 355 | 19.6k | | Ring-buffer call/stack history (was a 32-entry shift per call); cached epilogue signature per tail target | 387 | 20.6k | | Compiled-only tier: an evicted translation keeps its compiled code (when it holds no HIR pointers) and runs again without retranslating or recompiling | 503–543 | 2.7k | +| Small fast path for plain calls that hit the cache; interpreter kept out of the per-call entry; one read for `__restgprlr` register restores; cheap 64-bit key hash | 642 | 2.7k | What the profile showed: 74.5M guest calls in 30B instructions. The translation cache (192 MiB of HIR) holds ~1000 functions, fewer than one diff --git a/prepare-hir-hot-path-overlay.py b/prepare-hir-hot-path-overlay.py index 4518103b..37c50f0d 100644 --- a/prepare-hir-hot-path-overlay.py +++ b/prepare-hir-hot-path-overlay.py @@ -28,4 +28,17 @@ if '#include ' not in s: s = '#include \n' + s path.write_text(s) + +# The interpreter (ExecuteBuilder) runs well under 1% of guest instructions +# once the JIT is warm, but it was inlined into ExecuteHIRCorrectnessProbe, +# the per-call entry, which made every call pay for its frame. +s = path.read_text() +noinline_marker = 'R360_HOT_PATH_NOINLINE' +if noinline_marker not in s: + old = 'HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n' + if s.count(old) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: ExecuteBuilder anchor not found exactly once') + s = s.replace(old, '// ' + noinline_marker + ': kept out of the per-call entry.\n' + '__attribute__((noinline)) ' + old, 1) + path.write_text(s) print('R360_HOT_PATH_OVERLAY applied') diff --git a/src/xenia_web_bootstrap/kernel_import_probe.cpp b/src/xenia_web_bootstrap/kernel_import_probe.cpp index 361d3a4d..9dfd8c6c 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.cpp +++ b/src/xenia_web_bootstrap/kernel_import_probe.cpp @@ -257,6 +257,10 @@ bool RegisterKernelImportThunk(uint32_t thunk_address, uint32_t module_id, } return false; } +bool IsKernelImportThunk(uint32_t thunk_address) { + return FindKernelImport(thunk_address) != nullptr; +} + bool ResolveKernelImportThunk(uint32_t thunk_address) { const auto* entry = FindKernelImport(thunk_address); if (!entry) return false; diff --git a/src/xenia_web_bootstrap/kernel_import_probe.h b/src/xenia_web_bootstrap/kernel_import_probe.h index c7e42136..2848b322 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.h +++ b/src/xenia_web_bootstrap/kernel_import_probe.h @@ -10,6 +10,8 @@ bool RegisterKernelImportThunk(uint32_t thunk_address, uint32_t module_id, uint32_t ordinal, bool implemented, uint32_t abi_target); bool ResolveKernelImportThunk(uint32_t thunk_address); +// A registered import thunk (no side effects, unlike ResolveKernelImportThunk). +bool IsKernelImportThunk(uint32_t thunk_address); uint32_t KernelImportProbeCount(); uint32_t KernelImportProbeCalls(); uint32_t KernelImportProbeLastThunk(); diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index 19fa64d8..ef1e16a2 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -258,6 +258,23 @@ bool ExecuteSharedEpilogReturn(uint32_t address) { } const uint32_t r1 = static_cast(context->r[1]); + // rN..r31 are saved contiguously below the LR word at -8(r1): read the + // whole save area at once (the per-register loop below reports faults). + { + const uint32_t base = r1 - 16u - (31u - first_gpr) * 8u; + const uint32_t size = (32u - first_gpr) * 8u + 4u; + uint8_t area[18 * 8 + 4]; + if (ReadSparseGuestMemory(base, area, size)) { + for (uint32_t reg = first_gpr; reg <= 31u; ++reg) { + context->r[reg] = ReadBigEndian64(area + (reg - first_gpr) * 8u); + } + context->lr = ReadBigEndian32(area + (32u - first_gpr) * 8u); + R360_VERBOSE_TRACE( + "R360_EPILOG_HELPER executed target=0x%08X first_gpr=%u r1=0x%08X lr=0x%08X\n", + address, first_gpr, r1, static_cast(context->lr)); + return true; + } + } for (uint32_t reg = first_gpr; reg <= 31u; ++reg) { const int32_t disp = -16 - int32_t(31u - reg) * 8; const uint32_t ea = r1 + static_cast(disp); @@ -308,13 +325,20 @@ struct CachedTranslation { JitSlot jit; // compiled code for this translation (hir_wasm_jit.h) uint32_t hir_blocks = 0, hir_instructions = 0; }; -std::unordered_map g_translation_cache; +// libc++ hashes a 64-bit key with a byte-wise murmur on wasm32 (size_t is +// 32 bits); translation keys are looked up on every guest call. +struct TranslationKeyHash { + size_t operator()(uint64_t key) const { + return size_t(((key >> 32) ^ key) * 0x9E3779B97F4A7C15ull >> 32); + } +}; +std::unordered_map g_translation_cache; // Second tier: evicted translations whose compiled code needs no HIR // (JitSlot::builder_free) keep only that code here, so a function that // falls out of the HIR budget runs compiled again without retranslating or // recompiling. Entries have no builder; interior entries (which run HIR) and // interpreter-only runs still translate afresh. -std::unordered_map g_compiled_only_cache; +std::unordered_map g_compiled_only_cache; constexpr size_t kCompiledOnlyCacheLimit = 65536; uint64_t g_compiled_only_hits = 0; // Stands in for the freed builder: ExecuteHIRCorrectnessProbe only matches it @@ -513,8 +537,31 @@ bool TranslateNestedGuestAddress(uint32_t address, xe::cpu::Module* module) { return ok; } +bool TranslateNestedGuestAddressFull(uint32_t address, xe::cpu::Module* module, + uint32_t call_flags); + +// The common case of TranslateNestedGuestAddressFull, kept small: a plain +// (non-tail) call to a function with a cached translation. Tail calls (owner +// and epilogue handling), import thunks and misses take the full path. bool TranslateNestedGuestAddressOnce(uint32_t address, xe::cpu::Module* module, uint32_t call_flags) { + if (!(call_flags & xe::cpu::hir::CALL_TAIL) && !IsKernelImportThunk(address) && + StackHeadroom() >= kMinNestedStackHeadroom) { + if (CachedTranslation* cached = LookupTranslation(TranslationKey(address, 0u, false))) { + SetHIRCorrectnessExecutionEntry(0u); + NoteTrapPhase(kTrapPhaseTranslate, address); + ++g_trap_depth; + const bool translated = ExecuteCachedTranslation(*cached); + --g_trap_depth; + SetHIRCorrectnessExecutionEntry(0u); + return translated; + } + } + return TranslateNestedGuestAddressFull(address, module, call_flags); +} + +__attribute__((noinline)) bool TranslateNestedGuestAddressFull( + uint32_t address, xe::cpu::Module* module, uint32_t call_flags) { // Registered kernel/XAM import thunks are resolved before the bounded probe // memory check. Real XEX thunks may live outside the entry's 64 KiB staging // window, but a known HLE import is an external call boundary, not guest code From 91c2d7d072887f53f226db297a434b7e4fb6c742 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 06:26:56 +0000 Subject: [PATCH 39/65] CPU: memo translation-cache lookups; build at -O3 (642 -> 665 MIPS) The memo hits 99.9% of lookups and is validated by two epochs (cache map changes and executable-page rewrites). -O3 is ~4% faster than -O2. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 8 ++- build-xenia-ppc-bootstrap.sh | 5 +- link-xenia-ppc-bootstrap.sh | 2 +- src/xenia_web_bootstrap/probe_backend.cpp | 54 +++++++++++++++++-- .../sparse_guest_memory.cpp | 7 +++ .../wasm_backend_call_probe.h | 2 + tools/run-title.mjs | 2 +- 7 files changed, 70 insertions(+), 10 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index d79763f8..74cdbd65 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -7,7 +7,7 @@ Branch: `claude/xbox-360-emulator-optimization-74g72w`. Test title: Banjo-Tooie HIR executor and guest JIT. File loading finishes (`db360.textures.cmp`, ~50 MB, is read in full); 7 title threads run. - CPU: guest JIT compiles Xenia HIR to WebAssembly. Headless speed is about - 640M guest instructions/s over Banjo's first 30B instructions (see Step 1). + 665M guest instructions/s over Banjo's first 30B instructions (see Step 1). - Deterministic headless runs (`run-title --deterministic 1000`): two identical runs match through 58.3B instructions (1098 checkpoints, same frames, draws and GPU packets). Fixed: a JIT segment resumed after an @@ -101,6 +101,7 @@ Benchmark: Banjo-Tooie, first 30B guest instructions headless | Ring-buffer call/stack history (was a 32-entry shift per call); cached epilogue signature per tail target | 387 | 20.6k | | Compiled-only tier: an evicted translation keeps its compiled code (when it holds no HIR pointers) and runs again without retranslating or recompiling | 503–543 | 2.7k | | Small fast path for plain calls that hit the cache; interpreter kept out of the per-call entry; one read for `__restgprlr` register restores; cheap 64-bit key hash | 642 | 2.7k | +| Memo of cache lookups (99.9% hit; neutral); build at `-O3` instead of `-O2` | 663–671 | 2.7k | What the profile showed: 74.5M guest calls in 30B instructions. The translation cache (192 MiB of HIR) holds ~1000 functions, fewer than one @@ -111,8 +112,11 @@ recompile also leaked a module. The compiled-only tier fixes both. Only The cache budget is now checked against real arena bytes (Xenia's `Arena` chunks), not an estimate. Wasm memory at 30B: 668 MiB. +Benchmark noise between identical runs is about ±4%. + Next: cut the per-call path (JIT → resolver → cache → executor → JIT), which -is now the largest cost. +is now the largest cost: 74.5M guest calls go through ~10 host frames each, +all instrumented by Asyncify for guest-thread fibers. ## Not yet - Speed: reaching gameplay takes ~1 hour headless with the software diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 53de052d..3eea4b5b 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -64,10 +64,11 @@ python3 "$ROOT/prepare-xenia-spirv-browser-overlay.py" python3 "$ROOT/prepare-wasm-fpu-overlay.py" python3 "$ROOT/prepare-wasm-backend-cfg-overlay.py" -# Optimization level for the browser CPU runtime. -O0 made the HIR executor, +# Optimization level for the browser CPU runtime (-O3: ~4% faster guest code +# than -O2 on Banjo-Tooie). -O0 made the HIR executor, # sparse memory and kernel services several times slower on phones. # Override with R360_OPT=-O0 when bisecting a suspected miscompile. -R360_OPT="${R360_OPT:--O2}" +R360_OPT="${R360_OPT:--O3}" case "$R360_OPT" in -O0|-O1|-O2|-O3|-Os|-Oz) ;; *) echo "ERROR: invalid R360_OPT=$R360_OPT" >&2; exit 2 ;; esac # Xenia ships Release builds with NDEBUG ("We rely on assert being compiled out # in NDEBUG", xenia/base/assert.h). Debug-only asserts fire on real retail code diff --git a/link-xenia-ppc-bootstrap.sh b/link-xenia-ppc-bootstrap.sh index dd37121a..bbf823c9 100644 --- a/link-xenia-ppc-bootstrap.sh +++ b/link-xenia-ppc-bootstrap.sh @@ -148,7 +148,7 @@ EXPORT_LIST="$(IFS=,; echo "${EXPORTS[*]}")" # Xenos ExecuteBuffer has bounded nested command/constant scratch frames. Give # wasm32 an explicit 2 MiB stack so those frames cannot overwrite the sparse # guest-memory allocator while the source is being moved to static scratch. -R360_OPT="${R360_OPT:--O2}" +R360_OPT="${R360_OPT:--O3}" # Link without Binaryen optimization: Asyncify (below) must instrument the # module before any wasm-level inlining. A function that calls # asyncify.start_unwind is not instrumented itself, so inlining the fiber diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index ef1e16a2..08d36f8a 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -341,6 +341,8 @@ std::unordered_map g_translatio std::unordered_map g_compiled_only_cache; constexpr size_t kCompiledOnlyCacheLimit = 65536; uint64_t g_compiled_only_hits = 0; +// Any insert into or erase from either cache map. +uint32_t g_cache_epoch = 1; // Stands in for the freed builder: ExecuteHIRCorrectnessProbe only matches it // against the JIT candidate (JitSetCandidate) and runs the compiled code. xe::cpu::hir::HIRBuilder* CompiledOnlyBuilder() { @@ -398,10 +400,10 @@ void EvictTranslations() { code.jit = evicted.jit; code.hir_blocks = evicted.hir_blocks; code.hir_instructions = evicted.hir_instructions; - g_compiled_only_cache.insert_or_assign(victim->first, std::move(code)); + g_compiled_only_cache.insert_or_assign(victim->first, std::move(code)); ++g_cache_epoch; } JitReleaseSlot(&victim->second.jit); - g_translation_cache.erase(victim); + g_translation_cache.erase(victim); ++g_cache_epoch; } } @@ -419,6 +421,7 @@ CachedTranslation* LookupCompiledOnly(uint64_t key) { if (entry.generation_begin != GetWasmBackendExecutableContentGeneration(entry.begin) || entry.generation_end != GetWasmBackendExecutableContentGeneration(entry.end)) { if (entry.pins) return nullptr; + ++g_cache_epoch; g_compiled_only_cache.erase(it); return nullptr; } @@ -427,9 +430,48 @@ CachedTranslation* LookupCompiledOnly(uint64_t key) { return &entry; } +CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder); + +// Direct-mapped memo of LookupTranslation results. A slot holds while +// neither cache map has changed and no executable page has been rewritten +// (both epochs unchanged), so a hit needs no hashing or generation checks. +struct LookupMemo { + uint64_t key = 0; + CachedTranslation* entry = nullptr; + uint32_t cache_epoch = 0, content_epoch = 0; + bool compiled_only = false; +}; +std::array g_lookup_memo; +uint64_t g_lookup_memo_hits = 0; + // `need_builder`: the caller runs the HIR itself (an interior entry), so a // compiled-only entry does not count. CachedTranslation* LookupTranslation(uint64_t key, bool need_builder = false) { + if (need_builder) return LookupTranslationSlow(key, true); + LookupMemo& memo = g_lookup_memo[TranslationKeyHash{}(key) & 4095u]; + const uint32_t content_epoch = GetWasmBackendExecutableContentEpoch(); + if (memo.entry && memo.key == key && memo.cache_epoch == g_cache_epoch && + memo.content_epoch == content_epoch && (!memo.compiled_only || JitEnabled())) { + ++g_lookup_memo_hits; + if (memo.compiled_only) { + ++g_compiled_only_hits; + } else { + memo.entry->last_use = ++g_translation_cache_clock; + } + return memo.entry; + } + CachedTranslation* entry = LookupTranslationSlow(key, false); + // The slow lookup may have erased a stale entry (epoch bumped): record the + // epochs after it. + memo.key = key; + memo.entry = entry; + memo.cache_epoch = g_cache_epoch; + memo.content_epoch = GetWasmBackendExecutableContentEpoch(); + memo.compiled_only = entry && !entry->builder; + return entry; +} + +CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder) { auto it = g_translation_cache.find(key); if (it == g_translation_cache.end()) { if (!need_builder) { @@ -445,6 +487,7 @@ CachedTranslation* LookupTranslation(uint64_t key, bool need_builder = false) { NoteCacheMiss(key, 1); g_translation_cache_bytes -= entry.bytes; JitReleaseSlot(&entry.jit); + ++g_cache_epoch; g_translation_cache.erase(it); return nullptr; } @@ -867,10 +910,11 @@ void RetainTranslatedBuilder(std::unique_ptr builder) g_translation_cache_bytes -= it->second.bytes; JitReleaseSlot(&it->second.jit); g_translation_cache.erase(it); + ++g_cache_epoch; } if (auto code = g_compiled_only_cache.find(g_retain_key); code != g_compiled_only_cache.end() && !code->second.pins) { - g_compiled_only_cache.erase(code); + g_compiled_only_cache.erase(code); ++g_cache_epoch; } CachedTranslation entry; entry.begin = g_retain_begin; @@ -890,10 +934,11 @@ void RetainTranslatedBuilder(std::unique_ptr builder) entry.last_use = ++g_translation_cache_clock; entry.builder = std::move(builder); g_translation_cache_bytes += entry.bytes; - g_translation_cache.emplace(g_retain_key, std::move(entry)); + g_translation_cache.emplace(g_retain_key, std::move(entry)); ++g_cache_epoch; EvictTranslations(); } void ResetTranslationCache() { + ++g_cache_epoch; for (auto it = g_translation_cache.begin(); it != g_translation_cache.end();) { if (it->second.pins) { ++it; continue; } g_translation_cache_bytes -= it->second.bytes; @@ -1168,6 +1213,7 @@ uint32_t r360_hir_cache_hits() { return uint32_t(render360::xenia_web::g_transla uint32_t r360_hir_cache_misses() { return uint32_t(render360::xenia_web::g_translation_cache_misses); } uint32_t r360_hir_cache_entries() { return uint32_t(render360::xenia_web::g_translation_cache.size()); } uint32_t r360_hir_cache_compiled_only_entries() { return uint32_t(render360::xenia_web::g_compiled_only_cache.size()); } +uint32_t r360_hir_cache_memo_hits() { return uint32_t(render360::xenia_web::g_lookup_memo_hits); } uint32_t r360_hir_cache_compiled_only_hits() { return uint32_t(render360::xenia_web::g_compiled_only_hits); } uint32_t r360_hir_cache_kilobytes() { return uint32_t(render360::xenia_web::TranslationCacheLiveBytes() / 1024); } uint32_t r360_hir_cache_set_budget_mb(uint32_t megabytes) { diff --git a/src/xenia_web_bootstrap/sparse_guest_memory.cpp b/src/xenia_web_bootstrap/sparse_guest_memory.cpp index 985ccbcc..2497074a 100644 --- a/src/xenia_web_bootstrap/sparse_guest_memory.cpp +++ b/src/xenia_web_bootstrap/sparse_guest_memory.cpp @@ -117,7 +117,12 @@ uint32_t ContentGeneration(uint32_t address) { return generation ? generation : 1u; } +// Bumped with every content generation change (and on reset), so a cache of +// generation checks can tell nothing has been rewritten. +uint32_t g_executable_content_epoch = 1; + void BumpContentGeneration(uint32_t page) { + ++g_executable_content_epoch; uint32_t*& table = g_executable_content_generations[page >> kTableBits]; if (!table) table = new uint32_t[kTableEntries](); uint32_t& generation = table[page & (kTableEntries - 1u)]; @@ -237,11 +242,13 @@ void MarkWasmBackendExecutableContentChangedRange(uint32_t address, InvalidateWasmBackendExecutableRange(address, size); } +uint32_t GetWasmBackendExecutableContentEpoch() { return g_executable_content_epoch; } uint32_t GetWasmBackendExecutableContentGeneration(uint32_t address) { return ContentGeneration(address); } void ResetSparseGuestMemory() { + ++g_executable_content_epoch; for (PageEntry*& table : g_page_directory) { delete[] table; table = nullptr; diff --git a/src/xenia_web_bootstrap/wasm_backend_call_probe.h b/src/xenia_web_bootstrap/wasm_backend_call_probe.h index 5a50c956..dba63fd9 100644 --- a/src/xenia_web_bootstrap/wasm_backend_call_probe.h +++ b/src/xenia_web_bootstrap/wasm_backend_call_probe.h @@ -22,6 +22,8 @@ void MarkWasmBackendExecutableContentChangedRange(uint32_t address, uint32_t size); uint32_t GetWasmBackendExecutablePageGeneration(uint32_t address); uint32_t GetWasmBackendExecutableContentGeneration(uint32_t address); +// Changes whenever any executable content generation changes. +uint32_t GetWasmBackendExecutableContentEpoch(); uint32_t GetWasmBackendCallStatus(); uint32_t GetWasmBackendCallFunctionCount(); uint32_t GetWasmBackendCallFunctionAddress(uint32_t index); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index a293cdbf..05b78773 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -289,7 +289,7 @@ async function main(){ memoryFault:result.memoryFaultCode?{code:result.memoryFaultCode,address:hex(result.memoryFaultAddress)}:null, guestFibers:result.guestFibers??null, guestThreadWaits:globalThis.__r360Threads??null, - framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), + framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),cacheMemoHits:f('r360_hir_cache_memo_hits'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), mainThread:result.mainThreadContext?{stackBytes:result.mainThreadContext.stackBytes,tlsBytes:result.mainThreadContext.tlsBytes,tlsTemplate:result.mainThreadContext.tlsTemplate}:null, kernelVariables:{relocated:result.kernelVariableRegistration?.relocated?.map(v=>v.name),placeholders:result.kernelVariableRegistration?.placeholders?.map(v=>kernelExportName(v.module,v.ordinal))}, importedKernelFunctions:result.kernelImports?.plan?.filter(i=>i.isKernelModule&&i.kind==='function').length, From 0f7124484d9791fca25ea5f1decc90af4d704e0e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:33:00 +0000 Subject: [PATCH 40/65] Guest JIT: on-stack replacement into compiled code A function entered once that loops (a thread's main loop, a wait loop) never reached the call-count threshold and was interpreted for its whole life; past the first 30B instructions of Banjo-Tooie 2.4B HIR instructions ran in the interpreter, over half the host time. Interior (tail-call) entries were also always interpreted. - The interpreter hands a run over to compiled code at a block head after 1000 interpreted instructions (compiling it then), and at once for an interior entry of a hot function. Only for functions whose HIR values are all block-local, so every block head is an exact entry point. - Generated functions start at a requested dispatcher segment. - A nested call's first run after a translation miss now runs from its new cache entry (not inside Assemble), so it has a JIT slot too. - test-guest-jit-osr.mjs: a loop called once moves to compiled code with the interpreter's results. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- prepare-hir-hot-path-overlay.py | 45 ++++++++++ src/xenia_web_bootstrap/hir_jit_glue.inc | 32 ++++++- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 70 ++++++++++++++- src/xenia_web_bootstrap/hir_wasm_jit.h | 17 ++++ src/xenia_web_bootstrap/probe_backend.cpp | 42 ++++++++- test-guest-jit-osr.mjs | 105 ++++++++++++++++++++++ tools/run-title.mjs | 2 +- 7 files changed, 305 insertions(+), 8 deletions(-) create mode 100644 test-guest-jit-osr.mjs diff --git a/prepare-hir-hot-path-overlay.py b/prepare-hir-hot-path-overlay.py index 37c50f0d..31e79c76 100644 --- a/prepare-hir-hot-path-overlay.py +++ b/prepare-hir-hot-path-overlay.py @@ -41,4 +41,49 @@ s = s.replace(old, '// ' + noinline_marker + ': kept out of the per-call entry.\n' '__attribute__((noinline)) ' + old, 1) path.write_text(s) + +# On-stack replacement (hir_wasm_jit.h JitOsrFunction): a run that has +# interpreted many instructions, or an interior entry, continues in compiled +# code at the next block head. Without it a function entered once that loops +# (a thread's main loop, a wait loop) was interpreted for its whole life. +s = path.read_text() +osr_marker = 'R360_HOT_PATH_OSR' +if osr_marker not in s: + builder_at = s.index('HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n') + decl_at = s.rindex('\n', 0, s.rindex('// R360_HOT_PATH_NOINLINE', 0, builder_at)) + 1 + s = (s[:decl_at] + + '// ' + osr_marker + ' (prepare-hir-hot-path-overlay.py; defined in hir_jit_glue.inc).\n' + '} // namespace\n' + 'bool JitTryOsr(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot,\n' + ' const xe::cpu::hir::Block* block, bool hot, xe::Memory* memory,\n' + ' xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result);\n' + 'namespace {\n' + '// Interpreted instructions in one run before it moves to compiled code.\n' + 'constexpr uint32_t kOsrInstructions = 1000;\n\n' + s[decl_at:]) + builder_at = s.index('HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder,\n') + values = ' RuntimeValues values;\n' + at = s.index(values, builder_at) + len(values) + s = s[:at] + ' JitSlot* const osr_slot = JitTakeOsrSlot(builder);\n bool osr_tried = false;\n' + s[at:] + loop = ' while (block && supported && !reached_return) {\n auto* next_block = block->next;\n' + at = s.index(loop, builder_at) + if s.count(loop) != 1: + raise SystemExit('prepare-hir-hot-path-overlay: interpreter loop anchor not found exactly once') + hook = (' while (block && supported && !reached_return) {\n' + ' if (osr_slot) {\n' + ' // An interior entry starts at a block head: run it compiled once\n' + ' // the owner is hot; a long run moves over at its next block.\n' + ' const bool interior = first_execution_block && entry_instr;\n' + ' const bool hot = !osr_tried && result.instructions_executed >= kOsrInstructions;\n' + ' if (interior || hot) {\n' + ' if (hot) osr_tried = true;\n' + ' HIRCorrectnessResult compiled;\n' + ' if (JitTryOsr(builder, osr_slot, block, hot, memory, context, &compiled)) {\n' + ' compiled.instructions_executed = result.instructions_executed;\n' + ' return compiled;\n' + ' }\n' + ' }\n' + ' }\n' + ' auto* next_block = block->next;\n') + s = s[:at] + hook + s[at + len(loop):] + path.write_text(s) print('R360_HOT_PATH_OVERLAY applied') diff --git a/src/xenia_web_bootstrap/hir_jit_glue.inc b/src/xenia_web_bootstrap/hir_jit_glue.inc index 057082c4..fc5441a8 100644 --- a/src/xenia_web_bootstrap/hir_jit_glue.inc +++ b/src/xenia_web_bootstrap/hir_jit_glue.inc @@ -87,6 +87,8 @@ uint32_t JitInstructionCounterAddress() { uint32_t JitDebugWatchAddress() { return g_debug_watch_address; } uint32_t JitFaultAddress() { return uint32_t(reinterpret_cast(&g_jit_fault)); } uint32_t JitScratchAddress() { return uint32_t(reinterpret_cast(g_jit_scratch)); } +uint32_t g_jit_entry_segment = 0; +uint32_t JitEntrySegmentAddress() { return uint32_t(reinterpret_cast(&g_jit_entry_segment)); } uint32_t JitReturnAddressSlot() { return uint32_t(reinterpret_cast(&g_next_guest_return_address)); } @@ -119,12 +121,39 @@ void JitProfileInterpreted(xe::cpu::hir::HIRBuilder* builder, uint32_t reason, u ++e.runs; } +// Runs the compiled `function` from dispatcher segment `entry` and maps its +// status to an executor result. +void JitRun(uint32_t function, uint32_t entry, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result); + // Runs `builder` as compiled code when it has some (ExecuteHIRCorrectnessProbe // calls this in place of ExecuteBuilder for plain function entries). bool JitTryExecute(xe::cpu::hir::HIRBuilder* builder, xe::Memory* memory, xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { const uint32_t function = JitTakeFunction(builder); if (!function) return false; + JitRun(function, 0, memory, context, result); + return true; +} + +// ExecuteBuilder hands a run over to compiled code at the head of `block` +// (JitOsrFunction); false keeps interpreting. +uint64_t g_jit_osr_entries = 0; +bool JitTryOsr(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot, + const xe::cpu::hir::Block* block, bool hot, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { + const uint32_t function = JitOsrFunction(builder, slot, hot); + if (!function) return false; + const uint32_t segment = JitSegmentOfBlock(builder, block); + if (segment == 0xFFFFFFFFu) return false; + ++g_jit_osr_entries; + JitRun(function, segment, memory, context, result); + return true; +} + +void JitRun(uint32_t function, uint32_t entry, xe::Memory* memory, + xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { + g_jit_entry_segment = entry; g_jit_memory = memory; g_jit_fault = 0; g_jit_fail_kind = g_jit_fail_opcode = g_jit_fail_address = 0; @@ -149,7 +178,6 @@ bool JitTryExecute(xe::cpu::hir::HIRBuilder* builder, xe::Memory* memory, result->blocker_address = g_jit_fail_address; break; } - return true; } } // namespace render360::xenia_web @@ -278,6 +306,8 @@ R360_JIT_HELPER(mulhi64) uint64_t r360_jit_h_mulhi64(uint64_t a, uint64_t b, uin return is_unsigned ? uint64_t((unsigned __int128)a * (unsigned __int128)b >> 64) : uint64_t(((__int128)int64_t(a) * (__int128)int64_t(b)) >> 64); } +__attribute__((used, export_name("r360_jit_osr_entries"))) +uint32_t r360_jit_osr_entries() { return uint32_t(rxj::g_jit_osr_entries); } __attribute__((used, export_name("r360_jit_profile"))) uint32_t r360_jit_profile(uint32_t command) { if (command == 1) { rxj::g_jit_profile = true; rxj::g_jit_profile_entries.clear(); return 1; } diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index e5b17384..6b38da3c 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -20,6 +20,9 @@ namespace render360::xenia_web { uint32_t JitInstructionCounterAddress(); uint32_t JitFaultAddress(); uint32_t JitScratchAddress(); +// Dispatcher segment the next generated-function call starts at (0 = entry); +// generated code reads and clears it. +uint32_t JitEntrySegmentAddress(); uint32_t SparseGuestPageDirectoryAddress(); // Nonzero while a debug store watch (r360_debug_watch) is armed. uint32_t JitDebugWatchAddress(); @@ -51,6 +54,9 @@ uint32_t g_compiler = 0; uint32_t g_next_request = 1; std::unordered_map g_pending; HIRBuilder* g_candidate_builder = nullptr; +// The run JitTakeFunction last sent to the interpreter (JitTakeOsrSlot). +HIRBuilder* g_osr_builder = nullptr; +JitSlot* g_osr_slot = nullptr; uint32_t g_last_decision = 0; JitSlot* g_candidate_slot = nullptr; // Telemetry. @@ -246,6 +252,7 @@ class Emitter { bool Compile(std::vector* out); uint32_t reject_opcode() const { return reject_opcode_; } bool uses_exec() const { return uses_exec_; } + bool osr_capable() const { return osr_capable_; } private: struct Segment { @@ -345,6 +352,8 @@ class Emitter { uint32_t extra_ = 0; uint32_t reject_opcode_ = 0; bool uses_exec_ = false; + bool osr_capable_ = false; + uint32_t entry_slot_ = 0; uint32_t counter_ = 0, fault_ = 0, return_slot_ = 0, return_valid_ = 0, scratch_ = 0; uint32_t page_directory_ = 0; // Inline sparse page walk for an access of `size` bytes at kLocAddr: falls @@ -1742,14 +1751,32 @@ bool Emitter::Compile(std::vector* out) { scratch_ = JitScratchAddress(); page_directory_ = SparseGuestPageDirectoryAddress(); return_valid_ = JitReturnValidSlot(); + entry_slot_ = JitEntrySegmentAddress(); if (!Plan()) return false; AllocateTemporaries(); + // Block-local values only: every block head is a valid entry. + using namespace xe::cpu::hir; + osr_capable_ = true; + for (Block* block = builder_->first_block(); block && osr_capable_; block = block->next) { + for (Instr* i = block->instr_head; i && osr_capable_; i = i->next) { + const auto sig = i->opcode->signature; + const Value* operands[3] = { + GET_OPCODE_SIG_TYPE_SRC1(sig) == OPCODE_SIG_TYPE_V ? i->src1.value : nullptr, + GET_OPCODE_SIG_TYPE_SRC2(sig) == OPCODE_SIG_TYPE_V ? i->src2.value : nullptr, + GET_OPCODE_SIG_TYPE_SRC3(sig) == OPCODE_SIG_TYPE_V ? i->src3.value : nullptr}; + for (const Value* v : operands) { + if (v && !v->IsConstant() && (!v->def || v->def->block != block)) osr_capable_ = false; + } + } + } // Function body (after the local declarations, which depend on it). - // Entry: rewinding -> RESTORE, else segment 0. + // Entry: rewinding -> RESTORE, else the requested entry segment (0 unless + // the interpreter is handing over mid-run), which is then cleared. Call(kHState); I32(2); Op(oI32Eq); - If(kI32); I32(int32_t(restore_)); Else(); I32(0); End(); + If(kI32); I32(int32_t(restore_)); Else(); I32(int32_t(entry_slot_)); Mem(oI32Load, 2, 0); End(); Set(kLocPc); + I32(int32_t(entry_slot_)); I32(0); Mem(oI32Store, 2, 0); I32(int32_t(kPollBudget)); Set(kLocBudget); code_.u8(oLoop); code_.u8(kVoid); for (uint32_t i = 0; i < n_; ++i) { code_.u8(oBlock); code_.u8(kVoid); } @@ -1840,6 +1867,7 @@ uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { } const uint32_t request = g_next_request++; slot->builder_free = !emitter.uses_exec(); + slot->osr_capable = emitter.osr_capable(); slot->state = 1; slot->request = request; g_pending[request] = slot; @@ -1867,6 +1895,8 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { JitSlot* slot = g_candidate_builder == builder ? g_candidate_slot : nullptr; g_candidate_builder = nullptr; g_candidate_slot = nullptr; + g_osr_builder = builder; + g_osr_slot = slot; g_last_decision = 5; if (!g_mode || !g_compiler) return 0; g_last_decision = 1; @@ -1895,6 +1925,42 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { uint32_t JitLastDecision() { return g_last_decision; } bool JitEnabled() { return g_mode && g_compiler; } + +JitSlot* JitTakeOsrSlot(HIRBuilder* builder) { + JitSlot* slot = nullptr; + if (g_candidate_builder == builder) { + slot = g_candidate_slot; + } else if (g_osr_builder == builder) { + slot = g_osr_slot; + } + g_candidate_builder = g_osr_builder = nullptr; + g_candidate_slot = g_osr_slot = nullptr; + return slot; +} + +uint32_t JitOsrFunction(HIRBuilder* builder, JitSlot* slot, bool hot) { + if (!slot || !g_mode || !g_compiler) return 0; + if (!slot->function) { + if (slot->state) return 0; // pending or not compilable + if (!hot && ++slot->runs < g_hot_threshold) return 0; + if (!RequestCompile(builder, slot)) return 0; + } + return slot->osr_capable ? slot->function : 0; +} + +uint32_t JitSegmentOfBlock(HIRBuilder* builder, const Block* target) { + // Plan()'s split: one segment per block plus one per call site after the + // block's first instruction. + uint32_t segment = 0; + for (Block* block = builder->first_block(); block; block = block->next) { + if (block == target) return segment; + ++segment; + for (Instr* instr = block->instr_head; instr; instr = instr->next) { + if (instr != block->instr_head && instr->opcode && IsCallSite(instr->opcode->num)) ++segment; + } + } + return 0xFFFFFFFFu; +} uint32_t JitRejectOpcode(HIRBuilder* builder) { auto it = g_reject_by_builder.find(builder); return it == g_reject_by_builder.end() ? 0xFFu : it->second; diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.h b/src/xenia_web_bootstrap/hir_wasm_jit.h index bdd6eab1..8698fe68 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.h +++ b/src/xenia_web_bootstrap/hir_wasm_jit.h @@ -3,6 +3,7 @@ #include namespace xe::cpu::hir { +class Block; class HIRBuilder; } @@ -35,6 +36,9 @@ struct JitSlot { // The compiled code holds no pointer into its HIR builder (no single-op // executor fallbacks), so it can run after the builder is freed. bool builder_free = false; + // No HIR value is used outside its defining block, so the code can be + // entered at any block head (JitOsrFunction). + bool osr_capable = false; }; // Compiled code can run (a JIT compiler is installed and enabled). @@ -55,6 +59,19 @@ uint32_t JitLastDecision(); // First HIR opcode that kept `builder` from compiling (diagnostics). uint32_t JitRejectOpcode(xe::cpu::hir::HIRBuilder* builder); +// Entering compiled code from the interpreter (on-stack replacement): a +// function entered once that loops (a thread's main loop, a wait loop) never +// reaches the call-count threshold and would stay interpreted. +// The slot the interpreter's current run of `builder` belongs to (the +// candidate JitTakeFunction declined, or one an interior entry never took). +JitSlot* JitTakeOsrSlot(xe::cpu::hir::HIRBuilder* builder); +// Compiled function for entering `builder` mid-run, compiling it now when +// `hot` (else when it has run often enough); 0 when it cannot be entered. +uint32_t JitOsrFunction(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot, bool hot); +// Dispatcher segment where `block` starts in the compiled function. +uint32_t JitSegmentOfBlock(xe::cpu::hir::HIRBuilder* builder, + const xe::cpu::hir::Block* block); + // The cache entry owning `slot` is being destroyed. void JitReleaseSlot(JitSlot* slot); diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index 08d36f8a..82de1d28 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -495,13 +495,25 @@ CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder) { return &entry; } +// A nested call's first run after a translation miss: ProbeAssembler::Assemble +// skips executing a builder about to be retained, and DefineOrRunCached runs +// it from its new cache entry instead, so that run already has a JIT slot +// (compilation by call count, on-stack replacement of a long first run). +bool g_defer_first_run = false; // DefineOrRunCached is translating +bool g_deferred_first_run = false; // Assemble skipped the run +bool CanRetainTranslatedBuilder() { + if (!g_retain_pending) return false; + auto it = g_translation_cache.find(g_retain_key); + return it == g_translation_cache.end() || !it->second.pins; +} + // Runs a cached translation as ProbeAssembler::Assemble runs a nested one. -bool ExecuteCachedTranslation(CachedTranslation& entry) { +bool ExecuteCachedTranslation(CachedTranslation& entry, bool count_hit = true) { auto* memory = g_probe_backend && g_probe_backend->processor() ? g_probe_backend->processor()->memory() : nullptr; if (!memory) return false; - ++g_translation_cache_hits; + if (count_hit) ++g_translation_cache_hits; ++entry.pins; NoteTrapPhase(kTrapPhaseExecute, entry.begin); xe::cpu::hir::HIRBuilder* const builder = ExecutionBuilder(entry); @@ -527,7 +539,22 @@ bool DefineOrRunCached(xe::cpu::ppc::PPCFrontend* frontend, g_retain_key = key; g_retain_begin = function->address(); g_retain_end = function->end_address(); - const bool ok = frontend->DefineFunction(function, 0); + const bool saved_defer = g_defer_first_run; + g_defer_first_run = true; + g_deferred_first_run = false; + bool ok = frontend->DefineFunction(function, 0); + g_defer_first_run = saved_defer; + if (g_deferred_first_run) { + g_deferred_first_run = false; + // RetainTranslatedBuilder pinned the entry so nothing evicted it. + auto it = g_translation_cache.find(key); + if (!ok || it == g_translation_cache.end()) { + ok = false; + } else { + --it->second.pins; + ok = ExecuteCachedTranslation(it->second, false); + } + } if (g_retain_pending) NoteCacheMiss(key, ok ? 4u : 5u); // not retained g_retain_pending = saved_pending; g_retain_key = saved_key; @@ -932,6 +959,7 @@ void RetainTranslatedBuilder(std::unique_ptr builder) entry.hir_instructions = uint32_t(instructions); for (auto* block = builder->first_block(); block; block = block->next) ++entry.hir_blocks; entry.last_use = ++g_translation_cache_clock; + if (g_deferred_first_run) entry.pins = 1; // until DefineOrRunCached runs it entry.builder = std::move(builder); g_translation_cache_bytes += entry.bytes; g_translation_cache.emplace(g_retain_key, std::move(entry)); ++g_cache_epoch; @@ -1078,7 +1106,13 @@ bool ProbeAssembler::Assemble(xe::cpu::GuestFunction* function, xe::cpu::hir::HI } HIRCorrectnessResult correctness; - if (execute_correctness) { + if (nested_execution && g_defer_first_run && !g_deferred_first_run && + CanRetainTranslatedBuilder()) { + // DefineOrRunCached runs it once it is retained (see g_defer_first_run). + g_deferred_first_run = true; + correctness.supported = true; + correctness.reached_return_boundary = true; + } else if (execute_correctness) { NoteTrapPhase(kTrapPhaseExecute, function ? function->address() : 0u); correctness = ExecuteHIRCorrectnessProbe(builder, memory); } else { diff --git a/test-guest-jit-osr.mjs b/test-guest-jit-osr.mjs new file mode 100644 index 00000000..5972587b --- /dev/null +++ b/test-guest-jit-osr.mjs @@ -0,0 +1,105 @@ +// On-stack replacement test for the guest JIT (hir_wasm_jit.h JitOsrFunction): +// a guest function called once that runs a long loop starts interpreted (it +// has not reached the call-count threshold) and must continue in compiled +// code at a block head with exactly the interpreter's results. +// +// Usage: node test-guest-jit-osr.mjs [bootstrap.wasm] +// Requires powerpc64-linux-gnu-{as,ld} (apt: binutils-powerpc64-linux-gnu). +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import {execFileSync} from 'node:child_process'; +import {WASI} from 'node:wasi'; +import {spawnSync} from 'node:child_process'; +import {installGuestJit} from './render360-guest-jit.mjs'; + +// The probe translates and runs the guest code on one host stack; V8's +// default 984 KiB native stack can overflow when a wasm tier-up lands deep in +// it (a segfault, not a JS RangeError). Re-run with a larger stack. +if(!process.execArgv.some(a=>a.startsWith('--stack-size'))){ + const r=spawnSync(process.execPath,['--stack-size=4000',...process.execArgv,...process.argv.slice(1)],{stdio:'inherit'}); + process.exit(r.status??1); +} + +const wasmPath=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const BASE=0x82010000; + +// t0 calls loop once through the translation cache (a nested call, so its run +// has a JIT slot). loop mixes add, rotate, xor and a data-dependent branch +// for r5 iterations (several thousand HIR instructions per call). +const asm=` +t0: + mflr 12 + bl loop + mtlr 12 + blr +loop: + li 3, 0 + mtctr 5 +1: + add 3, 3, 4 + rotlwi 3, 3, 3 + xor 3, 3, 5 + andi. 6, 4, 1 + beq 2f + addi 3, 3, 7 +2: + addi 4, 4, 1 + bdnz 1b + blr +`; +const work=fs.mkdtempSync(path.join(os.tmpdir(),'r360-jit-osr-')); +const source=path.join(work,'osr.s'),obj=path.join(work,'osr.o'),bin=path.join(work,'osr.bin'); +fs.writeFileSync(source,asm); +execFileSync('powerpc64-linux-gnu-as',['-a32','-be','-mregnames','-R','-o',obj,source]); +execFileSync('powerpc64-linux-gnu-ld',['-melf32ppc','-EB','-nostdlib','--oformat=binary',`-Ttext=0x${BASE.toString(16)}`,`-e0x${BASE.toString(16)}`,'-o',bin,obj]); +const code=fs.readFileSync(bin); +fs.rmSync(work,{recursive:true,force:true}); + +const module=await WebAssembly.compile(fs.readFileSync(wasmPath)); +async function instantiate(jit){ + const wasi=new WASI({version:'preview1',args:[],env:{},preopens:{},returnOnExit:true}); + const imports=wasi.getImportObject(module); + imports.env||={};imports.env.emscripten_notify_memory_growth=()=>{}; + const instance=await WebAssembly.instantiate(module,imports); + wasi.initialize(instance); + // Mode 1: compile by call count, as in titles (mode 2 compiles every run). + if(jit&&!installGuestJit({exports:instance.exports},{mode:1}))throw new Error('guest JIT unavailable'); + return instance.exports; +} + +function run(e,r4,r5){ + const cstr=(off,text)=>{const b=new TextEncoder().encode(`${text}\0`);const p=e.r360_ppc_probe_input_buffer()+off;new Uint8Array(e.memory.buffer,p,b.length).set(b);return p;}; + e.r360_ppc_probe_reset(); + const buffer=e.r360_ppc_probe_input_buffer(); + new Uint8Array(e.memory.buffer,buffer,code.length).set(code); + if((e.r360_ppc_probe_load_at(BASE,buffer,code.length)>>>0)!==code.length)throw new Error('code load failed'); + e.r360_ppc_probe_set_execute_on_translate(1); + e.r360_ppc_probe_set_initial_lr(0xBCBCBCBCn); + e.r360_ppc_probe_set_initial_register(cstr(0,'r4'),cstr(64,String(r4))); + e.r360_ppc_probe_set_initial_register(cstr(0,'r5'),cstr(64,String(r5))); + const hir=e.r360_ppc_probe_translate_scanned_at(BASE)>>>0; + if(!hir||(e.r360_ppc_probe_correctness_status()>>>0)!==3)return 'did-not-return'; + const out=[]; + for(const reg of ['r3','r4','r6']){ + e.r360_ppc_probe_compare_register(cstr(0,reg),cstr(64,'0')); + const p=e.r360_ppc_probe_register_actual()>>>0,m=new Uint8Array(e.memory.buffer);let s=''; + for(let i=p;m[i];i++)s+=String.fromCharCode(m[i]); + out.push(`${reg}=${s}`); + } + return out.join(' '); +} + +const interp=await instantiate(false),jit=await instantiate(true); +const failures=[]; +let cases=0; +for(const [r4,r5] of [[1,600],[12345,1000],[0x7FFFFFF0,2500],[3,4000]]){ + const a=run(interp,r4,r5),b=run(jit,r4,r5); + cases++; + if(a!==b||a==='did-not-return')failures.push(`r4=${r4} r5=${r5}\n executor: ${a}\n jit: ${b}`); +} +const osr=jit.r360_jit_osr_entries?jit.r360_jit_osr_entries()>>>0:0; +console.log(`guest JIT OSR: ${cases} cases, ${failures.length} mismatching, ${osr} OSR entries`); +for(const f of failures)console.log(`FAIL ${f}`); +if(failures.length||!osr)process.exit(1); +console.log('GUEST_JIT_OSR_PASS'); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 05b78773..f9ebc0e5 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -289,7 +289,7 @@ async function main(){ memoryFault:result.memoryFaultCode?{code:result.memoryFaultCode,address:hex(result.memoryFaultAddress)}:null, guestFibers:result.guestFibers??null, guestThreadWaits:globalThis.__r360Threads??null, - framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),cacheMemoHits:f('r360_hir_cache_memo_hits'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), + framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),cacheMemoHits:f('r360_hir_cache_memo_hits'),jitOsrEntries:f('r360_jit_osr_entries'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), mainThread:result.mainThreadContext?{stackBytes:result.mainThreadContext.stackBytes,tlsBytes:result.mainThreadContext.tlsBytes,tlsTemplate:result.mainThreadContext.tlsTemplate}:null, kernelVariables:{relocated:result.kernelVariableRegistration?.relocated?.map(v=>v.name),placeholders:result.kernelVariableRegistration?.placeholders?.map(v=>kernelExportName(v.module,v.ordinal))}, importedKernelFunctions:result.kernelImports?.plan?.filter(i=>i.isKernelModule&&i.kind==='function').length, From a2649c7331ebebf3e99bade461a6be4d0f296f66 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 08:33:05 +0000 Subject: [PATCH 41/65] Guest JIT: per-thread fault state; OSR bisect switches; test WASI guard - The generated code's fault flag and failure record are fiber-local. A guest interrupt (RunGuestInterrupt swaps the fiber-local section) whose callback failed a wait left the flag set, and the interrupted compiled code's next fault check failed with the interrupt's blocker (Banjo-Tooie, 51.5B instructions, a new thread's first call). A nested compiled run also restores its caller's flag. - The deferred first-run flags are fiber-local (a fiber can switch while a non-deferred translation runs guest code). - JitTakeFunction records the interpreter's OSR slot only for runs it sends to the interpreter; a stale record could match a later builder at the same address. - r360_jit_set_osr (bit 0 long runs, bit 1 interior entries) and run-title R360_OSR=mask, --trace-from-minstr N for bisecting. - test-node-wasi-safe.mjs: Node 22's WASI fd_write fast-API callback can start a GC that crashes V8 (SIGSEGV); the JIT and PPC suite tests turn fast API calls off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/hir_jit_glue.inc | 25 +++++++++++++++++++++-- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 21 +++++++++++++++---- src/xenia_web_bootstrap/probe_backend.cpp | 12 +++++++++-- test-guest-jit-differential.mjs | 1 + test-guest-jit-osr.mjs | 9 +------- test-node-wasi-safe.mjs | 10 +++++++++ test-xenia-ppc-instruction-suite.mjs | 1 + tools/run-title.mjs | 7 +++++-- 8 files changed, 68 insertions(+), 18 deletions(-) create mode 100644 test-node-wasi-safe.mjs diff --git a/src/xenia_web_bootstrap/hir_jit_glue.inc b/src/xenia_web_bootstrap/hir_jit_glue.inc index fc5441a8..dc4c824f 100644 --- a/src/xenia_web_bootstrap/hir_jit_glue.inc +++ b/src/xenia_web_bootstrap/hir_jit_glue.inc @@ -9,11 +9,16 @@ namespace render360::xenia_web { namespace { xe::Memory* g_jit_memory = nullptr; -uint32_t g_jit_fault = 0; +// Fault state of the running generated function, per guest thread: a guest +// interrupt (RunGuestInterrupt swaps the fiber-local section) or another +// fiber can run nested JIT code that fails, and must not leave the fault set +// for the interrupted code's next FaultCheck. Generated code reads it at a +// fixed address, which the section swap keeps valid. +R360_FIBER_LOCAL uint32_t g_jit_fault = 0; // Operand/result exchange for r360_jit_h_exec: three 16-byte operand slots // and the result slot. alignas(16) uint8_t g_jit_scratch[64] = {}; -uint32_t g_jit_fail_kind = 0, g_jit_fail_opcode = 0, g_jit_fail_address = 0; +R360_FIBER_LOCAL uint32_t g_jit_fail_kind = 0, g_jit_fail_opcode = 0, g_jit_fail_address = 0; // Blocker for a failed helper, preferring a nested callee's blocker as the // executor does after a failed call. @@ -136,6 +141,13 @@ bool JitTryExecute(xe::cpu::hir::HIRBuilder* builder, xe::Memory* memory, return true; } +uint32_t JitBlockSource(const xe::cpu::hir::Block* block) { + for (auto* i = block->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + return 0; +} + // ExecuteBuilder hands a run over to compiled code at the head of `block` // (JitOsrFunction); false keeps interpreting. uint64_t g_jit_osr_entries = 0; @@ -148,6 +160,11 @@ bool JitTryOsr(xe::cpu::hir::HIRBuilder* builder, JitSlot* slot, if (segment == 0xFFFFFFFFu) return false; ++g_jit_osr_entries; JitRun(function, segment, memory, context, result); + if (!result->supported) { + std::fprintf(stderr, "R360_OSR_FAILED block_source=0x%08X segment=%u hot=%u blocker=%u@0x%08X\n", + JitBlockSource(block), segment, hot ? 1u : 0u, result->blocker_kind, + result->blocker_address); + } return true; } @@ -155,10 +172,14 @@ void JitRun(uint32_t function, uint32_t entry, xe::Memory* memory, xe::cpu::ppc::PPCContext& context, HIRCorrectnessResult* result) { g_jit_entry_segment = entry; g_jit_memory = memory; + // A caller in generated code learns of this run's failure from its + // helper's return value; its own fault flag stays as it was. + const uint32_t caller_fault = g_jit_fault; g_jit_fault = 0; g_jit_fail_kind = g_jit_fail_opcode = g_jit_fail_address = 0; const uint32_t status = reinterpret_cast(uintptr_t(function))( uint32_t(reinterpret_cast(&context))); + g_jit_fault = caller_fault; *result = HIRCorrectnessResult{}; result->r3 = context.r[3]; switch (status) { diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 6b38da3c..995fc95f 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -1895,8 +1895,11 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { JitSlot* slot = g_candidate_builder == builder ? g_candidate_slot : nullptr; g_candidate_builder = nullptr; g_candidate_slot = nullptr; - g_osr_builder = builder; - g_osr_slot = slot; + // Recorded only for a run going to the interpreter, which takes it at once + // (JitTakeOsrSlot): a stale record could match a later builder allocated at + // the same address. + g_osr_builder = nullptr; + g_osr_slot = nullptr; g_last_decision = 5; if (!g_mode || !g_compiler) return 0; g_last_decision = 1; @@ -1916,7 +1919,11 @@ uint32_t JitTakeFunction(HIRBuilder* builder) { return 0; } g_last_decision = 2; - if (++slot->runs < (g_mode >= 2 ? 1u : g_hot_threshold)) return 0; + if (++slot->runs < (g_mode >= 2 ? 1u : g_hot_threshold)) { + g_osr_builder = builder; + g_osr_slot = slot; + return 0; + } const uint32_t index = RequestCompile(builder, slot); if (!index) g_last_decision = slot->state == 1 ? 3 : 4; if (index) ++g_jit_calls; @@ -1938,8 +1945,10 @@ JitSlot* JitTakeOsrSlot(HIRBuilder* builder) { return slot; } +// Bit 0: long runs, bit 1: interior entries. +uint32_t g_osr_enabled = 3; uint32_t JitOsrFunction(HIRBuilder* builder, JitSlot* slot, bool hot) { - if (!slot || !g_mode || !g_compiler) return 0; + if (!slot || !g_mode || !g_compiler || !(g_osr_enabled & (hot ? 1u : 2u))) return 0; if (!slot->function) { if (slot->state) return 0; // pending or not compilable if (!hot && ++slot->runs < g_hot_threshold) return 0; @@ -1975,6 +1984,10 @@ void JitReleaseSlot(JitSlot* slot) { namespace rx = render360::xenia_web; extern "C" { +// On-stack replacement: bit 0 long runs, bit 1 interior entries (default 3; +// 0 for bisecting). +__attribute__((used, export_name("r360_jit_set_osr"))) +uint32_t r360_jit_set_osr(uint32_t mask) { rx::g_osr_enabled = mask & 3u; return rx::g_osr_enabled; } __attribute__((used, export_name("r360_jit_set_compiler"))) uint32_t r360_jit_set_compiler(uint32_t table_index) { rx::g_compiler = table_index; diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index 82de1d28..5bb6b3d6 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -499,8 +499,10 @@ CachedTranslation* LookupTranslationSlow(uint64_t key, bool need_builder) { // skips executing a builder about to be retained, and DefineOrRunCached runs // it from its new cache entry instead, so that run already has a JIT slot // (compilation by call count, on-stack replacement of a long first run). -bool g_defer_first_run = false; // DefineOrRunCached is translating -bool g_deferred_first_run = false; // Assemble skipped the run +// Per guest thread: a fiber can switch while a translation that was not +// deferred runs guest code inside Assemble. +R360_FIBER_LOCAL bool g_defer_first_run = false; // DefineOrRunCached is translating +R360_FIBER_LOCAL bool g_deferred_first_run = false; // Assemble skipped the run bool CanRetainTranslatedBuilder() { if (!g_retain_pending) return false; auto it = g_translation_cache.find(g_retain_key); @@ -520,6 +522,12 @@ bool ExecuteCachedTranslation(CachedTranslation& entry, bool count_hit = true) { JitSetCandidate(builder, &entry.jit); const HIRCorrectnessResult result = ExecuteHIRCorrectnessProbe(builder, memory); --entry.pins; + if (!(result.supported && result.reached_return_boundary)) { + R360_VERBOSE_TRACE("R360_CACHED_RUN_FAILED begin=0x%08X compiled_only=%u jit=%u supported=%u returned=%u blocker=%u@0x%08X instr=%u\n", + entry.begin, entry.builder ? 0u : 1u, entry.jit.function, + result.supported ? 1u : 0u, result.reached_return_boundary ? 1u : 0u, + result.blocker_kind, result.blocker_address, result.instructions_executed); + } return result.supported && result.reached_return_boundary; } diff --git a/test-guest-jit-differential.mjs b/test-guest-jit-differential.mjs index d231ee22..1cd6c209 100644 --- a/test-guest-jit-differential.mjs +++ b/test-guest-jit-differential.mjs @@ -6,6 +6,7 @@ // // Usage: node test-guest-jit-differential.mjs [bootstrap.wasm] [iterations] // Requires powerpc64-linux-gnu-{as,ld} (apt: binutils-powerpc64-linux-gnu). +import './test-node-wasi-safe.mjs'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/test-guest-jit-osr.mjs b/test-guest-jit-osr.mjs index 5972587b..3e60a212 100644 --- a/test-guest-jit-osr.mjs +++ b/test-guest-jit-osr.mjs @@ -5,21 +5,14 @@ // // Usage: node test-guest-jit-osr.mjs [bootstrap.wasm] // Requires powerpc64-linux-gnu-{as,ld} (apt: binutils-powerpc64-linux-gnu). +import './test-node-wasi-safe.mjs'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import {execFileSync} from 'node:child_process'; import {WASI} from 'node:wasi'; -import {spawnSync} from 'node:child_process'; import {installGuestJit} from './render360-guest-jit.mjs'; -// The probe translates and runs the guest code on one host stack; V8's -// default 984 KiB native stack can overflow when a wasm tier-up lands deep in -// it (a segfault, not a JS RangeError). Re-run with a larger stack. -if(!process.execArgv.some(a=>a.startsWith('--stack-size'))){ - const r=spawnSync(process.execPath,['--stack-size=4000',...process.execArgv,...process.argv.slice(1)],{stdio:'inherit'}); - process.exit(r.status??1); -} const wasmPath=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; const BASE=0x82010000; diff --git a/test-node-wasi-safe.mjs b/test-node-wasi-safe.mjs new file mode 100644 index 00000000..2456aa3f --- /dev/null +++ b/test-node-wasi-safe.mjs @@ -0,0 +1,10 @@ +// Import first in tests that run the bootstrap under node:wasi. +// +// Node 22's WASI fd_write fast-API callback allocates (uvwasi) and reports +// external memory to V8, which can start a garbage collection inside the fast +// call; V8 then crashes walking an optimized frame (SIGSEGV in +// InnerPointerToCodeCache::GetCacheEntry). Guest stderr output under heap +// pressure triggers it. Fast API calls off keeps WASI calls on the regular +// path, where GC is allowed. +import v8 from 'node:v8'; +v8.setFlagsFromString('--no-turbo-fast-api-calls'); diff --git a/test-xenia-ppc-instruction-suite.mjs b/test-xenia-ppc-instruction-suite.mjs index 342a70de..8f0f90d9 100644 --- a/test-xenia-ppc-instruction-suite.mjs +++ b/test-xenia-ppc-instruction-suite.mjs @@ -10,6 +10,7 @@ // // Not covered here: VMX128 files stock binutils cannot assemble (Xenia uses a // patched binutils for those) and the MEMORY_IN/OUT store tests. +import './test-node-wasi-safe.mjs'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; diff --git a/tools/run-title.mjs b/tools/run-title.mjs index f9ebc0e5..321481c0 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -41,6 +41,8 @@ function parseArgs(argv){ else if(a==='--max-minstr')args.maxMillions=Number(argv[++i]); else if(a==='--json')args.json=argv[++i]; else if(a==='--verbose'||a==='-v')args.verbose=true; + // --trace-from-minstr N: verbose runtime tracing (R360_VERBOSE_TRACE) from N million instructions on. + else if(a==='--trace-from-minstr')args.traceFrom=Number(argv[++i])>>>0; else if(a==='--trace-calls')args.traceCalls=true; else if(a==='--license')args.license=String(argv[++i]||'trial'); else if(a==='--log-draws')args.logDraws=Number(argv[++i])>>>0; @@ -139,7 +141,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; @@ -254,6 +256,7 @@ async function main(){ const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); globalThis.__r360Jit=jit; if(process.env.R360_JITPROF)bootstrap.exports.r360_jit_profile?.(1); + if(process.env.R360_OSR!==undefined)bootstrap.exports.r360_jit_set_osr?.(Number(process.env.R360_OSR)); (args.kernelWatch||[]).slice(0,4).forEach((v,k)=>bootstrap.exports.r360_kernel_watch_arg?.(k,v)); if(args.renderFrom!==undefined)bootstrap.exports.r360_xenos_soft_set_rasterize?.(args.renderFrom===0?1:0); // --max-minstr N: stop after N million guest instructions in total. @@ -265,7 +268,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.traceFrom!==undefined&&!globalThis.__r360TraceOn&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.traceFrom){globalThis.__r360TraceOn=1;x.r360_trace_set_verbose?.(1);}if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} From 44d8b79fe949b89213949f2c36bdfd633f376489 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 09:57:32 +0000 Subject: [PATCH 42/65] Diagnostics for runs that never return to the host - r360_trace_verbose_from(millions): verbose runtime tracing switched on inside the core at an instruction count (run-title --trace-from-minstr), since a stuck guest may never reach a host slice to turn it on. - r360_jit_diag / run-title R360_DIAG=1: a line every 2^27 guest instructions from the compiled-code poll with the scheduler state (fiber states, wake deadlines, kernel wait object/reason/caller per thread). - Failed cached runs and failed OSR runs are traced (verbose). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/guest_fibers.cpp | 39 ++++++++++++++++++++++++ src/xenia_web_bootstrap/guest_fibers.h | 3 ++ src/xenia_web_bootstrap/hir_jit_glue.inc | 17 +++++++++++ tools/run-title.mjs | 6 ++-- 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index e8b10638..79e6578c 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -25,6 +25,7 @@ extern "C" char __stop_r360_fiber[]; extern "C" { uint32_t r360_guest_thread_current(); +uint32_t r360_kernel_thread_wait(uint32_t thread, uint32_t field); uint32_t r360_guest_thread_set_current(uint32_t handle); uint32_t r360_guest_thread_runnable_list(uint32_t* out, uint32_t capacity); uint32_t r360_guest_thread_entry(uint32_t handle); @@ -328,6 +329,28 @@ bool GuestFiberYield(bool blocked) { bool GuestInterruptActive() { return g_in_interrupt; } +// Scheduler state for diagnostics (r360_jit_diag). +void GuestFiberDiagnostic(char* out, size_t size) { + uint32_t ready = 0, blocked = 0; + for (const auto& f : g_fibers) { + if (f.state == kFiberReady) ++ready; + if (f.state == kFiberBlocked) ++blocked; + } + int n = std::snprintf(out, size, "fibers=%u current=%u ready=%u blocked=%u clock_ms=%llu |", + uint32_t(g_fibers.size()), g_current, ready, blocked, + (unsigned long long)(GuestClockNanoseconds() / 1000000ull)); + // Per fiber: state, last kernel call (module<<16|ordinal), wake deadline, + // guest PC when it left. + for (size_t i = 0; i < g_fibers.size() && n > 0 && size_t(n) < size; ++i) { + const Fiber& f = g_fibers[i]; + // Kernel wait record: object, reason, caller. + n += std::snprintf(out + n, size - size_t(n), " %u:%u/%llu/obj=%08x/r=%u/lr=%08x", uint32_t(i), + uint32_t(f.state), (unsigned long long)(f.wake_ns / 1000000ull), + r360_kernel_thread_wait(f.thread, 1), r360_kernel_thread_wait(f.thread, 4), + r360_kernel_thread_wait(f.thread, 5)); + } +} + // Xenia blocks a sleeping or timed-waiting XThread on a host wait until its // deadline; here the fiber blocks with a guest-clock deadline and another // fiber runs. Returns true when resumed (the caller re-checks its condition), @@ -381,7 +404,15 @@ bool GuestFiberIdle(uint64_t deadline_ns) { return true; } +// Verbose runtime tracing from an instruction count on (r360_trace_verbose_from): +// checked here because a stuck guest may never return to the host to turn it on. +uint64_t g_trace_from_instructions = 0; + void GuestFiberHostYieldIfDue() { + if (g_trace_from_instructions && HIRTotalInstructions() >= g_trace_from_instructions) { + g_trace_from_instructions = 0; + g_r360_verbose_trace = true; + } #if defined(__wasm__) if (g_rewinding) { // Resumed after the page got its turn. @@ -403,6 +434,9 @@ void GuestFiberHostYieldIfDue() { return; } } + R360_VERBOSE_TRACE("R360_HOST_YIELD_CHECK fiber=%u interrupt=%u deadline=%llu now=%llu\n", + g_current, g_in_interrupt ? 1u : 0u, + (unsigned long long)g_host_slice_deadline_ms, (unsigned long long)HostMillis()); if (!g_enabled || g_in_interrupt || !g_host_slice_deadline_ms || g_current >= g_fibers.size() || HostMillis() < g_host_slice_deadline_ms) { return; @@ -490,6 +524,11 @@ uint32_t r360_fiber_set_host_slice(uint32_t milliseconds) { rx::g_host_slice_deadline_ms = milliseconds ? rx::HostMillis() + milliseconds : 0; return milliseconds; } +__attribute__((used, export_name("r360_trace_verbose_from"))) +uint32_t r360_trace_verbose_from(uint32_t millions) { + rx::g_trace_from_instructions = uint64_t(millions) * 1000000ull; + return millions; +} // 1 when the last unwind was a host time-slice yield (consumed by this call). uint32_t r360_fiber_take_host_yield() { const bool yielded = rx::g_host_yield; diff --git a/src/xenia_web_bootstrap/guest_fibers.h b/src/xenia_web_bootstrap/guest_fibers.h index c7b57301..b5318351 100644 --- a/src/xenia_web_bootstrap/guest_fibers.h +++ b/src/xenia_web_bootstrap/guest_fibers.h @@ -1,5 +1,6 @@ #pragma once +#include #include // Guest threads for the native HIR compatibility executor. @@ -37,6 +38,8 @@ uintptr_t GuestFiberStackLow(); bool RunGuestInterrupt(uint32_t address, uint32_t r3, uint32_t r4, uint32_t stack_top, uint32_t pcr); bool GuestInterruptActive(); +// Scheduler state as text, for diagnostics. +void GuestFiberDiagnostic(char* out, size_t size); // Browser time slicing: when the host slice set by the driver // (r360_fiber_set_host_slice) has run out, unwinds the running guest thread diff --git a/src/xenia_web_bootstrap/hir_jit_glue.inc b/src/xenia_web_bootstrap/hir_jit_glue.inc index dc4c824f..d4797bcf 100644 --- a/src/xenia_web_bootstrap/hir_jit_glue.inc +++ b/src/xenia_web_bootstrap/hir_jit_glue.inc @@ -6,6 +6,7 @@ // PPCContext, so guest calls, returns, memory, MMIO and atomics behave exactly // as in ExecuteBuilder above. // --------------------------------------------------------------------------- +extern "C" uint32_t r360_guest_thread_current(); namespace render360::xenia_web { namespace { xe::Memory* g_jit_memory = nullptr; @@ -93,6 +94,19 @@ uint32_t JitDebugWatchAddress() { return g_debug_watch_address; } uint32_t JitFaultAddress() { return uint32_t(reinterpret_cast(&g_jit_fault)); } uint32_t JitScratchAddress() { return uint32_t(reinterpret_cast(g_jit_scratch)); } uint32_t g_jit_entry_segment = 0; +// r360_jit_diag: a line every 2^27 guest instructions (where the guest runs +// when it never returns to the host, e.g. inside back-to-back interrupts). +bool g_jit_diag = false; +uint64_t g_jit_diag_next = 0; +void JitDiagnosticPoll() { + if (!g_jit_diag || g_total_instructions < g_jit_diag_next) return; + g_jit_diag_next = (g_total_instructions | ((uint64_t(1) << 27) - 1)) + 1; + char fibers[512]; + GuestFiberDiagnostic(fibers, sizeof(fibers)); + std::fprintf(stderr, "R360_DIAG minstr=%llu interrupt=%u active=%u thread=0x%08X source=0x%08X %s\n", + (unsigned long long)(g_total_instructions / 1000000u), GuestInterruptActive() ? 1u : 0u, + GuestFibersActive() ? 1u : 0u, r360_guest_thread_current(), g_current_source_address, fibers); +} uint32_t JitEntrySegmentAddress() { return uint32_t(reinterpret_cast(&g_jit_entry_segment)); } uint32_t JitReturnAddressSlot() { return uint32_t(reinterpret_cast(&g_next_guest_return_address)); @@ -258,6 +272,7 @@ R360_JIT_HELPER(st64) void r360_jit_h_st64(uint32_t a, uint64_t v, uint32_t s) { // Loops in generated code poll here: guest interrupts, preemption and host // time slices (may unwind), and the --max-minstr budget. R360_JIT_HELPER(poll) uint32_t r360_jit_h_poll() { + rxj::JitDiagnosticPoll(); rxj::DeliverGuestInterruptsNow(); if (rxj::g_total_instruction_budget && rxj::g_total_instructions > rxj::g_total_instruction_budget) { @@ -327,6 +342,8 @@ R360_JIT_HELPER(mulhi64) uint64_t r360_jit_h_mulhi64(uint64_t a, uint64_t b, uin return is_unsigned ? uint64_t((unsigned __int128)a * (unsigned __int128)b >> 64) : uint64_t(((__int128)int64_t(a) * (__int128)int64_t(b)) >> 64); } +__attribute__((used, export_name("r360_jit_diag"))) +uint32_t r360_jit_diag(uint32_t on) { rxj::g_jit_diag = on != 0; return on; } __attribute__((used, export_name("r360_jit_osr_entries"))) uint32_t r360_jit_osr_entries() { return uint32_t(rxj::g_jit_osr_entries); } __attribute__((used, export_name("r360_jit_profile"))) diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 321481c0..a5b8b367 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -141,7 +141,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR')||line.startsWith('R360_DIAG'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; @@ -256,6 +256,8 @@ async function main(){ const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); globalThis.__r360Jit=jit; if(process.env.R360_JITPROF)bootstrap.exports.r360_jit_profile?.(1); + if(process.env.R360_DIAG){bootstrap.exports.r360_jit_diag?.(1);} + if(args.traceFrom!==undefined){globalThis.__r360TraceOn=1;bootstrap.exports.r360_trace_verbose_from?.(args.traceFrom);} if(process.env.R360_OSR!==undefined)bootstrap.exports.r360_jit_set_osr?.(Number(process.env.R360_OSR)); (args.kernelWatch||[]).slice(0,4).forEach((v,k)=>bootstrap.exports.r360_kernel_watch_arg?.(k,v)); if(args.renderFrom!==undefined)bootstrap.exports.r360_xenos_soft_set_rasterize?.(args.renderFrom===0?1:0); @@ -268,7 +270,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.traceFrom!==undefined&&!globalThis.__r360TraceOn&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.traceFrom){globalThis.__r360TraceOn=1;x.r360_trace_set_verbose?.(1);}if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} From a36e877587f2b138ea524011294172061e417f8c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 10:58:01 +0000 Subject: [PATCH 43/65] WebGPU backend, stage 1: shared memory (port of Xenia SharedMemory) - webgpu_backend.cpp: the core records a command stream (as Xenia's VulkanCommandProcessor records a DeferredCommandBuffer). Shared memory is a port of Xenia's SharedMemory: RequestRange uploads the runs of pages not valid on the GPU; uploaded pages arm the sparse memory GPU write watch and stay valid while their write generation is unchanged; RangeWrittenByGpu for resolves. - render360-webgpu-backend.mjs replays the stream: a 512 MiB shared memory buffer (or the adapter's largest), uploads through a staging buffer and copyBufferToBuffer in command order. - tools/browser-test.mjs runs browser-side tests in headless Chromium with WebGPU (SwiftShader). - test-webgpu-shared-memory.mjs (core logic, Node) and test-webgpu-shared-memory-browser.mjs (GPU readback matches guest memory, one page re-uploaded after a CPU write). - docs/gpu/WEBGPU_BACKEND.md: the port plan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 3 +- docs/gpu/WEBGPU_BACKEND.md | 50 ++++++++ render360-webgpu-backend.mjs | 92 ++++++++++++++ src/xenia_web_bootstrap/guest_fibers.cpp | 4 +- src/xenia_web_bootstrap/hir_jit_glue.inc | 7 +- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 40 +++++- src/xenia_web_bootstrap/webgpu_backend.cpp | 136 +++++++++++++++++++++ src/xenia_web_bootstrap/webgpu_backend.h | 68 +++++++++++ test-webgpu-shared-memory-browser.mjs | 11 ++ test-webgpu-shared-memory.mjs | 71 +++++++++++ tests/browser/webgpu-shared-memory.mjs | 50 ++++++++ tools/browser-test.mjs | 60 +++++++++ tools/run-title.mjs | 3 +- 13 files changed, 589 insertions(+), 6 deletions(-) create mode 100644 docs/gpu/WEBGPU_BACKEND.md create mode 100644 render360-webgpu-backend.mjs create mode 100644 src/xenia_web_bootstrap/webgpu_backend.cpp create mode 100644 src/xenia_web_bootstrap/webgpu_backend.h create mode 100644 test-webgpu-shared-memory-browser.mjs create mode 100644 test-webgpu-shared-memory.mjs create mode 100644 tests/browser/webgpu-shared-memory.mjs create mode 100644 tools/browser-test.mjs diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 3eea4b5b..e9784477 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -198,6 +198,7 @@ queue_cpp "render360/kernel_runtime_foundation.cpp" "$ROOT/src/xenia_web_bootstr queue_cpp "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibers.cpp" queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" +queue_cpp "render360/webgpu_backend.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_backend.cpp" queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" queue_cpp "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" @@ -232,7 +233,7 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 30 )) +expected=$(( ${#SOURCES[@]} + 2 + 31 )) actual=$(( passed + failed )) echo diff --git a/docs/gpu/WEBGPU_BACKEND.md b/docs/gpu/WEBGPU_BACKEND.md new file mode 100644 index 00000000..ad639fe3 --- /dev/null +++ b/docs/gpu/WEBGPU_BACKEND.md @@ -0,0 +1,50 @@ +# WebGPU Xenos backend (step 2) + +Goal: render titles on the GPU through WebGPU, as a port of Xenia's Vulkan +backend (`src/xenia/gpu/vulkan`), with no CPU drawing in the play path. The +software renderer (`xenos_soft_renderer.cpp`) stays as the reference that +GPU frames are compared against. + +## What Xenia's Vulkan backend does, and the WebGPU equivalent + +| Xenia (Vulkan) | Role | Render360 (WebGPU) | +| --- | --- | --- | +| `SharedMemory` + `VulkanSharedMemory` | 512 MiB GPU copy of guest physical memory; ranges a draw needs are uploaded on demand; CPU writes invalidate pages through physical-memory access watches | Same base class compiled to wasm. Watches: a per-page watch bit next to the executable-alias count in the sparse page table, so JIT inline stores (which already check that field) take the slow path and invalidate. Uploads go through a staging ring and `copyBufferToBuffer` in command order. | +| `PrimitiveProcessor` + `VulkanPrimitiveProcessor` | Index buffers, primitive type conversion (fans, quads, rectangles), 32-bit index endian handling | Same base class; converted index data is uploaded to a GPU buffer. | +| `SpirvShaderTranslator` + `VulkanPipelineCache` | Xenos microcode → SPIR-V; pipelines keyed by shaders and render state | The translator already builds into the core (`xenos_spirv_translation_probe.cpp`); SPIR-V → WGSL through Naga (`render360-spirv-wgsl-runtime.mjs`); one WebGPU render pipeline per Xenia pipeline description. Descriptor sets map 1:1 to bind groups (shared memory/EDRAM, constants, vertex textures, pixel textures — 4, the WebGPU limit). | +| `VulkanRenderTargetCache` (host render targets path) | EDRAM modelled with host render targets; ownership transfers between formats; resolves (EDRAM → shared memory) with compute shaders | Host render targets as WebGPU textures; transfers and resolves with Xenia's own compute shaders (`shaders/*.xesl`, built to SPIR-V by Xenia), converted to WGSL by Naga at build time. No fragment shader interlock path (WebGPU has none). | +| `TextureCache` + `VulkanTextureCache` | Texture keys from fetch constants; untiling and format conversion with compute shaders (`texture_load_*`); invalidation through shared-memory watches | Same base class; Xenia's `texture_load_*` shaders via Naga; WebGPU textures. | +| `VulkanCommandProcessor` | PM4 → draws, copies, swaps; system constants; submission | The core's PM4 processor (`xenos_gpu_foundation.cpp`) calls the backend per draw/copy/swap; the backend records a command stream (like Xenia's `DeferredCommandBuffer`) that `render360-webgpu-xenos.mjs` replays into a `GPUCommandEncoder` and submits at swap. | + +## Data flow per frame + +1. Guest CPU writes vertex/index/texture data → watch bits invalidate pages. +2. PM4 draw → backend: `PrimitiveProcessor`, `SharedMemory::RequestRange` + for vertex fetch and index ranges (uploads only invalid pages), texture + cache requests, render target cache update, pipeline lookup, system and + guest constants → command stream. +3. Resolve (copy draw) → render target cache resolve: compute dispatch that + writes the shared memory buffer and marks the range as GPU-written + (`RangeWrittenByGpu`, as Xenia does). +4. Swap → front buffer texture presented to the canvas; the encoder is + submitted. + +## Order of work (each with a test in headless Chromium + SwiftShader) + +1. Physical write watches in sparse guest memory (unit test: watched page, + JIT store, interpreter store, kernel write all invalidate exactly once). +2. Shared memory: base class + WebGPU subclass + JS buffer mirror (test: + upload, CPU write, re-request uploads only the dirty page; GPU readback + matches guest memory). +3. Pipeline + draw path: translated shaders, vertex fetch from shared + memory, system constants, one host render target, present (test: a + captured Banjo frame's draws match the software renderer within a + tolerance). +4. Render target cache with EDRAM transfers and resolves. +5. Texture cache with tiled/endian-swapped formats. +6. Play path switched to WebGPU; software renderer only for verification. + +Rules kept: no game data, decrypted XEX or game-derived shaders in the +repository; translated shaders live only in the browser at run time. +Xenia's own compute shaders (resolve, texture load) are Xenia's code and are +converted from Xenia's SPIR-V at build time. diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs new file mode 100644 index 00000000..cb601023 --- /dev/null +++ b/render360-webgpu-backend.mjs @@ -0,0 +1,92 @@ +// Render360 WebGPU Xenos backend: replays the command stream the core +// records (src/xenia_web_bootstrap/webgpu_backend.cpp) into WebGPU, as +// Xenia's VulkanCommandProcessor replays its DeferredCommandBuffer. +// docs/gpu/WEBGPU_BACKEND.md describes the design. + +export const GPU_STREAM_UPLOAD=1; + +const BUFFER_USAGE={MAP_READ:0x1,COPY_SRC:0x4,COPY_DST:0x8,STORAGE:0x80}; +const SHARED_MEMORY_BYTES=512*1024*1024; // Xenia SharedMemory::kBufferSize +const STAGING_BYTES=16*1024*1024; + +// Shared memory buffer size the adapter allows: Xenia's 512 MiB, or the +// largest power of two below the device's limits (physical addresses above +// it then cannot be used by GPU emulation, which is reported). +export function sharedMemoryBytesForLimits(limits){ + const max=Math.min(limits.maxBufferSize,limits.maxStorageBufferBindingSize); + let bytes=SHARED_MEMORY_BYTES; + while(bytes>max)bytes/=2; + return bytes; +} + +export class XenosWebGpuBackend{ + constructor(device,exports,{sharedMemoryBytes=sharedMemoryBytesForLimits(device.limits)}={}){ + this.device=device; + this.exports=exports; + this.sharedMemoryBytes=sharedMemoryBytes; + // The GPU copy of guest physical memory (Xenia's shared memory buffer). + this.sharedMemory=device.createBuffer({label:'Render360 shared memory',size:sharedMemoryBytes, + usage:BUFFER_USAGE.STORAGE|BUFFER_USAGE.COPY_DST|BUFFER_USAGE.COPY_SRC}); + // Upload staging: writeBuffer is ordered before the next submit, so the + // region is reusable once the commands copying out of it are submitted. + this.staging=device.createBuffer({label:'Render360 upload staging',size:STAGING_BYTES, + usage:BUFFER_USAGE.COPY_SRC|BUFFER_USAGE.COPY_DST}); + this.stagingOffset=0; + this.encoder=null; + this.stats={uploads:0,uploadedBytes:0,droppedUploads:0,submits:0}; + } + + encoderForCommands(){ + if(!this.encoder)this.encoder=this.device.createCommandEncoder({label:'Render360 Xenos'}); + return this.encoder; + } + + submit(){ + if(this.encoder){this.device.queue.submit([this.encoder.finish()]);this.encoder=null;this.stats.submits++;} + this.stagingOffset=0; + } + + // Replays and clears the core's recorded commands. + replay(){ + const e=this.exports,count=e.r360_gpu_stream_words()>>>0; + if(!count)return; + const base=e.r360_gpu_stream_data()>>>0; + const words=new Uint32Array(e.memory.buffer,base,count); + for(let i=0;i>>8; + if(op===GPU_STREAM_UPLOAD)this.upload(words[i+1],words[i+2],base+(i+3)*4); + else throw new Error(`Render360 GPU stream: unknown op ${op} at word ${i}`); + i+=1+n; + } + e.r360_gpu_stream_reset(); + } + + upload(dest,length,bytePointer){ + if(dest+length>this.sharedMemoryBytes){this.stats.droppedUploads++;return;} + if(this.stagingOffset+length>STAGING_BYTES)this.submit(); + if(length>STAGING_BYTES){ + // Larger than the staging buffer: write directly (ordered before the + // next submit; nothing recorded after it reads the old contents). + this.device.queue.writeBuffer(this.sharedMemory,dest,this.exports.memory.buffer,bytePointer,length); + }else{ + this.device.queue.writeBuffer(this.staging,this.stagingOffset,this.exports.memory.buffer,bytePointer,length); + this.encoderForCommands().copyBufferToBuffer(this.staging,this.stagingOffset,this.sharedMemory,dest,length); + this.stagingOffset+=length; + } + this.stats.uploads++; + this.stats.uploadedBytes+=length; + } + + // Reads `length` bytes of the GPU shared memory (tests and resolve checks). + async readSharedMemory(offset,length){ + this.submit(); + const read=this.device.createBuffer({size:length,usage:BUFFER_USAGE.MAP_READ|BUFFER_USAGE.COPY_DST}); + const encoder=this.device.createCommandEncoder(); + encoder.copyBufferToBuffer(this.sharedMemory,offset,read,0,length); + this.device.queue.submit([encoder.finish()]); + await read.mapAsync(1); + const bytes=new Uint8Array(read.getMappedRange()).slice(); + read.unmap();read.destroy(); + return bytes; + } +} diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index 79e6578c..8ddb4ed7 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -26,6 +26,7 @@ extern "C" char __stop_r360_fiber[]; extern "C" { uint32_t r360_guest_thread_current(); uint32_t r360_kernel_thread_wait(uint32_t thread, uint32_t field); +uint32_t r360_guest_thread_kthread(uint32_t handle); uint32_t r360_guest_thread_set_current(uint32_t handle); uint32_t r360_guest_thread_runnable_list(uint32_t* out, uint32_t capacity); uint32_t r360_guest_thread_entry(uint32_t handle); @@ -344,7 +345,8 @@ void GuestFiberDiagnostic(char* out, size_t size) { for (size_t i = 0; i < g_fibers.size() && n > 0 && size_t(n) < size; ++i) { const Fiber& f = g_fibers[i]; // Kernel wait record: object, reason, caller. - n += std::snprintf(out + n, size - size_t(n), " %u:%u/%llu/obj=%08x/r=%u/lr=%08x", uint32_t(i), + n += std::snprintf(out + n, size - size_t(n), " %u:kt=%08x:%u/%llu/obj=%08x/r=%u/lr=%08x", uint32_t(i), + r360_guest_thread_kthread(f.thread), uint32_t(f.state), (unsigned long long)(f.wake_ns / 1000000ull), r360_kernel_thread_wait(f.thread, 1), r360_kernel_thread_wait(f.thread, 4), r360_kernel_thread_wait(f.thread, 5)); diff --git a/src/xenia_web_bootstrap/hir_jit_glue.inc b/src/xenia_web_bootstrap/hir_jit_glue.inc index d4797bcf..c81859db 100644 --- a/src/xenia_web_bootstrap/hir_jit_glue.inc +++ b/src/xenia_web_bootstrap/hir_jit_glue.inc @@ -94,6 +94,8 @@ uint32_t JitDebugWatchAddress() { return g_debug_watch_address; } uint32_t JitFaultAddress() { return uint32_t(reinterpret_cast(&g_jit_fault)); } uint32_t JitScratchAddress() { return uint32_t(reinterpret_cast(g_jit_scratch)); } uint32_t g_jit_entry_segment = 0; +uint32_t g_jit_poll_source = 0; +uint32_t JitPollSourceAddress() { return uint32_t(reinterpret_cast(&g_jit_poll_source)); } // r360_jit_diag: a line every 2^27 guest instructions (where the guest runs // when it never returns to the host, e.g. inside back-to-back interrupts). bool g_jit_diag = false; @@ -103,9 +105,10 @@ void JitDiagnosticPoll() { g_jit_diag_next = (g_total_instructions | ((uint64_t(1) << 27) - 1)) + 1; char fibers[512]; GuestFiberDiagnostic(fibers, sizeof(fibers)); - std::fprintf(stderr, "R360_DIAG minstr=%llu interrupt=%u active=%u thread=0x%08X source=0x%08X %s\n", + std::fprintf(stderr, "R360_DIAG minstr=%llu interrupt=%u active=%u thread=0x%08X source=0x%08X loop=0x%08X %s\n", (unsigned long long)(g_total_instructions / 1000000u), GuestInterruptActive() ? 1u : 0u, - GuestFibersActive() ? 1u : 0u, r360_guest_thread_current(), g_current_source_address, fibers); + GuestFibersActive() ? 1u : 0u, r360_guest_thread_current(), g_current_source_address, + g_jit_poll_source, fibers); } uint32_t JitEntrySegmentAddress() { return uint32_t(reinterpret_cast(&g_jit_entry_segment)); } uint32_t JitReturnAddressSlot() { diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 995fc95f..89c84ad9 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -23,6 +23,9 @@ uint32_t JitScratchAddress(); // Dispatcher segment the next generated-function call starts at (0 = entry); // generated code reads and clears it. uint32_t JitEntrySegmentAddress(); +// Guest address of the loop head a generated function last polled at +// (diagnostics: r360_jit_diag). +uint32_t JitPollSourceAddress(); uint32_t SparseGuestPageDirectoryAddress(); // Nonzero while a debug store watch (r360_debug_watch) is armed. uint32_t JitDebugWatchAddress(); @@ -353,7 +356,14 @@ class Emitter { uint32_t reject_opcode_ = 0; bool uses_exec_ = false; bool osr_capable_ = false; - uint32_t entry_slot_ = 0; + uint32_t entry_slot_ = 0, poll_source_ = 0; + // First guest address in segment k. + uint32_t SegmentSource(uint32_t k) const { + for (Instr* i = segments_[k].first; i && i != segments_[k].end; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + return 0; + } uint32_t counter_ = 0, fault_ = 0, return_slot_ = 0, return_valid_ = 0, scratch_ = 0; uint32_t page_directory_ = 0; // Inline sparse page walk for an access of `size` bytes at kLocAddr: falls @@ -447,6 +457,7 @@ void Emitter::Jump(uint32_t k, uint32_t j) { Else(); I32(int32_t(kPollBudget)); Set(kLocBudget); I32(int32_t(j)); Set(kLocPending); + I32(int32_t(poll_source_)); I32(int32_t(SegmentSource(j))); Mem(oI32Store, 2, 0); I32(int32_t(poll_)); Set(kLocPc); End(); BrTo(DepthToLoop(k)); @@ -1752,6 +1763,7 @@ bool Emitter::Compile(std::vector* out) { page_directory_ = SparseGuestPageDirectoryAddress(); return_valid_ = JitReturnValidSlot(); entry_slot_ = JitEntrySegmentAddress(); + poll_source_ = JitPollSourceAddress(); if (!Plan()) return false; AllocateTemporaries(); // Block-local values only: every block head is a valid entry. @@ -1854,7 +1866,27 @@ bool Emitter::Compile(std::vector* out) { return true; } +// Functions starting in [g_exclude_begin, g_exclude_end) stay interpreted +// (r360_jit_set_exclude; bisecting a suspected miscompile). +uint32_t g_exclude_begin = 0, g_exclude_end = 0; +bool Excluded(HIRBuilder* builder) { + if (g_exclude_begin >= g_exclude_end) return false; + for (Block* b = builder->first_block(); b; b = b->next) { + for (Instr* i = b->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) { + const uint32_t start = uint32_t(i->src1.offset); + return start >= g_exclude_begin && start < g_exclude_end; + } + } + } + return false; +} + uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { + if (Excluded(builder)) { + slot->state = 2; + return 0; + } Emitter emitter(builder); std::vector bytes; if (!emitter.Compile(&bytes)) { @@ -1984,6 +2016,12 @@ void JitReleaseSlot(JitSlot* slot) { namespace rx = render360::xenia_web; extern "C" { +__attribute__((used, export_name("r360_jit_set_exclude"))) +uint32_t r360_jit_set_exclude(uint32_t begin, uint32_t end) { + rx::g_exclude_begin = begin; + rx::g_exclude_end = end; + return end > begin ? end - begin : 0; +} // On-stack replacement: bit 0 long runs, bit 1 interior entries (default 3; // 0 for bisecting). __attribute__((used, export_name("r360_jit_set_osr"))) diff --git a/src/xenia_web_bootstrap/webgpu_backend.cpp b/src/xenia_web_bootstrap/webgpu_backend.cpp new file mode 100644 index 00000000..5a5eaa9f --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_backend.cpp @@ -0,0 +1,136 @@ +// WebGPU Xenos backend (see webgpu_backend.h, docs/gpu/WEBGPU_BACKEND.md). +#include "webgpu_backend.h" + +#include +#include + +#include "sparse_guest_memory.h" + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace render360::xenia_web { + +uint32_t* GpuCommandStream::Begin(GpuStreamOp op, uint32_t words) { + const size_t at = words_.size(); + words_.resize(at + 1 + words); + words_[at] = uint32_t(op) | (words << 8); + return words_.data() + at + 1; +} + +GpuCommandStream& GpuStream() { + static GpuCommandStream stream; + return stream; +} + +namespace { +// Guest virtual address through which the core maps physical `page`. +uint32_t PageVirtual(uint32_t page) { + return r360_kernel_gpu_address_to_virtual(page << WebGpuSharedMemory::kPageSizeLog2); +} +} // namespace + +void WebGpuSharedMemory::ClearCache() { + valid_generation_.assign(kPageCount, 0u); +} + +bool WebGpuSharedMemory::PageValid(uint32_t page) const { + const uint32_t generation = valid_generation_[page]; + return generation && generation == SparseGuestGpuGeneration(PageVirtual(page)); +} + +void WebGpuSharedMemory::MarkValid(uint32_t page) { + // Arming returns the generation the next CPU write will change. + valid_generation_[page] = SparseGuestGpuWatch(PageVirtual(page)); +} + +void WebGpuSharedMemory::Upload(uint32_t page_first, uint32_t page_count) { + constexpr uint32_t kPageBytes = 1u << kPageSizeLog2; + const uint32_t length = page_count * kPageBytes; + uint32_t* payload = GpuStream().Begin(kGpuStreamUpload, 2 + length / 4); + payload[0] = page_first * kPageBytes; + payload[1] = length; + uint8_t* bytes = reinterpret_cast(payload + 2); + for (uint32_t i = 0; i < page_count; ++i) { + // Unmapped physical pages read as zeros, as never-written GPU memory. + const uint8_t* host = SparseGuestPageHost(PageVirtual(page_first + i)); + if (host) { + std::memcpy(bytes + i * kPageBytes, host, kPageBytes); + } else { + std::memset(bytes + i * kPageBytes, 0, kPageBytes); + } + MarkValid(page_first + i); + } + uploaded_bytes_ += length; + ++upload_ranges_; +} + +bool WebGpuSharedMemory::RequestRange(uint32_t start, uint32_t length) { + // Some texture or buffer is empty: nothing to upload. + if (!length) return true; + if (start > kBufferSize || kBufferSize - start < length) return false; + if (valid_generation_.empty()) ClearCache(); + const uint32_t page_first = start >> kPageSizeLog2; + const uint32_t page_last = (start + length - 1) >> kPageSizeLog2; + // Contiguous runs of pages not valid on the GPU, as Xenia's + // SharedMemory::RequestRange builds its upload_ranges_. + uint32_t run_start = UINT32_MAX; + for (uint32_t page = page_first; page <= page_last; ++page) { + if (!PageValid(page)) { + if (run_start == UINT32_MAX) run_start = page; + continue; + } + if (run_start != UINT32_MAX) { + Upload(run_start, page - run_start); + run_start = UINT32_MAX; + } + } + if (run_start != UINT32_MAX) Upload(run_start, page_last + 1 - run_start); + return true; +} + +void WebGpuSharedMemory::RangeWrittenByGpu(uint32_t start, uint32_t length) { + if (!length || start >= kBufferSize) return; + if (valid_generation_.empty()) ClearCache(); + length = std::min(length, kBufferSize - start); + const uint32_t page_first = start >> kPageSizeLog2; + const uint32_t page_last = (start + length - 1) >> kPageSizeLog2; + for (uint32_t page = page_first; page <= page_last; ++page) MarkValid(page); +} + +WebGpuSharedMemory& GpuSharedMemory() { + static WebGpuSharedMemory shared_memory; + return shared_memory; +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// The recorded command stream (words) for render360-webgpu-xenos.mjs. +__attribute__((used, export_name("r360_gpu_stream_data"))) +uint32_t r360_gpu_stream_data() { + return uint32_t(reinterpret_cast(rx::GpuStream().words().data())); +} +__attribute__((used, export_name("r360_gpu_stream_words"))) +uint32_t r360_gpu_stream_words() { return uint32_t(rx::GpuStream().words().size()); } +__attribute__((used, export_name("r360_gpu_stream_reset"))) +void r360_gpu_stream_reset() { rx::GpuStream().Reset(); } + +__attribute__((used, export_name("r360_gpu_shared_memory_request"))) +uint32_t r360_gpu_shared_memory_request(uint32_t start, uint32_t length) { + return rx::GpuSharedMemory().RequestRange(start, length) ? 1u : 0u; +} +__attribute__((used, export_name("r360_gpu_shared_memory_written_by_gpu"))) +void r360_gpu_shared_memory_written_by_gpu(uint32_t start, uint32_t length) { + rx::GpuSharedMemory().RangeWrittenByGpu(start, length); +} +__attribute__((used, export_name("r360_gpu_shared_memory_clear"))) +void r360_gpu_shared_memory_clear() { rx::GpuSharedMemory().ClearCache(); } +__attribute__((used, export_name("r360_gpu_shared_memory_uploaded_kb"))) +uint32_t r360_gpu_shared_memory_uploaded_kb() { + return uint32_t(rx::GpuSharedMemory().uploaded_bytes() / 1024u); +} +__attribute__((used, export_name("r360_gpu_shared_memory_upload_ranges"))) +uint32_t r360_gpu_shared_memory_upload_ranges() { return rx::GpuSharedMemory().upload_ranges(); } +} // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h new file mode 100644 index 00000000..23bc7e27 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -0,0 +1,68 @@ +#pragma once + +#include +#include + +// WebGPU Xenos backend (docs/gpu/WEBGPU_BACKEND.md): a port of Xenia's Vulkan +// backend that records a command stream which render360-webgpu-xenos.mjs +// replays into WebGPU, as Xenia's VulkanCommandProcessor records into a +// DeferredCommandBuffer. +namespace render360::xenia_web { + +// Command stream words: [op | (payload words << 8)] then the payload. +enum GpuStreamOp : uint32_t { + // dest offset in the shared memory buffer, byte length, then the bytes + // (padded to 4). Copied at record time: the guest may rewrite the source + // before the stream is replayed. + kGpuStreamUpload = 1, +}; + +class GpuCommandStream { + public: + void Reset() { words_.clear(); } + // Payload of `words` words for `op`; valid until the next Begin. + uint32_t* Begin(GpuStreamOp op, uint32_t words); + const std::vector& words() const { return words_; } + + private: + std::vector words_; +}; +GpuCommandStream& GpuStream(); + +// Port of Xenia's SharedMemory (src/xenia/gpu/shared_memory.cc): the 512 MiB +// GPU copy of guest physical memory. RequestRange uploads the pages of a +// range that are not valid on the GPU; CPU writes invalidate pages. Xenia +// learns of CPU writes through physical memory access watches; here every +// uploaded page arms the sparse guest memory GPU watch +// (SparseGuestGpuWatch) and stays valid while its write generation is +// unchanged. +class WebGpuSharedMemory { + public: + static constexpr uint32_t kBufferSizeLog2 = 29; + static constexpr uint32_t kBufferSize = 1u << kBufferSizeLog2; + static constexpr uint32_t kPageSizeLog2 = 12; + static constexpr uint32_t kPageCount = kBufferSize >> kPageSizeLog2; + + void ClearCache(); + // False if the range is outside physical memory. + bool RequestRange(uint32_t start, uint32_t length); + // A resolve wrote the range on the GPU: valid there, no upload needed + // until the CPU writes it. + void RangeWrittenByGpu(uint32_t start, uint32_t length); + + uint64_t uploaded_bytes() const { return uploaded_bytes_; } + uint32_t upload_ranges() const { return upload_ranges_; } + + private: + bool PageValid(uint32_t page) const; + void MarkValid(uint32_t page); + void Upload(uint32_t page_first, uint32_t page_count); + + // Write generation each page had when it was made valid (0: not valid). + std::vector valid_generation_; + uint64_t uploaded_bytes_ = 0; + uint32_t upload_ranges_ = 0; +}; +WebGpuSharedMemory& GpuSharedMemory(); + +} // namespace render360::xenia_web diff --git a/test-webgpu-shared-memory-browser.mjs b/test-webgpu-shared-memory-browser.mjs new file mode 100644 index 00000000..8aa9b8a3 --- /dev/null +++ b/test-webgpu-shared-memory-browser.mjs @@ -0,0 +1,11 @@ +// WebGPU shared memory end to end in headless Chromium (SwiftShader): uploads +// the core records are replayed into the GPU buffer, which then matches guest +// memory (tests/browser/webgpu-shared-memory.mjs). +import {runBrowserTest} from './tools/browser-test.mjs'; + +const wasm=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const result=await runBrowserTest('tests/browser/webgpu-shared-memory.mjs',{args:[`/${wasm}`],onConsole:t=>process.env.VERBOSE&&console.log(t)}); +console.log(JSON.stringify(result)); +if(!result.ok)process.exit(1); +if(result.secondUploads!==1){console.log('expected exactly one page re-uploaded after the CPU write');process.exit(1);} +console.log('WEBGPU_SHARED_MEMORY_BROWSER_PASS'); diff --git a/test-webgpu-shared-memory.mjs b/test-webgpu-shared-memory.mjs new file mode 100644 index 00000000..66460dae --- /dev/null +++ b/test-webgpu-shared-memory.mjs @@ -0,0 +1,71 @@ +// WebGPU backend shared memory (src/xenia_web_bootstrap/webgpu_backend.cpp, a +// port of Xenia's SharedMemory): a requested range uploads exactly the pages +// that are not valid on the GPU, CPU writes invalidate pages through the +// sparse memory GPU watch, and GPU-written ranges need no upload. +import './test-node-wasi-safe.mjs'; +import fs from 'node:fs'; +import {WASI} from 'node:wasi'; + +const wasmPath=process.argv[2]||'build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm'; +const wasi=new WASI({version:'preview1',args:[],env:{},preopens:{},returnOnExit:true}); +const module=await WebAssembly.compile(fs.readFileSync(wasmPath)); +const imports=wasi.getImportObject(module); +imports.env||={};imports.env.emscripten_notify_memory_growth=()=>{}; +const instance=await WebAssembly.instantiate(module,imports); +wasi.initialize(instance); +const e=instance.exports; + +const expect=(cond,message)=>{if(!cond)throw new Error(message);}; +const PAGE=4096,BASE=0x00100000; // physical == virtual outside kernel physical ranges +e.r360_sparse_guest_memory_reset(); +const backing=e.r360_sparse_guest_memory_alloc(4); +expect(backing&&e.r360_sparse_guest_memory_map(BASE,4,backing,0,3),'map 4 pages'); +for(let p=0;p<4;p++)expect(e.r360_sparse_guest_memory_write_u32_be(BASE+p*PAGE,0x11110000+p),'write'); +e.r360_gpu_shared_memory_clear(); + +// Stream: [op | words << 8] payload; upload payload = dest, length, bytes. +function uploads(){ + const words=e.r360_gpu_stream_words()>>>0,ptr=e.r360_gpu_stream_data()>>>0; + const w=new Uint32Array(e.memory.buffer,ptr,words),out=[]; + for(let i=0;i>>8; + if(op===1){ + const dest=w[i+1],length=w[i+2]; + const bytes=new Uint8Array(e.memory.buffer,ptr+(i+3)*4,length); + const firstWords=[];for(let p=0;p>>0); + out.push({dest,length,firstWords}); + } + i+=1+n; + } + e.r360_gpu_stream_reset(); + return out; +} + +expect(e.r360_gpu_shared_memory_request(BASE,4*PAGE)===1,'request'); +let u=uploads(); +expect(u.length===1&&u[0].dest===BASE&&u[0].length===4*PAGE,`first request uploads the range once: ${JSON.stringify(u)}`); +expect(u[0].firstWords.join()===[0x11110000,0x11110001,0x11110002,0x11110003].join(),'uploaded bytes'); + +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +expect(uploads().length===0,'valid pages are not uploaded again'); + +e.r360_sparse_guest_memory_write_u32_be(BASE+2*PAGE+8,0xABCDEF01); +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +u=uploads(); +expect(u.length===1&&u[0].dest===BASE+2*PAGE&&u[0].length===PAGE,`a CPU write reuploads only its page: ${JSON.stringify(u)}`); + +e.r360_sparse_guest_memory_write_u32_be(BASE+3*PAGE,0x22222222); +e.r360_gpu_shared_memory_written_by_gpu(BASE+3*PAGE,PAGE); +e.r360_gpu_shared_memory_request(BASE,4*PAGE); +expect(uploads().length===0,'a GPU-written range needs no upload'); + +e.r360_sparse_guest_memory_write_u32_be(BASE,0x33333333); +e.r360_sparse_guest_memory_write_u32_be(BASE+PAGE,0x44444444); +e.r360_gpu_shared_memory_request(BASE+16,PAGE); // spans pages 0 and 1 +u=uploads(); +expect(u.length===1&&u[0].dest===BASE&&u[0].length===2*PAGE&&u[0].firstWords.join()===[0x33333333,0x44444444].join(), + `dirty neighbours upload as one range: ${JSON.stringify(u)}`); + +expect(e.r360_gpu_shared_memory_request(0x1FFFF000,0x2000)===0,'ranges past 512 MiB are refused'); +console.log(`uploaded ${e.r360_gpu_shared_memory_uploaded_kb()} KiB in ${e.r360_gpu_shared_memory_upload_ranges()} ranges`); +console.log('WEBGPU_SHARED_MEMORY_PASS'); diff --git a/tests/browser/webgpu-shared-memory.mjs b/tests/browser/webgpu-shared-memory.mjs new file mode 100644 index 00000000..4c16e45b --- /dev/null +++ b/tests/browser/webgpu-shared-memory.mjs @@ -0,0 +1,50 @@ +// Browser side of test-webgpu-shared-memory-browser.mjs: the core records +// shared memory uploads, the WebGPU backend replays them, and the GPU buffer +// read back matches guest memory, including after a CPU write that +// invalidates one page. +import {createRender360BrowserImports,attachRender360BrowserInstance} from '../../render360-browser-wasi.mjs'; +import {XenosWebGpuBackend} from '../../render360-webgpu-backend.mjs'; + +export default async function run(wasmPath){ + const adapter=await navigator.gpu?.requestAdapter(); + if(!adapter)return {ok:false,error:'no WebGPU adapter'}; + const device=await adapter.requestDevice({requiredLimits:{ + maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); + const host=createRender360BrowserImports(); + const module=await WebAssembly.compileStreaming(fetch(wasmPath)); + const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); + const e=instance.exports; + const backend=new XenosWebGpuBackend(device,e); + + const PAGE=4096,BASE=0x00100000; + e.r360_sparse_guest_memory_reset(); + const backing=e.r360_sparse_guest_memory_alloc(4); + e.r360_sparse_guest_memory_map(BASE,4,backing,0,3); + for(let p=0;p<4;p++)for(let w=0;w>>0); + e.r360_gpu_shared_memory_clear(); + + // Expected bytes: the words written above, big-endian, zero elsewhere. + const expected=()=>{ + const out=new Uint8Array(4*PAGE); + for(let p=0;p<4;p++)for(let w=0;w>>0,o=p*PAGE+w*4;out[o]=v>>>24;out[o+1]=v>>>16&255;out[o+2]=v>>>8&255;out[o+3]=v&255;} + return out; + }; + const want=expected(); + const same=(a,b)=>a.length===b.length&&a.every((x,i)=>x===b[i]); + + e.r360_gpu_shared_memory_request(BASE,4*PAGE); + backend.replay(); + const first=await backend.readSharedMemory(BASE,4*PAGE); + if(!same(first,want))return {ok:false,error:'shared memory differs from guest memory after the first upload'}; + + e.r360_sparse_guest_memory_write_u32_be(BASE+PAGE+8,0xCAFEF00D); + want.set([0xCA,0xFE,0xF0,0x0D],PAGE+8); + const uploadsBefore=backend.stats.uploads; + e.r360_gpu_shared_memory_request(BASE,4*PAGE); + backend.replay(); + const second=await backend.readSharedMemory(BASE,4*PAGE); + if(!same(second,want))return {ok:false,error:'shared memory differs after the CPU write'}; + return {ok:true,uploads:backend.stats.uploads,secondUploads:backend.stats.uploads-uploadsBefore, + uploadedBytes:backend.stats.uploadedBytes,sharedMemoryMiB:backend.sharedMemoryBytes/1048576, + adapter:adapter.info?.architecture||''}; +} diff --git a/tools/browser-test.mjs b/tools/browser-test.mjs new file mode 100644 index 00000000..cca055d1 --- /dev/null +++ b/tools/browser-test.mjs @@ -0,0 +1,60 @@ +// Runs a browser-side test module in headless Chromium with WebGPU +// (SwiftShader) and returns what it reports. +// +// import {runBrowserTest} from './tools/browser-test.mjs'; +// const result = await runBrowserTest('tests/browser/foo.mjs'); +// +// The repository root is served on localhost (WebGPU needs a secure +// context). The module's default export is awaited in the page; its return +// value comes back as JSON. Uses the globally installed Playwright. +import http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; +import {execSync} from 'node:child_process'; +import {createRequire} from 'node:module'; + +const ROOT=path.resolve(path.dirname(new URL(import.meta.url).pathname),'..'); +const TYPES={'.mjs':'text/javascript','.js':'text/javascript','.html':'text/html','.wasm':'application/wasm','.json':'application/json'}; + +function loadPlaywright(){ + const globalRoot=execSync('npm root -g').toString().trim(); + return createRequire(path.join(globalRoot,'noop.js'))(path.join(globalRoot,'playwright')); +} + +function serve(){ + const server=http.createServer((req,res)=>{ + const url=new URL(req.url,'http://localhost'); + if(url.pathname==='/__test__.html'){ + res.writeHead(200,{'content-type':'text/html'}); + res.end(''); + return; + } + const file=path.join(ROOT,decodeURIComponent(url.pathname)); + if(!file.startsWith(ROOT)||!fs.existsSync(file)||fs.statSync(file).isDirectory()){res.writeHead(404);res.end();return;} + res.writeHead(200,{'content-type':TYPES[path.extname(file)]||'application/octet-stream'}); + fs.createReadStream(file).pipe(res); + }); + return new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(server))); +} + +export async function runBrowserTest(modulePath,{args=[],timeoutMs=300000,onConsole=null}={}){ + const {chromium}=loadPlaywright(); + const server=await serve(); + const port=server.address().port; + const browser=await chromium.launch({args:['--enable-unsafe-webgpu','--enable-features=Vulkan', + '--use-vulkan=swiftshader','--use-webgpu-adapter=swiftshader','--disable-vulkan-surface']}); + try{ + const page=await browser.newPage(); + page.on('console',m=>onConsole?.(m.text())); + page.on('pageerror',e=>onConsole?.(`pageerror: ${e.message}`)); + await page.goto(`http://127.0.0.1:${port}/__test__.html`); + page.setDefaultTimeout(timeoutMs); + return await page.evaluate(async([m,a])=>{ + const mod=await import(m); + return JSON.stringify(await mod.default(...a)); + },[`/${modulePath}`,args]).then(JSON.parse); + }finally{ + await browser.close(); + server.close(); + } +} diff --git a/tools/run-title.mjs b/tools/run-title.mjs index a5b8b367..9c9aeb0b 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -253,10 +253,11 @@ async function main(){ // Guest JIT (render360-guest-jit.mjs): hot guest functions run as // generated WebAssembly. --no-jit keeps everything on the HIR executor. const {installGuestJit}=await import(rel('render360-guest-jit.mjs')); - const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); + const jit=args.jit===0?null:installGuestJit(bootstrap,{mode:args.jit||1,hotThreshold:Number(process.env.R360_JIT_HOT||2),onError:(err)=>{if(!globalThis.__r360JitErrShown){globalThis.__r360JitErrShown=1;console.error('JIT module error:',err.message);}}}); globalThis.__r360Jit=jit; if(process.env.R360_JITPROF)bootstrap.exports.r360_jit_profile?.(1); if(process.env.R360_DIAG){bootstrap.exports.r360_jit_diag?.(1);} + if(process.env.R360_JIT_EXCLUDE){const [b,e]=process.env.R360_JIT_EXCLUDE.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude?.(b,e);} if(args.traceFrom!==undefined){globalThis.__r360TraceOn=1;bootstrap.exports.r360_trace_verbose_from?.(args.traceFrom);} if(process.env.R360_OSR!==undefined)bootstrap.exports.r360_jit_set_osr?.(Number(process.env.R360_OSR)); (args.kernelWatch||[]).slice(0,4).forEach((v,k)=>bootstrap.exports.r360_kernel_watch_arg?.(k,v)); From a99ef192946ca7e22e4ee05f978b012a02444a86 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 11:54:46 +0000 Subject: [PATCH 44/65] WebGPU backend: record draws, pipelines, render targets and swaps Port of Xenia's Vulkan pipeline cache shader modifications, index conversion, system constants and float constant packing into the GPU command stream (r360_gpu_set_mode). run-title.mjs gains --gpu-capture to slice a stream for offline replay (written to a local path only), and the JIT gains compile-sequence exclusion for bisecting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 3 +- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 16 +- src/xenia_web_bootstrap/webgpu_backend.h | 72 ++ src/xenia_web_bootstrap/webgpu_draws.cpp | 617 ++++++++++++++++++ .../xenos_gpu_foundation.cpp | 3 + .../xenos_soft_renderer.cpp | 4 + tools/run-title.mjs | 34 +- 7 files changed, 745 insertions(+), 4 deletions(-) create mode 100644 src/xenia_web_bootstrap/webgpu_draws.cpp diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index e9784477..94c06a13 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -199,6 +199,7 @@ queue_cpp "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibe queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" queue_cpp "render360/webgpu_backend.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_backend.cpp" +queue_cpp "render360/webgpu_draws.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_draws.cpp" queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" queue_cpp "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" @@ -233,7 +234,7 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 31 )) +expected=$(( ${#SOURCES[@]} + 2 + 32 )) actual=$(( passed + failed )) echo diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 89c84ad9..64ab63b0 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -1882,8 +1882,14 @@ bool Excluded(HIRBuilder* builder) { return false; } +// Compile requests numbered in order; [g_exclude_seq_begin, end) stay +// interpreted (r360_jit_set_exclude_seq; bisecting by when code compiles, +// which keeps early, hot functions compiled). +uint32_t g_compile_seq = 0, g_exclude_seq_begin = 0, g_exclude_seq_end = 0; + uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { - if (Excluded(builder)) { + const uint32_t seq = g_compile_seq++; + if (Excluded(builder) || (seq >= g_exclude_seq_begin && seq < g_exclude_seq_end)) { slot->state = 2; return 0; } @@ -2016,6 +2022,14 @@ void JitReleaseSlot(JitSlot* slot) { namespace rx = render360::xenia_web; extern "C" { +__attribute__((used, export_name("r360_jit_set_exclude_seq"))) +uint32_t r360_jit_set_exclude_seq(uint32_t begin, uint32_t end) { + rx::g_exclude_seq_begin = begin; + rx::g_exclude_seq_end = end; + return rx::g_compile_seq; +} +__attribute__((used, export_name("r360_jit_compile_seq"))) +uint32_t r360_jit_compile_seq() { return rx::g_compile_seq; } __attribute__((used, export_name("r360_jit_set_exclude"))) uint32_t r360_jit_set_exclude(uint32_t begin, uint32_t end) { rx::g_exclude_begin = begin; diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h index 23bc7e27..ef1d5dd4 100644 --- a/src/xenia_web_bootstrap/webgpu_backend.h +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -15,8 +15,80 @@ enum GpuStreamOp : uint32_t { // (padded to 4). Copied at record time: the guest may rewrite the source // before the stream is replayed. kGpuStreamUpload = 1, + // A translated shader, once per (ucode, modification): id, stage (0 vertex, + // 1 pixel), texture binding count, sampler binding count, SPIR-V word + // count, then the texture bindings (fetch constant | dimension << 5 | + // signed << 7), the sampler bindings (fetch constant | mag << 5 | min << 7 + // | mip << 9 | aniso << 11) and the SPIR-V words. + kGpuStreamShader = 2, + // A render pipeline, once per description: id, then the + // WebGpuPipelineDescription words. + kGpuStreamPipeline = 3, + // The render targets subsequent draws write: WebGpuRenderTargetsKey words. + kGpuStreamRenderTargets = 4, + // A draw: WebGpuDrawHeader, the system constants, vertex and pixel float + // constants, bool/loop constants, fetch constants, then the indices. + kGpuStreamDraw = 5, + // A swap: the front buffer's texture fetch constant (6 words). + kGpuStreamSwap = 6, }; +// Pipeline state, following Xenia's VulkanPipelineCache::PipelineDescription. +struct WebGpuPipelineDescription { + uint32_t vertex_shader; // stream shader id + uint32_t pixel_shader; // 0: none (depth only) + uint32_t topology; // 0 points, 1 lines, 2 line strip, 3 triangles, 4 triangle strip + uint32_t cull_mode; // 0 none, 1 front, 2 back + uint32_t front_face_cw; + uint32_t depth_compare; // xenos::CompareFunction, kAlways when the test is off + uint32_t depth_write; + uint32_t stencil; // RB_DEPTHCONTROL bits 0x7FFF00 when stencil is on, else 0 + uint32_t stencil_masks; // RB_STENCILREFMASK (front) read/write masks + uint32_t color_formats[4]; // xenos::ColorRenderTargetFormat + 1, 0: unused + uint32_t color_write_masks; // 4 bits per render target + uint32_t blend_control[4]; // RB_BLENDCONTROL & 0x1FFF1FFF per render target + uint32_t depth_format; // xenos::DepthRenderTargetFormat + 1, 0: no depth + uint32_t msaa_samples; // xenos::MsaaSamples +}; + +// Bound render targets, keyed like Xenia's RenderTargetCache: EDRAM base +// (tiles), pitch (pixels), format; 0xFFFFFFFF base when unused. +struct WebGpuRenderTargetsKey { + uint32_t surface_pitch; + uint32_t msaa_samples; + uint32_t height; // pixels the draws can reach (viewport / scissor bound) + uint32_t color_base[4]; + uint32_t color_format[4]; + uint32_t depth_base; + uint32_t depth_format; +}; + +struct WebGpuDrawHeader { + uint32_t pipeline; + uint32_t viewport[4]; // x, y, width, height (pixels) + float depth_range[2]; + uint32_t scissor[4]; + uint32_t stencil_reference; + float blend_constant[4]; + uint32_t system_constant_words; + uint32_t float_vertex_words; + uint32_t float_pixel_words; + uint32_t bool_loop_words; + uint32_t fetch_words; + uint32_t index_format; // 0 none (vertex_count vertices), 1 uint16, 2 uint32 + uint32_t vertex_count; // indices, or vertices without an index buffer + uint32_t vertex_texture_mask; // fetch constants the shaders sample + uint32_t pixel_texture_mask; +}; + +// Records draws for the WebGPU backend when enabled (r360_gpu_set_mode); +// false when the draw uses something not implemented yet (counted). +struct XenosSoftDraw; +bool WebGpuIssueDraw(const XenosSoftDraw& draw); +bool WebGpuBackendEnabled(); +// PM4 XE_SWAP: the front buffer texture fetch constant (6 words). +void WebGpuSwap(const uint32_t* fetch_constant); + class GpuCommandStream { public: void Reset() { words_.clear(); } diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp new file mode 100644 index 00000000..1ca94036 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -0,0 +1,617 @@ +// WebGPU backend draws: the per-draw part of Xenia's VulkanCommandProcessor +// (IssueDraw, UpdateSystemConstantValues, UpdateBindings) and +// VulkanPipelineCache (shader modifications, translation, pipeline state), +// recording into the command stream (webgpu_backend.h) instead of a Vulkan +// command buffer. Render targets follow Xenia's host render target path. +#include +#include +#include +#include +#include + +#include "webgpu_backend.h" +#include "xenos_soft_draw.h" +#include "sparse_guest_memory.h" +#include "xenia/base/math.h" +#include "xenia/base/string_buffer.h" +#include "xenia/gpu/draw_util.h" +#include "xenia/gpu/register_file.h" +#include "xenia/gpu/registers.h" +#include "xenia/gpu/spirv_shader.h" +#include "xenia/gpu/spirv_shader_translator.h" +#include "xenia/gpu/xenos.h" + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace render360::xenia_web { +namespace { + +using xe::gpu::RegisterFile; +using xe::gpu::Shader; +using xe::gpu::SpirvShader; +using xe::gpu::SpirvShaderTranslator; +namespace reg = xe::gpu::reg; +namespace xenos = xe::gpu::xenos; +namespace draw_util = xe::gpu::draw_util; +using namespace xe::gpu; // XE_GPU_REG_* register indices + +uint32_t g_mode = 0; // 0 off, 1 record draws + +// Why draws were not recorded (r360_gpu_draw_stat). +enum DrawSkip : uint32_t { + kSkipNoVertexShader = 1, + kSkipTranslation, + kSkipPrimitive, + kSkipIndices, + kSkipVertexFetch, + kSkipCount, +}; +uint32_t g_draws = 0, g_skips[kSkipCount] = {}, g_last_skip = 0; +bool Skip(DrawSkip reason) { + ++g_skips[reason]; + g_last_skip = reason; + return false; +} + +RegisterFile& Regs() { + static RegisterFile registers; + return registers; +} + +SpirvShaderTranslator& Translator() { + static SpirvShaderTranslator* translator = [] { + SpirvShaderTranslator::Features features(false); + // One logical 512 MiB shared memory binding (see + // xenos_spirv_translation_probe.cpp: WGSL has no arrays of unsized + // storage structs). + features.max_storage_buffer_range = 512u * 1024u * 1024u; + // WebGPU texture views do not swizzle: the shaders apply the swizzle + // from the system constants, as Xenia does without + // imageViewFormatSwizzle. + features.image_view_format_swizzle = false; + return new SpirvShaderTranslator(features, false, false, false); + }(); + return *translator; +} + +// Analyzed shaders by type and ucode (Xenia's shader storage). +SpirvShader* GetShader(xenos::ShaderType type, const uint32_t* words, uint32_t dwords, + uint32_t hash) { + static std::unordered_map> shaders; + if (!words || !dwords) return nullptr; + const uint64_t key = (uint64_t(hash) << 32) ^ (uint64_t(dwords) << 1) ^ uint64_t(type); + auto it = shaders.find(key); + if (it != shaders.end()) return it->second.get(); + auto shader = std::make_unique(type, key, words, dwords, std::endian::native); + xe::StringBuffer disassembly; + shader->AnalyzeUcode(disassembly); + SpirvShader* result = shader.get(); + shaders.emplace(key, std::move(shader)); + return result; +} + +// Port of VulkanPipelineCache::GetCurrentVertexShaderModification (host +// vertex shader type kVertex). +SpirvShaderTranslator::Modification VertexShaderModification(const Shader& shader, + uint32_t interpolator_mask) { + const RegisterFile& regs = Regs(); + SpirvShaderTranslator::Modification modification( + Translator().GetDefaultVertexShaderModification( + shader.GetDynamicAddressableRegisterCount(regs.Get().vs_num_reg), + Shader::HostVertexShaderType::kVertex)); + modification.vertex.interpolator_mask = interpolator_mask; + modification.vertex.output_point_parameters = + uint32_t((shader.writes_point_size_edge_flag_kill_vertex() & 0b001) && + regs.Get().prim_type == xenos::PrimitiveType::kPointList); + return modification; +} + +// Port of VulkanPipelineCache::GetCurrentPixelShaderModification (host +// render targets path). +SpirvShaderTranslator::Modification PixelShaderModification(const Shader& shader, + uint32_t interpolator_mask, + uint32_t param_gen_pos) { + const RegisterFile& regs = Regs(); + SpirvShaderTranslator::Modification modification( + Translator().GetDefaultPixelShaderModification( + shader.GetDynamicAddressableRegisterCount(regs.Get().ps_num_reg))); + modification.pixel.interpolator_mask = interpolator_mask; + modification.pixel.interpolators_centroid = + interpolator_mask & + ~xenos::GetInterpolatorSamplingPattern(regs.Get().msaa_samples, + regs.Get().sc_sample_cntl, + regs.Get().sampling_pattern); + if (param_gen_pos < xenos::kMaxInterpolators) { + modification.pixel.param_gen_enable = 1; + modification.pixel.param_gen_interpolator = param_gen_pos; + modification.pixel.param_gen_point = + uint32_t(regs.Get().prim_type == xenos::PrimitiveType::kPointList); + } else { + modification.pixel.param_gen_enable = 0; + modification.pixel.param_gen_interpolator = 0; + modification.pixel.param_gen_point = 0; + } + using DepthStencilMode = SpirvShaderTranslator::Modification::DepthStencilMode; + if (shader.implicit_early_z_write_allowed() && + (!shader.writes_color_target(0) || + !draw_util::DoesCoverageDependOnAlpha(regs.Get()))) { + modification.pixel.depth_stencil_mode = DepthStencilMode::kEarlyHint; + } else { + modification.pixel.depth_stencil_mode = DepthStencilMode::kNoModifiers; + } + return modification; +} + +// Stream ids of translations already sent (0: none yet). +std::unordered_map& ShaderIds() { + static std::unordered_map ids; + return ids; +} +uint32_t g_next_shader_id = 1; + +// Translates (once) and returns the stream id, sending the shader the first +// time; 0 on failure. +uint32_t ShaderId(SpirvShader& shader, uint64_t modification) { + Shader::Translation* translation = shader.GetOrCreateTranslation(modification); + if (!translation) return 0; + auto& ids = ShaderIds(); + if (auto it = ids.find(translation); it != ids.end()) return it->second; + if (!translation->is_translated() && !Translator().TranslateAnalyzedShader(*translation)) { + ids.emplace(translation, 0u); + return 0; + } + const auto& binary = translation->translated_binary(); + if (!translation->is_valid() || binary.size() < 20 || (binary.size() & 3)) { + ids.emplace(translation, 0u); + return 0; + } + const auto& textures = shader.GetTextureBindingsAfterTranslation(); + const auto& samplers = shader.GetSamplerBindingsAfterTranslation(); + const uint32_t spirv_words = uint32_t(binary.size() / 4); + const uint32_t id = g_next_shader_id++; + uint32_t* w = GpuStream().Begin(kGpuStreamShader, + 5 + uint32_t(textures.size() + samplers.size()) + spirv_words); + *w++ = id; + *w++ = shader.type() == xenos::ShaderType::kVertex ? 0u : 1u; + *w++ = uint32_t(textures.size()); + *w++ = uint32_t(samplers.size()); + *w++ = spirv_words; + for (const auto& t : textures) { + *w++ = t.fetch_constant | (uint32_t(t.dimension) << 5) | (uint32_t(t.is_signed) << 7); + } + for (const auto& s : samplers) { + *w++ = s.fetch_constant | (uint32_t(s.mag_filter) << 5) | (uint32_t(s.min_filter) << 7) | + (uint32_t(s.mip_filter) << 9) | (uint32_t(s.aniso_filter) << 11); + } + std::memcpy(w, binary.data(), binary.size()); + ids.emplace(translation, id); + return id; +} + +// Pipelines already sent, by description. +struct PipelineKeyHash { + size_t operator()(const std::vector& v) const { + uint64_t h = 1469598103934665603ull; + for (uint32_t x : v) h = (h ^ x) * 1099511628211ull; + return size_t(h ^ (h >> 32)); + } +}; +uint32_t PipelineId(const WebGpuPipelineDescription& description) { + static std::unordered_map, uint32_t, PipelineKeyHash> pipelines; + static uint32_t next_id = 1; + constexpr uint32_t kWords = sizeof(description) / 4; + std::vector key(kWords); + std::memcpy(key.data(), &description, sizeof(description)); + if (auto it = pipelines.find(key); it != pipelines.end()) return it->second; + const uint32_t id = next_id++; + uint32_t* w = GpuStream().Begin(kGpuStreamPipeline, 1 + kWords); + w[0] = id; + std::memcpy(w + 1, &description, sizeof(description)); + pipelines.emplace(std::move(key), id); + return id; +} + +// Guest indices converted to host little-endian indices of the host +// primitive type (Xenia's PrimitiveProcessor converts fans, quads and +// endianness in the same way when the host cannot use them directly). +struct Indices { + uint32_t host_topology = 3; // see WebGpuPipelineDescription::topology + std::vector values; // empty: non-indexed with vertex_count + uint32_t vertex_count = 0; + bool use_32bit = false; +}; + +bool ReadGuestIndex(const XenosSoftDraw& draw, const reg::VGT_DRAW_INITIATOR& init, uint32_t i, + xenos::Endian endian, uint32_t* out) { + if (i >= draw.index_size) return false; + if (init.index_size == xenos::IndexFormat::kInt16) { + // The GPU swaps whole 32-bit words, then takes the 16-bit half (as the + // software renderer's ReadIndex does). + const uint32_t address = draw.index_base + i * 2u; + uint32_t word = 0; + if (!ReadSparseGuestMemory(r360_kernel_gpu_address_to_virtual(address & ~3u), &word, 4)) return false; + *out = (xenos::GpuSwap(word, endian) >> ((address & 2u) * 8u)) & 0xFFFFu; + return true; + } + uint32_t v = 0; + if (!ReadSparseGuestMemory(r360_kernel_gpu_address_to_virtual(draw.index_base + i * 4u), &v, 4)) return false; + *out = xenos::GpuSwap(v, endian) & 0xFFFFFFu; + return true; +} + +bool BuildIndices(const XenosSoftDraw& draw, Indices& out) { + const RegisterFile& regs = Regs(); + reg::VGT_DRAW_INITIATOR init; + init.value = draw.draw_initiator; + const uint32_t count = init.num_indices; + const bool indexed = init.source_select == xenos::SourceSelect::kDMA; + if (!indexed && init.source_select != xenos::SourceSelect::kAutoIndex) return false; + const auto endian = xenos::Endian(regs[XE_GPU_REG_VGT_DMA_SIZE] >> 30); + const uint32_t offset = regs[XE_GPU_REG_VGT_INDX_OFFSET]; + std::vector guest; + if (indexed) { + guest.resize(count); + for (uint32_t i = 0; i < count; ++i) { + if (!ReadGuestIndex(draw, init, i, endian, &guest[i])) return false; + guest[i] = (guest[i] + offset) & 0xFFFFFFu; + } + } + auto index_at = [&](uint32_t i) { return indexed ? guest[i] : (i + offset) & 0xFFFFFFu; }; + auto& v = out.values; + switch (init.prim_type) { + case xenos::PrimitiveType::kPointList: out.host_topology = 0; break; + case xenos::PrimitiveType::kLineList: out.host_topology = 1; break; + case xenos::PrimitiveType::kLineStrip: out.host_topology = 2; break; + case xenos::PrimitiveType::kTriangleList: out.host_topology = 3; break; + case xenos::PrimitiveType::kTriangleStrip: out.host_topology = 4; break; + case xenos::PrimitiveType::kTriangleFan: + out.host_topology = 3; + for (uint32_t i = 2; i < count; ++i) { + v.push_back(index_at(0)); v.push_back(index_at(i - 1)); v.push_back(index_at(i)); + } + break; + case xenos::PrimitiveType::kQuadList: + out.host_topology = 3; + for (uint32_t i = 0; i + 3 < count; i += 4) { + v.push_back(index_at(i)); v.push_back(index_at(i + 1)); v.push_back(index_at(i + 2)); + v.push_back(index_at(i)); v.push_back(index_at(i + 2)); v.push_back(index_at(i + 3)); + } + break; + case xenos::PrimitiveType::kLineLoop: + out.host_topology = 2; + for (uint32_t i = 0; i < count; ++i) v.push_back(index_at(i)); + if (count) v.push_back(index_at(0)); + break; + default: + return false; // rectangle lists, polygons, patches: not yet + } + const bool converted = !v.empty() || init.prim_type == xenos::PrimitiveType::kTriangleFan || + init.prim_type == xenos::PrimitiveType::kQuadList; + if (!converted) { + if (indexed || offset) { + for (uint32_t i = 0; i < count; ++i) v.push_back(index_at(i)); + } else { + out.vertex_count = count; + } + } + for (uint32_t x : v) out.use_32bit |= x > 0xFFFFu; + return true; +} + +// Port of VulkanCommandProcessor::UpdateSystemConstantValues for the host +// render targets path (no fragment shader interlock, no resolution scale). +void FillSystemConstants(SpirvShaderTranslator::SystemConstants& c, bool primitive_polygonal, + const draw_util::ViewportInfo& viewport_info) { + const RegisterFile& regs = Regs(); + std::memset(&c, 0, sizeof(c)); + auto pa_cl_vte_cntl = regs.Get(); + auto rb_colorcontrol = regs.Get(); + auto rb_depth_info = regs.Get(); + auto rb_surface_info = regs.Get(); + uint32_t flags = 0; + if (pa_cl_vte_cntl.vtx_xy_fmt) flags |= SpirvShaderTranslator::kSysFlag_XYDividedByW; + if (pa_cl_vte_cntl.vtx_z_fmt) flags |= SpirvShaderTranslator::kSysFlag_ZDividedByW; + if (pa_cl_vte_cntl.vtx_w0_fmt) flags |= SpirvShaderTranslator::kSysFlag_WNotReciprocal; + if (primitive_polygonal) flags |= SpirvShaderTranslator::kSysFlag_PrimitivePolygonal; + if (draw_util::IsPrimitiveLine(regs)) flags |= SpirvShaderTranslator::kSysFlag_PrimitiveLine; + flags |= uint32_t(rb_surface_info.msaa_samples) << SpirvShaderTranslator::kSysFlag_MsaaSamples_Shift; + if (rb_depth_info.depth_format == xenos::DepthRenderTargetFormat::kD24FS8) { + flags |= SpirvShaderTranslator::kSysFlag_DepthFloat24; + } + const xenos::CompareFunction alpha_test_function = + rb_colorcontrol.alpha_test_enable ? rb_colorcontrol.alpha_func : xenos::CompareFunction::kAlways; + flags |= uint32_t(alpha_test_function) << SpirvShaderTranslator::kSysFlag_AlphaPassIfLess_Shift; + for (uint32_t i = 0; i < xenos::kMaxColorRenderTargets; ++i) { + auto color_info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + if (color_info.color_format == xenos::ColorRenderTargetFormat::k_8_8_8_8_GAMMA) { + flags |= SpirvShaderTranslator::kSysFlag_ConvertColor0ToGamma << i; + } + int32_t color_exp_bias = color_info.color_exp_bias; + // Host k_16_16 / k_16_16_16_16 render targets are normalized to -1..1 in + // 32-unit range (Xenia's non-truncated fixed-point RG(BA)16). + if (color_info.color_format == xenos::ColorRenderTargetFormat::k_16_16 || + color_info.color_format == xenos::ColorRenderTargetFormat::k_16_16_16_16) { + color_exp_bias -= 5; + } + uint32_t bits = uint32_t(0x3F800000 + (color_exp_bias << 23)); + std::memcpy(&c.color_exp_bias[i], &bits, 4); + } + c.flags = flags; + c.vertex_index_endian = xenos::Endian::kNone; + c.vertex_base_index = 0; // applied while building the host indices + for (uint32_t i = 0; i < 3; ++i) { + c.ndc_scale[i] = viewport_info.ndc_scale[i]; + c.ndc_offset[i] = viewport_info.ndc_offset[i]; + } + if (regs.Get().prim_type == xenos::PrimitiveType::kPointList) { + auto minmax = regs.Get(); + auto size = regs.Get(); + c.point_vertex_diameter_min = float(minmax.min_size) * (2.0f / 16.0f); + c.point_vertex_diameter_max = float(minmax.max_size) * (2.0f / 16.0f); + c.point_constant_diameter[0] = float(size.width) * (2.0f / 16.0f); + c.point_constant_diameter[1] = float(size.height) * (2.0f / 16.0f); + c.point_screen_diameter_to_ndc_radius[0] = 1.0f / std::max(viewport_info.xy_extent[0], 1u); + c.point_screen_diameter_to_ndc_radius[1] = 1.0f / std::max(viewport_info.xy_extent[1], 1u); + } + // Texture signs and swizzles come from the texture cache (not yet: the + // backend binds placeholder textures, sampled as unsigned RGBA). + for (uint32_t i = 0; i < 16; ++i) c.texture_swizzles[i] = 0x688u | (0x688u << 12); // RGBA + c.alpha_test_reference = regs.Get(XE_GPU_REG_RB_ALPHA_REF); +} + +// Float constants used by the shader, packed in register order (Xenia's +// UpdateBindings tight packing). +void PackFloatConstants(const Shader& shader, bool pixel, std::vector& out) { + const RegisterFile& regs = Regs(); + const auto& map = shader.constant_register_map(); + const uint32_t base = XE_GPU_REG_SHADER_CONSTANT_000_X + (pixel ? 256u * 4u : 0u); + for (uint32_t i = 0; i < 4; ++i) { + uint64_t bits = map.float_bitmap[i]; + uint32_t index; + while (xe::bit_scan_forward(bits, &index)) { + bits &= ~(uint64_t(1) << index); + const uint32_t reg_index = base + (((i << 6) + index) << 2); + for (uint32_t c = 0; c < 4; ++c) out.push_back(regs[reg_index + c]); + } + } + if (out.empty()) out.assign(4, 0u); +} + +// The render targets the draw writes (host render targets path), as Xenia's +// RenderTargetCache::Update selects them. +WebGpuRenderTargetsKey RenderTargets(uint32_t normalized_color_mask, bool depth_enabled, + uint32_t height) { + const RegisterFile& regs = Regs(); + WebGpuRenderTargetsKey key{}; + auto surface = regs.Get(); + key.surface_pitch = surface.surface_pitch; + key.msaa_samples = uint32_t(surface.msaa_samples); + key.height = height; + for (uint32_t i = 0; i < 4; ++i) { + auto info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + const bool used = (normalized_color_mask >> (i * 4)) & 0xF; + key.color_base[i] = used ? info.color_base : 0xFFFFFFFFu; + key.color_format[i] = used ? uint32_t(info.color_format) : 0u; + } + auto depth = regs.Get(); + key.depth_base = depth_enabled ? depth.depth_base : 0xFFFFFFFFu; + key.depth_format = depth_enabled ? uint32_t(depth.depth_format) : 0u; + return key; +} + +WebGpuRenderTargetsKey g_bound_targets{}; +bool g_targets_bound = false; + +} // namespace + +bool WebGpuBackendEnabled() { return g_mode != 0; } + +void WebGpuSwap(const uint32_t* fetch_constant) { + if (!g_mode) return; + uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 6); + std::memcpy(w, fetch_constant, 6 * sizeof(uint32_t)); +} + +bool WebGpuIssueDraw(const XenosSoftDraw& draw) { + if (!g_mode) return false; + RegisterFile& regs = Regs(); + const uint32_t count = std::min(draw.register_count, RegisterFile::kRegisterCount); + std::memcpy(regs.values, draw.registers, count * sizeof(uint32_t)); + const auto edram_mode = regs.Get().edram_mode; + if (edram_mode != xenos::EdramMode::kColorDepth && edram_mode != xenos::EdramMode::kDepthOnly) { + return true; // copies are resolves (not recorded here yet) + } + + SpirvShader* vertex_shader = + GetShader(xenos::ShaderType::kVertex, draw.vertex_shader, draw.vertex_shader_dwords, + draw.vertex_shader_hash); + if (!vertex_shader || !vertex_shader->is_ucode_analyzed()) return Skip(kSkipNoVertexShader); + SpirvShader* pixel_shader = nullptr; + if (edram_mode == xenos::EdramMode::kColorDepth && draw.pixel_shader) { + pixel_shader = GetShader(xenos::ShaderType::kPixel, draw.pixel_shader, draw.pixel_shader_dwords, + draw.pixel_shader_hash); + if (pixel_shader && !pixel_shader->is_ucode_analyzed()) return Skip(kSkipTranslation); + } + const bool primitive_polygonal = draw_util::IsPrimitivePolygonal(regs); + if (!draw_util::IsRasterizationPotentiallyDone(regs, primitive_polygonal)) return true; + + uint32_t param_gen_pos = UINT32_MAX; + const uint32_t interpolator_mask = + pixel_shader ? vertex_shader->writes_interpolators() & + pixel_shader->GetInterpolatorInputMask(regs.Get(), + regs.Get(), + param_gen_pos) + : 0u; + const uint32_t vs_id = + ShaderId(*vertex_shader, VertexShaderModification(*vertex_shader, interpolator_mask).value); + if (!vs_id) return Skip(kSkipTranslation); + uint32_t ps_id = 0; + if (pixel_shader) { + ps_id = ShaderId(*pixel_shader, + PixelShaderModification(*pixel_shader, interpolator_mask, param_gen_pos).value); + if (!ps_id) return Skip(kSkipTranslation); + } + + Indices indices; + if (!BuildIndices(draw, indices)) return Skip(kSkipPrimitive); + + // Pipeline state (VulkanPipelineCache::GetCurrentStateDescription). + const reg::RB_DEPTHCONTROL depth_control = draw_util::GetNormalizedDepthControl(regs); + const uint32_t color_mask = + pixel_shader ? draw_util::GetNormalizedColorMask(regs, pixel_shader->writes_color_targets()) : 0u; + WebGpuPipelineDescription description{}; + description.vertex_shader = vs_id; + description.pixel_shader = ps_id; + description.topology = indices.host_topology; + auto pa_su_sc_mode_cntl = regs.Get(); + if (primitive_polygonal) { + description.cull_mode = pa_su_sc_mode_cntl.cull_front ? 1u : (pa_su_sc_mode_cntl.cull_back ? 2u : 0u); + if (pa_su_sc_mode_cntl.cull_front && pa_su_sc_mode_cntl.cull_back) return true; // nothing drawn + } + description.front_face_cw = pa_su_sc_mode_cntl.face ? 1u : 0u; + const bool depth_used = depth_control.z_enable || depth_control.stencil_enable; + description.depth_compare = + depth_control.z_enable ? uint32_t(depth_control.zfunc) : uint32_t(xenos::CompareFunction::kAlways); + description.depth_write = depth_control.z_enable && depth_control.z_write_enable; + if (depth_control.stencil_enable) { + description.stencil = depth_control.value & 0x7FFF00u; + description.stencil_masks = regs[XE_GPU_REG_RB_STENCILREFMASK] & 0xFFFF00u; + } + for (uint32_t i = 0; i < 4; ++i) { + const uint32_t mask = (color_mask >> (i * 4)) & 0xF; + if (!mask) continue; + auto info = regs.Get(reg::RB_COLOR_INFO::rt_register_indices[i]); + description.color_formats[i] = uint32_t(info.color_format) + 1u; + description.color_write_masks |= mask << (i * 4); + description.blend_control[i] = regs[reg::RB_BLENDCONTROL::rt_register_indices[i]] & 0x1FFF1FFFu; + } + if (depth_used) { + description.depth_format = uint32_t(regs.Get().depth_format) + 1u; + } + description.msaa_samples = uint32_t(regs.Get().msaa_samples); + + // Viewport and scissor in render target pixels (origin top-left, no + // resolution scale), as VulkanCommandProcessor computes them. + auto surface = regs.Get(); + const uint32_t pitch = std::max(surface.surface_pitch, 1u); + constexpr uint32_t kMaxHeight = 2560; + draw_util::ViewportInfo viewport_info; + draw_util::GetHostViewportInfo(regs, 1, 1, false, pitch, kMaxHeight, false, depth_control, + false, false, pixel_shader && pixel_shader->writes_depth(), + viewport_info); + draw_util::Scissor scissor; + draw_util::GetScissor(regs, scissor); + const uint32_t height = std::min( + kMaxHeight, std::max(scissor.offset[1] + scissor.extent[1], + viewport_info.xy_offset[1] + viewport_info.xy_extent[1])); + + // Render targets: a new set ends the current render pass. + const WebGpuRenderTargetsKey targets = RenderTargets(color_mask, depth_used, height); + if (!g_targets_bound || std::memcmp(&targets, &g_bound_targets, sizeof(targets)) != 0) { + uint32_t* w = GpuStream().Begin(kGpuStreamRenderTargets, sizeof(targets) / 4); + std::memcpy(w, &targets, sizeof(targets)); + g_bound_targets = targets; + g_targets_bound = true; + } + + // Vertex data the shader fetches from shared memory. + for (const auto& binding : vertex_shader->vertex_bindings()) { + const xenos::xe_gpu_vertex_fetch_t fetch = regs.GetVertexFetch(binding.fetch_constant); + if (fetch.type != xenos::FetchConstantType::kVertex) return Skip(kSkipVertexFetch); + if (!GpuSharedMemory().RequestRange(fetch.address << 2, fetch.size << 2)) { + return Skip(kSkipVertexFetch); + } + } + + // Constants. + SpirvShaderTranslator::SystemConstants system{}; + FillSystemConstants(system, primitive_polygonal, viewport_info); + std::vector float_vertex, float_pixel; + PackFloatConstants(*vertex_shader, false, float_vertex); + if (pixel_shader) PackFloatConstants(*pixel_shader, true, float_pixel); + else float_pixel.assign(4, 0u); + // Bool (8 dwords) and loop (32 dwords) constants, then the 32 texture / + // vertex fetch constants (6 dwords each), as Xenia uploads them. + constexpr uint32_t kBoolLoopWords = 8 + 32, kFetchWords = 32 * 6; + + const uint32_t index_words = + indices.values.empty() ? 0u + : (indices.use_32bit ? uint32_t(indices.values.size()) + : uint32_t((indices.values.size() + 1) / 2)); + const uint32_t system_words = sizeof(system) / 4; + const uint32_t payload = sizeof(WebGpuDrawHeader) / 4 + system_words + + uint32_t(float_vertex.size() + float_pixel.size()) + kBoolLoopWords + + kFetchWords + index_words; + const uint32_t pipeline_id = PipelineId(description); + uint32_t* w = GpuStream().Begin(kGpuStreamDraw, payload); + WebGpuDrawHeader header{}; + header.pipeline = pipeline_id; + header.viewport[0] = viewport_info.xy_offset[0]; + header.viewport[1] = viewport_info.xy_offset[1]; + header.viewport[2] = viewport_info.xy_extent[0]; + header.viewport[3] = viewport_info.xy_extent[1]; + header.depth_range[0] = viewport_info.z_min; + header.depth_range[1] = viewport_info.z_max; + header.scissor[0] = scissor.offset[0]; + header.scissor[1] = scissor.offset[1]; + header.scissor[2] = scissor.extent[0]; + header.scissor[3] = scissor.extent[1]; + header.stencil_reference = regs.Get().stencilref; + header.blend_constant[0] = regs.Get(XE_GPU_REG_RB_BLEND_RED); + header.blend_constant[1] = regs.Get(XE_GPU_REG_RB_BLEND_GREEN); + header.blend_constant[2] = regs.Get(XE_GPU_REG_RB_BLEND_BLUE); + header.blend_constant[3] = regs.Get(XE_GPU_REG_RB_BLEND_ALPHA); + header.system_constant_words = system_words; + header.float_vertex_words = uint32_t(float_vertex.size()); + header.float_pixel_words = uint32_t(float_pixel.size()); + header.bool_loop_words = kBoolLoopWords; + header.fetch_words = kFetchWords; + header.index_format = indices.values.empty() ? 0u : (indices.use_32bit ? 2u : 1u); + header.vertex_count = indices.values.empty() ? indices.vertex_count : uint32_t(indices.values.size()); + header.vertex_texture_mask = vertex_shader->GetUsedTextureMaskAfterTranslation(); + header.pixel_texture_mask = pixel_shader ? pixel_shader->GetUsedTextureMaskAfterTranslation() : 0u; + std::memcpy(w, &header, sizeof(header)); + w += sizeof(header) / 4; + std::memcpy(w, &system, sizeof(system)); + w += system_words; + std::memcpy(w, float_vertex.data(), float_vertex.size() * 4); + w += float_vertex.size(); + std::memcpy(w, float_pixel.data(), float_pixel.size() * 4); + w += float_pixel.size(); + std::memcpy(w, ®s[XE_GPU_REG_SHADER_CONSTANT_BOOL_000_031], kBoolLoopWords * 4); + w += kBoolLoopWords; + std::memcpy(w, ®s[XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0], kFetchWords * 4); + w += kFetchWords; + if (index_words) { + if (indices.use_32bit) { + std::memcpy(w, indices.values.data(), indices.values.size() * 4); + } else { + auto* h = reinterpret_cast(w); + for (size_t i = 0; i < indices.values.size(); ++i) h[i] = uint16_t(indices.values[i]); + if (indices.values.size() & 1) h[indices.values.size()] = 0; + } + } + ++g_draws; + return true; +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// 0 off, 1 record draws for the WebGPU backend. +__attribute__((used, export_name("r360_gpu_set_mode"))) +uint32_t r360_gpu_set_mode(uint32_t mode) { + rx::g_mode = mode; + rx::g_targets_bound = false; + return mode; +} +// 0 draws recorded, 1..5 skips by reason (see DrawSkip), 6 last skip reason. +__attribute__((used, export_name("r360_gpu_draw_stat"))) +uint32_t r360_gpu_draw_stat(uint32_t index) { + if (index == 0) return rx::g_draws; + if (index < rx::kSkipCount) return rx::g_skips[index]; + return rx::g_last_skip; +} +} // extern "C" diff --git a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp index 385b8d3e..a5d1c8dc 100644 --- a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp +++ b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp @@ -16,6 +16,8 @@ extern "C" __attribute__((weak)) uint32_t r360_debug_watch_address() { return 0; // standalone Xenos foundation keeps its bounded bring-up raster. namespace render360::xenia_web { __attribute__((weak)) bool RenderXenosDraw(const XenosSoftDraw&) { return false; } +// The WebGPU backend (webgpu_draws.cpp) records the swap's front buffer. +__attribute__((weak)) void WebGpuSwap(const uint32_t*) {} } namespace render360::xenia_web { @@ -452,6 +454,7 @@ bool ExecuteBuffer(const uint32_t* words, uint32_t word_count, uint32_t depth) { case kPm4DrawIndx: case kPm4DrawIndx2: handled = ExecuteDraw(opcode, p, count); break; case kPm4XeSwap: for (uint32_t w = 0; w < 6u; ++w) g_swap_fetch[w] = g_regs[0x4800u + w]; + WebGpuSwap(g_swap_fetch.data()); handled = ExecuteSwap(p, count); break; case kPm4RegRmw: { if (count != 3u) { handled = false; g_status = kStatusInvalid; break; } diff --git a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp index 3b5a70ed..21f2b58e 100644 --- a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp +++ b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp @@ -7,6 +7,7 @@ // assembly, triangle rasterization, the output merger and resolve copies. #include "xenos_soft_renderer.h" +#include "webgpu_backend.h" #include #include @@ -1226,6 +1227,9 @@ bool RenderXenosDraw(const XenosSoftDraw& draw) { return ok; } bool RenderXenosDrawUntimed(const XenosSoftDraw& draw) { + // The WebGPU backend records the draw for the browser; the software + // renderer still runs (for comparison) unless rasterization is off. + if (WebGpuBackendEnabled()) WebGpuIssueDraw(draw); // Headless fast-forward (r360_xenos_soft_set_rasterize(0)): no EDRAM // work at all; the command processor still executes every packet. if (!g_rasterize) return true; diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 9c9aeb0b..c0bee31e 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -58,6 +58,7 @@ function parseArgs(argv){ else if(a==='--render-from-minstr')args.renderFrom=Number(argv[++i])>>>0; else if(a==='--frame')args.frame=argv[++i]; // --frame-at M1,M2,...:PREFIX saves PREFIX-M.png when the run passes M million instructions. + else if(a==='--gpu-capture'){const [from,swaps,...file]=String(argv[++i]).split(':');args.gpuCapture={from:Number(from),swaps:Number(swaps),file:file.join(':')};} else if(a==='--frame-at'){const v=String(argv[++i]),c=v.lastIndexOf(':');args.frameAt={at:v.slice(0,c).split(',').map(Number).sort((x,y)=>x-y),prefix:v.slice(c+1)};} // --press FROM:TO:BUTTONS holds gamepad 0 buttons (XINPUT bits, e.g. 0x10 = START, 0x1000 = A) between FROM and TO million instructions. // --dialog-button N answers every XamShowMessageBoxUI with button N (the player's choice); without it the focused button is taken (Xenia headless). @@ -96,6 +97,33 @@ function saveFramePng(file){ return {file,width,height,hash:frame.hash,format:frame.format,tiled:frame.tiled,nonBlackPixels:nonBlack}; } let zlibModule=null; +// --gpu-capture M:SWAPS:FILE records the WebGPU backend command stream +// (webgpu_backend.h) from M million instructions for SWAPS swaps to FILE +// (game data: keep it out of the repository). +const gpuCapture={chunks:[],started:false,done:false,startSwaps:0}; +function sliceGpuCapture(x,m){ + const c=runArgs.gpuCapture; + if(!c||gpuCapture.done||!x.r360_gpu_set_mode)return; + if(!gpuCapture.started){ + if(m>>0;return; + } + const words=x.r360_gpu_stream_words()>>>0; + if(words)gpuCapture.chunks.push(Buffer.from(new Uint8Array(x.memory.buffer,x.r360_gpu_stream_data()>>>0,words*4))); + x.r360_gpu_stream_reset(); + // Count swap ops recorded so far. + let swaps=0;for(const b of gpuCapture.chunks){const w=new Uint32Array(b.buffer,b.byteOffset,b.byteLength/4);for(let i=0;i>>8))if((w[i]&0xFF)===6)swaps++;} + if(swaps>=c.swaps){ + x.r360_gpu_set_mode(0);gpuCapture.done=true; + fs.writeFileSync(c.file,Buffer.concat(gpuCapture.chunks)); + const info={swaps,minstr:m,draws:x.r360_gpu_draw_stat(0)>>>0,skips:[1,2,3,4,5].map(i=>x.r360_gpu_draw_stat(i)>>>0), + uploadedKiB:x.r360_gpu_shared_memory_uploaded_kb()>>>0}; + process.stderr.write(`gpu capture ${c.file}: ${JSON.stringify(info)}\n`); + if(frontbufferModule)info.frame=saveFramePng(c.file+'.png'); + fs.writeFileSync(c.file+'.json',JSON.stringify(info)); + } +} function slicePressAndFrames(x){ if(runArgs.dialogButton!==undefined&&x.r360_xam_dialog_pending?.()){ const str=w=>Buffer.from(new Uint8Array(x.memory.buffer,x.r360_xam_dialog_string_ptr(w)>>>0,x.r360_xam_dialog_string_len(w)>>>0)).toString('utf8'); @@ -103,6 +131,7 @@ function slicePressAndFrames(x){ process.stderr.write(`dialog "${str(0)}" -> ${choice} (${str(2+choice)})\n`);x.r360_xam_dialog_answer(choice); } const m=x.r360_hir_total_instructions_millions?.()>>>0; + sliceGpuCapture(x,m); if(runArgs.press||runArgs.stick){ let buttons=0,lx=0,ly=0; for(const p of runArgs.press||[])if(m>=p.from&&mNumber(v)>>>0);bootstrap.exports.r360_jit_set_exclude_seq?.(b,e);} if(process.env.R360_JIT_EXCLUDE){const [b,e]=process.env.R360_JIT_EXCLUDE.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude?.(b,e);} if(args.traceFrom!==undefined){globalThis.__r360TraceOn=1;bootstrap.exports.r360_trace_verbose_from?.(args.traceFrom);} if(process.env.R360_OSR!==undefined)bootstrap.exports.r360_jit_set_osr?.(Number(process.env.R360_OSR)); @@ -271,7 +301,7 @@ async function main(){ let error=null,result=null; try{ result=await runWithGuestVfsRetries( - ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), + ()=>handoffDefaultXex({core,bootstrap,defaultXex:title.defaultXex,encryptedSecurityKey,scanEntryFunction:true,prepareMainThreadContext:true,guestSliceMs:args.sliceMs||((args.renderFrom!==undefined||args.progress||args.frameAt||args.gpuCapture||args.press||args.stick||args.dialogButton!==undefined)?200:0),onGuestSlice:(args.sliceMs||args.renderFrom!==undefined||args.progress||args.dumpShaders||args.xenosTraceFrom!==undefined||args.frameAt||args.gpuCapture||args.press||args.stick||args.dialogButton!==undefined)?(s=>{const x=bootstrap.exports;slicePressAndFrames(x);if(args.dumpShaders)dumpCurrentShaders(x,args.dumpShaders);if(args.xenosTraceFrom!==undefined&&!globalThis.__r360XenosTrace&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.xenosTraceFrom){globalThis.__r360XenosTrace=1;x.r360_xenos_trace_ibs?.(1);}if(args.progress){const now=Date.now();if(!globalThis.__r360LastProgress||now-globalThis.__r360LastProgress>5000){globalThis.__r360LastProgress=now;const g=n=>typeof x[n]==='function'?(x[n]()>>>0):0;globalThis.__r360Threads=Array.from({length:g('r360_fiber_count')},(_,k)=>{const t=x.r360_fiber_thread(k)>>>0,w=f=>(x.r360_kernel_thread_wait?.(t,f)??0)>>>0,id=w(0);return {fiber:k,thread:hex(t),state:['new','running','ready','blocked','done'][x.r360_fiber_state(k)>>>0]??'?',resumes:x.r360_fiber_resumes?.(k)>>>0,left:['-','blocked','yield','preempt','host'][x.r360_fiber_leave?.(k,0)>>>0],leaves:[3,4,5,6].map(f=>x.r360_fiber_leave?.(k,f)>>>0).join('/'),leftAfter:(c=>c?kernelExportName(c>>>16,c&0xFFFF):'-')(x.r360_fiber_leave?.(k,1)>>>0),minstr:x.r360_fiber_instructions_millions?.(k)>>>0,wait:id?kernelExportName(id>>>16,id&0xFFFF):null,object:id?hex(w(1)):null,handle:id?hex(w(2)):null,objectType:id?w(3):null,reason:id?w(4):null,callerLr:id?hex(w(5)):null,retries:id?w(6):null,...(()=>{const q=f=>(x.r360_kernel_thread_poll?.(t,f)??0)>>>0,pid=q(0);return pid?{poll:kernelExportName(pid>>>16,pid&0xFFFF),pollObject:hex(q(1)),pollHandle:hex(q(2)),pollType:q(3),pollTimeout:hex(q(4)),pollLr:hex(q(5)),polls:q(6)}:{};})()};});process.stdout.write(`progress ${g('r360_hir_total_instructions_millions')}M instr · ${g('r360_kernel_import_calls')} kernel calls · ${g('r360_title_gpu_vd_swap_calls')} frames · ${g('r360_xenos_soft_draws')} drawn · ${g('r360_xenos_soft_pixels')} px · ${g('r360_fiber_count')} fibers · ${g('r360_fiber_switches')} switches · ${g('r360_fiber_preemptions')} preemptions · ${g('r360_kernel_audio_callbacks')} audio callbacks · jit ${globalThis.__r360Jit?(()=>{const t=globalThis.__r360Jit.telemetry();return `${t.functions}fn/${t.rejected}rej/${Math.round(t.calls/1000)}kcalls`;})():'off'} · resolve ${g('r360_xenos_soft_resolves')}/${g('r360_xenos_soft_resolve_kpixels')}kpx clear ${g('r360_xenos_soft_clear_ksamples')}ks info 0x${g('r360_xenos_soft_last_resolve_info').toString(16)} · cp ${g('r360_xenos_status').toString(16)} stalled ${g('r360_title_gpu_stalled')} ready ${g('r360_xenos_stall_ready')} pumps ${g('r360_title_gpu_pumps')}/${g('r360_title_gpu_status')} waits ${g('r360_xenos_waits')} stall ${[0,1,2,3,4].map(i=>hex(x.r360_xenos_stall_wait?.(i)??0)).join(',')} wptr ${g('r360_title_gpu_write_pointer')} lastop 0x${g('r360_xenos_last_opcode').toString(16)} · pcs ${Array.from({length:g('r360_fiber_count')},(_,k)=>hex(x.r360_fiber_leave?.(k,7))).join(',')}\n`);}}if(args.renderFrom!==undefined&&(x.r360_hir_total_instructions_millions?.()>>>0)>=args.renderFrom)x.r360_xenos_soft_set_rasterize?.(1);if(args.sliceMs&&(s.slices<5||s.slices%50===0))process.stderr.write(`slice ${s.slices}: ${x.r360_title_gpu_vd_swap_calls?.()>>>0} frames\n`);}):null}), {bootstrap,fetchPending:async()=>false}, ); }catch(caught){if(process.env.R360_TRAP_STACK)console.error(caught?.stack);error=wrapCoreTrap(caught,bootstrap,{context:"run-title"});} From d9a01635973baf809f953d223f5649c4bd3c5d46 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:02:49 +0000 Subject: [PATCH 45/65] WebGPU backend: replay shaders, pipelines, render targets and draws render360-webgpu-backend.mjs now replays the whole command stream: Xenia SPIR-V translated to WGSL by Naga, bind group layouts from the WGSL declarations (Xenia's descriptor sets as groups 0-3), pipeline state from the WebGpuPipelineDescription, render targets keyed by EDRAM base, constants in a dynamic-offset uniform ring and indices in an index ring. Draws use the D3D12 viewport convention (WebGPU clip space has Y up) and keep back-face stencil state. test-webgpu-replay-capture-browser.mjs replays a local capture in headless Chromium (served from a data root outside the repository; it skips without one). A Banjo-Tooie menu capture replays all 1390 draws with no validation errors; textures are placeholders until the texture cache port lands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-webgpu-backend.mjs | 424 ++++++++++++++++++++++- src/xenia_web_bootstrap/webgpu_backend.h | 2 +- src/xenia_web_bootstrap/webgpu_draws.cpp | 7 +- test-webgpu-replay-capture-browser.mjs | 19 + tests/browser/webgpu-replay-capture.mjs | 51 +++ tools/browser-test.mjs | 14 +- 6 files changed, 498 insertions(+), 19 deletions(-) create mode 100644 test-webgpu-replay-capture-browser.mjs create mode 100644 tests/browser/webgpu-replay-capture.mjs diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs index cb601023..c20f1218 100644 --- a/render360-webgpu-backend.mjs +++ b/render360-webgpu-backend.mjs @@ -4,8 +4,15 @@ // docs/gpu/WEBGPU_BACKEND.md describes the design. export const GPU_STREAM_UPLOAD=1; +export const GPU_STREAM_SHADER=2; +export const GPU_STREAM_PIPELINE=3; +export const GPU_STREAM_RENDER_TARGETS=4; +export const GPU_STREAM_DRAW=5; +export const GPU_STREAM_SWAP=6; -const BUFFER_USAGE={MAP_READ:0x1,COPY_SRC:0x4,COPY_DST:0x8,STORAGE:0x80}; +const BUFFER_USAGE={MAP_READ:0x1,COPY_SRC:0x4,COPY_DST:0x8,INDEX:0x10,UNIFORM:0x40,STORAGE:0x80}; +const TEXTURE_USAGE={COPY_SRC:0x1,COPY_DST:0x2,TEXTURE_BINDING:0x4,RENDER_ATTACHMENT:0x10}; +const SHADER_STAGE={VERTEX:0x1,FRAGMENT:0x2}; const SHARED_MEMORY_BYTES=512*1024*1024; // Xenia SharedMemory::kBufferSize const STAGING_BYTES=16*1024*1024; @@ -33,7 +40,26 @@ export class XenosWebGpuBackend{ usage:BUFFER_USAGE.COPY_SRC|BUFFER_USAGE.COPY_DST}); this.stagingOffset=0; this.encoder=null; - this.stats={uploads:0,uploadedBytes:0,droppedUploads:0,submits:0}; + this.stats={uploads:0,uploadedBytes:0,droppedUploads:0,submits:0,shaders:0,pipelines:0, + pipelineFailures:0,draws:0,skippedDraws:0,renderPasses:0,swaps:0,targetsCreated:0}; + this.convert=null; + this.shaders=new Map(); // stream id -> {stage, module, bindings, outputs} + this.pipelines=new Map(); // stream id -> {pipeline, layouts, description} or {error} + this.layouts=new Map(); // layout key -> GPUBindGroupLayout + this.bindGroups=new Map(); // layout key -> GPUBindGroup (shared memory, placeholders) + this.targets=new Map(); // render target key -> {texture, view, format, width, height} + this.boundTargets=null; // WebGpuRenderTargetsKey of op 4 + this.pass=null; + this.lastSwap=null; + this.uniforms=new XenosUniformRing(device); + this.indices=new XenosRing(device,'Render360 indices',BUFFER_USAGE.INDEX,8*1024*1024); + } + + // Loads the SPIR-V to WGSL converter (Naga); needed before shaders replay. + async init(){ + const {loadSpirvToWgslConverter}=await import('./render360-spirv-wgsl-runtime.mjs'); + this.convert=(await loadSpirvToWgslConverter()).convert; + return this; } encoderForCommands(){ @@ -42,6 +68,8 @@ export class XenosWebGpuBackend{ } submit(){ + this.endPass(); + this.uniforms.flush();this.indices.flush(); if(this.encoder){this.device.queue.submit([this.encoder.finish()]);this.encoder=null;this.stats.submits++;} this.stagingOffset=0; } @@ -51,25 +79,282 @@ export class XenosWebGpuBackend{ const e=this.exports,count=e.r360_gpu_stream_words()>>>0; if(!count)return; const base=e.r360_gpu_stream_data()>>>0; - const words=new Uint32Array(e.memory.buffer,base,count); - for(let i=0;i>>8; - if(op===GPU_STREAM_UPLOAD)this.upload(words[i+1],words[i+2],base+(i+3)*4); + this.replayWords(new Uint32Array(e.memory.buffer,base,count)); + e.r360_gpu_stream_reset(); + } + + // Replays stream words (from the core's memory, or a capture). + replayWords(words){ + const bytes=new Uint8Array(words.buffer,words.byteOffset,words.byteLength); + for(let i=0;i>>8,p=words.subarray(i+1,i+1+n); + if(op===GPU_STREAM_UPLOAD)this.upload(p[0],p[1],bytes.subarray((i+3)*4,(i+3)*4+p[1])); + else if(op===GPU_STREAM_SHADER)this.defineShader(p); + else if(op===GPU_STREAM_PIPELINE)this.definePipeline(p); + else if(op===GPU_STREAM_RENDER_TARGETS){this.endPass();this.boundTargets=parseRenderTargets(p);} + else if(op===GPU_STREAM_DRAW)this.draw(p); + else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.submit();} else throw new Error(`Render360 GPU stream: unknown op ${op} at word ${i}`); i+=1+n; } - e.r360_gpu_stream_reset(); } - upload(dest,length,bytePointer){ + // Shader op: translated SPIR-V, converted to WGSL by Naga. + defineShader(p){ + if(!this.convert)throw new Error('Render360 WebGPU backend: init() before replaying shaders'); + const [id,stage,textureCount,samplerCount,spirvWords]=p; + const spirv=new Uint8Array(p.buffer,p.byteOffset+(5+textureCount+samplerCount)*4,spirvWords*4).slice(); + const shader={id,stage,textures:Array.from(p.subarray(5,5+textureCount)), + samplers:Array.from(p.subarray(5+textureCount,5+textureCount+samplerCount))}; + try{ + shader.wgsl=this.convert(spirv); + shader.bindings=parseWgslBindings(shader.wgsl); + shader.module=this.device.createShaderModule({label:`Render360 Xenos ${stage?'pixel':'vertex'} shader ${id}`,code:shader.wgsl}); + }catch(error){shader.error=String(error?.message||error);} + this.shaders.set(id,shader); + this.stats.shaders++; + } + + // Pipeline op: the WebGpuPipelineDescription, as Xenia's + // VulkanPipelineCache::EnsurePipelineCreated turns it into a pipeline. + definePipeline(p){ + const id=p[0],d=parsePipelineDescription(p.subarray(1)); + const entry={description:d}; + try{ + const vs=this.shaders.get(d.vertexShader),ps=d.pixelShader?this.shaders.get(d.pixelShader):null; + if(!vs?.module)throw new Error(`vertex shader ${d.vertexShader}: ${vs?.error||'missing'}`); + if(d.pixelShader&&!ps?.module)throw new Error(`pixel shader ${d.pixelShader}: ${ps?.error||'missing'}`); + // Bind groups (Xenia's descriptor sets): 0 shared memory, 1 constant + // buffers, 2 vertex textures, 3 pixel textures. + entry.layouts=[0,1,2,3].map(g=>this.groupLayout(g,[vs,ps].filter(Boolean))); + const layout=this.device.createPipelineLayout({bindGroupLayouts:entry.layouts.map(l=>l.layout)}); + const targets=[]; + for(let i=0;i<4;i++){ + if(!d.colorFormats[i])continue; + const format=colorFormat(d.colorFormats[i]-1); + while(targets.length>>(i*4))&0xF}; + const blend=blendState(d.blendControl[i]); + if(blend&&blendableFormat(format))target.blend=blend; + targets.push(target); + } + const descriptor={label:`Render360 Xenos pipeline ${id}`,layout, + vertex:{module:vs.module,entryPoint:'main'}, + primitive:{topology:['point-list','line-list','line-strip','triangle-list','triangle-strip'][d.topology], + cullMode:['none','front','back'][d.cullMode],frontFace:d.frontFaceCw?'cw':'ccw'}, + multisample:{count:1}}; + if(ps||targets.length)descriptor.fragment={module:(ps||vs).module,entryPoint:'main',targets}; + if(!ps)delete descriptor.fragment; + if(d.depthFormat){ + const stencil=d.stencil,on=(stencil&1)!==0; + const face=(func,fail,zpass,zfail)=>({compare:COMPARE[func],failOp:STENCIL_OP[fail],depthFailOp:STENCIL_OP[zfail],passOp:STENCIL_OP[zpass]}); + const front=on?face((stencil>>>8)&7,(stencil>>>11)&7,(stencil>>>14)&7,(stencil>>>17)&7):{}; + const back=on?((stencil>>>7)&1?face((stencil>>>20)&7,(stencil>>>23)&7,(stencil>>>26)&7,(stencil>>>29)&7):front):{}; + descriptor.depthStencil={format:this.depthFormat(d.depthFormat-1),depthWriteEnabled:!!d.depthWrite, + depthCompare:COMPARE[d.depthCompare],stencilFront:front,stencilBack:back, + stencilReadMask:on?(d.stencilMasks>>>8)&0xFF:0xFF,stencilWriteMask:on?(d.stencilMasks>>>16)&0xFF:0}; + } + entry.pipeline=this.device.createRenderPipeline(descriptor); + this.stats.pipelines++; + }catch(error){entry.error=String(error?.message||error);this.stats.pipelineFailures++;} + this.pipelines.set(id,entry); + } + + depthFormat(guest){ + // kD24FS8 (20e4 float depth): 32-bit float depth where the device has it. + return guest===1&&this.device.features?.has?.('depth32float-stencil8')?'depth32float-stencil8':'depth24plus-stencil8'; + } + + // A bind group layout (and its constant bind group when it has one) for + // the WGSL declarations of the pipeline's shaders in `group`. + groupLayout(group,shaders){ + const entries=new Map(); + if(group===1){ + // Constant buffers at dynamic offsets in the uniform ring. + for(let b=0;b<5;b++)entries.set(b,{binding:b,visibility:SHADER_STAGE.VERTEX|SHADER_STAGE.FRAGMENT,buffer:{type:'uniform',hasDynamicOffset:true}}); + }else{ + for(const shader of shaders)for(const decl of shader.bindings){ + if(decl.group!==group)continue; + const visibility=shader.stage?SHADER_STAGE.FRAGMENT:SHADER_STAGE.VERTEX; + const prior=entries.get(decl.binding); + if(prior){prior.visibility|=visibility;continue;} + const entry={binding:decl.binding,visibility}; + if(decl.kind==='storage'){ + if(decl.write&&!shader.stage)throw new Error('vertex shader memory export is not supported yet'); + entry.buffer={type:decl.write?'storage':'read-only-storage'}; + }else if(decl.kind==='uniform')entry.buffer={type:'uniform'}; + else if(decl.kind==='sampler')entry.sampler={type:decl.comparison?'comparison':'filtering'}; + else if(decl.kind==='texture')entry.texture={sampleType:decl.sampleType,viewDimension:decl.viewDimension,multisampled:false}; + else throw new Error(`unsupported WGSL binding ${decl.type}`); + entries.set(decl.binding,entry); + } + } + const list=[...entries.values()].sort((a,b)=>a.binding-b.binding); + const key=`${group}:${JSON.stringify(list)}`; + let cached=this.layouts.get(key); + if(!cached){ + const layout=this.device.createBindGroupLayout({label:`Render360 Xenos group ${group}`,entries:list}); + cached={key,layout,group:group===1?null:this.device.createBindGroup({layout,entries:list.map(e=>({binding:e.binding,resource:this.placeholderResource(e)}))})}; + if(group===1)cached.group=this.uniforms.bindGroup(layout); + this.layouts.set(key,cached); + } + return cached; + } + + // The shared memory buffer, or a placeholder texture / sampler until the + // texture cache is ported. + placeholderResource(entry){ + if(entry.buffer)return {buffer:this.sharedMemory}; + if(entry.sampler){ + const key=`sampler:${entry.sampler.type}`; + if(!this.bindGroups.has(key))this.bindGroups.set(key,this.device.createSampler(entry.sampler.type==='comparison'?{compare:'less'}:{magFilter:'linear',minFilter:'linear'})); + return this.bindGroups.get(key); + } + const {sampleType,viewDimension}=entry.texture,key=`texture:${sampleType}:${viewDimension}`; + if(!this.bindGroups.has(key)){ + const format=sampleType==='sint'?'rgba8sint':sampleType==='uint'?'rgba8uint':sampleType==='depth'?'depth32float':'rgba8unorm'; + const layers=viewDimension==='cube'?6:1; + const texture=this.device.createTexture({label:`Render360 placeholder ${viewDimension}`,format, + dimension:viewDimension==='3d'?'3d':'2d',size:{width:1,height:1,depthOrArrayLayers:layers},usage:TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_DST}); + if(format!=='depth32float'){ + const texel=new Uint8Array(4*layers).fill(255); + this.device.queue.writeTexture({texture},texel,{bytesPerRow:4,rowsPerImage:1},{width:1,height:1,depthOrArrayLayers:layers}); + } + this.bindGroups.set(key,texture.createView({dimension:viewDimension})); + } + return this.bindGroups.get(key); + } + + // Host render target for an EDRAM base / format / pitch (Xenia's + // RenderTargetCache key without the resolution scale). + target(base,guestFormat,depth,pitch,height){ + const key=`${depth?'d':'c'}:${base}:${guestFormat}:${pitch}`; + let t=this.targets.get(key); + if(t&&t.height>=height)return t; + const format=depth?this.depthFormat(guestFormat):colorFormat(guestFormat); + const texture=this.device.createTexture({label:`Render360 EDRAM ${key}`,format,size:{width:pitch,height:Math.max(height,t?.height||0,720)}, + usage:TEXTURE_USAGE.RENDER_ATTACHMENT|TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_SRC|TEXTURE_USAGE.COPY_DST}); + // A taller target replaces the old one; its contents are kept by copying. + const fresh={key,base,guestFormat,depth,texture,view:texture.createView(),format,width:pitch,height:texture.height,initialized:false}; + if(t){ + this.endPass(); + this.encoderForCommands().copyTextureToTexture({texture:t.texture},{texture},{width:t.width,height:t.height}); + fresh.initialized=t.initialized;t.texture.destroy(); + } + this.targets.set(key,fresh); + this.stats.targetsCreated++; + return fresh; + } + + // Begins a render pass on the bound render targets. + beginPass(){ + if(this.pass)return this.pass; + const k=this.boundTargets; + if(!k||!k.surfacePitch)return null; + const colorAttachments=[]; + const used=[]; + for(let i=0;i<4;i++){ + if(k.colorBase[i]===0xFFFFFFFF)continue; + const t=this.target(k.colorBase[i],k.colorFormat[i],false,k.surfacePitch,k.height); + while(colorAttachments.lengtht.height))}; + this.pass=this.encoderForCommands().beginRenderPass(pass); + this.passState={pipeline:null,groups:[]}; + this.stats.renderPasses++; + return this.pass; + } + + endPass(){ + if(this.pass){this.pass.end();this.pass=null;} + } + + // Draw op: header, system / float / bool-loop / fetch constants, indices. + draw(p){ + const h=parseDrawHeader(p); + const entry=this.pipelines.get(h.pipeline); + if(!entry?.pipeline){this.stats.skippedDraws++;return;} + let o=DRAW_HEADER_WORDS; + const constants=[h.systemWords,h.floatVertexWords,h.floatPixelWords,h.boolLoopWords,h.fetchWords].map(n=>{const c=p.subarray(o,o+n);o+=n;return c;}); + const indexWords=h.indexFormat===2?h.vertexCount:h.indexFormat===1?(h.vertexCount+1)>>>1:0; + const indexData=p.subarray(o,o+indexWords); + // Constants and indices are written before the pass using them is + // submitted (both rings flush on submit). + if(!this.uniforms.fits(constants)||!this.indices.fits(indexData.byteLength))this.submit(); + const pass=this.beginPass(); + if(!pass){this.stats.skippedDraws++;return;} + const offsets=constants.map(c=>this.uniforms.push(c)); + const W=this.passSize.width,H=this.passSize.height; + const vx=Math.max(0,Math.min(h.viewport[0],W)),vy=Math.max(0,Math.min(h.viewport[1],H)); + const vw=Math.min(h.viewport[2],W-vx),vh=Math.min(h.viewport[3],H-vy); + const sx=Math.min(h.scissor[0],W),sy=Math.min(h.scissor[1],H); + const sw=Math.min(h.scissor[2],W-sx),sh=Math.min(h.scissor[3],H-sy); + if(vw<=0||vh<=0||sw<=0||sh<=0){this.stats.skippedDraws++;return;} + const s=this.passState; + if(s.pipeline!==entry.pipeline){pass.setPipeline(entry.pipeline);s.pipeline=entry.pipeline;} + for(let g=0;g<4;g++){ + const group=entry.layouts[g].group; + if(g===1)pass.setBindGroup(1,group,offsets); + else if(s.groups[g]!==group){pass.setBindGroup(g,group);s.groups[g]=group;} + } + let z0=Math.max(0,Math.min(1,h.depthRange[0])),z1=Math.max(0,Math.min(1,h.depthRange[1])); + if(z0>z1)[z0,z1]=[z1,z0]; + pass.setViewport(vx,vy,vw,vh,z0,z1); + pass.setScissorRect(sx,sy,sw,sh); + pass.setStencilReference(h.stencilReference); + pass.setBlendConstant({r:h.blendConstant[0],g:h.blendConstant[1],b:h.blendConstant[2],a:h.blendConstant[3]}); + if(h.indexFormat){ + const bytes=new Uint8Array(indexData.buffer,indexData.byteOffset,h.indexFormat===2?h.vertexCount*4:h.vertexCount*2); + const offset=this.indices.push(bytes); + pass.setIndexBuffer(this.indices.buffer,h.indexFormat===2?'uint32':'uint16',offset,bytes.byteLength); + pass.drawIndexed(h.vertexCount); + }else{ + pass.draw(h.vertexCount); + } + this.stats.draws++; + } + + // RGBA8 pixels of a color render target (tests and the frame preview). + async readTarget(t){ + this.submit(); + if(t.format!=='rgba8unorm')throw new Error(`readTarget: ${t.format} not supported`); + const bytesPerRow=Math.ceil(t.width*4/256)*256; + const read=this.device.createBuffer({size:bytesPerRow*t.height,usage:BUFFER_USAGE.MAP_READ|BUFFER_USAGE.COPY_DST}); + const encoder=this.device.createCommandEncoder(); + encoder.copyTextureToBuffer({texture:t.texture},{buffer:read,bytesPerRow},{width:t.width,height:t.height}); + this.device.queue.submit([encoder.finish()]); + await read.mapAsync(1); + const mapped=new Uint8Array(read.getMappedRange()),out=new Uint8Array(t.width*t.height*4); + for(let y=0;ythis.sharedMemoryBytes){this.stats.droppedUploads++;return;} if(this.stagingOffset+length>STAGING_BYTES)this.submit(); + length=(length+3)&~3; if(length>STAGING_BYTES){ // Larger than the staging buffer: write directly (ordered before the // next submit; nothing recorded after it reads the old contents). - this.device.queue.writeBuffer(this.sharedMemory,dest,this.exports.memory.buffer,bytePointer,length); + this.endPass(); + this.device.queue.writeBuffer(this.sharedMemory,dest,bytes.buffer,bytes.byteOffset,length); }else{ - this.device.queue.writeBuffer(this.staging,this.stagingOffset,this.exports.memory.buffer,bytePointer,length); + // Copies happen outside render passes; draws after this one see the data. + this.endPass(); + this.device.queue.writeBuffer(this.staging,this.stagingOffset,bytes.buffer,bytes.byteOffset,length); this.encoderForCommands().copyBufferToBuffer(this.staging,this.stagingOffset,this.sharedMemory,dest,length); this.stagingOffset+=length; } @@ -90,3 +375,122 @@ export class XenosWebGpuBackend{ return bytes; } } + +const COMPARE=['never','less','equal','less-equal','greater','not-equal','greater-equal','always']; +const STENCIL_OP=['keep','zero','replace','increment-clamp','decrement-clamp','invert','increment-wrap','decrement-wrap']; +const BLEND_FACTOR={0:'zero',1:'one',4:'src',5:'one-minus-src',6:'src-alpha',7:'one-minus-src-alpha',8:'dst',9:'one-minus-dst', + 10:'dst-alpha',11:'one-minus-dst-alpha',12:'constant',13:'one-minus-constant',14:'constant',15:'one-minus-constant',16:'src-alpha-saturated'}; +const BLEND_ALPHA_FACTOR={...BLEND_FACTOR,4:'src-alpha',5:'one-minus-src-alpha',8:'dst-alpha',9:'one-minus-dst-alpha'}; +const BLEND_OP=['add','subtract','min','max','reverse-subtract']; + +// xenos::ColorRenderTargetFormat to the host format Xenia's Vulkan render +// target cache picks (16_16(_16_16) use float here: WebGPU has no +// renderable snorm16; the system constants scale them as Xenia does). +export function colorFormat(guest){ + switch(guest){ + case 0:case 1:return 'rgba8unorm'; + case 2:case 10:return 'rgb10a2unorm'; + case 3:case 12:case 5:case 7:return 'rgba16float'; + case 4:case 6:return 'rg16float'; + case 14:return 'r32float'; + case 15:return 'rg32float'; + default:throw new Error(`unknown color render target format ${guest}`); + } +} +function blendableFormat(format){return format!=='r32float'&&format!=='rg32float';} + +// RB_BLENDCONTROL to a blend state (undefined: replace, blending off). +function blendState(control){ + const cs=control&31,cop=(control>>>5)&7,cd=(control>>>8)&31,as=(control>>>16)&31,aop=(control>>>21)&7,ad=(control>>>24)&31; + if(cs===1&&cd===0&&cop===0&&as===1&&ad===0&&aop===0)return undefined; + const component=(src,op,dst,map)=>{ + const operation=BLEND_OP[op]||'add'; + // WebGPU min / max ignore the factors and require one. + if(operation==='min'||operation==='max')return {operation,srcFactor:'one',dstFactor:'one'}; + return {operation,srcFactor:map[src]||'zero',dstFactor:map[dst]||'zero'}; + }; + return {color:component(cs,cop,cd,BLEND_FACTOR),alpha:component(as,aop,ad,BLEND_ALPHA_FACTOR)}; +} + +function parsePipelineDescription(w){ + return {vertexShader:w[0],pixelShader:w[1],topology:w[2],cullMode:w[3],frontFaceCw:w[4],depthCompare:w[5],depthWrite:w[6], + stencil:w[7],stencilMasks:w[8],colorFormats:Array.from(w.subarray(9,13)),colorWriteMasks:w[13], + blendControl:Array.from(w.subarray(14,18)),depthFormat:w[18],msaaSamples:w[19]}; +} + +function parseRenderTargets(w){ + return {surfacePitch:w[0],msaaSamples:w[1],height:w[2],colorBase:Array.from(w.subarray(3,7)), + colorFormat:Array.from(w.subarray(7,11)),depthBase:w[11],depthFormat:w[12]}; +} + +const DRAW_HEADER_WORDS=25; +function parseDrawHeader(w){ + const f=new Float32Array(w.buffer,w.byteOffset,DRAW_HEADER_WORDS); + return {pipeline:w[0],viewport:Array.from(w.subarray(1,5)),depthRange:[f[5],f[6]],scissor:Array.from(w.subarray(7,11)), + stencilReference:w[11],blendConstant:[f[12],f[13],f[14],f[15]],systemWords:w[16],floatVertexWords:w[17], + floatPixelWords:w[18],boolLoopWords:w[19],fetchWords:w[20],indexFormat:w[21],vertexCount:w[22], + vertexTextureMask:w[23],pixelTextureMask:w[24]}; +} + +// Resource declarations of Naga's WGSL: group, binding, kind and type. +export function parseWgslBindings(wgsl){ + const out=[]; + const re=/@group\((\d+)\)\s*@binding\((\d+)\)\s*var(?:<([^>]*)>)?\s+\w+\s*:\s*([^;]+);/g; + for(let m;(m=re.exec(wgsl));){ + const group=+m[1],binding=+m[2],space=(m[3]||'').replace(/\s/g,''),type=m[4].trim(); + const decl={group,binding,type}; + if(space.startsWith('storage')){decl.kind='storage';decl.write=space.includes('read_write');} + else if(space==='uniform')decl.kind='uniform'; + else if(type==='sampler'||type==='sampler_comparison'){decl.kind='sampler';decl.comparison=type==='sampler_comparison';} + else if(type.startsWith('texture_')){ + decl.kind='texture'; + const t=/^texture_(depth_)?(multisampled_)?(1d|2d_array|2d|3d|cube_array|cube)(?:<(\w+)>)?/.exec(type); + if(!t)throw new Error(`unsupported WGSL texture type ${type}`); + decl.viewDimension=t[3].replace('_','-'); + decl.sampleType=t[1]?'depth':t[4]==='i32'?'sint':t[4]==='u32'?'uint':'float'; + }else decl.kind='unknown'; + out.push(decl); + } + return out; +} + +// A CPU-side ring written to a GPU buffer in one writeBuffer on flush. +class XenosRing{ + constructor(device,label,usage,size,align=4){ + this.device=device;this.size=size;this.align=align; + this.buffer=device.createBuffer({label,size,usage:usage|BUFFER_USAGE.COPY_DST}); + this.cpu=new Uint8Array(size);this.offset=0; + } + fits(bytes){return this.offset+((bytes+this.align-1)&~(this.align-1))<=this.size;} + push(bytes){ + const at=this.offset; + this.cpu.set(bytes,at); + this.offset=at+((bytes.byteLength+this.align-1)&~(this.align-1)); + return at; + } + flush(){ + if(this.offset)this.device.queue.writeBuffer(this.buffer,0,this.cpu,0,this.offset); + this.offset=0; + } +} + +// The five constant buffers of a draw at dynamic offsets (Xenia's uniform +// buffer pool). Bindings are 4 KiB windows: the largest constant buffer +// (256 float4 registers) fits, and the ring keeps 4 KiB of slack at its end. +const CONSTANT_WINDOW=4096; +class XenosUniformRing extends XenosRing{ + constructor(device){ + const align=device.limits.minUniformBufferOffsetAlignment||256; + super(device,'Render360 constants',BUFFER_USAGE.UNIFORM,8*1024*1024+CONSTANT_WINDOW,align); + this.limit=8*1024*1024; + } + fits(constants){ + let total=0;for(const c of constants)total+=(c.byteLength+this.align-1)&~(this.align-1); + return this.offset+total<=this.limit; + } + push(words){return super.push(new Uint8Array(words.buffer,words.byteOffset,words.byteLength));} + bindGroup(layout){ + return this.device.createBindGroup({label:'Render360 constants',layout, + entries:[0,1,2,3,4].map(b=>({binding:b,resource:{buffer:this.buffer,offset:0,size:CONSTANT_WINDOW}}))}); + } +} diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h index ef1d5dd4..06c12dde 100644 --- a/src/xenia_web_bootstrap/webgpu_backend.h +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -42,7 +42,7 @@ struct WebGpuPipelineDescription { uint32_t front_face_cw; uint32_t depth_compare; // xenos::CompareFunction, kAlways when the test is off uint32_t depth_write; - uint32_t stencil; // RB_DEPTHCONTROL bits 0x7FFF00 when stencil is on, else 0 + uint32_t stencil; // RB_DEPTHCONTROL bits 0 and 7..31 when stencil is on, else 0 uint32_t stencil_masks; // RB_STENCILREFMASK (front) read/write masks uint32_t color_formats[4]; // xenos::ColorRenderTargetFormat + 1, 0: unused uint32_t color_write_masks; // 4 bits per render target diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp index 1ca94036..04d9040c 100644 --- a/src/xenia_web_bootstrap/webgpu_draws.cpp +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -474,7 +474,7 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { depth_control.z_enable ? uint32_t(depth_control.zfunc) : uint32_t(xenos::CompareFunction::kAlways); description.depth_write = depth_control.z_enable && depth_control.z_write_enable; if (depth_control.stencil_enable) { - description.stencil = depth_control.value & 0x7FFF00u; + description.stencil = depth_control.value & 0xFFFFFF81u; description.stencil_masks = regs[XE_GPU_REG_RB_STENCILREFMASK] & 0xFFFF00u; } for (uint32_t i = 0; i < 4; ++i) { @@ -491,12 +491,13 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { description.msaa_samples = uint32_t(regs.Get().msaa_samples); // Viewport and scissor in render target pixels (origin top-left, no - // resolution scale), as VulkanCommandProcessor computes them. + // resolution scale). WebGPU clip space has Y up like Direct3D 12, so the + // NDC transform is D3D12CommandProcessor's (origin_bottom_left). auto surface = regs.Get(); const uint32_t pitch = std::max(surface.surface_pitch, 1u); constexpr uint32_t kMaxHeight = 2560; draw_util::ViewportInfo viewport_info; - draw_util::GetHostViewportInfo(regs, 1, 1, false, pitch, kMaxHeight, false, depth_control, + draw_util::GetHostViewportInfo(regs, 1, 1, true, pitch, kMaxHeight, false, depth_control, false, false, pixel_shader && pixel_shader->writes_depth(), viewport_info); draw_util::Scissor scissor; diff --git a/test-webgpu-replay-capture-browser.mjs b/test-webgpu-replay-capture-browser.mjs new file mode 100644 index 00000000..a3cb9f80 --- /dev/null +++ b/test-webgpu-replay-capture-browser.mjs @@ -0,0 +1,19 @@ +// Replays a local GPU capture (run-title.mjs --gpu-capture M:SWAPS:FILE) in +// headless Chromium WebGPU (tests/browser/webgpu-replay-capture.mjs). +// Captures hold game data: they stay outside the repository and the test +// skips without one. +// node test-webgpu-replay-capture-browser.mjs /path/to/capture.bin [out.png] +import fs from 'node:fs'; +import path from 'node:path'; +import {runBrowserTest} from './tools/browser-test.mjs'; + +const capture=process.argv[2]||process.env.R360_GPU_CAPTURE; +if(!capture||!fs.existsSync(capture)){console.log('WEBGPU_REPLAY_CAPTURE_SKIP (no local capture)');process.exit(0);} +const dir=path.dirname(path.resolve(capture)),name=path.basename(capture); +const reference=fs.existsSync(`${capture}.png`)?`/__data__/${name}.png`:null; +const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference],dataRoot:dir, + onConsole:t=>process.env.VERBOSE&&console.log(t)}); +if(result.png){if(process.argv[3])fs.writeFileSync(process.argv[3],Buffer.from(result.png,'base64'));delete result.png;} +console.log(JSON.stringify(result,null,1)); +if(!result.ok)process.exit(1); +console.log('WEBGPU_REPLAY_CAPTURE_PASS'); diff --git a/tests/browser/webgpu-replay-capture.mjs b/tests/browser/webgpu-replay-capture.mjs new file mode 100644 index 00000000..6daf58be --- /dev/null +++ b/tests/browser/webgpu-replay-capture.mjs @@ -0,0 +1,51 @@ +// Browser side of test-webgpu-replay-capture-browser.mjs: replays a GPU +// command stream captured by run-title.mjs --gpu-capture (served from the +// local data root, never the repository) and compares the color render +// target at EDRAM base 0 with the software renderer's frame. +import {XenosWebGpuBackend} from '../../render360-webgpu-backend.mjs'; + +async function decodePng(url){ + const bitmap=await createImageBitmap(await (await fetch(url)).blob()); + const canvas=new OffscreenCanvas(bitmap.width,bitmap.height),ctx=canvas.getContext('2d'); + ctx.drawImage(bitmap,0,0); + return {width:bitmap.width,height:bitmap.height,pixels:ctx.getImageData(0,0,bitmap.width,bitmap.height).data}; +} + +export default async function run(captureUrl,referenceUrl){ + const adapter=await navigator.gpu?.requestAdapter(); + if(!adapter)return {ok:false,error:'no WebGPU adapter'}; + const device=await adapter.requestDevice({requiredLimits:{ + maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); + const errors=[]; + device.onuncapturederror=e=>{if(errors.length<20)errors.push(e.error.message.slice(0,400));}; + const backend=await new XenosWebGpuBackend(device,null).init(); + const words=new Uint32Array(await (await fetch(captureUrl)).arrayBuffer()); + const started=performance.now(); + backend.replayWords(words); + backend.submit(); + await device.queue.onSubmittedWorkDone(); + const replayMs=performance.now()-started; + const shaderErrors=[...backend.shaders.values()].filter(s=>s.error).map(s=>`${s.id}: ${s.error.slice(0,300)}`).slice(0,5); + const pipelineErrors=[...backend.pipelines.entries()].filter(([,p])=>p.error).map(([id,p])=>`${id}: ${p.error.slice(0,300)}`).slice(0,5); + const result={ok:true,stats:backend.stats,replayMs:Math.round(replayMs),shaderErrors,pipelineErrors,errors, + targets:[...backend.targets.values()].map(t=>`${t.key} ${t.format} ${t.width}x${t.height}`)}; + const front=[...backend.targets.values()].find(t=>!t.depth&&t.base===0&&t.format==='rgba8unorm'); + if(front&&referenceUrl){ + const got=await backend.readTarget(front),want=await decodePng(referenceUrl); + const w=Math.min(got.width,want.width),h=Math.min(got.height,want.height); + let diff=0,close=0,lit=0; + for(let y=0;y(a.push(b),a),[]))); + } + if(errors.length||!backend.stats.draws)result.ok=false; + return result; +} diff --git a/tools/browser-test.mjs b/tools/browser-test.mjs index cca055d1..75646f05 100644 --- a/tools/browser-test.mjs +++ b/tools/browser-test.mjs @@ -21,7 +21,7 @@ function loadPlaywright(){ return createRequire(path.join(globalRoot,'noop.js'))(path.join(globalRoot,'playwright')); } -function serve(){ +function serve(dataRoot){ const server=http.createServer((req,res)=>{ const url=new URL(req.url,'http://localhost'); if(url.pathname==='/__test__.html'){ @@ -29,17 +29,21 @@ function serve(){ res.end(''); return; } - const file=path.join(ROOT,decodeURIComponent(url.pathname)); - if(!file.startsWith(ROOT)||!fs.existsSync(file)||fs.statSync(file).isDirectory()){res.writeHead(404);res.end();return;} + // /__data__/ serves dataRoot: local inputs (game captures) kept outside + // the repository. + const data=dataRoot&&url.pathname.startsWith('/__data__/'); + const root=data?path.resolve(dataRoot):ROOT; + const file=path.join(root,decodeURIComponent(data?url.pathname.slice(9):url.pathname)); + if(!file.startsWith(root)||!fs.existsSync(file)||fs.statSync(file).isDirectory()){res.writeHead(404);res.end();return;} res.writeHead(200,{'content-type':TYPES[path.extname(file)]||'application/octet-stream'}); fs.createReadStream(file).pipe(res); }); return new Promise(resolve=>server.listen(0,'127.0.0.1',()=>resolve(server))); } -export async function runBrowserTest(modulePath,{args=[],timeoutMs=300000,onConsole=null}={}){ +export async function runBrowserTest(modulePath,{args=[],timeoutMs=300000,onConsole=null,dataRoot=null}={}){ const {chromium}=loadPlaywright(); - const server=await serve(); + const server=await serve(dataRoot); const port=server.address().port; const browser=await chromium.launch({args:['--enable-unsafe-webgpu','--enable-features=Vulkan', '--use-vulkan=swiftshader','--use-webgpu-adapter=swiftshader','--disable-vulkan-surface']}); From 24dc36b91e003ad29c49501c8cdae43f4de427b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:52:51 +0000 Subject: [PATCH 46/65] WebGPU backend: texture cache, EDRAM resolves and clears webgpu_textures.cpp ports Xenia's TextureCache bindings and keys with VulkanTextureCache's host formats and LoadTextureDataFromResidentMemoryImpl: Xenia's own texture_load_* compute shaders (sent once in the stream, converted by Naga) untile and convert from the shared memory buffer, then the scratch buffer is copied into WebGPU textures. Fallbacks where WebGPU lacks Vulkan's formats: S3TC decompression, 16-bit packed texels expanded to RGBA8, 16-bit normalized to float16, separate signed textures. A Banjo-Tooie menu capture loads all 144 textures and renders them. Resolves follow VulkanRenderTargetCache's host render target path: the owners of the source tiles are dumped into an EDRAM buffer in Xenia's layout (WGSL port of XeEdramOffsetBytes), Xenia's resolve copy shaders write shared memory, and resolve clears clear the host render targets. Swaps carry the front buffer texture. With the software rasterizer off, draws still reach the WebGPU recorder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- build-xenia-ppc-bootstrap.sh | 3 +- docs/gpu/WEBGPU_BACKEND.md | 30 +- render360-webgpu-backend.mjs | 543 ++++++++++- src/xenia_web_bootstrap/webgpu_backend.h | 32 +- src/xenia_web_bootstrap/webgpu_draws.cpp | 166 +++- src/xenia_web_bootstrap/webgpu_textures.cpp | 883 ++++++++++++++++++ src/xenia_web_bootstrap/webgpu_textures.h | 73 ++ .../xenos_soft_renderer.cpp | 6 +- test-webgpu-replay-capture-browser.mjs | 2 +- tests/browser/webgpu-replay-capture.mjs | 20 +- 10 files changed, 1727 insertions(+), 31 deletions(-) create mode 100644 src/xenia_web_bootstrap/webgpu_textures.cpp create mode 100644 src/xenia_web_bootstrap/webgpu_textures.h diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 94c06a13..2c7d5ff3 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -200,6 +200,7 @@ queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_j queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" queue_cpp "render360/webgpu_backend.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_backend.cpp" queue_cpp "render360/webgpu_draws.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_draws.cpp" +queue_cpp "render360/webgpu_textures.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_textures.cpp" queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" queue_cpp "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" @@ -234,7 +235,7 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 32 )) +expected=$(( ${#SOURCES[@]} + 2 + 33 )) actual=$(( passed + failed )) echo diff --git a/docs/gpu/WEBGPU_BACKEND.md b/docs/gpu/WEBGPU_BACKEND.md index ad639fe3..0d41e297 100644 --- a/docs/gpu/WEBGPU_BACKEND.md +++ b/docs/gpu/WEBGPU_BACKEND.md @@ -44,7 +44,35 @@ GPU frames are compared against. 5. Texture cache with tiled/endian-swapped formats. 6. Play path switched to WebGPU; software renderer only for verification. +## Status + +- Steps 1-3 done. `render360-webgpu-backend.mjs` replays the whole stream: + Naga turns the translated SPIR-V into WGSL, bind group layouts come from + the WGSL declarations, constants go to a dynamic-offset uniform ring, and + indices go to an index ring. Draws use the D3D12 viewport convention: + WebGPU clip space has Y up. +- Step 5 in progress (`webgpu_textures.cpp`), a port of Xenia's + `TextureCache` keys and bindings, and of `VulkanTextureCache`'s host + formats and `LoadTextureDataFromResidentMemoryImpl`. + - Xenia's own `texture_load_*` compute shaders untile and convert from + the shared memory buffer into a scratch buffer, which is then copied + into the texture. + - The SPIR-V travels in the stream on first use: `NonReadable` is + stripped, and the push constants become a uniform at group 2. + - Unsigned and signed versions are separate textures whenever their + formats differ, because WebGPU views cannot reinterpret unorm as snorm. + - S3TC/DXN/DXT5A are decompressed by Xenia's fallback shaders (BC is + optional in WebGPU and absent on iOS). + - 16-bit packed formats (565, 655, 1555, 4444) are loaded as 16bpb and + expanded to RGBA8. + - Xenia's 16-bit normalized outputs are converted to float16 in place. + - Host rows are padded to the 256-byte `bytesPerRow` WebGPU requires. + - Texture pages are re-checked against the sparse memory GPU watch + generations. +- Test: `test-webgpu-replay-capture-browser.mjs` replays a local capture + (`run-title.mjs --gpu-capture`) and compares it with the software frame. + Rules kept: no game data, decrypted XEX or game-derived shaders in the repository; translated shaders live only in the browser at run time. Xenia's own compute shaders (resolve, texture load) are Xenia's code and are -converted from Xenia's SPIR-V at build time. +converted from Xenia's SPIR-V by Naga in the browser. diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs index c20f1218..ca2287eb 100644 --- a/render360-webgpu-backend.mjs +++ b/render360-webgpu-backend.mjs @@ -9,6 +9,21 @@ export const GPU_STREAM_PIPELINE=3; export const GPU_STREAM_RENDER_TARGETS=4; export const GPU_STREAM_DRAW=5; export const GPU_STREAM_SWAP=6; +export const GPU_STREAM_LOAD_SHADER=7; +export const GPU_STREAM_TEXTURE=8; +export const GPU_STREAM_TEXTURE_LOAD=9; +export const GPU_STREAM_EDRAM_DUMP=10; +export const GPU_STREAM_RESOLVE=11; +export const GPU_STREAM_CLEAR=12; + +const EDRAM_TILES=2048,EDRAM_TILE_DWORDS=80*16; +// xenos::IsColorRenderTargetFormat64bpp. +const COLOR_64BPP=new Set([5,7,15]); + +// WebGpuTextureFormat (src/xenia_web_bootstrap/webgpu_textures.h). +const TEXTURE_FORMATS=[null,'r8unorm','r8snorm','rg8unorm','rg8snorm','rgba8unorm','rgba8snorm','rgb10a2unorm', + 'r16float','rg16float','rgba16float','r32float','rg32float','rgba32float']; +const UNFILTERABLE_FORMATS=new Set(['r32float','rg32float','rgba32float']); const BUFFER_USAGE={MAP_READ:0x1,COPY_SRC:0x4,COPY_DST:0x8,INDEX:0x10,UNIFORM:0x40,STORAGE:0x80}; const TEXTURE_USAGE={COPY_SRC:0x1,COPY_DST:0x2,TEXTURE_BINDING:0x4,RENDER_ATTACHMENT:0x10}; @@ -41,7 +56,11 @@ export class XenosWebGpuBackend{ this.stagingOffset=0; this.encoder=null; this.stats={uploads:0,uploadedBytes:0,droppedUploads:0,submits:0,shaders:0,pipelines:0, - pipelineFailures:0,draws:0,skippedDraws:0,renderPasses:0,swaps:0,targetsCreated:0}; + pipelineFailures:0,draws:0,skippedDraws:0,renderPasses:0,swaps:0,targetsCreated:0, + textures:0,textureLoads:0,textureFailures:0,textureLoadFailures:0,loadShaderFailures:0,unbindableTextures:0, + dumps:0,resolves:0,resolveFailures:0,clears:0}; + // r32float and wider float textures are filterable only with this feature. + this.float32Filterable=!!device.features?.has?.('float32-filterable'); this.convert=null; this.shaders=new Map(); // stream id -> {stage, module, bindings, outputs} this.pipelines=new Map(); // stream id -> {pipeline, layouts, description} or {error} @@ -51,6 +70,17 @@ export class XenosWebGpuBackend{ this.boundTargets=null; // WebGpuRenderTargetsKey of op 4 this.pass=null; this.lastSwap=null; + this.loadShaders=new Map(); // TextureCache::LoadShaderIndex -> compute pipeline + this.textures=new Map(); // stream texture id -> {texture, views, format} + this.samplers=new Map(); // packed sampler parameters -> GPUSampler + this.textureGroups=new Map();// bind groups of groups 2 / 3 by contents + this.scratch=null;this.scratchRetired=[]; + // Xenia's EDRAM buffer (render target dumps for resolves) and the host + // render target owning each tile (RenderTargetCache ownership). + this.edram=device.createBuffer({label:'Render360 EDRAM',size:EDRAM_TILES*EDRAM_TILE_DWORDS*4, + usage:BUFFER_USAGE.STORAGE|BUFFER_USAGE.COPY_SRC|BUFFER_USAGE.COPY_DST}); + this.tileOwner=new Array(EDRAM_TILES).fill(null); + this.frontTexture=null; this.uniforms=new XenosUniformRing(device); this.indices=new XenosRing(device,'Render360 indices',BUFFER_USAGE.INDEX,8*1024*1024); } @@ -71,6 +101,8 @@ export class XenosWebGpuBackend{ this.endPass(); this.uniforms.flush();this.indices.flush(); if(this.encoder){this.device.queue.submit([this.encoder.finish()]);this.encoder=null;this.stats.submits++;} + for(const b of this.scratchRetired)b.destroy(); + this.scratchRetired.length=0; this.stagingOffset=0; } @@ -93,7 +125,13 @@ export class XenosWebGpuBackend{ else if(op===GPU_STREAM_PIPELINE)this.definePipeline(p); else if(op===GPU_STREAM_RENDER_TARGETS){this.endPass();this.boundTargets=parseRenderTargets(p);} else if(op===GPU_STREAM_DRAW)this.draw(p); - else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.submit();} + else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.frontTexture=this.textures.get(p[6])||null;this.submit();} + else if(op===GPU_STREAM_EDRAM_DUMP)this.dumpEdram(p); + else if(op===GPU_STREAM_RESOLVE)this.resolve(p); + else if(op===GPU_STREAM_CLEAR)this.clear(p); + else if(op===GPU_STREAM_LOAD_SHADER)this.defineLoadShader(p); + else if(op===GPU_STREAM_TEXTURE)this.defineTexture(p); + else if(op===GPU_STREAM_TEXTURE_LOAD)this.loadTexture(p); else throw new Error(`Render360 GPU stream: unknown op ${op} at word ${i}`); i+=1+n; } @@ -194,7 +232,7 @@ export class XenosWebGpuBackend{ let cached=this.layouts.get(key); if(!cached){ const layout=this.device.createBindGroupLayout({label:`Render360 Xenos group ${group}`,entries:list}); - cached={key,layout,group:group===1?null:this.device.createBindGroup({layout,entries:list.map(e=>({binding:e.binding,resource:this.placeholderResource(e)}))})}; + cached={key,layout,entries:list,group:group===1?null:this.device.createBindGroup({layout,entries:list.map(e=>({binding:e.binding,resource:this.placeholderResource(e)}))})}; if(group===1)cached.group=this.uniforms.bindGroup(layout); this.layouts.set(key,cached); } @@ -227,15 +265,16 @@ export class XenosWebGpuBackend{ // Host render target for an EDRAM base / format / pitch (Xenia's // RenderTargetCache key without the resolution scale). - target(base,guestFormat,depth,pitch,height){ - const key=`${depth?'d':'c'}:${base}:${guestFormat}:${pitch}`; + target(base,guestFormat,depth,pitch,height,msaa=0){ + const key=`${depth?'d':'c'}:${base}:${guestFormat}:${pitch}:${msaa}`; let t=this.targets.get(key); if(t&&t.height>=height)return t; const format=depth?this.depthFormat(guestFormat):colorFormat(guestFormat); const texture=this.device.createTexture({label:`Render360 EDRAM ${key}`,format,size:{width:pitch,height:Math.max(height,t?.height||0,720)}, usage:TEXTURE_USAGE.RENDER_ATTACHMENT|TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_SRC|TEXTURE_USAGE.COPY_DST}); // A taller target replaces the old one; its contents are kept by copying. - const fresh={key,base,guestFormat,depth,texture,view:texture.createView(),format,width:pitch,height:texture.height,initialized:false}; + const fresh={key,base,guestFormat,depth,texture,view:texture.createView(),format,width:pitch,height:texture.height,initialized:false, + msaa,...tileGeometry(pitch,msaa,!depth&&COLOR_64BPP.has(guestFormat))}; if(t){ this.endPass(); this.encoderForCommands().copyTextureToTexture({texture:t.texture},{texture},{width:t.width,height:t.height}); @@ -255,7 +294,7 @@ export class XenosWebGpuBackend{ const used=[]; for(let i=0;i<4;i++){ if(k.colorBase[i]===0xFFFFFFFF)continue; - const t=this.target(k.colorBase[i],k.colorFormat[i],false,k.surfacePitch,k.height); + const t=this.target(k.colorBase[i],k.colorFormat[i],false,k.surfacePitch,k.height,k.msaaSamples); while(colorAttachments.lengtht.height))}; this.pass=this.encoderForCommands().beginRenderPass(pass); this.passState={pipeline:null,groups:[]}; @@ -284,10 +323,12 @@ export class XenosWebGpuBackend{ // Draw op: header, system / float / bool-loop / fetch constants, indices. draw(p){ const h=parseDrawHeader(p); + if(this.drawLimit!==undefined&&this.stats.draws>=this.drawLimit){this.stats.skippedDraws++;return;} const entry=this.pipelines.get(h.pipeline); if(!entry?.pipeline){this.stats.skippedDraws++;return;} let o=DRAW_HEADER_WORDS; const constants=[h.systemWords,h.floatVertexWords,h.floatPixelWords,h.boolLoopWords,h.fetchWords].map(n=>{const c=p.subarray(o,o+n);o+=n;return c;}); + const bindingWords=p.subarray(o,o+h.bindingWords);o+=h.bindingWords; const indexWords=h.indexFormat===2?h.vertexCount:h.indexFormat===1?(h.vertexCount+1)>>>1:0; const indexData=p.subarray(o,o+indexWords); // Constants and indices are written before the pass using them is @@ -304,8 +345,9 @@ export class XenosWebGpuBackend{ if(vw<=0||vh<=0||sw<=0||sh<=0){this.stats.skippedDraws++;return;} const s=this.passState; if(s.pipeline!==entry.pipeline){pass.setPipeline(entry.pipeline);s.pipeline=entry.pipeline;} + const textureGroups=this.textureBindGroups(entry,bindingWords); for(let g=0;g<4;g++){ - const group=entry.layouts[g].group; + const group=g>=2?textureGroups[g-2]:entry.layouts[g].group; if(g===1)pass.setBindGroup(1,group,offsets); else if(s.groups[g]!==group){pass.setBindGroup(g,group);s.groups[g]=group;} } @@ -326,6 +368,298 @@ export class XenosWebGpuBackend{ this.stats.draws++; } + // Bind groups 2 (vertex) and 3 (pixel) of a draw: its textures (by + // stream id, 0 for Xenia's null texture) and samplers. + textureBindGroups(entry,words){ + const out=[];let o=0; + for(let g=2;g<4;g++){ + const shader=this.shaders.get(g===2?entry.description.vertexShader:entry.description.pixelShader); + const layout=entry.layouts[g]; + if(!shader||!layout.entries.length){out.push(layout.group);if(shader)o+=shader.textures.length+shader.samplers.length;continue;} + const n=shader.textures.length,m=shader.samplers.length,ids=words.subarray(o,o+n+m);o+=n+m; + const key=`${layout.key}|${ids.join(',')}`; + let group=this.textureGroups.get(key); + if(!group){ + if(this.textureGroups.size>4096)this.textureGroups.clear(); + group=this.device.createBindGroup({layout:layout.layout,entries:layout.entries.map(e=>{ + if(e.texture){ + const t=e.binding=n&&e.bindingm===0?'repeat':m===1?'mirror-repeat':'clamp-to-edge'; + const mag=(parameters>>>11)&1,min=(parameters>>>12)&1,mip=(parameters>>>13)&1; + const aniso=(parameters>>>14)&7,baseMap=(parameters>>>17)&1,minLevel=(parameters>>>18)&15; + const descriptor={addressModeU:address(parameters&7),addressModeV:address((parameters>>>3)&7),addressModeW:address((parameters>>>6)&7), + magFilter:mag?'linear':'nearest',minFilter:min?'linear':'nearest',mipmapFilter:mip?'linear':'nearest', + lodMinClamp:minLevel,lodMaxClamp:baseMap?minLevel+0.25:32}; + // Anisotropy needs every filter linear in WebGPU. + if(aniso>=2&&mag&&min&&mip)descriptor.maxAnisotropy=Math.min(16,1<<(aniso-1)); + sampler=this.device.createSampler(descriptor); + this.samplers.set(parameters,sampler); + return sampler; + } + + // One of Xenia's texture_load_* compute shaders. Naga rejects write-only + // storage (NonReadable) and has no push constants in WGSL: the decoration + // is dropped and the push constant block becomes a uniform buffer. + defineLoadShader(p){ + const index=p[0],spirv=stripNonReadable(p.subarray(2,2+p[1])); + const entry={}; + try{ + const wgsl=this.convert(new Uint8Array(spirv.buffer,spirv.byteOffset,spirv.byteLength)) + .replace(/var<(?:immediate|push_constant)>\s+(\w+)\s*:/,'@group(2) @binding(0) var $1:'); + const module=this.device.createShaderModule({label:`Xenia texture load ${index}`,code:wgsl}); + const S=0x4; // COMPUTE + // Texture loads: group 0 destination, 1 source. Resolve copies (64 + + // ResolveCopyShaderIndex): group 0 EDRAM, 1 shared memory destination. + const resolve=index>=64; + const layouts=[ + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:resolve?'read-only-storage':'storage'}}]}), + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:resolve?'storage':'read-only-storage'}}]}), + this.device.createBindGroupLayout({entries:[{binding:0,visibility:S,buffer:{type:'uniform',hasDynamicOffset:true}}]})]; + entry.layouts=layouts; + entry.pipeline=this.device.createComputePipeline({label:`Xenia texture load ${index}`, + layout:this.device.createPipelineLayout({bindGroupLayouts:layouts}),compute:{module,entryPoint:'main'}}); + entry.constants=this.device.createBindGroup({layout:layouts[2],entries:[{binding:0,resource:{buffer:this.uniforms.buffer,offset:0,size:256}}]}); + }catch(error){entry.error=String(error?.message||error);this.stats.loadShaderFailures++;} + this.loadShaders.set(index,entry); + } + + // Texture op: VulkanTextureCache::CreateTexture. + defineTexture(p){ + const [id,formatIndex,dimension,width,height,depth,mips]=p; + const format=TEXTURE_FORMATS[formatIndex]; + const old=this.textures.get(id); + if(old)old.texture.destroy(); + if(!format){this.stats.textureFailures++;return;} + const is3d=dimension===1; + const texture=this.device.createTexture({label:`Xenos texture ${id}`,format,dimension:is3d?'3d':'2d', + size:{width,height,depthOrArrayLayers:depth},mipLevelCount:mips,usage:TEXTURE_USAGE.TEXTURE_BINDING|TEXTURE_USAGE.COPY_DST|TEXTURE_USAGE.COPY_SRC}); + const views={}; + if(is3d)views['3d']=texture.createView({dimension:'3d'}); + else if(dimension===2)views.cube=texture.createView({dimension:'cube'}); + else views['2d-array']=texture.createView({dimension:'2d-array'}); + this.textures.set(id,{id,texture,views,format,dimension,width,height}); + this.textureGroups.clear(); + this.stats.textures++; + } + + // Texture load op: Xenia's load shader dispatches into a scratch buffer + // (VulkanTextureCache::LoadTextureDataFromResidentMemoryImpl), an + // optional expansion pass, then copies into the texture. + loadTexture(p){ + const [id,shaderIndex,expand,bufferSize,baseOffset,baseSize,mipsOffset,mipsSize,dispatchCount,copyCount]=p; + const t=this.textures.get(id),shader=this.loadShaders.get(shaderIndex); + if(!t||!shader?.pipeline){this.stats.textureLoadFailures++;return;} + this.endPass(); + const expanded=expand>=1&&expand<=4; + const scratchBytes=bufferSize*(expanded?3:1)+256; + if(!this.scratch||this.scratch.sizesize?this.device.createBindGroup({layout:shader.layouts[1],entries:[{binding:0,resource:{buffer:this.sharedMemory,offset,size}}]}):null; + const sources=[source(baseOffset,baseSize),source(mipsOffset,mipsSize)]; + const pass=this.encoderForCommands().beginComputePass({label:'Xenia texture load'}); + pass.setPipeline(shader.pipeline); + pass.setBindGroup(0,dest); + let o=10; + for(let d=0;d=5,words=bufferSize/4; + const out=inPlace?0:Math.ceil(bufferSize/256)*256; + const group=this.device.createBindGroup({layout:entry.pipeline.getBindGroupLayout(0),entries:[ + {binding:0,resource:{buffer:this.scratch,offset:0,size:bufferSize}}, + ...(inPlace?[]:[{binding:1,resource:{buffer:this.scratch,offset:out,size:bufferSize*2}}])]}); + const pass=this.encoderForCommands().beginComputePass({label:'Render360 texel expand'}); + pass.setPipeline(entry.pipeline);pass.setBindGroup(0,group); + const groups=Math.ceil(words/64); + pass.dispatchWorkgroups(Math.min(groups,65535),Math.ceil(groups/65535)); + pass.end(); + return inPlace?{buffer:this.scratch,scale:1,base:0}:{buffer:this.scratch,scale:2,base:out}; + } + + // The render target owns the EDRAM tiles it covers up to `height` pixels. + own(t,height){ + const rows=Math.ceil(Math.min(height,t.height)/t.tileHeight); + for(let r=0;rthis.sharedMemoryBytes){this.stats.resolveFailures++;return;} + this.endPass(); + const constants=p.subarray(1,6); + if(!this.uniforms.fits([constants]))this.submit(); + const at=this.uniforms.push(constants); + const pass=this.encoderForCommands().beginComputePass({label:'Xenia resolve'}); + pass.setPipeline(shader.pipeline); + pass.setBindGroup(0,this.device.createBindGroup({layout:shader.layouts[0],entries:[{binding:0,resource:{buffer:this.edram}}]})); + pass.setBindGroup(1,this.device.createBindGroup({layout:shader.layouts[1],entries:[{binding:0,resource:{buffer:this.sharedMemory,offset,size}}]})); + pass.setBindGroup(2,shader.constants,[at]); + pass.dispatchWorkgroups(groupsX,groupsY,1); + pass.end(); + this.stats.resolves++; + } + + // Clear op: the host render targets at the cleared EDRAM region + // (VulkanRenderTargetCache::PrepareHostRenderTargetsResolveClear and + // PerformTransfersAndResolveClears). + clear(p){ + const [isDepth,base,pitchTiles,msaa,format,x,y,width,height,lo,hi]=p; + this.endPass(); + for(const t of this.targets.values()){ + if(!!t.depth!==!!isDepth||t.pitchTiles!==pitchTiles||t.msaa!==msaa||t.guestFormat!==format)continue; + const delta=(base-t.base+EDRAM_TILES)%EDRAM_TILES; + const x0=(delta%pitchTiles)*t.tileWidth+x,y0=Math.floor(delta/pitchTiles)*t.tileHeight+y; + if(x0>=t.width||y0>=t.height)continue; + const w=Math.min(width,t.width-x0),h=Math.min(height,t.height-y0); + const whole=x0===0&&y0===0&&w>=t.width&&h>=t.height; + const value=isDepth?depthClearValue(format,lo,this.depthFormat(format)):colorClearValue(format,lo,hi); + const attachment=isDepth + ?{depthStencilAttachment:{view:t.view,depthLoadOp:whole?'clear':'load',depthClearValue:value.depth,depthStoreOp:'store', + stencilLoadOp:whole?'clear':'load',stencilClearValue:value.stencil,stencilStoreOp:'store'},colorAttachments:[]} + :{colorAttachments:[{view:t.view,loadOp:whole?'clear':'load',clearValue:value,storeOp:'store'}]}; + const pass=this.encoderForCommands().beginRenderPass(attachment); + if(!whole){ + pass.setPipeline(this.clearPipeline(t)); + const words=new Float32Array(isDepth?[value.depth,0,0,0]:[value.r,value.g,value.b,value.a]); + if(!this.uniforms.fits([words])){pass.end();this.submit();this.clear(p);return;} + const at=this.uniforms.push(new Uint32Array(words.buffer)); + pass.setBindGroup(0,this.clearGroup(t),[at]); + pass.setScissorRect(x0,y0,w,h); + if(isDepth)pass.setStencilReference(value.stencil); + pass.draw(3); + } + pass.end(); + t.initialized=true; + this.stats.clears++; + } + } + + clearPipeline(t){ + this.clearPipelines??=new Map(); + let pipeline=this.clearPipelines.get(t.format); + if(!pipeline){ + const module=this.device.createShaderModule({label:'Render360 clear',code:CLEAR_SHADER}); + const layout=this.clearLayout(); + const descriptor={label:`Render360 clear ${t.format}`,layout:this.device.createPipelineLayout({bindGroupLayouts:[layout]}), + vertex:{module,entryPoint:'vs'},primitive:{topology:'triangle-list'}}; + if(t.depth){ + descriptor.fragment={module,entryPoint:'fs_depth',targets:[]}; + const face={compare:'always',passOp:'replace',failOp:'replace',depthFailOp:'replace'}; + descriptor.depthStencil={format:t.format,depthWriteEnabled:true,depthCompare:'always',stencilFront:face,stencilBack:face,stencilWriteMask:0xFF}; + }else descriptor.fragment={module,entryPoint:'fs_color',targets:[{format:t.format}]}; + pipeline=this.device.createRenderPipeline(descriptor); + this.clearPipelines.set(t.format,pipeline); + } + return pipeline; + } + clearLayout(){ + this.clearBindGroupLayout??=this.device.createBindGroupLayout({entries:[{binding:0,visibility:SHADER_STAGE.FRAGMENT,buffer:{type:'uniform',hasDynamicOffset:true}}]}); + return this.clearBindGroupLayout; + } + clearGroup(){ + this.clearBindGroup??=this.device.createBindGroup({layout:this.clearLayout(),entries:[{binding:0,resource:{buffer:this.uniforms.buffer,offset:0,size:16}}]}); + return this.clearBindGroup; + } + // RGBA8 pixels of a color render target (tests and the frame preview). async readTarget(t){ this.submit(); @@ -423,13 +757,13 @@ function parseRenderTargets(w){ colorFormat:Array.from(w.subarray(7,11)),depthBase:w[11],depthFormat:w[12]}; } -const DRAW_HEADER_WORDS=25; +const DRAW_HEADER_WORDS=26; function parseDrawHeader(w){ const f=new Float32Array(w.buffer,w.byteOffset,DRAW_HEADER_WORDS); return {pipeline:w[0],viewport:Array.from(w.subarray(1,5)),depthRange:[f[5],f[6]],scissor:Array.from(w.subarray(7,11)), stencilReference:w[11],blendConstant:[f[12],f[13],f[14],f[15]],systemWords:w[16],floatVertexWords:w[17], floatPixelWords:w[18],boolLoopWords:w[19],fetchWords:w[20],indexFormat:w[21],vertexCount:w[22], - vertexTextureMask:w[23],pixelTextureMask:w[24]}; + vertexTextureMask:w[23],pixelTextureMask:w[24],bindingWords:w[25]}; } // Resource declarations of Naga's WGSL: group, binding, kind and type. @@ -494,3 +828,188 @@ class XenosUniformRing extends XenosRing{ entries:[0,1,2,3,4].map(b=>({binding:b,resource:{buffer:this.buffer,offset:0,size:CONSTANT_WINDOW}}))}); } } + +// SPIR-V without NonReadable decorations (OpDecorate / OpMemberDecorate 25). +export function stripNonReadable(words){ + const out=Array.from(words.subarray(0,5)); + for(let i=5;i>>16,op=words[i]&0xFFFF; + if(!n)break; + const drop=(op===71&&words[i+2]===25)||(op===72&&words[i+3]===25); + if(!drop)for(let k=0;k src: array;\n`; + const index=`let i = id.x + id.y * 65535u * 64u; if (i >= arrayLength(&src)) { return; }`; + if(mode>=5){ + const conv=mode===5?'vec2(f32(v & 0xFFFFu), f32(v >> 16u)) / 65535.0' + :'max(vec2(f32((bitcast(v) << 16u) >> 16u), f32(bitcast(v) >> 16u)) / 32767.0, vec2(-1.0))'; + return `${head}@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + ${index} let v = src[i]; src[i] = pack2x16float(${conv}); }`; + } + const unpack={ + 1:'vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 63u) / 63.0, f32((t >> 11u) & 31u) / 31.0, 1.0)', + 2:'vec4(f32(t & 31u) / 31.0, f32((t >> 10u) & 63u) / 63.0, f32((t >> 5u) & 31u) / 31.0, 1.0)', + 3:'vec4(f32(t & 31u) / 31.0, f32((t >> 5u) & 31u) / 31.0, f32((t >> 10u) & 31u) / 31.0, f32(t >> 15u))', + 4:'vec4(f32(t & 15u), f32((t >> 4u) & 15u), f32((t >> 8u) & 15u), f32(t >> 12u)) / 15.0'}[mode]; + return `${head}@group(0) @binding(1) var dst: array; +fn texel(t: u32) -> u32 { return pack4x8unorm(${unpack}); } +@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3) { + ${index} let v = src[i]; dst[2u * i] = texel(v & 0xFFFFu); dst[2u * i + 1u] = texel(v >> 16u); }`; +} + +// EDRAM tile geometry of a host render target in pixels (80x16 32bpp +// samples per tile, 40x16 at 64bpp; 2x MSAA doubles Y, 4x also X). +function tileGeometry(pitch,msaa,is64bpp){ + const sx=msaa>=2?2:1,sy=msaa>=1?2:1; + const tileWidth=(is64bpp?40:80)/sx,tileHeight=16/sy; + return {is64bpp,tileWidth,tileHeight,pitchTiles:Math.ceil(pitch/tileWidth)}; +} + +function float7e3To32(f10){ + f10&=0x3FF;if(!f10)return 0; + let mantissa=f10&0x7F,exponent=f10>>>7; + if(!exponent){let lz=7-(31-Math.clz32(mantissa));exponent=1-lz;mantissa=(mantissa<>>0]).buffer)[0]; +} +function float20e4To32(f24){ + f24&=0xFFFFFF;if(!f24)return 0; + let mantissa=f24&0xFFFFF,exponent=f24>>>20; + if(!exponent){let lz=20-(31-Math.clz32(mantissa));exponent=1-lz;mantissa=(mantissa<>>0]).buffer)[0]; +} +function halfToFloat(h){ + const s=h&0x8000?-1:1,e=(h>>>10)&31,m=h&1023; + if(!e)return s*m*2**-24;if(e===31)return m?NaN:s*Infinity; + return s*(1+m/1024)*2**(e-15); +} + +// Guest clear values to host clear colors (VulkanRenderTargetCache), for the +// host formats render360 picks (16-bit fixed formats stored as float in +// Xenia's -1...1 host scale). +function colorClearValue(format,lo,hi){ + const v=BigInt(lo>>>0)|(BigInt(hi>>>0)<<32n),bits=(shift,n)=>Number((v>>BigInt(shift))&((1n<Math.max(((x<<16)>>16)/32767,-1); + switch(format){ + case 0:case 1:return {r:bits(0,8)/255,g:bits(8,8)/255,b:bits(16,8)/255,a:bits(24,8)/255}; + case 2:case 10:return {r:bits(0,10)/1023,g:bits(10,10)/1023,b:bits(20,10)/1023,a:bits(30,2)/3}; + case 3:case 12:return {r:float7e3To32(bits(0,10)),g:float7e3To32(bits(10,10)),b:float7e3To32(bits(20,10)),a:bits(30,2)/3}; + case 4:return {r:s16(bits(0,16)),g:s16(bits(16,16)),b:0,a:0}; + case 5:return {r:s16(bits(0,16)),g:s16(bits(16,16)),b:s16(bits(32,16)),a:s16(bits(48,16))}; + case 6:return {r:halfToFloat(bits(0,16)),g:halfToFloat(bits(16,16)),b:0,a:0}; + case 7:return {r:halfToFloat(bits(0,16)),g:halfToFloat(bits(16,16)),b:halfToFloat(bits(32,16)),a:halfToFloat(bits(48,16))}; + case 14:{const f=new Float32Array(new Uint32Array([lo>>>0]).buffer)[0];return {r:f,g:0,b:0,a:0};} + case 15:{const f=new Float32Array(new Uint32Array([lo>>>0,hi>>>0]).buffer);return {r:f[0],g:f[1],b:0,a:0};} + default:return {r:0,g:0,b:0,a:0}; + } +} +function depthClearValue(format,value,hostFormat){ + const d24=(value>>>8)&0xFFFFFF; + // D24FS8: Xenia's host depth takes [0, 2) to [0, 1). + const depth=format===1?float20e4To32(d24)*0.5:d24/0xFFFFFF; + return {depth:Math.min(1,Math.max(0,depth)),stencil:value&0xFF}; +} + +const CLEAR_SHADER=`@group(0) @binding(0) var value: vec4; +@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + return vec4(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0, 0.0, 1.0); +} +@fragment fn fs_color() -> @location(0) vec4 { return value; } +@fragment fn fs_depth() -> @builtin(frag_depth) f32 { return value.x; }`; + +// EDRAM dump of one host render target region (WGSL port of edram.xesli +// XeEdramOffsetBytes and the EDRAM pixel formats of pixel_formats.xesli). +function edramDumpShader(depth){ + return `struct Dump { + base_tiles: u32, pitch_tiles: u32, msaa: u32, format: u32, + x0: u32, y0: u32, width: u32, height: u32, is_64bpp: u32, depth_float32: u32, pad0: u32, pad1: u32, +} +@group(0) @binding(0) var edram: array; +@group(0) @binding(1) var dump: Dump; +${depth?`@group(0) @binding(2) var depth_texture: texture_depth_2d; +@group(0) @binding(3) var stencil_texture: texture_2d;`:`@group(0) @binding(2) var color_texture: texture_2d;`} + +fn edram_offset_dwords(pixel: vec2, sample: u32) -> u32 { + var s = pixel << vec2(select(0u, 1u, dump.msaa >= 2u), select(0u, 1u, dump.msaa >= 1u)); + s += (vec2(sample) >> vec2(1u, 0u)) & vec2(1u); + let ints_log2 = dump.is_64bpp; + let tile_size = vec2(80u >> ints_log2, 16u); + let tile = s / tile_size; + var base = dump.base_tiles + tile.y * dump.pitch_tiles + tile.x; + s -= tile * tile_size; + ${depth?`let half = tile_size.x >> 1u; + s.x = select(s.x + half, s.x - half, s.x >= half);`:''} + let address = base * 1280u + ((s.y * tile_size.x + s.x) << ints_log2); + return address % (1280u * 2048u); +} + +fn f32_to_7e3(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x41FF8000u) { return 0x3FFu; } + if (u < 0x3E800000u) { + let shift = min(125u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC2000000u; + } + u += 0x7FFFu + ((u >> 16u) & 1u); + return (u >> 16u) & 0x3FFu; +} +fn f32_to_20e4(f: f32) -> u32 { + if (!(f > 0.0)) { return 0u; } + var u = bitcast(f); + if (u >= 0x3FFFFFF8u) { return 0xFFFFFFu; } + if (u < 0x38800000u) { + let shift = min(113u - (u >> 23u), 24u); + u = (0x800000u | (u & 0x7FFFFFu)) >> shift; + } else { + u += 0xC8000000u; + } + u += 3u + ((u >> 3u) & 1u); + return (u >> 3u) & 0xFFFFFFu; +} +fn s16(f: f32) -> u32 { return u32(i32(round(clamp(f, -1.0, 1.0) * 32767.0))) & 0xFFFFu; } +fn unorm(f: f32, bits: u32) -> u32 { let m = f32((1u << bits) - 1u); return u32(round(clamp(f, 0.0, 1.0) * m)); } + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) id: vec3) { + if (id.x >= dump.width || id.y >= dump.height) { return; } + let pixel = vec2(dump.x0 + id.x, dump.y0 + id.y); + var lo = 0u; + var hi = 0u; + ${depth?`let d = textureLoad(depth_texture, vec2(pixel), 0); + let stencil = textureLoad(stencil_texture, vec2(pixel), 0).x & 0xFFu; + // D24FS8: Xenia's host depth takes [0, 2) to [0, 1). + let d24 = select(u32(round(clamp(d, 0.0, 1.0) * 16777215.0)), f32_to_20e4(d * 2.0), dump.format == 1u); + lo = (d24 << 8u) | stencil;`:`let c = textureLoad(color_texture, vec2(pixel), 0); + switch dump.format { + case 0u, 1u: { lo = pack4x8unorm(c); } + case 2u, 10u: { lo = unorm(c.x, 10u) | (unorm(c.y, 10u) << 10u) | (unorm(c.z, 10u) << 20u) | (unorm(c.w, 2u) << 30u); } + case 3u, 12u: { lo = f32_to_7e3(c.x) | (f32_to_7e3(c.y) << 10u) | (f32_to_7e3(c.z) << 20u) | (unorm(c.w, 2u) << 30u); } + case 4u: { lo = s16(c.x) | (s16(c.y) << 16u); } + case 5u: { lo = s16(c.x) | (s16(c.y) << 16u); hi = s16(c.z) | (s16(c.w) << 16u); } + case 6u: { lo = pack2x16float(c.xy); } + case 7u: { lo = pack2x16float(c.xy); hi = pack2x16float(c.zw); } + case 14u: { lo = bitcast(c.x); } + case 15u: { lo = bitcast(c.x); hi = bitcast(c.y); } + default: { lo = pack4x8unorm(c); } + }`} + // One host sample: every guest sample of the pixel gets its value. + let samples = select(select(1u, 2u, dump.msaa == 1u), 4u, dump.msaa >= 2u); + for (var s = 0u; s < samples; s++) { + let o = edram_offset_dwords(pixel, s); + edram[o] = lo; + if (dump.is_64bpp != 0u) { edram[o + 1u] = hi; } + } +}`; +} diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h index 06c12dde..ad59251c 100644 --- a/src/xenia_web_bootstrap/webgpu_backend.h +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -29,8 +29,34 @@ enum GpuStreamOp : uint32_t { // A draw: WebGpuDrawHeader, the system constants, vertex and pixel float // constants, bool/loop constants, fetch constants, then the indices. kGpuStreamDraw = 5, - // A swap: the front buffer's texture fetch constant (6 words). + // A swap: the front buffer's texture fetch constant (6 words), then its + // texture id (0: none). kGpuStreamSwap = 6, + // One of Xenia's texture_load_* compute shaders, once: load shader index + // (TextureCache::LoadShaderIndex), SPIR-V word count, SPIR-V. + kGpuStreamLoadShader = 7, + // A texture: id, format (WebGpuTextureFormat), dimension (0 2D array, + // 1 3D, 2 cube), width, height, depth or layers, mip levels. + kGpuStreamTexture = 8, + // Texture data load (webgpu_textures.cpp LoadTextureData): id, load + // shader, expand, scratch size, base offset / size and mips offset / size + // in shared memory, dispatch count, copy count, then the dispatches + // (source, LoadConstants, 3 group counts) and copies (buffer offset, + // bytes per row, rows per image, mip level, layers, width, height, depth). + kGpuStreamTextureLoad = 9, + // Before a resolve copy (VulkanRenderTargetCache::DumpRenderTargets): the + // EDRAM tile span to write from the host render targets owning it into + // the EDRAM buffer: base tiles, row length used, rows, pitch (tiles). + kGpuStreamEdramDump = 10, + // Resolve copy (VulkanRenderTargetCache::Resolve): copy shader + // (draw_util::ResolveCopyShaderIndex, SPIR-V sent as load shader 64 + + // index), the 5 ResolveCopyShaderConstants words (dest_base relative to + // the binding), group counts x / y, shared memory binding offset / size. + kGpuStreamResolve = 11, + // Resolve clear of host render targets: is_depth, EDRAM base tiles, pitch + // tiles, MSAA samples, format, x / y / width / height (pixels from the + // base tile), clear value low / high (guest encoding). + kGpuStreamClear = 12, }; // Pipeline state, following Xenia's VulkanPipelineCache::PipelineDescription. @@ -79,6 +105,10 @@ struct WebGpuDrawHeader { uint32_t vertex_count; // indices, or vertices without an index buffer uint32_t vertex_texture_mask; // fetch constants the shaders sample uint32_t pixel_texture_mask; + // After the fetch constants: for the vertex then the pixel shader, a + // texture id per texture binding then packed sampler parameters per + // sampler binding (webgpu_textures.h). + uint32_t binding_words; }; // Records draws for the WebGPU backend when enabled (r360_gpu_set_mode); diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp index 04d9040c..0ccbdf57 100644 --- a/src/xenia_web_bootstrap/webgpu_draws.cpp +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -10,6 +10,7 @@ #include #include "webgpu_backend.h" +#include "webgpu_textures.h" #include "xenos_soft_draw.h" #include "sparse_guest_memory.h" #include "xenia/base/math.h" @@ -19,7 +20,21 @@ #include "xenia/gpu/registers.h" #include "xenia/gpu/spirv_shader.h" #include "xenia/gpu/spirv_shader_translator.h" +#include "xenia/gpu/trace_writer.h" #include "xenia/gpu/xenos.h" +#include "ppc_translation_probe_runtime.h" + +namespace xe::gpu::shaders { +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_32bpp_1x2xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_32bpp_4xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_64bpp_1x2xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_fast_64bpp_4xmsaa_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_128bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_16bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_32bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_64bpp_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/resolve_full_8bpp_cs.h" +} // namespace xe::gpu::shaders extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); @@ -301,7 +316,7 @@ bool BuildIndices(const XenosSoftDraw& draw, Indices& out) { // Port of VulkanCommandProcessor::UpdateSystemConstantValues for the host // render targets path (no fragment shader interlock, no resolution scale). void FillSystemConstants(SpirvShaderTranslator::SystemConstants& c, bool primitive_polygonal, - const draw_util::ViewportInfo& viewport_info) { + const draw_util::ViewportInfo& viewport_info, uint32_t used_texture_mask) { const RegisterFile& regs = Regs(); std::memset(&c, 0, sizeof(c)); auto pa_cl_vte_cntl = regs.Get(); @@ -353,9 +368,16 @@ void FillSystemConstants(SpirvShaderTranslator::SystemConstants& c, bool primiti c.point_screen_diameter_to_ndc_radius[0] = 1.0f / std::max(viewport_info.xy_extent[0], 1u); c.point_screen_diameter_to_ndc_radius[1] = 1.0f / std::max(viewport_info.xy_extent[1], 1u); } - // Texture signs and swizzles come from the texture cache (not yet: the - // backend binds placeholder textures, sampled as unsigned RGBA). - for (uint32_t i = 0; i < 16; ++i) c.texture_swizzles[i] = 0x688u | (0x688u << 12); // RGBA + // Texture signedness / gamma and host swizzles (applied in the shader: + // WebGPU views do not swizzle) from the texture cache. + uint32_t textures_remaining = used_texture_mask, texture_index; + while (xe::bit_scan_forward(textures_remaining, &texture_index)) { + textures_remaining &= ~(1u << texture_index); + c.texture_swizzled_signs[texture_index >> 2] |= uint32_t(WebGpuTextureSwizzledSigns(texture_index)) + << (8 * (texture_index & 3)); + c.texture_swizzles[texture_index >> 1] |= WebGpuTextureHostSwizzle(texture_index) + << (12 * (texture_index & 1)); + } c.alpha_test_reference = regs.Get(XE_GPU_REG_RB_ALPHA_REF); } @@ -399,6 +421,103 @@ WebGpuRenderTargetsKey RenderTargets(uint32_t normalized_color_mask, bool depth_ return key; } +// Xenia's resolve copy shaders, sent once as load shaders 64 + index. +void SendResolveShader(draw_util::ResolveCopyShaderIndex index) { + static bool sent[size_t(draw_util::ResolveCopyShaderIndex::kCount)] = {}; + if (sent[size_t(index)]) return; + sent[size_t(index)] = true; + static const std::pair kShaders[] = { + {shaders::resolve_fast_32bpp_1x2xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_1x2xmsaa_cs)}, + {shaders::resolve_fast_32bpp_4xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_4xmsaa_cs)}, + {shaders::resolve_fast_64bpp_1x2xmsaa_cs, sizeof(shaders::resolve_fast_64bpp_1x2xmsaa_cs)}, + {shaders::resolve_fast_64bpp_4xmsaa_cs, sizeof(shaders::resolve_fast_64bpp_4xmsaa_cs)}, + {shaders::resolve_full_8bpp_cs, sizeof(shaders::resolve_full_8bpp_cs)}, + {shaders::resolve_full_16bpp_cs, sizeof(shaders::resolve_full_16bpp_cs)}, + {shaders::resolve_full_32bpp_cs, sizeof(shaders::resolve_full_32bpp_cs)}, + {shaders::resolve_full_64bpp_cs, sizeof(shaders::resolve_full_64bpp_cs)}, + {shaders::resolve_full_128bpp_cs, sizeof(shaders::resolve_full_128bpp_cs)}, + }; + const auto& shader = kShaders[size_t(index)]; + uint32_t* w = GpuStream().Begin(kGpuStreamLoadShader, 2 + uint32_t(shader.second / 4)); + w[0] = 64u + uint32_t(index); + w[1] = uint32_t(shader.second / 4); + std::memcpy(w + 2, shader.first, shader.second); +} + +// VulkanRenderTargetCache::Resolve for the host render targets path: dump +// the render targets owning the source span into the EDRAM buffer, run +// Xenia's resolve copy shader into shared memory, then clear. +uint32_t g_resolves = 0, g_resolve_failures = 0; +void Resolve() { + const RegisterFile& regs = Regs(); + xe::Memory* memory = ActiveProbeMemory(); + if (!memory) { + ++g_resolve_failures; + return; + } + // GetResolveInfo reads guest memory only through the sparse memory + // overlay; its trace writer is never used (as in xenos_soft_renderer.cpp). + alignas(TraceWriter) static uint8_t trace_storage[sizeof(TraceWriter)] = {}; + auto& trace_writer = *reinterpret_cast(trace_storage); + draw_util::ResolveInfo info; + if (!draw_util::GetResolveInfo(regs, *memory, trace_writer, 1, 1, false, false, info)) { + ++g_resolve_failures; + return; + } + if (!info.coordinate_info.width_div_8 || !info.height_div_8) return; + ++g_resolves; + if (info.copy_dest_extent_length) { + uint32_t dump_base, dump_row_length_used, dump_rows, dump_pitch; + info.GetCopyEdramTileSpan(dump_base, dump_row_length_used, dump_rows, dump_pitch); + uint32_t* w = GpuStream().Begin(kGpuStreamEdramDump, 4); + w[0] = dump_base; + w[1] = dump_row_length_used; + w[2] = dump_rows; + w[3] = dump_pitch; + draw_util::ResolveCopyShaderConstants constants; + uint32_t group_count_x, group_count_y; + const draw_util::ResolveCopyShaderIndex copy_shader = + info.GetCopyShader(1, 1, constants, group_count_x, group_count_y); + if (copy_shader != draw_util::ResolveCopyShaderIndex::kUnknown && + GpuSharedMemory().RequestRange(info.copy_dest_extent_start, info.copy_dest_extent_length)) { + SendResolveShader(copy_shader); + // Storage bindings start at 256-byte multiples in WebGPU. + const uint32_t binding_offset = info.copy_dest_base & ~255u; + const uint32_t binding_size = + xe::align(info.copy_dest_extent_start - binding_offset + info.copy_dest_extent_length, 16u); + constants.dest_base -= binding_offset; + static_assert(sizeof(constants) == 20, "ResolveCopyShaderConstants layout"); + w = GpuStream().Begin(kGpuStreamResolve, 10); + w[0] = uint32_t(copy_shader); + std::memcpy(w + 1, &constants, sizeof(constants)); + w[6] = group_count_x; + w[7] = group_count_y; + w[8] = binding_offset; + w[9] = binding_size; + GpuSharedMemory().RangeWrittenByGpu(info.copy_dest_extent_start, info.copy_dest_extent_length); + WebGpuTexturesMarkRangeResolved(info.copy_dest_extent_start, info.copy_dest_extent_length); + } + } + auto clear = [&](bool depth, const draw_util::ResolveEdramInfo& edram, uint32_t lo, uint32_t hi) { + uint32_t* w = GpuStream().Begin(kGpuStreamClear, 11); + w[0] = depth; + w[1] = edram.base_tiles; + w[2] = edram.pitch_tiles; + w[3] = uint32_t(edram.msaa_samples); + w[4] = edram.format; + w[5] = info.coordinate_info.edram_offset_x_div_8 * 8u; + w[6] = info.coordinate_info.edram_offset_y_div_8 * 8u; + w[7] = info.coordinate_info.width_div_8 * 8u; + w[8] = info.height_div_8 * 8u; + w[9] = lo; + w[10] = hi; + }; + if (info.IsClearingDepth()) clear(true, info.depth_edram_info, info.rb_depth_clear, 0); + if (info.IsClearingColor()) { + clear(false, info.color_edram_info, info.rb_color_clear, info.rb_color_clear_lo); + } +} + WebGpuRenderTargetsKey g_bound_targets{}; bool g_targets_bound = false; @@ -408,8 +527,10 @@ bool WebGpuBackendEnabled() { return g_mode != 0; } void WebGpuSwap(const uint32_t* fetch_constant) { if (!g_mode) return; - uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 6); + const uint32_t texture = WebGpuSwapTexture(fetch_constant); + uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 7); std::memcpy(w, fetch_constant, 6 * sizeof(uint32_t)); + w[6] = texture; } bool WebGpuIssueDraw(const XenosSoftDraw& draw) { @@ -418,8 +539,12 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { const uint32_t count = std::min(draw.register_count, RegisterFile::kRegisterCount); std::memcpy(regs.values, draw.registers, count * sizeof(uint32_t)); const auto edram_mode = regs.Get().edram_mode; + if (edram_mode == xenos::EdramMode::kCopy) { + Resolve(); + return true; + } if (edram_mode != xenos::EdramMode::kColorDepth && edram_mode != xenos::EdramMode::kDepthOnly) { - return true; // copies are resolves (not recorded here yet) + return true; } SpirvShader* vertex_shader = @@ -524,9 +649,26 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { } } + // Textures (VulkanCommandProcessor::IssueDraw requests them before + // updating the constants and bindings). + const uint32_t used_texture_mask = + vertex_shader->GetUsedTextureMaskAfterTranslation() | + (pixel_shader ? pixel_shader->GetUsedTextureMaskAfterTranslation() : 0u); + WebGpuRequestTextures(regs, used_texture_mask); + std::vector binding_words; + for (const SpirvShader* shader : {vertex_shader, pixel_shader}) { + if (!shader) continue; + for (const auto& t : shader->GetTextureBindingsAfterTranslation()) { + binding_words.push_back(WebGpuTextureForBinding(t)); + } + for (const auto& s : shader->GetSamplerBindingsAfterTranslation()) { + binding_words.push_back(WebGpuSamplerParameters(regs, s)); + } + } + // Constants. SpirvShaderTranslator::SystemConstants system{}; - FillSystemConstants(system, primitive_polygonal, viewport_info); + FillSystemConstants(system, primitive_polygonal, viewport_info, used_texture_mask); std::vector float_vertex, float_pixel; PackFloatConstants(*vertex_shader, false, float_vertex); if (pixel_shader) PackFloatConstants(*pixel_shader, true, float_pixel); @@ -542,7 +684,7 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { const uint32_t system_words = sizeof(system) / 4; const uint32_t payload = sizeof(WebGpuDrawHeader) / 4 + system_words + uint32_t(float_vertex.size() + float_pixel.size()) + kBoolLoopWords + - kFetchWords + index_words; + kFetchWords + uint32_t(binding_words.size()) + index_words; const uint32_t pipeline_id = PipelineId(description); uint32_t* w = GpuStream().Begin(kGpuStreamDraw, payload); WebGpuDrawHeader header{}; @@ -571,6 +713,7 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { header.vertex_count = indices.values.empty() ? indices.vertex_count : uint32_t(indices.values.size()); header.vertex_texture_mask = vertex_shader->GetUsedTextureMaskAfterTranslation(); header.pixel_texture_mask = pixel_shader ? pixel_shader->GetUsedTextureMaskAfterTranslation() : 0u; + header.binding_words = uint32_t(binding_words.size()); std::memcpy(w, &header, sizeof(header)); w += sizeof(header) / 4; std::memcpy(w, &system, sizeof(system)); @@ -583,6 +726,8 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { w += kBoolLoopWords; std::memcpy(w, ®s[XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0], kFetchWords * 4); w += kFetchWords; + std::memcpy(w, binding_words.data(), binding_words.size() * 4); + w += binding_words.size(); if (index_words) { if (indices.use_32bit) { std::memcpy(w, indices.values.data(), indices.values.size() * 4); @@ -608,11 +753,14 @@ uint32_t r360_gpu_set_mode(uint32_t mode) { rx::g_targets_bound = false; return mode; } -// 0 draws recorded, 1..5 skips by reason (see DrawSkip), 6 last skip reason. +// 0 draws recorded, 1..5 skips by reason (see DrawSkip), 6 last skip reason, +// 7 resolves, 8 resolve failures. __attribute__((used, export_name("r360_gpu_draw_stat"))) uint32_t r360_gpu_draw_stat(uint32_t index) { if (index == 0) return rx::g_draws; if (index < rx::kSkipCount) return rx::g_skips[index]; + if (index == 7) return rx::g_resolves; + if (index == 8) return rx::g_resolve_failures; return rx::g_last_skip; } } // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_textures.cpp b/src/xenia_web_bootstrap/webgpu_textures.cpp new file mode 100644 index 00000000..adcf87d8 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_textures.cpp @@ -0,0 +1,883 @@ +// WebGPU texture cache (see webgpu_textures.h): Xenia's TextureCache binding +// and texture key logic (src/xenia/gpu/texture_cache.cc) and +// VulkanTextureCache's host formats and LoadTextureDataFromResidentMemoryImpl +// (src/xenia/gpu/vulkan/vulkan_texture_cache.cc), recording WebGPU stream +// ops instead of Vulkan commands. +#include "webgpu_textures.h" + +#include +#include +#include +#include +#include + +#include "sparse_guest_memory.h" +#include "webgpu_backend.h" +#include "xenia/base/math.h" +#include "xenia/gpu/texture_cache.h" +#include "xenia/gpu/texture_info.h" +#include "xenia/gpu/texture_util.h" + +extern "C" uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); + +namespace xe::gpu::shaders { +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_128bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_16bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_32bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_64bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_8bpb_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_bgrg8_rgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_bgrg8_rgbg8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_ctx1_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_depth_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_depth_unorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxn_rg8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt1_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3a_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3aas1111_argb4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt3aas1111_bgra4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt5_rgba8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_dxt5a_r8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_gbgr8_grgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_gbgr8_rgb8_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r10g11b11_rgba16_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r10g11b11_rgba16_snorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r11g11b10_rgba16_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r11g11b10_rgba16_snorm_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r16_unorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r4g4b4a4_a4r4g4b4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r4g4b4a4_b4g4r4a4_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g5b5a1_b5g5r5a1_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_r5g6b5_b5g6r5_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rg16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rg16_unorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rgba16_snorm_float_cs.h" +#include "xenia/gpu/shaders/bytecode/vulkan_spirv/texture_load_rgba16_unorm_float_cs.h" +} // namespace xe::gpu::shaders + +namespace render360::xenia_web { + +using namespace xe::gpu; + +namespace { + +// Xenia's TextureCache types (protected there; this class is never +// instantiated). +class Types : public TextureCache { + public: + using TextureCache::kLoadGuestXThreadsPerGroupLog2; + using TextureCache::kLoadGuestYBlocksPerGroupLog2; + using TextureCache::LoadConstants; + using TextureCache::LoadShaderIndex; + using TextureCache::LoadShaderInfo; + using TextureCache::TextureKey; + using TextureCache::kLoadShaderCount; + using TextureCache::kLoadShaderIndex128bpb; + using TextureCache::kLoadShaderIndex16bpb; + using TextureCache::kLoadShaderIndex32bpb; + using TextureCache::kLoadShaderIndex64bpb; + using TextureCache::kLoadShaderIndex8bpb; + using TextureCache::kLoadShaderIndexBGRG8ToRGB8; + using TextureCache::kLoadShaderIndexCTX1; + using TextureCache::kLoadShaderIndexDXNToRG8; + using TextureCache::kLoadShaderIndexDXT1ToRGBA8; + using TextureCache::kLoadShaderIndexDXT3A; + using TextureCache::kLoadShaderIndexDXT3ToRGBA8; + using TextureCache::kLoadShaderIndexDXT5AToR8; + using TextureCache::kLoadShaderIndexDXT5ToRGBA8; + using TextureCache::kLoadShaderIndexDepthFloat; + using TextureCache::kLoadShaderIndexDepthUnorm; + using TextureCache::kLoadShaderIndexGBGR8ToRGB8; + using TextureCache::kLoadShaderIndexR10G11B11ToRGBA16; + using TextureCache::kLoadShaderIndexR10G11B11ToRGBA16SNorm; + using TextureCache::kLoadShaderIndexR11G11B10ToRGBA16; + using TextureCache::kLoadShaderIndexR11G11B10ToRGBA16SNorm; + using TextureCache::kLoadShaderIndexR16SNormToFloat; + using TextureCache::kLoadShaderIndexR16UNormToFloat; + using TextureCache::kLoadShaderIndexRG16SNormToFloat; + using TextureCache::kLoadShaderIndexRG16UNormToFloat; + using TextureCache::kLoadShaderIndexRGBA16SNormToFloat; + using TextureCache::kLoadShaderIndexRGBA16UNormToFloat; + using TextureCache::kLoadShaderIndexUnknown; + + // TextureCache::GuestToHostSwizzle (texture_cache.cc is not linked). + static uint32_t GuestToHostSwizzle(uint32_t guest_swizzle, uint32_t host_format_swizzle) { + uint32_t host_swizzle = 0; + for (uint32_t i = 0; i < 4; ++i) { + const uint32_t guest_component = (guest_swizzle >> (3 * i)) & 0b111; + const uint32_t host_component = guest_component >= xenos::XE_GPU_TEXTURE_SWIZZLE_0 + ? guest_component & 0b101 + : (host_format_swizzle >> (3 * guest_component)) & 0b111; + host_swizzle |= host_component << (3 * i); + } + return host_swizzle; + } + // VulkanTextureCache::AreDimensionsCompatible. + static constexpr bool AreDimensionsCompatible(xenos::FetchOpDimension binding_dimension, + xenos::DataDimension resource_dimension) { + switch (binding_dimension) { + case xenos::FetchOpDimension::k1D: + case xenos::FetchOpDimension::k2D: + return resource_dimension == xenos::DataDimension::k1D || + resource_dimension == xenos::DataDimension::k2DOrStacked; + case xenos::FetchOpDimension::k3DOrStacked: + return resource_dimension == xenos::DataDimension::k3D; + case xenos::FetchOpDimension::kCube: + return resource_dimension == xenos::DataDimension::kCube; + default: + return false; + } + } +}; +using TextureKey = Types::TextureKey; +using LoadShaderIndex = Types::LoadShaderIndex; +constexpr LoadShaderIndex kUnknown = Types::kLoadShaderIndexUnknown; + +// TextureCache::load_shader_info_ and the Vulkan SPIR-V of each load shader. +struct LoadShader { + Types::LoadShaderInfo info; + const uint32_t* spirv; + uint32_t spirv_bytes; +}; +#define R360_LOAD_SHADER(bytes, log2, name) \ + {{bytes, log2}, shaders::name, uint32_t(sizeof(shaders::name))} +const LoadShader kLoadShaders[Types::kLoadShaderCount] = { + R360_LOAD_SHADER(1, 4, texture_load_8bpb_cs), + R360_LOAD_SHADER(2, 4, texture_load_16bpb_cs), + R360_LOAD_SHADER(4, 3, texture_load_32bpb_cs), + R360_LOAD_SHADER(8, 2, texture_load_64bpb_cs), + R360_LOAD_SHADER(16, 1, texture_load_128bpb_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g5b5a1_b5g5r5a1_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g6b5_b5g6r5_cs), + R360_LOAD_SHADER(2, 4, texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs), + R360_LOAD_SHADER(2, 4, texture_load_r4g4b4a4_b4g4r4a4_cs), + R360_LOAD_SHADER(2, 4, texture_load_r4g4b4a4_a4r4g4b4_cs), + R360_LOAD_SHADER(4, 3, texture_load_gbgr8_grgb8_cs), + R360_LOAD_SHADER(8, 3, texture_load_gbgr8_rgb8_cs), + R360_LOAD_SHADER(4, 3, texture_load_bgrg8_rgbg8_cs), + R360_LOAD_SHADER(8, 3, texture_load_bgrg8_rgb8_cs), + R360_LOAD_SHADER(8, 3, texture_load_r10g11b11_rgba16_cs), + R360_LOAD_SHADER(8, 3, texture_load_r10g11b11_rgba16_snorm_cs), + R360_LOAD_SHADER(8, 3, texture_load_r11g11b10_rgba16_cs), + R360_LOAD_SHADER(8, 3, texture_load_r11g11b10_rgba16_snorm_cs), + R360_LOAD_SHADER(2, 4, texture_load_r16_unorm_float_cs), + R360_LOAD_SHADER(2, 4, texture_load_r16_snorm_float_cs), + R360_LOAD_SHADER(4, 3, texture_load_rg16_unorm_float_cs), + R360_LOAD_SHADER(4, 3, texture_load_rg16_snorm_float_cs), + R360_LOAD_SHADER(8, 2, texture_load_rgba16_unorm_float_cs), + R360_LOAD_SHADER(8, 2, texture_load_rgba16_snorm_float_cs), + R360_LOAD_SHADER(4, 2, texture_load_dxt1_rgba8_cs), + R360_LOAD_SHADER(4, 1, texture_load_dxt3_rgba8_cs), + R360_LOAD_SHADER(4, 1, texture_load_dxt5_rgba8_cs), + R360_LOAD_SHADER(2, 1, texture_load_dxn_rg8_cs), + R360_LOAD_SHADER(1, 2, texture_load_dxt3a_cs), + R360_LOAD_SHADER(2, 2, texture_load_dxt3aas1111_bgra4_cs), + R360_LOAD_SHADER(2, 2, texture_load_dxt3aas1111_argb4_cs), + R360_LOAD_SHADER(1, 2, texture_load_dxt5a_r8_cs), + R360_LOAD_SHADER(2, 2, texture_load_ctx1_cs), + R360_LOAD_SHADER(4, 3, texture_load_depth_unorm_cs), + R360_LOAD_SHADER(4, 3, texture_load_depth_float_cs), +}; +#undef R360_LOAD_SHADER + +// VulkanTextureCache::HostFormat for WebGPU. +struct HostFormat { + LoadShaderIndex load_shader = kUnknown; + WebGpuTextureFormat format = kWebGpuFormatNone; + WebGpuTextureExpand expand = kWebGpuExpandNone; + bool linear_filterable = true; +}; +struct HostFormatPair { + HostFormat format_unsigned; + HostFormat format_signed; + uint32_t swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; +}; + +// VulkanTextureCache::kBestHostFormats with its fallbacks for formats +// WebGPU lacks: S3TC, DXN and DXT5A decompressed (BC is optional in +// WebGPU and absent on iOS), 4:2:2 to RGBA8, 16-bit normalized through the +// *ToFloat load shaders, and 16-bit packed formats expanded to RGBA8. +const HostFormatPair* HostFormats() { + static HostFormatPair formats[64]; + static bool initialized = false; + if (initialized) return formats; + initialized = true; + using F = xenos::TextureFormat; + auto set = [](F f, HostFormat u, HostFormat s, uint32_t swizzle) { + formats[uint32_t(f)] = {u, s, swizzle}; + }; + constexpr uint32_t RRRR = xenos::XE_GPU_TEXTURE_SWIZZLE_RRRR; + constexpr uint32_t RGGG = xenos::XE_GPU_TEXTURE_SWIZZLE_RGGG; + constexpr uint32_t RGBA = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; + constexpr uint32_t RGBB = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBB; + const HostFormat none; + auto h = [](LoadShaderIndex shader, WebGpuTextureFormat format, + WebGpuTextureExpand expand = kWebGpuExpandNone, bool filterable = true) { + return HostFormat{shader, format, expand, filterable}; + }; + set(F::k_1_REVERSE, none, none, RRRR); + set(F::k_1, none, none, RRRR); + set(F::k_8, h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Unorm), + h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Snorm), RRRR); + set(F::k_1_5_5_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand1555), + none, RGBA); + set(F::k_5_6_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand565), + none, RGBB); + // On the host, green bits in blue, blue bits in green (as Xenia's + // R5G5B6ToB5G6R5WithRBGASwizzle). + set(F::k_6_5_5, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand655), + none, XE_GPU_MAKE_TEXTURE_SWIZZLE(R, B, G, G)); + set(F::k_8_8_8_8, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Snorm), RGBA); + // No snorm 10:10:10:2 in WebGPU. + set(F::k_2_10_10_10, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGB10A2Unorm), none, RGBA); + set(F::k_8_A, h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Unorm), + h(Types::kLoadShaderIndex8bpb, kWebGpuFormatR8Snorm), RRRR); + set(F::k_8_B, none, none, RRRR); + set(F::k_8_8, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRG8Unorm), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRG8Snorm), RGGG); + set(F::k_Cr_Y1_Cb_Y0_REP, h(Types::kLoadShaderIndexGBGR8ToRGB8, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndexGBGR8ToRGB8, kWebGpuFormatRGBA8Snorm), RGBB); + set(F::k_Y1_Cr_Y0_Cb_REP, h(Types::kLoadShaderIndexBGRG8ToRGB8, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndexBGRG8ToRGB8, kWebGpuFormatRGBA8Snorm), RGBB); + set(F::k_16_16_EDRAM, none, none, RGGG); + set(F::k_8_8_8_8_A, none, none, RGBA); + set(F::k_4_4_4_4, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatRGBA8Unorm, kWebGpuExpand4444), + none, RGBA); + set(F::k_10_11_11, + h(Types::kLoadShaderIndexR11G11B10ToRGBA16, kWebGpuFormatRGBA16Float, kWebGpuExpandUnorm16ToFloat), + h(Types::kLoadShaderIndexR11G11B10ToRGBA16SNorm, kWebGpuFormatRGBA16Float, + kWebGpuExpandSnorm16ToFloat), + RGBB); + set(F::k_11_11_10, + h(Types::kLoadShaderIndexR10G11B11ToRGBA16, kWebGpuFormatRGBA16Float, kWebGpuExpandUnorm16ToFloat), + h(Types::kLoadShaderIndexR10G11B11ToRGBA16SNorm, kWebGpuFormatRGBA16Float, + kWebGpuExpandSnorm16ToFloat), + RGBB); + set(F::k_DXT1, h(Types::kLoadShaderIndexDXT1ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_DXT2_3, h(Types::kLoadShaderIndexDXT3ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_DXT4_5, h(Types::kLoadShaderIndexDXT5ToRGBA8, kWebGpuFormatRGBA8Unorm), none, RGBA); + set(F::k_16_16_16_16_EDRAM, none, none, RGBA); + // Depth as R32_SFLOAT; filterable only with float32-filterable, which is + // optional (sampled with point filtering, as Xenia does for formats + // without linear filtering). + set(F::k_24_8, h(Types::kLoadShaderIndexDepthUnorm, kWebGpuFormatR32Float, kWebGpuExpandNone, false), + none, RRRR); + set(F::k_24_8_FLOAT, + h(Types::kLoadShaderIndexDepthFloat, kWebGpuFormatR32Float, kWebGpuExpandNone, false), none, + RRRR); + set(F::k_16, h(Types::kLoadShaderIndexR16UNormToFloat, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndexR16SNormToFloat, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16, h(Types::kLoadShaderIndexRG16UNormToFloat, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndexRG16SNormToFloat, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16, h(Types::kLoadShaderIndexRGBA16UNormToFloat, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndexRGBA16SNormToFloat, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_16_EXPAND, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16_EXPAND, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16_EXPAND, h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_16_FLOAT, h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), + h(Types::kLoadShaderIndex16bpb, kWebGpuFormatR16Float), RRRR); + set(F::k_16_16_FLOAT, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRG16Float), RGGG); + set(F::k_16_16_16_16_FLOAT, h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), + h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRGBA16Float), RGBA); + set(F::k_32, none, none, RRRR); + set(F::k_32_32, none, none, RGGG); + set(F::k_32_32_32_32, none, none, RGBA); + const HostFormat r32f = h(Types::kLoadShaderIndex32bpb, kWebGpuFormatR32Float, kWebGpuExpandNone, false); + set(F::k_32_FLOAT, r32f, r32f, RRRR); + const HostFormat rg32f = h(Types::kLoadShaderIndex64bpb, kWebGpuFormatRG32Float, kWebGpuExpandNone, false); + set(F::k_32_32_FLOAT, rg32f, rg32f, RGGG); + const HostFormat rgba32f = + h(Types::kLoadShaderIndex128bpb, kWebGpuFormatRGBA32Float, kWebGpuExpandNone, false); + set(F::k_32_32_32_32_FLOAT, rgba32f, rgba32f, RGBA); + set(F::k_32_AS_8, none, none, RRRR); + set(F::k_32_AS_8_8, none, none, RGGG); + set(F::k_16_MPEG, none, none, RRRR); + set(F::k_16_16_MPEG, none, none, RGGG); + set(F::k_8_INTERLACED, none, none, RRRR); + set(F::k_32_AS_8_INTERLACED, none, none, RRRR); + set(F::k_32_AS_8_8_INTERLACED, none, none, RGGG); + set(F::k_16_INTERLACED, none, none, RRRR); + set(F::k_16_MPEG_INTERLACED, none, none, RRRR); + set(F::k_16_16_MPEG_INTERLACED, none, none, RGGG); + set(F::k_DXN, h(Types::kLoadShaderIndexDXNToRG8, kWebGpuFormatRG8Unorm), none, RGGG); + set(F::k_8_8_8_8_AS_16_16_16_16, h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Unorm), + h(Types::kLoadShaderIndex32bpb, kWebGpuFormatRGBA8Snorm), RGBA); + formats[uint32_t(F::k_DXT1_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT1)]; + formats[uint32_t(F::k_DXT2_3_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT2_3)]; + formats[uint32_t(F::k_DXT4_5_AS_16_16_16_16)] = formats[uint32_t(F::k_DXT4_5)]; + formats[uint32_t(F::k_2_10_10_10_AS_16_16_16_16)] = formats[uint32_t(F::k_2_10_10_10)]; + formats[uint32_t(F::k_10_11_11_AS_16_16_16_16)] = formats[uint32_t(F::k_10_11_11)]; + formats[uint32_t(F::k_11_11_10_AS_16_16_16_16)] = formats[uint32_t(F::k_11_11_10)]; + set(F::k_32_32_32_FLOAT, none, none, RGBB); + set(F::k_DXT3A, h(Types::kLoadShaderIndexDXT3A, kWebGpuFormatR8Unorm), none, RRRR); + set(F::k_DXT5A, h(Types::kLoadShaderIndexDXT5AToR8, kWebGpuFormatR8Unorm), none, RRRR); + set(F::k_CTX1, h(Types::kLoadShaderIndexCTX1, kWebGpuFormatRG8Unorm), none, RGGG); + // Xenia loads DXT3A_AS_1_1_1_1 into 4:4:4:4, which WebGPU lacks (not yet). + set(F::k_DXT3A_AS_1_1_1_1, none, none, RGBA); + set(F::k_8_8_8_8_GAMMA_EDRAM, none, none, RGBA); + set(F::k_2_10_10_10_FLOAT_EDRAM, none, none, RGBA); + return formats; +} + +const HostFormatPair& GetHostFormatPair(const TextureKey& key) { + return HostFormats()[uint32_t(key.format)]; +} + +// Unsigned and signed versions are separate textures whenever both exist +// with different formats: WebGPU views cannot reinterpret unorm as snorm +// (Vulkan's mutable-format images can, for Xenia's +// unsigned_signed_compatible formats). +bool IsSignedVersionSeparateForFormat(const TextureKey& key) { + const HostFormatPair& pair = GetHostFormatPair(key); + return pair.format_unsigned.format && pair.format_signed.format && + pair.format_unsigned.format != pair.format_signed.format; +} + +const HostFormat& GetHostFormat(const TextureKey& key) { + const HostFormatPair& pair = GetHostFormatPair(key); + bool is_signed = IsSignedVersionSeparateForFormat(key) + ? bool(key.signed_separate) + : pair.format_unsigned.load_shader == kUnknown; + return is_signed ? pair.format_signed : pair.format_unsigned; +} + +// Guest physical pages backing a texture, with the GPU write-watch +// generation each had when loaded (Xenia watches them with memory access +// watches; here the sparse guest memory GPU watch). +struct PageRange { + std::vector generations; + uint32_t first_page = 0; + void Watch(uint32_t start, uint32_t length) { + generations.clear(); + if (!length) return; + first_page = start >> 12; + const uint32_t last_page = (start + length - 1) >> 12; + for (uint32_t page = first_page; page <= last_page; ++page) { + generations.push_back(SparseGuestGpuWatch(r360_kernel_gpu_address_to_virtual(page << 12))); + } + } + bool Outdated() const { + for (size_t i = 0; i < generations.size(); ++i) { + const uint32_t page = first_page + uint32_t(i); + if (generations[i] != SparseGuestGpuGeneration(r360_kernel_gpu_address_to_virtual(page << 12))) { + return true; + } + } + return false; + } +}; + +struct Texture { + TextureKey key; + uint32_t id = 0; + texture_util::TextureGuestLayout guest_layout; + bool loaded_base = false, loaded_mips = false; + PageRange base_pages, mip_pages; + uint32_t GetGuestBaseSize() const { return guest_layout.base.level_data_extent_bytes; } + uint32_t GetGuestMipsSize() const { return guest_layout.mips_total_extent_bytes; } +}; + +struct TextureKeyHasher { + size_t operator()(const TextureKey& key) const { + uint64_t words[2] = {}; + std::memcpy(words, &key, std::min(sizeof(key), sizeof(words))); + uint64_t h = words[0] * 0x9E3779B97F4A7C15ull ^ words[1]; + return size_t(h ^ (h >> 29)); + } +}; + +// TextureCache::TextureBinding. +struct TextureBinding { + TextureKey key; + uint32_t host_swizzle = 0; + uint8_t swizzled_signs = 0; + Texture* texture = nullptr; + Texture* texture_signed = nullptr; + void Reset() { + key.MakeInvalid(); + host_swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_0000; + swizzled_signs = uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); + texture = nullptr; + texture_signed = nullptr; + } +}; + +struct Cache { + std::unordered_map, TextureKeyHasher> textures; + TextureBinding bindings[32]; + uint32_t next_id = 1; + bool load_shader_sent[Types::kLoadShaderCount] = {}; + uint32_t loads = 0, load_failures = 0, created = 0; +}; +Cache& cache() { + static Cache c; + return c; +} + +// TextureCache::BindingInfoFromFetchConstant. +void BindingInfoFromFetchConstant(const xenos::xe_gpu_texture_fetch_t& fetch, TextureKey& key_out, + uint8_t* swizzled_signs_out) { + key_out.MakeInvalid(); + if (swizzled_signs_out) { + *swizzled_signs_out = uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); + } + // gpu_allow_invalid_fetch_constants is off by default in Xenia. + if (fetch.type != xenos::FetchConstantType::kTexture) return; + uint32_t width_minus_1, height_minus_1, depth_or_array_size_minus_1; + uint32_t base_page, mip_page, mip_max_level; + texture_util::GetSubresourcesFromFetchConstant(fetch, &width_minus_1, &height_minus_1, + &depth_or_array_size_minus_1, &base_page, + &mip_page, nullptr, &mip_max_level); + if (base_page == 0 && mip_page == 0) return; + if (fetch.dimension == xenos::DataDimension::k1D) { + if (width_minus_1 >= xenos::kTexture2DCubeMaxWidthHeight || fetch.tiled || fetch.packed_mips) { + return; + } + } + key_out.base_page = base_page; + key_out.mip_page = mip_page; + key_out.dimension = fetch.dimension; + key_out.width_minus_1 = width_minus_1; + key_out.height_minus_1 = height_minus_1; + key_out.depth_or_array_size_minus_1 = depth_or_array_size_minus_1; + key_out.pitch = fetch.pitch; + key_out.mip_max_level = mip_max_level; + key_out.tiled = fetch.tiled; + key_out.packed_mips = fetch.packed_mips; + key_out.format = GetBaseFormat(fetch.format); + key_out.endianness = fetch.endianness; + key_out.is_valid = 1; + if (swizzled_signs_out) *swizzled_signs_out = texture_util::SwizzleSigns(fetch); +} + +// The stream's texture dimensions: 0 2D array (1D and 2D), 1 3D, 2 cube. +uint32_t StreamDimension(xenos::DataDimension dimension) { + switch (dimension) { + case xenos::DataDimension::k3D: return 1; + case xenos::DataDimension::kCube: return 2; + default: return 0; + } +} + +// TextureCache::FindOrCreateTexture and VulkanTextureCache::CreateTexture. +Texture* FindOrCreateTexture(const TextureKey& key) { + Cache& c = cache(); + // WebGPU guaranteed limits (maxTextureDimension2D / 3D, array layers). + constexpr uint32_t kMax2D = 8192, kMax3D = 2048, kMaxLayers = 256; + const uint32_t max_width_height = key.dimension == xenos::DataDimension::k3D ? kMax3D : kMax2D; + const uint32_t max_depth = key.dimension == xenos::DataDimension::k3D ? kMax3D + : key.dimension == xenos::DataDimension::kCube ? 6u + : kMaxLayers; + if (key.GetWidth() > max_width_height || key.GetHeight() > max_width_height || + key.GetDepthOrArraySize() > max_depth) { + return nullptr; + } + if (auto it = c.textures.find(key); it != c.textures.end()) return it->second.get(); + const HostFormat& host_format = GetHostFormat(key); + if (!host_format.format || host_format.load_shader == kUnknown) return nullptr; + auto texture = std::make_unique(); + texture->key = key; + texture->id = c.next_id++; + texture->guest_layout = key.GetGuestLayout(); + uint32_t* w = GpuStream().Begin(kGpuStreamTexture, 7); + w[0] = texture->id; + w[1] = host_format.format; + w[2] = StreamDimension(key.dimension); + w[3] = key.GetWidth(); + w[4] = key.GetHeight(); + w[5] = key.GetDepthOrArraySize(); + w[6] = key.mip_max_level + 1; + ++c.created; + Texture* result = texture.get(); + c.textures.emplace(key, std::move(texture)); + return result; +} + +void SendLoadShader(LoadShaderIndex index) { + Cache& c = cache(); + if (c.load_shader_sent[index]) return; + c.load_shader_sent[index] = true; + const LoadShader& shader = kLoadShaders[index]; + uint32_t* w = GpuStream().Begin(kGpuStreamLoadShader, 2 + shader.spirv_bytes / 4); + w[0] = index; + w[1] = shader.spirv_bytes / 4; + std::memcpy(w + 2, shader.spirv, shader.spirv_bytes); +} + +// VulkanTextureCache::LoadTextureDataFromResidentMemoryImpl: the load +// shader dispatches into a scratch buffer and the copies from it into the +// texture, as one stream op. Host rows are padded to WebGPU's 256-byte +// bytesPerRow alignment for buffer to texture copies. +bool LoadTextureData(Texture& texture, bool load_base, bool load_mips) { + const TextureKey& key = texture.key; + const HostFormat& host_format = GetHostFormat(key); + const LoadShaderIndex load_shader = host_format.load_shader; + if (load_shader == kUnknown) return false; + const Types::LoadShaderInfo& load_shader_info = kLoadShaders[load_shader].info; + + const texture_util::TextureGuestLayout& guest_layout = texture.guest_layout; + const xenos::DataDimension dimension = key.dimension; + const bool is_3d = dimension == xenos::DataDimension::k3D; + const uint32_t width = key.GetWidth(), height = key.GetHeight(); + const uint32_t depth_or_array_size = key.GetDepthOrArraySize(); + const uint32_t depth = is_3d ? depth_or_array_size : 1; + const uint32_t array_size = is_3d ? 1 : depth_or_array_size; + const xenos::TextureFormat guest_format = key.format; + const FormatInfo* guest_format_info = FormatInfo::Get(guest_format); + const uint32_t block_width = guest_format_info->block_width; + const uint32_t block_height = guest_format_info->block_height; + const uint32_t bytes_per_block = guest_format_info->bytes_per_block(); + const uint32_t level_first = load_base ? 0 : 1; + const uint32_t level_last = load_mips ? key.mip_max_level : 0; + if (level_first > level_last) return true; + const uint32_t level_packed = guest_layout.packed_level; + const uint32_t level_stored_first = std::min(level_first, level_packed); + const uint32_t level_stored_last = std::min(level_last, level_packed); + uint32_t loop_level_first, loop_level_last; + if (level_packed == 0) { + loop_level_first = uint32_t(level_first != 0); + loop_level_last = uint32_t(level_last != 0); + } else { + loop_level_first = level_stored_first; + loop_level_last = level_stored_last; + } + + // Host layout (no resolution scale, host formats never block-compressed). + uint32_t host_x_blocks_per_thread = (1u << load_shader_info.guest_x_blocks_per_thread_log2) * block_width; + // bytesPerRow multiple of 256 (of 128 when expanded to twice the size). + const uint32_t row_alignment_bytes = + (host_format.expand >= kWebGpuExpand565 && host_format.expand <= kWebGpuExpand4444) ? 128u : 256u; + const uint32_t row_alignment_blocks = std::max(row_alignment_bytes / load_shader_info.bytes_per_host_block, 1u); + const uint32_t x_pitch_alignment = std::max(host_x_blocks_per_thread, row_alignment_blocks); + struct HostLayout { + uint32_t offset_bytes, slice_size_bytes, x_pitch_blocks, y_pitch_blocks; + }; + HostLayout host_layout_base{}, host_layout_mips[xenos::kTextureMaxMips]{}; + uint32_t host_buffer_size = 0; + for (uint32_t loop_level = loop_level_first; loop_level <= loop_level_last; ++loop_level) { + const bool is_base = loop_level == 0; + const uint32_t level = level_packed == 0 ? 0 : loop_level; + HostLayout& l = is_base ? host_layout_base : host_layout_mips[level]; + l.offset_bytes = host_buffer_size; + uint32_t x_texels, y_texels, z_texels; + if (level == level_packed) { + const auto& packed = is_base ? guest_layout.base : guest_layout.mips[level]; + x_texels = packed.x_extent_blocks * block_width; + y_texels = packed.y_extent_blocks * block_height; + z_texels = packed.z_extent; + } else { + x_texels = std::max(width >> level, 1u); + y_texels = std::max(height >> level, 1u); + z_texels = std::max(depth >> level, 1u); + } + l.x_pitch_blocks = xe::round_up(x_texels, x_pitch_alignment); + l.y_pitch_blocks = y_texels; + l.slice_size_bytes = load_shader_info.bytes_per_host_block * l.x_pitch_blocks * l.y_pitch_blocks * z_texels; + host_buffer_size += l.slice_size_bytes * array_size; + } + host_buffer_size = xe::align(host_buffer_size, 16u); + + // Guest data in the shared memory buffer. + const uint32_t base_offset = key.base_page << 12, mips_offset = key.mip_page << 12; + const uint32_t base_size = xe::align(texture.GetGuestBaseSize(), 16u); + const uint32_t mips_size = xe::align(texture.GetGuestMipsSize(), 16u); + if (level_first == 0 && !GpuSharedMemory().RequestRange(base_offset, base_size)) return false; + if (level_last != 0 && !GpuSharedMemory().RequestRange(mips_offset, mips_size)) return false; + SendLoadShader(load_shader); + + // Dispatches: source (0 base, 1 mips), LoadConstants (10 words), groups. + struct Dispatch { + uint32_t source; + Types::LoadConstants constants; + uint32_t groups[3]; + }; + static_assert(sizeof(Types::LoadConstants) == 40, "LoadConstants layout"); + std::vector dispatches; + Types::LoadConstants load_constants{}; + load_constants.is_tiled_3d_endian_scale = uint32_t(key.tiled) | (uint32_t(is_3d) << 1) | + (uint32_t(key.endianness) << 2) | (1u << 4) | (1u << 7); + const uint32_t guest_x_blocks_per_group_log2 = + Types::kLoadGuestXThreadsPerGroupLog2 + load_shader_info.guest_x_blocks_per_thread_log2; + for (uint32_t loop_level = loop_level_first; loop_level <= loop_level_last; ++loop_level) { + const bool is_base = loop_level == 0; + const uint32_t level = level_packed == 0 ? 0 : loop_level; + load_constants.guest_offset = is_base ? 0 : guest_layout.mip_offsets_bytes[level]; + const auto& level_guest_layout = is_base ? guest_layout.base : guest_layout.mips[level]; + load_constants.guest_pitch_aligned = level_guest_layout.row_pitch_bytes / bytes_per_block; + load_constants.guest_z_stride_block_rows_aligned = level_guest_layout.z_slice_stride_block_rows; + uint32_t level_width, level_height, level_depth; + if (level == level_packed) { + level_width = level_guest_layout.x_extent_blocks * block_width; + level_height = level_guest_layout.y_extent_blocks * block_height; + level_depth = level_guest_layout.z_extent; + } else { + level_width = std::max(width >> level, 1u); + level_height = std::max(height >> level, 1u); + level_depth = std::max(depth >> level, 1u); + } + load_constants.size_blocks[0] = (level_width + (block_width - 1)) / block_width; + load_constants.size_blocks[1] = (level_height + (block_height - 1)) / block_height; + load_constants.size_blocks[2] = level_depth; + load_constants.height_texels = level_height; + const uint32_t group_count_x = + (load_constants.size_blocks[0] + ((1u << guest_x_blocks_per_group_log2) - 1)) >> + guest_x_blocks_per_group_log2; + const uint32_t group_count_y = + (load_constants.size_blocks[1] + ((1u << Types::kLoadGuestYBlocksPerGroupLog2) - 1)) >> + Types::kLoadGuestYBlocksPerGroupLog2; + const HostLayout& l = is_base ? host_layout_base : host_layout_mips[level]; + load_constants.host_offset = l.offset_bytes; + load_constants.host_pitch = load_shader_info.bytes_per_host_block * l.x_pitch_blocks; + for (uint32_t slice = 0; slice < array_size; ++slice) { + dispatches.push_back({is_base ? 0u : 1u, load_constants, {group_count_x, group_count_y, load_constants.size_blocks[2]}}); + load_constants.guest_offset += level_guest_layout.array_slice_stride_bytes; + load_constants.host_offset += l.slice_size_bytes; + } + } + + // Copies: buffer offset, bytes per row, rows per image, mip level, + // layers, width, height, depth. + struct Copy { + uint32_t words[8]; + }; + std::vector copies; + for (uint32_t level = level_first; level <= level_last; ++level) { + const HostLayout& l = level != 0 ? host_layout_mips[std::min(level, level_packed)] : host_layout_base; + uint32_t buffer_offset = l.offset_bytes; + if (level >= level_packed) { + uint32_t offset_x, offset_y, offset_z; + texture_util::GetPackedMipOffset(width, height, depth, guest_format, level, offset_x, offset_y, + offset_z); + offset_x *= block_width; + offset_y *= block_height; + buffer_offset += load_shader_info.bytes_per_host_block * + (offset_x + l.x_pitch_blocks * (offset_y + l.y_pitch_blocks * offset_z)); + } + copies.push_back({{buffer_offset, l.x_pitch_blocks * load_shader_info.bytes_per_host_block, l.y_pitch_blocks, + level, array_size, std::max(width >> level, 1u), std::max(height >> level, 1u), + std::max(depth >> level, 1u)}}); + } + + // id, load shader, expand, host buffer size, base offset / size, mips + // offset / size, dispatch count, copy count, dispatches (14 words), copies + // (8 words). + const uint32_t words = 10 + uint32_t(dispatches.size()) * 14 + uint32_t(copies.size()) * 8; + uint32_t* w = GpuStream().Begin(kGpuStreamTextureLoad, words); + w[0] = texture.id; + w[1] = load_shader; + w[2] = host_format.expand; + w[3] = host_buffer_size; + w[4] = base_offset; + w[5] = base_size; + w[6] = mips_offset; + w[7] = mips_size; + w[8] = uint32_t(dispatches.size()); + w[9] = uint32_t(copies.size()); + w += 10; + for (const Dispatch& d : dispatches) { + *w++ = d.source; + std::memcpy(w, &d.constants, sizeof(d.constants)); + w += 10; + *w++ = d.groups[0]; + *w++ = d.groups[1]; + *w++ = d.groups[2]; + } + for (const Copy& copy : copies) { + std::memcpy(w, copy.words, sizeof(copy.words)); + w += 8; + } + return true; +} + +// TextureCache::LoadTextureData: loads what CPU writes have outdated. +void MakeUpToDate(Texture& texture) { + const bool has_base = texture.key.base_page != 0; + const bool has_mips = texture.key.mip_max_level != 0 && texture.key.mip_page != 0; + const bool base_outdated = has_base && (!texture.loaded_base || texture.base_pages.Outdated()); + const bool mips_outdated = has_mips && (!texture.loaded_mips || texture.mip_pages.Outdated()); + if (!base_outdated && !mips_outdated) return; + Cache& c = cache(); + if (!LoadTextureData(texture, base_outdated, mips_outdated)) { + ++c.load_failures; + return; + } + ++c.loads; + if (base_outdated) { + texture.loaded_base = true; + texture.base_pages.Watch(texture.key.base_page << 12, texture.GetGuestBaseSize()); + } + if (mips_outdated) { + texture.loaded_mips = true; + texture.mip_pages.Watch(texture.key.mip_page << 12, texture.GetGuestMipsSize()); + } +} + +} // namespace + +// TextureCache::RequestTextures, rechecking every used binding each draw +// (the bindings stay as Xenia keeps them; pages are checked against their +// write generations instead of watch callbacks). +void WebGpuRequestTextures(const RegisterFile& regs, uint32_t used_texture_mask) { + Cache& c = cache(); + uint32_t remaining = used_texture_mask, index; + while (xe::bit_scan_forward(remaining, &index)) { + remaining &= ~(1u << index); + TextureBinding& binding = c.bindings[index]; + const xenos::xe_gpu_texture_fetch_t fetch = regs.GetTextureFetch(index); + TextureKey key; + uint8_t swizzled_signs; + BindingInfoFromFetchConstant(fetch, key, &swizzled_signs); + if (!key.is_valid) { + binding.Reset(); + continue; + } + binding.key = key; + binding.swizzled_signs = swizzled_signs; + binding.host_swizzle = Types::GuestToHostSwizzle(fetch.swizzle, GetHostFormatPair(key).swizzle); + binding.texture = nullptr; + binding.texture_signed = nullptr; + if (IsSignedVersionSeparateForFormat(key)) { + if (texture_util::IsAnySignNotSigned(swizzled_signs)) binding.texture = FindOrCreateTexture(key); + if (texture_util::IsAnySignSigned(swizzled_signs)) { + TextureKey signed_key = key; + signed_key.signed_separate = 1; + binding.texture_signed = FindOrCreateTexture(signed_key); + } + } else { + binding.texture = FindOrCreateTexture(key); + } + if (binding.texture) MakeUpToDate(*binding.texture); + if (binding.texture_signed) MakeUpToDate(*binding.texture_signed); + } +} + +// VulkanTextureCache::GetActiveBindingOrNullImageView. +uint32_t WebGpuTextureForBinding(const SpirvShader::TextureBinding& shader_binding) { + const TextureBinding& binding = cache().bindings[shader_binding.fetch_constant]; + if (!binding.key.is_valid || + !Types::AreDimensionsCompatible(shader_binding.dimension, binding.key.dimension)) { + return 0; + } + const Texture* texture = binding.texture; + if (shader_binding.is_signed && IsSignedVersionSeparateForFormat(binding.key)) { + texture = binding.texture_signed; + } + return texture && (texture->loaded_base || texture->loaded_mips) ? texture->id : 0; +} + +// VulkanTextureCache::RequestSwapTexture. +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant) { + xenos::xe_gpu_texture_fetch_t fetch; + std::memcpy(&fetch, fetch_constant, sizeof(fetch)); + TextureKey key; + BindingInfoFromFetchConstant(fetch, key, nullptr); + if (!key.is_valid || !key.base_page || key.dimension != xenos::DataDimension::k2DOrStacked) return 0; + Texture* texture = FindOrCreateTexture(key); + if (!texture) return 0; + MakeUpToDate(*texture); + return texture->loaded_base ? texture->id : 0; +} + +void WebGpuTexturesMarkRangeResolved(uint32_t start, uint32_t length) { + if (!length) return; + const uint32_t end = start + length; + for (auto& [key, texture] : cache().textures) { + const uint32_t base = key.base_page << 12, mips = key.mip_page << 12; + if (texture->loaded_base && base < end && start < base + texture->GetGuestBaseSize()) { + texture->loaded_base = false; + } + if (texture->loaded_mips && mips < end && start < mips + texture->GetGuestMipsSize()) { + texture->loaded_mips = false; + } + } +} + +uint32_t WebGpuTextureHostSwizzle(uint32_t fetch_constant) { + const TextureBinding& binding = cache().bindings[fetch_constant & 31]; + return binding.key.is_valid ? binding.host_swizzle : xenos::XE_GPU_TEXTURE_SWIZZLE_0000; +} + +uint8_t WebGpuTextureSwizzledSigns(uint32_t fetch_constant) { + const TextureBinding& binding = cache().bindings[fetch_constant & 31]; + return binding.key.is_valid ? binding.swizzled_signs + : uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); +} + +// VulkanTextureCache::GetSamplerParameters, packed: clamp x / y / z (3 bits +// each), border color (2), mag / min / mip linear, aniso filter (3), mip +// base map, mip min level (4). +uint32_t WebGpuSamplerParameters(const RegisterFile& regs, const SpirvShader::SamplerBinding& binding) { + const xenos::xe_gpu_texture_fetch_t fetch = regs.GetTextureFetch(binding.fetch_constant); + xenos::ClampMode clamp[3]; + texture_util::GetClampModesForDimension(fetch, clamp[0], clamp[1], clamp[2]); + // NormalizeClampMode: no clamp to halfway; mirror clamp falls back to + // mirrored repeat (WebGPU has neither mirror clamp nor border colors). + for (auto& mode : clamp) { + if (mode == xenos::ClampMode::kClampToHalfway) mode = xenos::ClampMode::kClampToEdge; + if (mode == xenos::ClampMode::kMirrorClampToEdge || mode == xenos::ClampMode::kMirrorClampToHalfway || + mode == xenos::ClampMode::kMirrorClampToBorder) { + mode = xenos::ClampMode::kMirroredRepeat; + } + } + const bool border = xenos::ClampModeUsesBorder(clamp[0]) || xenos::ClampModeUsesBorder(clamp[1]) || + xenos::ClampModeUsesBorder(clamp[2]); + const uint32_t border_color = border ? uint32_t(fetch.border_color) : 0u; + auto filter = [](xenos::TextureFilter binding_filter, xenos::TextureFilter fetch_filter) { + return binding_filter == xenos::TextureFilter::kUseFetchConst ? fetch_filter : binding_filter; + }; + const xenos::TextureFilter mip_filter = filter(binding.mip_filter, fetch.mip_filter); + bool mag_linear = filter(binding.mag_filter, fetch.mag_filter) == xenos::TextureFilter::kLinear; + bool min_linear = filter(binding.min_filter, fetch.min_filter) == xenos::TextureFilter::kLinear; + bool mip_linear = mip_filter == xenos::TextureFilter::kLinear; + if (mag_linear || min_linear || mip_linear) { + TextureKey key; + uint8_t signs; + BindingInfoFromFetchConstant(fetch, key, &signs); + bool linear_filterable = key.is_valid; + if (key.is_valid) { + const HostFormatPair& pair = GetHostFormatPair(key); + if ((texture_util::IsAnySignNotSigned(signs) && !pair.format_unsigned.linear_filterable) || + (texture_util::IsAnySignSigned(signs) && !pair.format_signed.linear_filterable)) { + linear_filterable = false; + } + } + if (!linear_filterable) mag_linear = min_linear = mip_linear = false; + } + const xenos::AnisoFilter aniso_filter = std::min( + binding.aniso_filter == xenos::AnisoFilter::kUseFetchConst ? fetch.aniso_filter : binding.aniso_filter, + xenos::AnisoFilter::kMax_16_1); + uint32_t mip_min_level; + texture_util::GetSubresourcesFromFetchConstant(fetch, nullptr, nullptr, nullptr, nullptr, nullptr, + &mip_min_level, nullptr); + return uint32_t(clamp[0]) | (uint32_t(clamp[1]) << 3) | (uint32_t(clamp[2]) << 6) | (border_color << 9) | + (uint32_t(mag_linear) << 11) | (uint32_t(min_linear) << 12) | (uint32_t(mip_linear) << 13) | + (uint32_t(aniso_filter) << 14) | (uint32_t(mip_filter == xenos::TextureFilter::kBaseMap) << 17) | + (std::min(mip_min_level, 15u) << 18); +} + +} // namespace render360::xenia_web + +namespace rx = render360::xenia_web; + +extern "C" { +// 0 textures, 1 created, 2 loads, 3 load failures. +__attribute__((used, export_name("r360_gpu_texture_stat"))) +uint32_t r360_gpu_texture_stat(uint32_t index) { + auto& c = rx::cache(); + switch (index) { + case 0: return uint32_t(c.textures.size()); + case 1: return c.created; + case 2: return c.loads; + case 3: return c.load_failures; + default: return 0; + } +} +} // extern "C" diff --git a/src/xenia_web_bootstrap/webgpu_textures.h b/src/xenia_web_bootstrap/webgpu_textures.h new file mode 100644 index 00000000..92e66007 --- /dev/null +++ b/src/xenia_web_bootstrap/webgpu_textures.h @@ -0,0 +1,73 @@ +#pragma once + +// WebGPU texture cache (webgpu_textures.cpp): a port of Xenia's TextureCache +// (src/xenia/gpu/texture_cache.cc) with VulkanTextureCache's host formats and +// texture loading. Textures are untiled and converted on the GPU by Xenia's +// texture_load_* compute shaders reading the shared memory buffer, as Xenia +// does, then copied into WebGPU textures. + +#include + +#include "xenia/gpu/register_file.h" +#include "xenia/gpu/spirv_shader.h" + +namespace render360::xenia_web { + +// WebGPU texture formats (render360-webgpu-backend.mjs TEXTURE_FORMATS). +enum WebGpuTextureFormat : uint32_t { + kWebGpuFormatNone = 0, + kWebGpuFormatR8Unorm, + kWebGpuFormatR8Snorm, + kWebGpuFormatRG8Unorm, + kWebGpuFormatRG8Snorm, + kWebGpuFormatRGBA8Unorm, + kWebGpuFormatRGBA8Snorm, + kWebGpuFormatRGB10A2Unorm, + kWebGpuFormatR16Float, + kWebGpuFormatRG16Float, + kWebGpuFormatRGBA16Float, + kWebGpuFormatR32Float, + kWebGpuFormatRG32Float, + kWebGpuFormatRGBA32Float, +}; + +// Second pass over the load shader output where WebGPU has no format for +// what Xenia's Vulkan backend loads into (render360-webgpu-backend.mjs). +enum WebGpuTextureExpand : uint32_t { + kWebGpuExpandNone = 0, + // Guest 16-bit packed texels (16bpb load: untiled, endian-swapped) to + // RGBA8 with the host component order of Xenia's Vulkan formats. + kWebGpuExpand565, + kWebGpuExpand655, + kWebGpuExpand1555, + kWebGpuExpand4444, + // 16-bit normalized components (Xenia's R16G16B16A16_UNORM / SNORM + // outputs) to float16 in place. + kWebGpuExpandUnorm16ToFloat, + kWebGpuExpandSnorm16ToFloat, +}; + +// Makes the textures of the fetch constants in `used_texture_mask` resident +// and up to date (Xenia's TextureCache::RequestTextures), recording texture +// creation and load ops. +void WebGpuRequestTextures(const xe::gpu::RegisterFile& regs, uint32_t used_texture_mask); + +// For the bindings of the last WebGpuRequestTextures: stream texture id for +// a shader texture binding (0: null texture), host swizzle and swizzled +// signs for the system constants, and the packed sampler parameters +// (render360-webgpu-backend.mjs sampler()). +uint32_t WebGpuTextureForBinding(const xe::gpu::SpirvShader::TextureBinding& binding); +uint32_t WebGpuTextureHostSwizzle(uint32_t fetch_constant); +uint8_t WebGpuTextureSwizzledSigns(uint32_t fetch_constant); +uint32_t WebGpuSamplerParameters(const xe::gpu::RegisterFile& regs, + const xe::gpu::SpirvShader::SamplerBinding& binding); + +// The front buffer texture of a swap (6 fetch constant words), loaded; 0 +// if there is none. +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant); + +// A resolve wrote the range on the GPU (TextureCache::MarkRangeAsResolved): +// textures in it are reloaded on their next use. +void WebGpuTexturesMarkRangeResolved(uint32_t start, uint32_t length); + +} // namespace render360::xenia_web diff --git a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp index 21f2b58e..c83c0e94 100644 --- a/src/xenia_web_bootstrap/xenos_soft_renderer.cpp +++ b/src/xenia_web_bootstrap/xenos_soft_renderer.cpp @@ -1220,7 +1220,11 @@ uint64_t MonotonicNs() { } bool RenderXenosDrawUntimed(const XenosSoftDraw& draw); bool RenderXenosDraw(const XenosSoftDraw& draw) { - if (!g_rasterize) return true; + if (!g_rasterize) { + // WebGPU play path: the software renderer does no work at all. + if (WebGpuBackendEnabled()) WebGpuIssueDraw(draw); + return true; + } const uint64_t start = MonotonicNs(); const bool ok = RenderXenosDrawUntimed(draw); g_render_ns += MonotonicNs() - start; diff --git a/test-webgpu-replay-capture-browser.mjs b/test-webgpu-replay-capture-browser.mjs index a3cb9f80..11f6070c 100644 --- a/test-webgpu-replay-capture-browser.mjs +++ b/test-webgpu-replay-capture-browser.mjs @@ -11,7 +11,7 @@ const capture=process.argv[2]||process.env.R360_GPU_CAPTURE; if(!capture||!fs.existsSync(capture)){console.log('WEBGPU_REPLAY_CAPTURE_SKIP (no local capture)');process.exit(0);} const dir=path.dirname(path.resolve(capture)),name=path.basename(capture); const reference=fs.existsSync(`${capture}.png`)?`/__data__/${name}.png`:null; -const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference],dataRoot:dir, +const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference,process.env.R360_DRAW_LIMIT?Number(process.env.R360_DRAW_LIMIT):null],dataRoot:dir, onConsole:t=>process.env.VERBOSE&&console.log(t)}); if(result.png){if(process.argv[3])fs.writeFileSync(process.argv[3],Buffer.from(result.png,'base64'));delete result.png;} console.log(JSON.stringify(result,null,1)); diff --git a/tests/browser/webgpu-replay-capture.mjs b/tests/browser/webgpu-replay-capture.mjs index 6daf58be..8449297a 100644 --- a/tests/browser/webgpu-replay-capture.mjs +++ b/tests/browser/webgpu-replay-capture.mjs @@ -11,14 +11,15 @@ async function decodePng(url){ return {width:bitmap.width,height:bitmap.height,pixels:ctx.getImageData(0,0,bitmap.width,bitmap.height).data}; } -export default async function run(captureUrl,referenceUrl){ +export default async function run(captureUrl,referenceUrl,drawLimit){ const adapter=await navigator.gpu?.requestAdapter(); if(!adapter)return {ok:false,error:'no WebGPU adapter'}; - const device=await adapter.requestDevice({requiredLimits:{ + const device=await adapter.requestDevice({requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)),requiredLimits:{ maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); const errors=[]; device.onuncapturederror=e=>{if(errors.length<20)errors.push(e.error.message.slice(0,400));}; const backend=await new XenosWebGpuBackend(device,null).init(); + if(drawLimit!==undefined&&drawLimit!==null)backend.drawLimit=drawLimit; const words=new Uint32Array(await (await fetch(captureUrl)).arrayBuffer()); const started=performance.now(); backend.replayWords(words); @@ -27,9 +28,14 @@ export default async function run(captureUrl,referenceUrl){ const replayMs=performance.now()-started; const shaderErrors=[...backend.shaders.values()].filter(s=>s.error).map(s=>`${s.id}: ${s.error.slice(0,300)}`).slice(0,5); const pipelineErrors=[...backend.pipelines.entries()].filter(([,p])=>p.error).map(([id,p])=>`${id}: ${p.error.slice(0,300)}`).slice(0,5); - const result={ok:true,stats:backend.stats,replayMs:Math.round(replayMs),shaderErrors,pipelineErrors,errors, + const loadShaderErrors=[...backend.loadShaders.entries()].filter(([,l])=>l.error).map(([i,l])=>`${i}: ${l.error.slice(0,300)}`).slice(0,5); + const result={ok:true,stats:backend.stats,loadShaderErrors,replayMs:Math.round(replayMs),shaderErrors,pipelineErrors,errors, targets:[...backend.targets.values()].map(t=>`${t.key} ${t.format} ${t.width}x${t.height}`)}; - const front=[...backend.targets.values()].find(t=>!t.depth&&t.base===0&&t.format==='rgba8unorm'); + // The swapped front buffer (resolved into shared memory, loaded by the + // texture cache), else the color render target at EDRAM base 0. + const front=(backend.frontTexture?.format==='rgba8unorm'?backend.frontTexture:null)|| + [...backend.targets.values()].find(t=>!t.depth&&t.base===0&&t.format==='rgba8unorm'); + result.front=front===backend.frontTexture?'front buffer':'render target'; if(front&&referenceUrl){ const got=await backend.readTarget(front),want=await decodePng(referenceUrl); const w=Math.min(got.width,want.width),h=Math.min(got.height,want.height); @@ -41,10 +47,14 @@ export default async function run(captureUrl,referenceUrl){ } result.compare={size:`${w}x${h}`,meanAbsDiff:+(diff/(w*h*3)).toFixed(2),closePixels:+(close/(w*h)).toFixed(4),litPixels:+(lit/(w*h)).toFixed(4)}; // The frame for viewing: PNG data URL of the WebGPU render target. + // Opaque for viewing (render target alpha is the game's, often 0). + for(let i=3;i(a.push(b),a),[]))); + const png=new Uint8Array(await blob.arrayBuffer());let text=''; + for(let i=0;i Date: Sat, 17 Oct 2026 13:20:24 +0000 Subject: [PATCH 47/65] WebGPU play path (opt-in), state reset on mode change, JIT compile logging - render360-webgpu-play.mjs: ?gpu=xenos runs the page on the WebGPU backend; the software renderer does no work and the swapped front buffer is presented from the GPU. - r360_gpu_set_mode resets shaders, pipelines, textures, load/resolve shaders and shared memory so a new stream consumer starts consistent. - R360_JIT_LOG_SEQ / R360_JIT_LOG_DUMP print the guest function, HIR and wasm of chosen compile requests (naming a bisected miscompile). - PROGRESS.md: step 2 section. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- PROGRESS.md | 24 ++++++++++ render360-browser-modern-content-bridge.mjs | 22 ++++++++- render360-guest-fibers.mjs | 3 +- render360-webgpu-backend.mjs | 39 ++++++++++++++++ render360-webgpu-play.mjs | 52 +++++++++++++++++++++ src/xenia_web_bootstrap/hir_wasm_jit.cpp | 46 ++++++++++++++++++ src/xenia_web_bootstrap/webgpu_draws.cpp | 18 +++++-- src/xenia_web_bootstrap/webgpu_textures.cpp | 7 +++ src/xenia_web_bootstrap/webgpu_textures.h | 3 ++ tools/run-title.mjs | 3 +- 10 files changed, 210 insertions(+), 7 deletions(-) create mode 100644 render360-webgpu-play.mjs diff --git a/PROGRESS.md b/PROGRESS.md index 74cdbd65..342337b6 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -118,6 +118,30 @@ Next: cut the per-call path (JIT → resolver → cache → executor → JIT), w is now the largest cost: 74.5M guest calls go through ~10 host frames each, all instrumented by Asyncify for guest-thread fibers. +## Step 2: WebGPU renderer (in progress) +A port of Xenia's Vulkan backend (docs/gpu/WEBGPU_BACKEND.md). + +- **Core side:** records a command stream. +- **Replay:** `render360-webgpu-backend.mjs` replays it into WebGPU. +- **Shaders:** Xenia's SPIR-V shader translator, converted to WGSL by Naga. +- **Vertex fetch:** read from a 512 MiB shared memory buffer. +- **Texture cache:** a port of `TextureCache`/`VulkanTextureCache`. Xenia's own texture load compute shaders do the untiling and format conversion. +- **Resolves:** the host render targets owning the tiles are dumped into an EDRAM buffer. Xenia's resolve copy shaders then write shared memory. + +Measured on a Banjo-Tooie main menu capture (2 frames; headless Chromium, SwiftShader): + +| Stage | Draws replayed | Validation errors | Result | +| --- | --- | --- | --- | +| Draw path, placeholder textures | 1390 | 0 | geometry only | +| Texture cache | 2400 | 0 | 144 textures loaded, menu art and text correct | + +The menu is drawn in screen tiles (predicated tiling) and assembled by +resolves, so the presented frame needs the resolve path. + +Opt-in in the browser: `?gpu=xenos` switches the page to the WebGPU play +path. The software renderer then does no work, and each frame presents the +swapped front buffer from the GPU. + ## Not yet - Speed: reaching gameplay takes ~1 hour headless with the software renderer; the browser needs the WebGPU renderer and faster CPU emulation diff --git a/render360-browser-modern-content-bridge.mjs b/render360-browser-modern-content-bridge.mjs index 347daa43..f9a1e40e 100644 --- a/render360-browser-modern-content-bridge.mjs +++ b/render360-browser-modern-content-bridge.mjs @@ -9,6 +9,7 @@ import {inspectCapturedXenosShaders} from './render360-xenos-shader-runtime.mjs' import {validateCapturedXenosShadersWebGPU} from './render360-webgpu-title-shaders.mjs'; import {captureTitleFrontbuffer,ensureTitleWebGPUCanvas,hideTitleFrontbuffer,presentTitleFrontbuffer,showTitleWebGPUCanvas} from './render360-title-frontbuffer.mjs'; import {createRgbaFramePresenter} from './render360-webgpu-runtime.mjs'; +import {createXenosWebGpuPlayPath,webGpuPlayPathRequested} from './render360-webgpu-play.mjs'; import {browserPerformanceDefaults,createAdaptivePerformancePolicy} from './render360-performance-policy.mjs'; import {prepareStfsGuestVfs,prepareXexGuestVfs,runWithGuestVfsRetries} from './render360-guest-vfs.mjs'; @@ -22,7 +23,26 @@ let activePresenter=null; function stage(onStage,stage,message,extra={}){onStage?.({stage,message,...extra});} function guestRunOptions(bootstrap,onStage){ - return browserGuestRunOptions({bootstrap,onProgress:(message,extra)=>stage(onStage,'execute',message,extra),onFrame:()=>{const frame=captureTitleFrontbuffer({bootstrap});if(frame?.captured)presentTitleFrontbuffer(frame);}}); + // WebGPU play path (render360-webgpu-play.mjs) when requested; frames + // come from the software renderer until it is ready or if it fails. + const play={path:null,pending:false,failed:false}; + if(webGpuPlayPathRequested(null)&&globalThis.navigator?.gpu){ + play.pending=true; + createXenosWebGpuPlayPath(bootstrap,ensureTitleWebGPUCanvas()).then(path=>{ + play.path=path;activePresenter=path; + stage(onStage,'renderer','WebGPU Xenos renderer active (port of Xenia’s Vulkan backend)'); + },error=>{ + play.failed=true; + console.warn('[Render360] WebGPU Xenos renderer unavailable:',error); + stage(onStage,'renderer',`WebGPU Xenos renderer unavailable: ${error?.message||error}`); + }).finally(()=>{play.pending=false;}); + } + return browserGuestRunOptions({bootstrap,onProgress:(message,extra)=>stage(onStage,'execute',message,extra), + onSlice:()=>play.path?.slice(), + onFrame:()=>{ + if(play.path&&!play.path.lost){play.path.frame();return;} + const frame=captureTitleFrontbuffer({bootstrap});if(frame?.captured)presentTitleFrontbuffer(frame); + }}); } async function getBootstrap(onStage=null){ const wasCached=Boolean(globalThis.render360PpcRuntimeIdentity?.verified); diff --git a/render360-guest-fibers.mjs b/render360-guest-fibers.mjs index 10e383a1..e6c3662d 100644 --- a/render360-guest-fibers.mjs +++ b/render360-guest-fibers.mjs @@ -78,7 +78,7 @@ export async function runWithGuestFibers(bootstrap,callPrimary,{maxSwitches=1e9, // Browser options for a continuous title run: ~25 ms host slices, Stop through // globalThis.render360GuestRun.stop() (aborts at the next slice), and a // progress line about twice a second. -export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,sliceMs=25}={}){ +export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,onSlice=null,sliceMs=25}={}){ let lastFrames=-1; globalThis.render360GuestRun?.stop?.(); const controller=new AbortController(); @@ -100,6 +100,7 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,s const gpuMs=((renderUs-lastRenderUs)>>>0)/1000;lastRenderUs=renderUs; pushGuestControllerState(bootstrap); showGuestDialog(bootstrap); + try{onSlice?.();}catch{} const frames=read('r360_title_gpu_vd_swap_calls'); perf.submitted(t,frames); // Present every new guest frame (software Xenos backend output). diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs index ca2287eb..7819fcbf 100644 --- a/render360-webgpu-backend.mjs +++ b/render360-webgpu-backend.mjs @@ -660,6 +660,34 @@ export class XenosWebGpuBackend{ return this.clearBindGroup; } + // Draws the front buffer of the last swap to a canvas context configured + // on this device (the play path's present; Xenia's swap presenter). + present(context,format){ + const front=this.frontTexture; + if(!front)return false; + this.presentPipelines??=new Map(); + let pipeline=this.presentPipelines.get(format); + if(!pipeline){ + const module=this.device.createShaderModule({label:'Render360 present',code:PRESENT_SHADER}); + pipeline=this.device.createRenderPipeline({label:'Render360 present',layout:'auto', + vertex:{module,entryPoint:'vs'},fragment:{module,entryPoint:'fs',targets:[{format}]},primitive:{topology:'triangle-list'}}); + this.presentPipelines.set(format,pipeline); + } + if(this.presentSource!==front.texture||this.presentPipeline!==pipeline){ + this.presentSampler??=this.device.createSampler({magFilter:'linear',minFilter:'linear'}); + this.presentGroup=this.device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:[ + {binding:0,resource:front.views['2d-array']},{binding:1,resource:this.presentSampler}]}); + this.presentSource=front.texture;this.presentPipeline=pipeline; + } + const encoder=this.encoderForCommands(); + this.endPass(); + const pass=encoder.beginRenderPass({colorAttachments:[{view:context.getCurrentTexture().createView(),loadOp:'clear',clearValue:{r:0,g:0,b:0,a:1},storeOp:'store'}]}); + pass.setPipeline(pipeline);pass.setBindGroup(0,this.presentGroup);pass.draw(3);pass.end(); + this.submit(); + this.stats.presents=(this.stats.presents||0)+1; + return true; + } + // RGBA8 pixels of a color render target (tests and the frame preview). async readTarget(t){ this.submit(); @@ -1013,3 +1041,14 @@ fn main(@builtin(global_invocation_id) id: vec3) { } }`; } + +const PRESENT_SHADER=`struct Out { @builtin(position) position: vec4, @location(0) uv: vec2 } +@vertex fn vs(@builtin(vertex_index) i: u32) -> Out { + let p = vec2(f32(i == 1u) * 4.0 - 1.0, f32(i == 2u) * 4.0 - 1.0); + return Out(vec4(p, 0.0, 1.0), vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5)); +} +@group(0) @binding(0) var front: texture_2d_array; +@group(0) @binding(1) var front_sampler: sampler; +@fragment fn fs(i: Out) -> @location(0) vec4 { + return vec4(textureSample(front, front_sampler, i.uv, 0).rgb, 1.0); +}`; diff --git a/render360-webgpu-play.mjs b/render360-webgpu-play.mjs new file mode 100644 index 00000000..20aca6db --- /dev/null +++ b/render360-webgpu-play.mjs @@ -0,0 +1,52 @@ +// Render360 WebGPU play path: the core records draws, textures and resolves +// for render360-webgpu-backend.mjs (Xenia's Vulkan backend ported to +// WebGPU) and the software renderer does no work; each frame the stream is +// replayed and the swapped front buffer is drawn to the canvas. +// +// Opt-in while it is verified against the software renderer: `?gpu=xenos` +// in the page URL, or config.renderer === 'webgpu-xenos'. +import {XenosWebGpuBackend} from './render360-webgpu-backend.mjs'; + +export function webGpuPlayPathRequested(config){ + if(config?.renderer==='webgpu-xenos')return true; + try{return new URLSearchParams(globalThis.location?.search||'').get('gpu')==='xenos';}catch{return false;} +} + +export async function createXenosWebGpuPlayPath(bootstrap,canvas){ + const e=bootstrap.exports; + if(typeof e.r360_gpu_set_mode!=='function')throw new Error('core has no WebGPU recorder'); + const adapter=await navigator.gpu?.requestAdapter({powerPreference:'high-performance'}); + if(!adapter)throw new Error('no WebGPU adapter'); + const device=await adapter.requestDevice({ + requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)), + requiredLimits:{maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); + const context=canvas.getContext('webgpu'); + const format=navigator.gpu.getPreferredCanvasFormat(); + context.configure({device,format,alphaMode:'opaque'}); + const backend=await new XenosWebGpuBackend(device,e).init(); + let lost=null; + device.lost.then(info=>{lost=info?.message||'device lost';}); + e.r360_gpu_set_mode(1); + e.r360_xenos_soft_set_rasterize?.(0); + // Replays at least this often (loading screens can go long without swaps; + // the stream holds uploaded pages until it is replayed). + const maxPendingWords=4*1024*1024; + return { + backend, + get lost(){return lost;}, + slice(){if(!lost&&(e.r360_gpu_stream_words()>>>0)>maxPendingWords)backend.replay();}, + frame(){ + if(lost)return false; + backend.replay(); + const front=backend.frontTexture; + if(front&&(canvas.width!==front.width||canvas.height!==front.height)){canvas.width=front.width;canvas.height=front.height;} + canvas.style.display='block'; + return backend.present(context,format); + }, + destroy(){ + e.r360_gpu_set_mode(0); + e.r360_xenos_soft_set_rasterize?.(1); + try{device.destroy();}catch{} + }, + }; +} diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 64ab63b0..84a4b774 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -1,11 +1,14 @@ // Render360 guest JIT: finalized Xenia HIR -> WebAssembly (see hir_wasm_jit.h). #include "hir_wasm_jit.h" +#include #include #include +#include #include #include +#include "xenia/base/string_buffer.h" #include "xenia/cpu/function.h" #include "xenia/cpu/hir/block.h" #include "xenia/cpu/hir/hir_builder.h" @@ -1886,9 +1889,38 @@ bool Excluded(HIRBuilder* builder) { // interpreted (r360_jit_set_exclude_seq; bisecting by when code compiles, // which keeps early, hot functions compiled). uint32_t g_compile_seq = 0, g_exclude_seq_begin = 0, g_exclude_seq_end = 0; +// Compile requests in [g_log_seq_begin, end) print their guest function +// (r360_jit_set_log_seq; naming what a sequence bisect found). +uint32_t g_log_seq_begin = 0, g_log_seq_end = 0; +bool g_log_dump = false; // also the HIR and the wasm module + +uint32_t SourceStart(HIRBuilder* builder) { + for (Block* b = builder->first_block(); b; b = b->next) { + for (Instr* i = b->instr_head; i; i = i->next) { + if (i->opcode && i->opcode->num == xe::cpu::hir::OPCODE_SOURCE_OFFSET) return uint32_t(i->src1.offset); + } + } + return 0; +} uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { const uint32_t seq = g_compile_seq++; + const bool logged = seq >= g_log_seq_begin && seq < g_log_seq_end; + if (logged) { + std::fprintf(stderr, "R360_JIT_SEQ seq=%u start=0x%08X\n", seq, SourceStart(builder)); + if (g_log_dump) { + xe::StringBuffer dump; + builder->Dump(&dump); + const std::string text = dump.to_string(); + size_t at = 0; + while (at < text.size()) { + size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + std::fprintf(stderr, "R360_JIT_SEQ_HIR %u %.*s\n", seq, int(end - at), text.data() + at); + at = end + 1; + } + } + } if (Excluded(builder) || (seq >= g_exclude_seq_begin && seq < g_exclude_seq_end)) { slot->state = 2; return 0; @@ -1903,6 +1935,13 @@ uint32_t RequestCompile(HIRBuilder* builder, JitSlot* slot) { g_reject_by_builder[builder] = g_last_reject_opcode; return 0; } + if (logged && g_log_dump) { + for (size_t at = 0; at < bytes.size(); at += 64) { + std::fprintf(stderr, "R360_JIT_SEQ_WASM %u ", seq); + for (size_t k = at; k < std::min(bytes.size(), at + 64); ++k) std::fprintf(stderr, "%02x", bytes[k]); + std::fprintf(stderr, "\n"); + } + } const uint32_t request = g_next_request++; slot->builder_free = !emitter.uses_exec(); slot->osr_capable = emitter.osr_capable(); @@ -2028,6 +2067,13 @@ uint32_t r360_jit_set_exclude_seq(uint32_t begin, uint32_t end) { rx::g_exclude_seq_end = end; return rx::g_compile_seq; } +__attribute__((used, export_name("r360_jit_set_log_seq"))) +uint32_t r360_jit_set_log_seq(uint32_t begin, uint32_t end, uint32_t dump) { + rx::g_log_dump = dump != 0; + rx::g_log_seq_begin = begin; + rx::g_log_seq_end = end; + return rx::g_compile_seq; +} __attribute__((used, export_name("r360_jit_compile_seq"))) uint32_t r360_jit_compile_seq() { return rx::g_compile_seq; } __attribute__((used, export_name("r360_jit_set_exclude"))) diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp index 0ccbdf57..b1f7fa8c 100644 --- a/src/xenia_web_bootstrap/webgpu_draws.cpp +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -211,8 +211,9 @@ struct PipelineKeyHash { return size_t(h ^ (h >> 32)); } }; +std::unordered_map, uint32_t, PipelineKeyHash> g_pipelines; uint32_t PipelineId(const WebGpuPipelineDescription& description) { - static std::unordered_map, uint32_t, PipelineKeyHash> pipelines; + auto& pipelines = g_pipelines; static uint32_t next_id = 1; constexpr uint32_t kWords = sizeof(description) / 4; std::vector key(kWords); @@ -422,10 +423,10 @@ WebGpuRenderTargetsKey RenderTargets(uint32_t normalized_color_mask, bool depth_ } // Xenia's resolve copy shaders, sent once as load shaders 64 + index. +bool g_resolve_shader_sent[size_t(draw_util::ResolveCopyShaderIndex::kCount)] = {}; void SendResolveShader(draw_util::ResolveCopyShaderIndex index) { - static bool sent[size_t(draw_util::ResolveCopyShaderIndex::kCount)] = {}; - if (sent[size_t(index)]) return; - sent[size_t(index)] = true; + if (g_resolve_shader_sent[size_t(index)]) return; + g_resolve_shader_sent[size_t(index)] = true; static const std::pair kShaders[] = { {shaders::resolve_fast_32bpp_1x2xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_1x2xmsaa_cs)}, {shaders::resolve_fast_32bpp_4xmsaa_cs, sizeof(shaders::resolve_fast_32bpp_4xmsaa_cs)}, @@ -749,8 +750,17 @@ extern "C" { // 0 off, 1 record draws for the WebGPU backend. __attribute__((used, export_name("r360_gpu_set_mode"))) uint32_t r360_gpu_set_mode(uint32_t mode) { + // A new mode starts a new stream consumer: everything sent once (shaders, + // pipelines, textures, load and resolve shaders, shared memory) is sent + // again. rx::g_mode = mode; rx::g_targets_bound = false; + rx::ShaderIds().clear(); + rx::g_pipelines.clear(); + for (bool& sent : rx::g_resolve_shader_sent) sent = false; + rx::WebGpuTexturesReset(); + rx::GpuSharedMemory().ClearCache(); + rx::GpuStream().Reset(); return mode; } // 0 draws recorded, 1..5 skips by reason (see DrawSkip), 6 last skip reason, diff --git a/src/xenia_web_bootstrap/webgpu_textures.cpp b/src/xenia_web_bootstrap/webgpu_textures.cpp index adcf87d8..785346db 100644 --- a/src/xenia_web_bootstrap/webgpu_textures.cpp +++ b/src/xenia_web_bootstrap/webgpu_textures.cpp @@ -773,6 +773,13 @@ uint32_t WebGpuTextureForBinding(const SpirvShader::TextureBinding& shader_bindi return texture && (texture->loaded_base || texture->loaded_mips) ? texture->id : 0; } +void WebGpuTexturesReset() { + Cache& c = cache(); + c.textures.clear(); + for (TextureBinding& binding : c.bindings) binding.Reset(); + for (bool& sent : c.load_shader_sent) sent = false; +} + // VulkanTextureCache::RequestSwapTexture. uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant) { xenos::xe_gpu_texture_fetch_t fetch; diff --git a/src/xenia_web_bootstrap/webgpu_textures.h b/src/xenia_web_bootstrap/webgpu_textures.h index 92e66007..43563066 100644 --- a/src/xenia_web_bootstrap/webgpu_textures.h +++ b/src/xenia_web_bootstrap/webgpu_textures.h @@ -66,6 +66,9 @@ uint32_t WebGpuSamplerParameters(const xe::gpu::RegisterFile& regs, // if there is none. uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant); +// Forgets every texture (a new stream consumer, r360_gpu_set_mode). +void WebGpuTexturesReset(); + // A resolve wrote the range on the GPU (TextureCache::MarkRangeAsResolved): // textures in it are reloaded on their next use. void WebGpuTexturesMarkRangeResolved(uint32_t start, uint32_t length); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index c0bee31e..009bc776 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -170,7 +170,7 @@ async function loadBootstrap(file,verbose){ let pending=''; const bytes=fs.readFileSync(file); const stderr=[]; - const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR')||line.startsWith('R360_DIAG'))process.stderr.write(line+'\n');}}}); + const host=createRender360BrowserImports({onStdout:t=>{if(verbose)process.stdout.write(t+'\n');},onStderr:t=>{pending+=t;let n;while((n=pending.indexOf('\n'))>=0){const line=pending.slice(0,n);pending=pending.slice(n+1);stderr.push(line);if(stderr.length>4000)stderr.shift();if(verbose||globalThis.__r360TraceOn||line.startsWith('R360_KWATCH')||line.startsWith('R360_WATCH')||line.startsWith('R360_DET')||line.startsWith('R360_XENOS_')||line.startsWith('R360_JITPROF')||line.startsWith('R360_PRIMARY_EXIT')||line.startsWith('R360_MESSAGE_BOX')||line.startsWith('R360_FIBER_')||line.startsWith('R360_THREAD_EXIT')||line.startsWith('R360_OSR')||line.startsWith('R360_DIAG')||line.startsWith('R360_JIT_SEQ'))process.stderr.write(line+'\n');}}}); const module=await WebAssembly.compile(bytes); const instance=attachRender360BrowserInstance(host,await WebAssembly.instantiate(module,host.imports)); return {instance,host,stderr}; @@ -286,6 +286,7 @@ async function main(){ globalThis.__r360Jit=jit; if(process.env.R360_JITPROF)bootstrap.exports.r360_jit_profile?.(1); if(process.env.R360_DIAG){bootstrap.exports.r360_jit_diag?.(1);} + if(process.env.R360_JIT_LOG_SEQ){const [b,e]=process.env.R360_JIT_LOG_SEQ.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_log_seq?.(b,e,process.env.R360_JIT_LOG_DUMP?1:0);} if(process.env.R360_JIT_EXCLUDE_SEQ){const [b,e]=process.env.R360_JIT_EXCLUDE_SEQ.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude_seq?.(b,e);} if(process.env.R360_JIT_EXCLUDE){const [b,e]=process.env.R360_JIT_EXCLUDE.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude?.(b,e);} if(args.traceFrom!==undefined){globalThis.__r360TraceOn=1;bootstrap.exports.r360_trace_verbose_from?.(args.traceFrom);} From 697ae47a15303df29705cc4df84068f8072f3410 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 14:55:56 +0000 Subject: [PATCH 48/65] WebGPU resolves verified on a Banjo-Tooie menu capture; swap swizzle The EDRAM dump shader used the reserved WGSL word 'unorm'. With it renamed, a menu capture recorded with the software renderer off replays with 6 EDRAM dumps, 6 resolves and 8 clears and no validation errors: the predicated-tiling strips assemble into the full front buffer. Swaps now carry the front buffer's host swizzle (VulkanTextureCache:: RequestSwapTexture) and the present shader applies it. The JIT gains r360_jit_set_reject_tail (R360_JIT_REJECT_TAIL) to isolate a tail-call miscompile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-webgpu-backend.mjs | 25 ++++++++++++++++----- src/xenia_web_bootstrap/hir_wasm_jit.cpp | 7 ++++++ src/xenia_web_bootstrap/webgpu_backend.h | 4 ++-- src/xenia_web_bootstrap/webgpu_draws.cpp | 6 +++-- src/xenia_web_bootstrap/webgpu_textures.cpp | 4 +++- src/xenia_web_bootstrap/webgpu_textures.h | 4 ++-- tests/browser/webgpu-replay-capture.mjs | 8 +++++++ tools/run-title.mjs | 1 + 8 files changed, 46 insertions(+), 13 deletions(-) diff --git a/render360-webgpu-backend.mjs b/render360-webgpu-backend.mjs index 7819fcbf..0301da06 100644 --- a/render360-webgpu-backend.mjs +++ b/render360-webgpu-backend.mjs @@ -125,7 +125,7 @@ export class XenosWebGpuBackend{ else if(op===GPU_STREAM_PIPELINE)this.definePipeline(p); else if(op===GPU_STREAM_RENDER_TARGETS){this.endPass();this.boundTargets=parseRenderTargets(p);} else if(op===GPU_STREAM_DRAW)this.draw(p); - else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.frontTexture=this.textures.get(p[6])||null;this.submit();} + else if(op===GPU_STREAM_SWAP){this.stats.swaps++;this.lastSwap=p.slice();this.frontTexture=this.textures.get(p[6])||null;this.frontSwizzle=p[7]??0x688;this.submit();} else if(op===GPU_STREAM_EDRAM_DUMP)this.dumpEdram(p); else if(op===GPU_STREAM_RESOLVE)this.resolve(p); else if(op===GPU_STREAM_CLEAR)this.clear(p); @@ -673,10 +673,13 @@ export class XenosWebGpuBackend{ vertex:{module,entryPoint:'vs'},fragment:{module,entryPoint:'fs',targets:[{format}]},primitive:{topology:'triangle-list'}}); this.presentPipelines.set(format,pipeline); } + this.presentSwizzleBuffer??=this.device.createBuffer({size:16,usage:BUFFER_USAGE.UNIFORM|BUFFER_USAGE.COPY_DST}); + this.device.queue.writeBuffer(this.presentSwizzleBuffer,0,new Uint32Array([this.frontSwizzle??0x688,0,0,0])); if(this.presentSource!==front.texture||this.presentPipeline!==pipeline){ this.presentSampler??=this.device.createSampler({magFilter:'linear',minFilter:'linear'}); this.presentGroup=this.device.createBindGroup({layout:pipeline.getBindGroupLayout(0),entries:[ - {binding:0,resource:front.views['2d-array']},{binding:1,resource:this.presentSampler}]}); + {binding:0,resource:front.views['2d-array']},{binding:1,resource:this.presentSampler}, + {binding:2,resource:{buffer:this.presentSwizzleBuffer}}]}); this.presentSource=front.texture;this.presentPipeline=pipeline; } const encoder=this.encoderForCommands(); @@ -1007,7 +1010,7 @@ fn f32_to_20e4(f: f32) -> u32 { return (u >> 3u) & 0xFFFFFFu; } fn s16(f: f32) -> u32 { return u32(i32(round(clamp(f, -1.0, 1.0) * 32767.0))) & 0xFFFFu; } -fn unorm(f: f32, bits: u32) -> u32 { let m = f32((1u << bits) - 1u); return u32(round(clamp(f, 0.0, 1.0) * m)); } +fn to_unorm(f: f32, bits: u32) -> u32 { let m = f32((1u << bits) - 1u); return u32(round(clamp(f, 0.0, 1.0) * m)); } @compute @workgroup_size(8, 8) fn main(@builtin(global_invocation_id) id: vec3) { @@ -1022,8 +1025,8 @@ fn main(@builtin(global_invocation_id) id: vec3) { lo = (d24 << 8u) | stencil;`:`let c = textureLoad(color_texture, vec2(pixel), 0); switch dump.format { case 0u, 1u: { lo = pack4x8unorm(c); } - case 2u, 10u: { lo = unorm(c.x, 10u) | (unorm(c.y, 10u) << 10u) | (unorm(c.z, 10u) << 20u) | (unorm(c.w, 2u) << 30u); } - case 3u, 12u: { lo = f32_to_7e3(c.x) | (f32_to_7e3(c.y) << 10u) | (f32_to_7e3(c.z) << 20u) | (unorm(c.w, 2u) << 30u); } + case 2u, 10u: { lo = to_unorm(c.x, 10u) | (to_unorm(c.y, 10u) << 10u) | (to_unorm(c.z, 10u) << 20u) | (to_unorm(c.w, 2u) << 30u); } + case 3u, 12u: { lo = f32_to_7e3(c.x) | (f32_to_7e3(c.y) << 10u) | (f32_to_7e3(c.z) << 20u) | (to_unorm(c.w, 2u) << 30u); } case 4u: { lo = s16(c.x) | (s16(c.y) << 16u); } case 5u: { lo = s16(c.x) | (s16(c.y) << 16u); hi = s16(c.z) | (s16(c.w) << 16u); } case 6u: { lo = pack2x16float(c.xy); } @@ -1049,6 +1052,16 @@ const PRESENT_SHADER=`struct Out { @builtin(position) position: vec4, @loca } @group(0) @binding(0) var front: texture_2d_array; @group(0) @binding(1) var front_sampler: sampler; +// Host swizzle of the swap fetch constant (3 bits per component: 0-3 RGBA, +// 4 zero, 5 one), as Xenia's swap texture view applies it. +@group(0) @binding(2) var swizzle: vec4; +fn component(t: vec4, s: u32) -> f32 { + if (s >= 5u) { return 1.0; } + if (s == 4u) { return 0.0; } + return t[s]; +} @fragment fn fs(i: Out) -> @location(0) vec4 { - return vec4(textureSample(front, front_sampler, i.uv, 0).rgb, 1.0); + let t = textureSample(front, front_sampler, i.uv, 0); + let s = swizzle.x; + return vec4(component(t, s & 7u), component(t, (s >> 3u) & 7u), component(t, (s >> 6u) & 7u), 1.0); }`; diff --git a/src/xenia_web_bootstrap/hir_wasm_jit.cpp b/src/xenia_web_bootstrap/hir_wasm_jit.cpp index 84a4b774..eb24f0e2 100644 --- a/src/xenia_web_bootstrap/hir_wasm_jit.cpp +++ b/src/xenia_web_bootstrap/hir_wasm_jit.cpp @@ -959,6 +959,7 @@ bool Emitter::EmitGeneric(Instr* instr, uint32_t source) { return true; } +extern bool g_reject_tail_calls; bool Emitter::EmitInstr(Instr* instr, uint32_t k, uint32_t source) { const size_t mark = code_.b.size(); const uint32_t extra = extra_; @@ -1589,6 +1590,7 @@ bool Emitter::EmitNative(Instr* instr, uint32_t k, uint32_t source) { return true; case OPCODE_CALL: case OPCODE_CALL_TRUE: { + if ((instr->flags & CALL_TAIL) && g_reject_tail_calls) return Reject(instr); const bool conditional = op == OPCODE_CALL_TRUE; auto* symbol = conditional ? instr->src2.symbol : instr->src1.symbol; uint32_t direct_target = 0; @@ -1893,6 +1895,9 @@ uint32_t g_compile_seq = 0, g_exclude_seq_begin = 0, g_exclude_seq_end = 0; // (r360_jit_set_log_seq; naming what a sequence bisect found). uint32_t g_log_seq_begin = 0, g_log_seq_end = 0; bool g_log_dump = false; // also the HIR and the wasm module +// Functions with direct tail calls stay interpreted (r360_jit_set_reject_tail; +// isolating a tail-call miscompile). +bool g_reject_tail_calls = false; uint32_t SourceStart(HIRBuilder* builder) { for (Block* b = builder->first_block(); b; b = b->next) { @@ -2074,6 +2079,8 @@ uint32_t r360_jit_set_log_seq(uint32_t begin, uint32_t end, uint32_t dump) { rx::g_log_seq_end = end; return rx::g_compile_seq; } +__attribute__((used, export_name("r360_jit_set_reject_tail"))) +uint32_t r360_jit_set_reject_tail(uint32_t on) { rx::g_reject_tail_calls = on != 0; return on; } __attribute__((used, export_name("r360_jit_compile_seq"))) uint32_t r360_jit_compile_seq() { return rx::g_compile_seq; } __attribute__((used, export_name("r360_jit_set_exclude"))) diff --git a/src/xenia_web_bootstrap/webgpu_backend.h b/src/xenia_web_bootstrap/webgpu_backend.h index ad59251c..3f9908b2 100644 --- a/src/xenia_web_bootstrap/webgpu_backend.h +++ b/src/xenia_web_bootstrap/webgpu_backend.h @@ -29,8 +29,8 @@ enum GpuStreamOp : uint32_t { // A draw: WebGpuDrawHeader, the system constants, vertex and pixel float // constants, bool/loop constants, fetch constants, then the indices. kGpuStreamDraw = 5, - // A swap: the front buffer's texture fetch constant (6 words), then its - // texture id (0: none). + // A swap: the front buffer's texture fetch constant (6 words), its + // texture id (0: none) and the host swizzle to present it with. kGpuStreamSwap = 6, // One of Xenia's texture_load_* compute shaders, once: load shader index // (TextureCache::LoadShaderIndex), SPIR-V word count, SPIR-V. diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp index b1f7fa8c..991e84d9 100644 --- a/src/xenia_web_bootstrap/webgpu_draws.cpp +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -528,10 +528,12 @@ bool WebGpuBackendEnabled() { return g_mode != 0; } void WebGpuSwap(const uint32_t* fetch_constant) { if (!g_mode) return; - const uint32_t texture = WebGpuSwapTexture(fetch_constant); - uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 7); + uint32_t swizzle; + const uint32_t texture = WebGpuSwapTexture(fetch_constant, &swizzle); + uint32_t* w = GpuStream().Begin(kGpuStreamSwap, 8); std::memcpy(w, fetch_constant, 6 * sizeof(uint32_t)); w[6] = texture; + w[7] = swizzle; } bool WebGpuIssueDraw(const XenosSoftDraw& draw) { diff --git a/src/xenia_web_bootstrap/webgpu_textures.cpp b/src/xenia_web_bootstrap/webgpu_textures.cpp index 785346db..4c247b3c 100644 --- a/src/xenia_web_bootstrap/webgpu_textures.cpp +++ b/src/xenia_web_bootstrap/webgpu_textures.cpp @@ -781,12 +781,14 @@ void WebGpuTexturesReset() { } // VulkanTextureCache::RequestSwapTexture. -uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant) { +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant, uint32_t* host_swizzle) { xenos::xe_gpu_texture_fetch_t fetch; std::memcpy(&fetch, fetch_constant, sizeof(fetch)); TextureKey key; BindingInfoFromFetchConstant(fetch, key, nullptr); + *host_swizzle = xenos::XE_GPU_TEXTURE_SWIZZLE_RGBA; if (!key.is_valid || !key.base_page || key.dimension != xenos::DataDimension::k2DOrStacked) return 0; + *host_swizzle = Types::GuestToHostSwizzle(fetch.swizzle, GetHostFormatPair(key).swizzle); Texture* texture = FindOrCreateTexture(key); if (!texture) return 0; MakeUpToDate(*texture); diff --git a/src/xenia_web_bootstrap/webgpu_textures.h b/src/xenia_web_bootstrap/webgpu_textures.h index 43563066..284eb9b6 100644 --- a/src/xenia_web_bootstrap/webgpu_textures.h +++ b/src/xenia_web_bootstrap/webgpu_textures.h @@ -63,8 +63,8 @@ uint32_t WebGpuSamplerParameters(const xe::gpu::RegisterFile& regs, const xe::gpu::SpirvShader::SamplerBinding& binding); // The front buffer texture of a swap (6 fetch constant words), loaded; 0 -// if there is none. -uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant); +// if there is none. `host_swizzle` gets the swizzle to present it with. +uint32_t WebGpuSwapTexture(const uint32_t* fetch_constant, uint32_t* host_swizzle); // Forgets every texture (a new stream consumer, r360_gpu_set_mode). void WebGpuTexturesReset(); diff --git a/tests/browser/webgpu-replay-capture.mjs b/tests/browser/webgpu-replay-capture.mjs index 8449297a..31450fb1 100644 --- a/tests/browser/webgpu-replay-capture.mjs +++ b/tests/browser/webgpu-replay-capture.mjs @@ -38,6 +38,14 @@ export default async function run(captureUrl,referenceUrl,drawLimit){ result.front=front===backend.frontTexture?'front buffer':'render target'; if(front&&referenceUrl){ const got=await backend.readTarget(front),want=await decodePng(referenceUrl); + // The front buffer as presented: the swap's host swizzle. + if(front===backend.frontTexture){ + const sw=backend.frontSwizzle??0x688,px=got.pixels; + for(let i=0;i{const v=(sw>>>(3*k))&7;return v>=5?255:v===4?0:t[v];}; + px[i]=c(0);px[i+1]=c(1);px[i+2]=c(2);px[i+3]=c(3); + } + } const w=Math.min(got.width,want.width),h=Math.min(got.height,want.height); let diff=0,close=0,lit=0; for(let y=0;yNumber(v)>>>0);bootstrap.exports.r360_jit_set_log_seq?.(b,e,process.env.R360_JIT_LOG_DUMP?1:0);} if(process.env.R360_JIT_EXCLUDE_SEQ){const [b,e]=process.env.R360_JIT_EXCLUDE_SEQ.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude_seq?.(b,e);} if(process.env.R360_JIT_EXCLUDE){const [b,e]=process.env.R360_JIT_EXCLUDE.split('-').map(v=>Number(v)>>>0);bootstrap.exports.r360_jit_set_exclude?.(b,e);} From 2730502fb9c76a70532a6b10dc0cba33f9cbf102 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 16:08:10 +0000 Subject: [PATCH 49/65] WebGPU capture debugging: resolve/draw logging, EDRAM comparison r360_gpu_set_mode bit 1 (run-title R360_GPU_DEBUG) logs resolve rectangles, offsets and window offsets and sampled draw viewports; the capture replay test can compare the EDRAM buffer with the render target (R360_DEBUG_EDRAM). Used to locate a 32-pixel horizontal offset in the resolved front buffer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- src/xenia_web_bootstrap/webgpu_draws.cpp | 22 +++++++++++++++++++ test-webgpu-replay-capture-browser.mjs | 2 +- tests/browser/webgpu-replay-capture.mjs | 28 +++++++++++++++++++++++- tools/run-title.mjs | 2 +- 4 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/xenia_web_bootstrap/webgpu_draws.cpp b/src/xenia_web_bootstrap/webgpu_draws.cpp index 991e84d9..bb29f749 100644 --- a/src/xenia_web_bootstrap/webgpu_draws.cpp +++ b/src/xenia_web_bootstrap/webgpu_draws.cpp @@ -4,6 +4,7 @@ // recording into the command stream (webgpu_backend.h) instead of a Vulkan // command buffer. Render targets follow Xenia's host render target path. #include +#include #include #include #include @@ -467,6 +468,19 @@ void Resolve() { } if (!info.coordinate_info.width_div_8 || !info.height_div_8) return; ++g_resolves; + if (g_mode & 2) { + const auto window = regs.Get(); + const draw_util::ResolveEdramInfo& e = info.IsCopyingDepth() ? info.depth_edram_info : info.color_edram_info; + std::fprintf(stderr, + "R360_XENOS_WGPU_RESOLVE base=%u pitch=%u msaa=%u fmt=%u off=%u,%u size=%ux%u " + "dest=0x%08X dest_off=%u,%u dest_pitch=%u window=%d,%d window_enable=%u\n", + e.base_tiles, e.pitch_tiles, uint32_t(e.msaa_samples), e.format, + info.coordinate_info.edram_offset_x_div_8 * 8u, info.coordinate_info.edram_offset_y_div_8 * 8u, + info.coordinate_info.width_div_8 * 8u, info.height_div_8 * 8u, info.copy_dest_base, + info.copy_dest_coordinate_info.offset_x_div_8 * 8u, info.copy_dest_coordinate_info.offset_y_div_8 * 8u, + info.copy_dest_coordinate_info.pitch_aligned_div_32 * 32u, int(window.window_x_offset), + int(window.window_y_offset), uint32_t(regs.Get().vtx_window_offset_enable)); + } if (info.copy_dest_extent_length) { uint32_t dump_base, dump_row_length_used, dump_rows, dump_pitch; info.GetCopyEdramTileSpan(dump_base, dump_row_length_used, dump_rows, dump_pitch); @@ -689,6 +703,14 @@ bool WebGpuIssueDraw(const XenosSoftDraw& draw) { uint32_t(float_vertex.size() + float_pixel.size()) + kBoolLoopWords + kFetchWords + uint32_t(binding_words.size()) + index_words; const uint32_t pipeline_id = PipelineId(description); + if ((g_mode & 2) && g_draws < 4000 && (g_draws % 50) == 0) { + const auto window = regs.Get(); + std::fprintf(stderr, "R360_XENOS_WGPU_DRAW n=%u viewport=%u,%u %ux%u scissor=%u,%u %ux%u window=%d,%d enable=%u\n", + g_draws, viewport_info.xy_offset[0], viewport_info.xy_offset[1], viewport_info.xy_extent[0], + viewport_info.xy_extent[1], scissor.offset[0], scissor.offset[1], scissor.extent[0], scissor.extent[1], + int(window.window_x_offset), int(window.window_y_offset), + uint32_t(pa_su_sc_mode_cntl.vtx_window_offset_enable)); + } uint32_t* w = GpuStream().Begin(kGpuStreamDraw, payload); WebGpuDrawHeader header{}; header.pipeline = pipeline_id; diff --git a/test-webgpu-replay-capture-browser.mjs b/test-webgpu-replay-capture-browser.mjs index 11f6070c..20896eb0 100644 --- a/test-webgpu-replay-capture-browser.mjs +++ b/test-webgpu-replay-capture-browser.mjs @@ -11,7 +11,7 @@ const capture=process.argv[2]||process.env.R360_GPU_CAPTURE; if(!capture||!fs.existsSync(capture)){console.log('WEBGPU_REPLAY_CAPTURE_SKIP (no local capture)');process.exit(0);} const dir=path.dirname(path.resolve(capture)),name=path.basename(capture); const reference=fs.existsSync(`${capture}.png`)?`/__data__/${name}.png`:null; -const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference,process.env.R360_DRAW_LIMIT?Number(process.env.R360_DRAW_LIMIT):null],dataRoot:dir, +const result=await runBrowserTest('tests/browser/webgpu-replay-capture.mjs',{args:[`/__data__/${name}`,reference,process.env.R360_DRAW_LIMIT?Number(process.env.R360_DRAW_LIMIT):null,!!process.env.R360_DEBUG_EDRAM],dataRoot:dir, onConsole:t=>process.env.VERBOSE&&console.log(t)}); if(result.png){if(process.argv[3])fs.writeFileSync(process.argv[3],Buffer.from(result.png,'base64'));delete result.png;} console.log(JSON.stringify(result,null,1)); diff --git a/tests/browser/webgpu-replay-capture.mjs b/tests/browser/webgpu-replay-capture.mjs index 31450fb1..17e3e724 100644 --- a/tests/browser/webgpu-replay-capture.mjs +++ b/tests/browser/webgpu-replay-capture.mjs @@ -11,7 +11,13 @@ async function decodePng(url){ return {width:bitmap.width,height:bitmap.height,pixels:ctx.getImageData(0,0,bitmap.width,bitmap.height).data}; } -export default async function run(captureUrl,referenceUrl,drawLimit){ +async function readBuffer(device,buffer,offset,size){ + const read=device.createBuffer({size,usage:0x1|0x8}); + const e=device.createCommandEncoder();e.copyBufferToBuffer(buffer,offset,read,0,size);device.queue.submit([e.finish()]); + await read.mapAsync(1);const out=new Uint8Array(read.getMappedRange()).slice();read.unmap();read.destroy();return out; +} + +export default async function run(captureUrl,referenceUrl,drawLimit,debugEdram){ const adapter=await navigator.gpu?.requestAdapter(); if(!adapter)return {ok:false,error:'no WebGPU adapter'}; const device=await adapter.requestDevice({requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)),requiredLimits:{ @@ -20,6 +26,7 @@ export default async function run(captureUrl,referenceUrl,drawLimit){ device.onuncapturederror=e=>{if(errors.length<20)errors.push(e.error.message.slice(0,400));}; const backend=await new XenosWebGpuBackend(device,null).init(); if(drawLimit!==undefined&&drawLimit!==null)backend.drawLimit=drawLimit; + backend.debugEdram=!!debugEdram; const words=new Uint32Array(await (await fetch(captureUrl)).arrayBuffer()); const started=performance.now(); backend.replayWords(words); @@ -33,6 +40,25 @@ export default async function run(captureUrl,referenceUrl,drawLimit){ targets:[...backend.targets.values()].map(t=>`${t.key} ${t.format} ${t.width}x${t.height}`)}; // The swapped front buffer (resolved into shared memory, loaded by the // texture cache), else the color render target at EDRAM base 0. + // Debug: the EDRAM buffer against the color render target at base 0 + // (Xenia's layout, 32bpp), at X shifts, to locate resolve offsets. + if(globalThis.location?.search?.includes('edram')||backend.debugEdram){ + const rt=[...backend.targets.values()].find(t=>!t.depth&&t.base===0); + const img=await backend.readTarget(rt); + const ed=new Uint32Array((await readBuffer(device,backend.edram,0,backend.edram.size)).buffer); + const sx=rt.msaa>=2?2:1,sy=rt.msaa>=1?2:1,scores={}; + for(const shift of [-64,-32,0,32,64]){ + let same=0,n=0; + for(let y=0;y>>0)===(v>>>0))same++; + } + scores[shift]=+(same/n).toFixed(3); + } + result.edramMatchByShift=scores; + } const front=(backend.frontTexture?.format==='rgba8unorm'?backend.frontTexture:null)|| [...backend.targets.values()].find(t=>!t.depth&&t.base===0&&t.format==='rgba8unorm'); result.front=front===backend.frontTexture?'front buffer':'render target'; diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 1c06be05..7cb81e83 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -106,7 +106,7 @@ function sliceGpuCapture(x,m){ if(!c||gpuCapture.done||!x.r360_gpu_set_mode)return; if(!gpuCapture.started){ if(m>>0;return; } const words=x.r360_gpu_stream_words()>>>0; From 9274379a7f1aceffcb4187c90303f92218e118d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 16:32:57 +0000 Subject: [PATCH 50/65] 30 FPS bar: overlay and per-device log The overlay now judges guest frames (VdSwap presents/s): - game FPS, 60 s average and 1% low, stutters over 50 ms per minute; - emulation speed (100% + headroom when the guest idles, else game FPS/30), guest MIPS and the interpreted share; - CPU ms per guest frame and GPU ms per frame (WebGPU submit to completion); - a frame-time graph with 30 FPS and 50 ms lines and a PASS / not met verdict for the bar (avg >= 30, 1% low >= 25, speed >= 100%, <= 1 stutter/min over >= 10 s). L downloads a once-a-second JSON log with device details (UA, cores, memory, GPU adapter) for comparing devices. The core exports r360_perf_counter (guest and interpreted instructions) and r360_fiber_idle_ms; run-title reports the same in a perf block. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- render360-browser-modern-content-bridge.mjs | 1 + render360-guest-fibers.mjs | 7 +- render360-perf-overlay.mjs | 143 +++++++++++++++++- render360-webgpu-play.mjs | 13 +- src/xenia_web_bootstrap/guest_fibers.cpp | 6 + .../hir_correctness_executor.cpp | 13 ++ test-perf-overlay.mjs | 38 +++++ tools/run-title.mjs | 4 + 8 files changed, 218 insertions(+), 7 deletions(-) diff --git a/render360-browser-modern-content-bridge.mjs b/render360-browser-modern-content-bridge.mjs index f9a1e40e..4852a3e0 100644 --- a/render360-browser-modern-content-bridge.mjs +++ b/render360-browser-modern-content-bridge.mjs @@ -39,6 +39,7 @@ function guestRunOptions(bootstrap,onStage){ } return browserGuestRunOptions({bootstrap,onProgress:(message,extra)=>stage(onStage,'execute',message,extra), onSlice:()=>play.path?.slice(), + gpuFrameMs:()=>play.path?.takeGpuMs?.()??null, onFrame:()=>{ if(play.path&&!play.path.lost){play.path.frame();return;} const frame=captureTitleFrontbuffer({bootstrap});if(frame?.captured)presentTitleFrontbuffer(frame); diff --git a/render360-guest-fibers.mjs b/render360-guest-fibers.mjs index e6c3662d..9a274d29 100644 --- a/render360-guest-fibers.mjs +++ b/render360-guest-fibers.mjs @@ -78,7 +78,7 @@ export async function runWithGuestFibers(bootstrap,callPrimary,{maxSwitches=1e9, // Browser options for a continuous title run: ~25 ms host slices, Stop through // globalThis.render360GuestRun.stop() (aborts at the next slice), and a // progress line about twice a second. -export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,onSlice=null,sliceMs=25}={}){ +export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,onSlice=null,gpuFrameMs=null,sliceMs=25}={}){ let lastFrames=-1; globalThis.render360GuestRun?.stop?.(); const controller=new AbortController(); @@ -107,6 +107,11 @@ export function browserGuestRunOptions({bootstrap,onProgress=null,onFrame=null,o let presentMs=0; if(onFrame&&frames!==lastFrames){lastFrames=frames;const p0=now();try{onFrame();}catch{}presentMs=now()-p0;perf.framePresented(now());} perf.slice(t,t-sliceExit,gpuMs,presentMs); + const counter=bootstrap?.exports?.r360_perf_counter,idle=bootstrap?.exports?.r360_fiber_idle_ms; + if(typeof counter==='function')perf.counters(t,counter(0),counter(1),typeof idle==='function'?idle():0); + const gpuFrame=gpuFrameMs?.(); + if(gpuFrame!==null&&gpuFrame!==undefined)perf.gpuFrame(t,gpuFrame); + perf.record(t); if(overlay&&t-lastOverlay>=1000){lastOverlay=t;overlay.update(perf.snapshot(t));} globalThis.render360Perf=perf; sliceExit=now(); diff --git a/render360-perf-overlay.mjs b/render360-perf-overlay.mjs index c7ab98a8..97ff5ec8 100644 --- a/render360-perf-overlay.mjs +++ b/render360-perf-overlay.mjs @@ -10,6 +10,14 @@ // // Shown: current FPS (last second), average FPS (last 60 s), frame time, 1% // low FPS, CPU emulation vs GPU rendering time, submitted vs presented. +// +// The 30 FPS bar (PROGRESS.md "30 FPS bar"), judged on guest frames (VdSwap +// presents per second, "game FPS"): average >= 30 and 1% low >= 25 over the +// last 60 s, emulation speed >= 100%, at most one frame over 50 ms per minute. +// Emulation speed is 100% plus the headroom when the guest had idle time +// (nothing runnable: the emulator is ahead of real time); without idle time +// it is game FPS / 30. Counters (counters()) come from the core: guest and +// interpreted instructions, guest idle ms. const WINDOW_MS = 60000; @@ -22,6 +30,24 @@ export class PerfStats { this.lastSubmitted = null; this.totalPresented = 0; this.totalSubmitted = 0; + this.guestFrameTimes = []; // time of each guest frame (VdSwap) + this.counterSamples = []; // [time, instructions, interpreted, idleMs] + this.gpuFrames = []; // [time, gpuMs] per presented frame (WebGPU path) + this.log = []; // one record per second (exportLog) + this.lastLogAt = 0; + } + + // Core counters at time t (cumulative): guest instructions, interpreted + // instructions, guest idle milliseconds. + counters(t, instructions, interpreted, idleMs) { + this.counterSamples.push([t, instructions, interpreted, idleMs]); + this.trim(t); + } + + // GPU time of one frame on the WebGPU path (submit to completion, ms). + gpuFrame(t, ms) { + this.gpuFrames.push([t, ms]); + this.trim(t); } // One presented frame at time t (ms). @@ -37,6 +63,7 @@ export class PerfStats { const n = cumulative - this.lastSubmitted; this.submitEvents.push([t, n]); this.totalSubmitted += n; + for (let i = 0; i < n; ++i) this.guestFrameTimes.push(t); } this.lastSubmitted = cumulative; this.trim(t); @@ -54,6 +81,9 @@ export class PerfStats { while (this.presentTimes.length && this.presentTimes[0] < old) this.presentTimes.shift(); while (this.submitEvents.length && this.submitEvents[0][0] < old) this.submitEvents.shift(); while (this.slices.length && this.slices[0][0] < old) this.slices.shift(); + while (this.guestFrameTimes.length && this.guestFrameTimes[0] < old) this.guestFrameTimes.shift(); + while (this.counterSamples.length > 2 && this.counterSamples[1][0] < old) this.counterSamples.shift(); + while (this.gpuFrames.length && this.gpuFrames[0][0] < old) this.gpuFrames.shift(); } snapshot(t) { @@ -79,7 +109,51 @@ export class PerfStats { const recent = this.slices.filter(([time]) => time >= t - 1000); const cpuMs = recent.reduce((a, s) => a + s[1], 0); const gpuMs = recent.reduce((a, s) => a + s[2], 0); + // Game FPS from guest frames: last second, 60 s average, 1% low, + // frames over 50 ms in the last minute. + const g = this.guestFrameTimes; + const gameFps = g.filter(x => x > t - 1000).length; + const gSpan = g.length > 1 ? Math.max(1, t - g[0]) : 0; + const gameAverageFps = gSpan ? (g.length - 1) * 1000 / gSpan : gameFps; + const gDeltas = []; + for (let i = 1; i < g.length; ++i) if (g[i] > g[i - 1]) gDeltas.push(g[i] - g[i - 1]); + let gameLow1Fps = 0; + if (gDeltas.length) { + const sorted = [...gDeltas].sort((a, b) => b - a); + const worst = sorted.slice(0, Math.max(1, Math.ceil(sorted.length / 100))); + gameLow1Fps = 1000 / (worst.reduce((a, b) => a + b, 0) / worst.length); + } + const stutters = gDeltas.filter(d => d > 50).length; + const minutes = Math.max(1 / 60, Math.min(this.windowMs, gSpan || 1000) / 60000); + // Counter rates over the last second (or the oldest sample in it). + const cs = this.counterSamples; + let mips = 0, interpretedPercent = 0, idlePercent = 0; + if (cs.length > 1) { + const last = cs[cs.length - 1]; + let first = cs[0]; + for (const c of cs) { if (c[0] >= t - 1000) { first = c; break; } } + if (first === last) first = cs[cs.length - 2]; + const dt = Math.max(1, last[0] - first[0]); + const di = last[1] - first[1]; + mips = di / dt / 1000; + interpretedPercent = di > 0 ? 100 * (last[2] - first[2]) / di : 0; + idlePercent = Math.min(100, 100 * (last[3] - first[3]) / dt); + } + const emulationSpeedPercent = idlePercent > 0 ? 100 / Math.max(0.01, 1 - idlePercent / 100) + : Math.min(100, 100 * gameFps / 30); + const gpuRecent = this.gpuFrames.filter(([time]) => time >= t - 1000); + const gpuMsPerFrame = gpuRecent.length ? gpuRecent.reduce((a, [, ms]) => a + ms, 0) / gpuRecent.length : null; + const cpuMsPerGuestFrame = gameFps ? cpuMs / gameFps : null; + const stuttersPerMinute = stutters / minutes; + const bar = { + average: gameAverageFps >= 30, low1: gameLow1Fps >= 25, speed: emulationSpeedPercent >= 100, + stutter: stuttersPerMinute <= 1, + }; + bar.pass = bar.average && bar.low1 && bar.speed && bar.stutter && gSpan >= 10000; return { + gameFps, gameAverageFps, gameLow1Fps, stuttersPerMinute, emulationSpeedPercent, idlePercent, + mips, interpretedPercent, cpuMsPerGuestFrame, gpuMsPerFrame, bar, + frameTimes: gDeltas.slice(-120), fps: current, averageFps: average, frameMs, @@ -93,16 +167,41 @@ export class PerfStats { totalPresented: this.totalPresented, }; } + + // Appends a once-a-second record to the log (exportLog). + record(t, extra = {}) { + if (t - this.lastLogAt < 1000) return; + this.lastLogAt = t; + const s = this.snapshot(t); + const {frameTimes, ...rest} = s; + this.log.push({t: Math.round(t), ...rest, ...extra}); + if (this.log.length > 7200) this.log.shift(); + } + + // The run log with device details, as one JSON-serializable object. + exportLog(device = {}) { + return {format: 'render360-perf-log-1', device, bar: '30 FPS: avg >= 30, 1% low >= 25, speed >= 100%, <= 1 stutter (>50 ms) per minute', + records: this.log}; + } } export function formatPerf(s) { const f = (x, d = 1) => Number.isFinite(x) ? x.toFixed(d) : '—'; + const mark = ok => ok ? '✓' : '✗'; + const game = s.gameFps === undefined ? [] : [ + `Game FPS ${f(s.gameFps, 0)} avg ${f(s.gameAverageFps)} 1% low ${f(s.gameLow1Fps)} stutters ${f(s.stuttersPerMinute, 1)}/min`, + `Emulation speed ${f(s.emulationSpeedPercent, 0)}% idle ${f(s.idlePercent, 0)}% ${f(s.mips, 0)} MIPS interpreted ${f(s.interpretedPercent, 2)}%`, + `CPU ${f(s.cpuMsPerGuestFrame)} ms/frame GPU ${s.gpuMsPerFrame === null ? '—' : f(s.gpuMsPerFrame) + ' ms/frame'}`, + `30 FPS bar: ${s.bar.pass ? 'PASS' : 'not met'} avg${mark(s.bar.average)} low${mark(s.bar.low1)} speed${mark(s.bar.speed)} stutter${mark(s.bar.stutter)}`, + ]; return [ + ...game, `FPS ${f(s.fps, 0)} avg ${f(s.averageFps)} 1% low ${f(s.low1Fps)}`, `Frame time ${f(s.frameMs)} ms`, `CPU emulation ${f(s.cpuMsPerSecond, 0)} ms/s GPU rendering ${f(s.gpuMsPerSecond, 0)} ms/s`, `Bottleneck: ${s.bottleneck}`, `Frames submitted ${f(s.submittedPerSecond, 0)}/s presented ${f(s.presentedPerSecond, 0)}/s`, + 'Audio: not implemented (no XMA yet)', ].join('\n'); } @@ -116,15 +215,51 @@ export function createPerfOverlay(doc = globalThis.document) { 'border-radius:6px;pointer-events:none;white-space:pre;max-width:calc(100vw - 16px);overflow:hidden'; el.textContent = 'FPS —'; doc.body.append(el); + // Frame-time graph: guest frame times, 33.3 ms (30 FPS) and 50 ms lines. + const graph = doc.createElement('canvas'); + graph.width = 240; graph.height = 60; + graph.style.cssText = 'display:block;margin-top:6px;width:240px;height:60px'; + el.after(graph); + const box = doc.createElement('div'); + box.style.cssText = 'position:fixed;top:8px;left:8px;z-index:9998;pointer-events:none'; + el.style.position = 'static'; + el.replaceWith(box); + box.append(el, graph); + const drawGraph = times => { + const ctx = graph.getContext?.('2d'); + if (!ctx) return; + ctx.clearRect(0, 0, 240, 60); + ctx.fillStyle = 'rgba(0,0,0,.66)'; ctx.fillRect(0, 0, 240, 60); + const y = ms => 60 - Math.min(60, ms * 60 / 100); + ctx.strokeStyle = 'rgba(120,255,120,.5)'; ctx.beginPath(); ctx.moveTo(0, y(1000 / 30)); ctx.lineTo(240, y(1000 / 30)); ctx.stroke(); + ctx.strokeStyle = 'rgba(255,120,120,.5)'; ctx.beginPath(); ctx.moveTo(0, y(50)); ctx.lineTo(240, y(50)); ctx.stroke(); + ctx.fillStyle = '#e8f5e9'; + times.forEach((ms, i) => { const h = 60 - y(ms); ctx.fillRect(i * 2, 60 - h, 2, h); }); + }; let visible = true; - const toggle = () => { visible = !visible; el.style.display = visible ? '' : 'none'; }; - const onKey = e => { if (e.key === '`') toggle(); }; + const toggle = () => { visible = !visible; box.style.display = visible ? '' : 'none'; }; + // L downloads the run log (globalThis.render360Perf.exportLog). + const download = () => { + const perf = globalThis.render360Perf; + if (!perf?.exportLog) return; + const nav = globalThis.navigator || {}; + const device = {userAgent: nav.userAgent, cores: nav.hardwareConcurrency, memoryGiB: nav.deviceMemory, + gpu: globalThis.render360GpuAdapterInfo || null, screen: globalThis.screen ? `${screen.width}x${screen.height}@${globalThis.devicePixelRatio}` : null}; + const blob = new Blob([JSON.stringify(perf.exportLog(device), null, 1)], {type: 'application/json'}); + const a = doc.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = `render360-perf-${new Date().toISOString().replace(/[:.]/g, '-')}.json`; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 10000); + }; + const onKey = e => { if (e.key === '`') toggle(); else if (e.key === 'L' || e.key === 'l') download(); }; doc.addEventListener('keydown', onKey); const overlay = { element: el, toggle, - update(snapshot) { if (visible) el.textContent = formatPerf(snapshot); }, - remove() { doc.removeEventListener('keydown', onKey); el.remove(); }, + update(snapshot) { if (visible) { el.textContent = formatPerf(snapshot) + '\n[`] hide [L] download log'; drawGraph(snapshot.frameTimes || []); } }, + download, + remove() { doc.removeEventListener('keydown', onKey); box.remove(); }, }; globalThis.render360PerfOverlay = overlay; return overlay; diff --git a/render360-webgpu-play.mjs b/render360-webgpu-play.mjs index 20aca6db..d9504bf8 100644 --- a/render360-webgpu-play.mjs +++ b/render360-webgpu-play.mjs @@ -17,6 +17,7 @@ export async function createXenosWebGpuPlayPath(bootstrap,canvas){ if(typeof e.r360_gpu_set_mode!=='function')throw new Error('core has no WebGPU recorder'); const adapter=await navigator.gpu?.requestAdapter({powerPreference:'high-performance'}); if(!adapter)throw new Error('no WebGPU adapter'); + globalThis.render360GpuAdapterInfo={vendor:adapter.info?.vendor,architecture:adapter.info?.architecture,device:adapter.info?.device,description:adapter.info?.description}; const device=await adapter.requestDevice({ requiredFeatures:['float32-filterable'].filter(f=>adapter.features.has(f)), requiredLimits:{maxBufferSize:adapter.limits.maxBufferSize,maxStorageBufferBindingSize:adapter.limits.maxStorageBufferBindingSize}}); @@ -24,7 +25,7 @@ export async function createXenosWebGpuPlayPath(bootstrap,canvas){ const format=navigator.gpu.getPreferredCanvasFormat(); context.configure({device,format,alphaMode:'opaque'}); const backend=await new XenosWebGpuBackend(device,e).init(); - let lost=null; + let lost=null,gpuMs=null,pendingGpu=false; device.lost.then(info=>{lost=info?.message||'device lost';}); e.r360_gpu_set_mode(1); e.r360_xenos_soft_set_rasterize?.(0); @@ -35,13 +36,21 @@ export async function createXenosWebGpuPlayPath(bootstrap,canvas){ backend, get lost(){return lost;}, slice(){if(!lost&&(e.r360_gpu_stream_words()>>>0)>maxPendingWords)backend.replay();}, + // Submit-to-completion time of the last frame's GPU work (ms), once. + takeGpuMs(){const ms=gpuMs;gpuMs=null;return ms;}, frame(){ if(lost)return false; + const t0=performance.now(); backend.replay(); const front=backend.frontTexture; if(front&&(canvas.width!==front.width||canvas.height!==front.height)){canvas.width=front.width;canvas.height=front.height;} canvas.style.display='block'; - return backend.present(context,format); + const presented=backend.present(context,format); + if(!pendingGpu){ + pendingGpu=true; + device.queue.onSubmittedWorkDone().then(()=>{gpuMs=performance.now()-t0;pendingGpu=false;},()=>{pendingGpu=false;}); + } + return presented; }, destroy(){ e.r360_gpu_set_mode(0); diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index 8ddb4ed7..18e9c572 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -390,6 +390,9 @@ bool GuestFiberSleepUntil(uint64_t deadline_ns) { // steps no longer than a vblank period, delivering the interrupts that fall // in between (their handlers may wake a thread). Returns false if idling is // not possible here. +// Guest time spent idle (nothing runnable): the emulator was ahead of the +// guest's real-time needs (render360-perf-overlay.mjs headroom). +uint64_t g_idle_ns = 0; bool GuestFiberIdle(uint64_t deadline_ns) { if (!g_enabled || g_in_interrupt) return false; const uint64_t now = GuestClockNanoseconds(); @@ -402,6 +405,7 @@ bool GuestFiberIdle(uint64_t deadline_ns) { constexpr uint64_t kMaxIdleStepNs = 4000000ull; // 4 ms if (until > now + kMaxIdleStepNs) until = now + kMaxIdleStepNs; if (!GuestClockIdleUntil(until)) return false; + g_idle_ns += until - now; DeliverGuestInterruptsNow(); return true; } @@ -539,6 +543,8 @@ uint32_t r360_fiber_take_host_yield() { } uint32_t r360_fiber_host_yields() { return rx::g_host_yields; } uint32_t r360_fiber_preemptions() { return rx::g_preemptions; } +__attribute__((used, export_name("r360_fiber_idle_ms"))) +double r360_fiber_idle_ms() { return double(rx::g_idle_ns) / 1e6; } // Guest JIT frames (hir_wasm_jit.cpp) save their locals in the current // fiber's Asyncify buffer like Binaryen-instrumented functions: pushed on // unwind (after their callees), popped on rewind (before them). diff --git a/src/xenia_web_bootstrap/hir_correctness_executor.cpp b/src/xenia_web_bootstrap/hir_correctness_executor.cpp index e4900c6b..177c9cfa 100644 --- a/src/xenia_web_bootstrap/hir_correctness_executor.cpp +++ b/src/xenia_web_bootstrap/hir_correctness_executor.cpp @@ -1050,6 +1050,8 @@ bool ExecuteIndirect(uint64_t target, uint32_t flags, bool* reached_return, uint32_t g_debug_watch_address = 0; uint64_t g_total_instruction_budget = 0; uint64_t g_total_instructions = 0; +// Instructions run by this interpreter (the rest ran in generated code). +uint64_t g_interpreted_instructions = 0; uint64_t g_opcode_histogram[256] = {}; // executed HIR opcodes (run-title R360_OPHIST) // Guest address of the last SOURCE_OFFSET executed (diagnostics). uint32_t g_last_source_address = 0; @@ -1632,6 +1634,7 @@ HIRCorrectnessResult ExecuteBuilder(xe::cpu::hir::HIRBuilder* builder, break; } + ++g_interpreted_instructions; if (++g_total_instructions > g_total_instruction_budget && g_total_instruction_budget) { result.blocker_kind = kHIRBlockerInstructionLimit; @@ -2241,6 +2244,16 @@ uint32_t r360_hir_set_total_instruction_budget(uint32_t millions) { render360::xenia_web::g_total_instruction_budget = uint64_t(millions) * 1000000ull; return millions; } +// Performance overlay counters (render360-perf-overlay.mjs), as doubles: +// 0 guest instructions, 1 interpreted instructions. +extern "C" __attribute__((used, export_name("r360_perf_counter"))) +double r360_perf_counter(uint32_t index) { + switch (index) { + case 0: return double(render360::xenia_web::g_total_instructions); + case 1: return double(render360::xenia_web::g_interpreted_instructions); + default: return 0.0; + } +} extern "C" __attribute__((used, export_name("r360_hir_total_instructions_millions"))) uint32_t r360_hir_total_instructions_millions() { return uint32_t(render360::xenia_web::g_total_instructions / 1000000ull); diff --git a/test-perf-overlay.mjs b/test-perf-overlay.mjs index 85571e84..5a957d32 100644 --- a/test-perf-overlay.mjs +++ b/test-perf-overlay.mjs @@ -41,4 +41,42 @@ for (let i = 1; i <= 600; ++i) w.framePresented(60000 + i * 50); // then 20 FPS expect(near(w.snapshot(90000).averageFps, 15, 1.5), `windowed average ${w.snapshot(90000).averageFps}`); console.log(text); +// 30 FPS bar on guest frames. 60 s at 30 guest FPS with 20% idle, 2% of +// instructions interpreted: passes. One 80 ms hitch per 10 s: fails stutter. +{ + const run = (hitchEvery) => { + const b = new PerfStats(); + let t = 0, swaps = 0, instr = 0, interp = 0, idle = 0; + b.submitted(t, swaps); + b.counters(t, instr, interp, idle); + for (let frame = 1; frame <= 1800; ++frame) { + t += hitchEvery && frame % hitchEvery === 0 ? 80 : 1000 / 30; + b.submitted(t, ++swaps); + instr += 20e6; interp += 0.4e6; idle += (1000 / 30) * 0.2; + b.counters(t, instr, interp, idle); + b.slice(t, 20, 4, 1); + b.gpuFrame(t, 6); + b.record(t); + } + return b; + }; + const good = run(0), gs = good.snapshot(1800 * 1000 / 30); + expect(near(gs.gameFps, 30, 1) && near(gs.gameAverageFps, 30, 0.5), `game FPS ${gs.gameFps}/${gs.gameAverageFps}`); + expect(near(gs.interpretedPercent, 2, 0.01), `interpreted ${gs.interpretedPercent}`); + expect(near(gs.idlePercent, 20, 0.5) && near(gs.emulationSpeedPercent, 125, 1), `speed ${gs.emulationSpeedPercent} idle ${gs.idlePercent}`); + expect(near(gs.mips, 600, 5), `MIPS ${gs.mips}`); + expect(near(gs.gpuMsPerFrame, 6, 0.01) && near(gs.cpuMsPerGuestFrame, 16, 1), `ms/frame ${gs.cpuMsPerGuestFrame}/${gs.gpuMsPerFrame}`); + expect(gs.bar.pass && gs.stuttersPerMinute === 0, `bar should pass: ${JSON.stringify(gs.bar)}`); + expect(good.log.length >= 59 && good.exportLog({cores: 8}).records.length === good.log.length, 'log records'); + expect(formatPerf(gs).includes('30 FPS bar: PASS'), 'overlay verdict'); + const hitchy = run(300).snapshot(1800 * 1000 / 30); + expect(!hitchy.bar.pass && !hitchy.bar.stutter && near(hitchy.stuttersPerMinute, 6, 0.6), `stutters ${hitchy.stuttersPerMinute}`); + // No idle time and 20 guest FPS: speed is 20/30, bar not met. + const slow = new PerfStats(); + let t = 0; + slow.submitted(0, 0); slow.counters(0, 0, 0, 0); + for (let f = 1; f <= 600; ++f) { t += 50; slow.submitted(t, f); slow.counters(t, f * 1e7, 0, 0); } + const ss = slow.snapshot(t); + expect(near(ss.emulationSpeedPercent, 66.7, 1) && !ss.bar.pass && !ss.bar.average, `slow ${ss.emulationSpeedPercent}`); +} console.log('PERF_OVERLAY_STATS=PASS'); diff --git a/tools/run-title.mjs b/tools/run-title.mjs index 7cb81e83..5b424227 100644 --- a/tools/run-title.mjs +++ b/tools/run-title.mjs @@ -327,6 +327,10 @@ async function main(){ memoryFault:result.memoryFaultCode?{code:result.memoryFaultCode,address:hex(result.memoryFaultAddress)}:null, guestFibers:result.guestFibers??null, guestThreadWaits:globalThis.__r360Threads??null, + // 30 FPS bar inputs for a headless run (render360-perf-overlay.mjs): + // guest frames per wall second, instruction rate, interpreted share, + // guest idle time. + perf:(()=>{const x=bootstrap.exports;if(typeof x.r360_perf_counter!=='function')return null;const wall=(Date.now()-started)/1000,instr=x.r360_perf_counter(0),interp=x.r360_perf_counter(1),frames=(x.r360_title_gpu_vd_swap_calls?.()>>>0)||0;return {wallSeconds:+wall.toFixed(1),guestFrames:frames,gameFpsWall:+(frames/Math.max(wall,0.001)).toFixed(2),mips:+(instr/Math.max(wall,0.001)/1e6).toFixed(1),interpretedPercent:+(instr?100*interp/instr:0).toFixed(3),guestIdleMs:+(x.r360_fiber_idle_ms?.()??0).toFixed(0)};})(), framesPresented:(()=>{const x=bootstrap.exports;const f=n=>typeof x[n]==='function'?(x[n]()>>>0):null;return {vdSwapCalls:f('r360_title_gpu_vd_swap_calls'),vblankInterrupts:f('r360_kernel_vblank_interrupts'),cpInterrupts:f('r360_kernel_cp_interrupts'),gpuPackets:f('r360_xenos_packets'),gpuDraws:f('r360_xenos_draws'),gpuIndirect:f('r360_xenos_indirect_buffers'),gpuStatus:f('r360_xenos_status'),gpuInterruptsRaised:f('r360_xenos_interrupts'),gpuLastOpcode:f('r360_xenos_last_opcode'),gpuFaultWord:f('r360_xenos_last_fault_word'),gpuMemoryWrites:f('r360_xenos_memory_writes'),gpuSwaps:f('r360_xenos_swaps'),gpuWaits:f('r360_xenos_waits'),softDraws:f('r360_xenos_soft_draws'),cacheHits:f('r360_hir_cache_hits'),cacheMisses:f('r360_hir_cache_misses'),cacheEntries:f('r360_hir_cache_entries'),cacheKB:f('r360_hir_cache_kilobytes'),cacheCompiledOnly:f('r360_hir_cache_compiled_only_entries'),cacheCompiledOnlyHits:f('r360_hir_cache_compiled_only_hits'),cacheMemoHits:f('r360_hir_cache_memo_hits'),jitOsrEntries:f('r360_jit_osr_entries'),softSkipped:f('r360_xenos_soft_skipped'),softLastSkip:f('r360_xenos_soft_last_skip'),softResolves:f('r360_xenos_soft_resolves'),softPixels:f('r360_xenos_soft_pixels'),softTextureFailures:f('r360_xenos_soft_texture_failures'),softLastTextureFormat:f('r360_xenos_soft_last_texture_format'),vdSwapFailures:f('r360_title_gpu_vd_swap_failures'),width:f('r360_title_gpu_last_vd_swap_width'),height:f('r360_title_gpu_last_vd_swap_height')};})(), mainThread:result.mainThreadContext?{stackBytes:result.mainThreadContext.stackBytes,tlsBytes:result.mainThreadContext.tlsBytes,tlsTemplate:result.mainThreadContext.tlsTemplate}:null, kernelVariables:{relocated:result.kernelVariableRegistration?.relocated?.map(v=>v.name),placeholders:result.kernelVariableRegistration?.placeholders?.map(v=>kernelExportName(v.module,v.ordinal))}, From 54e10d91be5123f3bf55ecfd7d83a19df187af9d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 16:38:21 +0000 Subject: [PATCH 51/65] docs: prompt for an agent on the owner's Mac (native iOS app plan) How the project works, its honest status, the hard rules, locking down the public test-games repository, and the native iOS app plan: native core (pthread baton fibers, interpreter only), XcodeGen project, wgpu-native or Metal renderer, persistent translation cache, optional JIT detection, entitlements to verify, Wi-Fi game import with resume, telemetry, and per-device 30 FPS reporting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L3e1c533TFYvFAP78LRa6o --- docs/MAC_AGENT_PROMPT.md | 287 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 287 insertions(+) create mode 100644 docs/MAC_AGENT_PROMPT.md diff --git a/docs/MAC_AGENT_PROMPT.md b/docs/MAC_AGENT_PROMPT.md new file mode 100644 index 00000000..d5f6a6d2 --- /dev/null +++ b/docs/MAC_AGENT_PROMPT.md @@ -0,0 +1,287 @@ +# Prompt for an AI agent working on the owner's MacBook + +Copy everything below the line into the agent. + +--- + +You are working on **Render360**, a Xbox 360 emulator that runs in the browser. +It is a port of the Xenia emulator to WebAssembly. You have access to the +owner's **2018 Intel MacBook Pro** and to their paired **iPhone 11**. + +The project lives on an external drive whose name contains a space. Always +quote paths: `"/Volumes/EXTERNAL HD/..."`. Find the clone with +`ls "/Volumes/EXTERNAL HD"`. If none is there, clone it there: + +``` +git clone https://github.com/matthewcodergamer/Render360 "/Volumes/EXTERNAL HD/Render360" +git -C "/Volumes/EXTERNAL HD/Render360" checkout claude/xbox-360-emulator-optimization-74g72w +``` + +Work on branch **`claude/xbox-360-emulator-optimization-74g72w`** (open PR #19). +- Commit small, focused changes with clear messages. +- Push with `git push -u origin claude/xbox-360-emulator-optimization-74g72w`. +- Do not force-push. Do not rewrite history. + +## Hard rules (from the owner, non-negotiable) + +1. **Game files never go into any Git repository or GitHub release.** That + covers ISOs, STFS/CON packages, decrypted XEX, extracted assets, GPU + captures, and game-derived shaders or recompiled code. They live only on + the Mac or the phone. + - Add new game-file extensions to `.gitignore` before working with them. + - Check `git status` before every commit. +2. **The owner's own legally dumped games only.** +3. **Keep the HIR interpreter** as the correctness fallback; never delete it. +4. **Port Xenia, don't imitate it.** When Xenia has code for something, + reuse or port that code, citing the Xenia file and function in a comment. +5. **Fail closed, and report honest numbers.** + - Never claim something works without having run it. + - Report measured FPS, speed and memory, plus what is limiting them. + - Don't hide a weak device behind a strong one: report each device + separately. +6. Update `PROGRESS.md` and the PR description after each step. + +## First task: lock down the test-games repository (do this before anything else) + +`matthewcodergamer/render360-test-games` is **public**, and release `v1` +holds a Banjo-Tooie package (asset `ABB9CAB336175357D09F2D922735D23C62F90DDD58`). +The cloud agent was refused repository-settings writes. Using the owner's own +`gh` login on the Mac: + +``` +gh repo edit matthewcodergamer/render360-test-games --visibility private --accept-visibility-change-consequences +gh release view v1 -R matthewcodergamer/render360-test-games +gh release delete-asset v1 ABB9CAB336175357D09F2D922735D23C62F90DDD58 -R matthewcodergamer/render360-test-games --yes # only after the owner has a local copy +``` + +Keep a local copy of the package on the Mac first. Ask the owner before +deleting the asset. + +## How the project works today + +### Core (C++ compiled to WebAssembly) + +Directory `src/xenia_web_bootstrap/`, plus Xenia sources from +`upstream/xenia` patched by `prepare-*.py` overlay scripts at build time. + +| File | What it does | +| --- | --- | +| `probe_backend.cpp` | Guest call resolver, translation cache (HIR builders + a compiled-only tier), tail-call trampoline (`TranslateNestedGuestAddress`) | +| `hir_correctness_executor.cpp` | The HIR **interpreter** (Xenia's PPC frontend → HIR → interpreted) | +| `hir_wasm_jit.cpp` + `hir_jit_glue.inc` | HIR → **WebAssembly JIT** (segment dispatcher, OSR, polls). Wasm-only | +| `guest_fibers.cpp` | Guest threads as cooperative fibers switched with **Emscripten Asyncify** (`#if defined(__wasm__)`). Wasm-only; the native build has no thread switching at all | +| `sparse_guest_memory.cpp` | Guest memory: page table, write watches for GPU invalidation | +| `kernel_xboxkrnl_services.cpp` | xboxkrnl/XAM kernel services ported from Xenia; interrupts, vblank, XMA register window (no audio decode yet) | +| `xenos_gpu_foundation.cpp` | PM4 command processor (ring buffer, draws, swaps) | +| `xenos_soft_renderer.cpp` | CPU software renderer (the frames the web player shows today) | +| `webgpu_backend.cpp/.h`, `webgpu_draws.cpp`, `webgpu_textures.cpp` | **WebGPU recorder**: a port of Xenia's Vulkan backend that records a command stream (ops 1–12 in `webgpu_backend.h`). Shaders come from Xenia's SPIR-V translator; Xenia's texture cache and its own `texture_load_*` / `resolve_*` compute shaders are used | + +### JavaScript + +| File | What it does | +| --- | --- | +| `render360-webgpu-backend.mjs` | Replays the recorded stream into WebGPU. Naga (`render360_spirv_wgsl*`) converts SPIR-V to WGSL | +| `render360-webgpu-play.mjs` | Browser play path, opt-in with `?gpu=xenos` | +| `render360-perf-overlay.mjs` | The 30 FPS bar overlay. Backtick toggles it; **L** downloads a JSON log with device info | +| `tools/run-title.mjs` | Headless runner (Node 22). The JSON report has a `perf` block | + +### Build + +`build-xenia-ppc-bootstrap.sh` then `link-xenia-ppc-bootstrap.sh`, with +emsdk sourced. Run `git -C upstream/xenia checkout -- .` before building, +because the overlays patch that tree. The output is +`build/xenia-ppc-bootstrap/xenia_ppc_bootstrap.wasm` (~3.9 MB). + +### Tests + +The tests are the `test-*.mjs` files at the repo root. + +| Test | Covers | +| --- | --- | +| `test-perf-overlay.mjs` | Overlay statistics | +| `test-webgpu-shared-memory*.mjs` | WebGPU shared memory | +| `test-webgpu-replay-capture-browser.mjs` | Replays a **local** GPU capture in headless Chromium; skips without one | +| `test-guest-jit-osr.mjs` | JIT OSR | + +Plus the PPC instruction suite and the JIT differential test. + +### Status (honest) + +- **Banjo-Tooie gameplay:** reaches controllable gameplay headlessly. +- **Wasm CPU:** ~660 guest MIPS on a fast x86 core. At the headless runner's + deterministic clock (1 ns per instruction) real time is ~1000 MIPS, so the + wasm CPU runs at roughly 65% of real time before graphics. +- **WebGPU renderer:** renders a correct Banjo main menu frame from a capture, + through draws, textures, EDRAM resolves and clears. +- **Known renderer bug:** the resolved image is shifted 32 px right. Suspects + are the window offset / resolve rectangle handling in `webgpu_draws.cpp` + `Resolve()` and the EDRAM dump in `render360-webgpu-backend.mjs` `dumpEdram()`. +- **Known CPU bug:** at ~105B instructions the game stalls when two functions + are JIT-compiled: `0x822398D8` (a table fixed-point loop) and `0x8227E6A0` + (a thunk ending in a direct tail call `call.2`). The prime suspect is + compiled tail calls interacting with the tail-call trampoline. The + interpreter is correct. +- **Audio:** none (XMA decoding not implemented). + +## Your task: Render360 as a native iOS app on the iPhone 11 + +**Why:** Safari kills the web tab for memory, so the browser version cannot +run Banjo on the phone. + +### Step 0: measure what exists, on the Mac's own browsers (one hour, do it first) + +Serve the repo locally, e.g. `python3 -m http.server 8080` from the repo +root; WebGPU needs localhost or https. Then open the player with +`?gpu=xenos` in Chrome and in Safari, load Banjo, and play for 5 minutes. +Press **L** to save the perf log. Report game FPS, 1% low, emulation speed +and interpreted %, for each browser separately. + +### Step 1: native core (macOS first, then iOS arm64) + +1. Add a CMake build, e.g. `native/CMakeLists.txt`, that compiles the same + source set as `build-xenia-ppc-bootstrap.sh`, including the overlays + produced by the `prepare-*.py` scripts, with clang for the host. Mirror + the shell script's source list exactly. Don't hand-pick files. +2. Provide native replacements for the wasm-only pieces: + - **Guest fibers:** replace Asyncify with one pthread per guest thread and + a baton (mutex + condition variable), so exactly one guest thread runs + at a time. That preserves today's cooperative scheduling and + determinism. Keep the same API as `guest_fibers.h`. + `swapcontext` is unavailable on iOS; don't use it. + - **JIT:** compile `hir_wasm_jit.cpp` out (stub `JitEnabled()` to false). + Native runs are **interpreter only** at first. + - **WASI / `export_name` / host imports:** route the `r360_*` exports to a + small C API header, e.g. `native/render360_core.h`, that the app calls. +3. Native headless runner (`native/run-title`): load a STFS/XEX from a path, + run N billion instructions, write the same JSON report as + `tools/run-title.mjs`. Verify on the Mac that Banjo reaches the same + swap counts as the wasm build at the same instruction counts + (deterministic mode). Report native MIPS, interpreter only, on the Mac. + +### Step 2: the iOS app shell (`ios/`) + +**Project and build** +- SwiftUI app with the core linked as a static library. +- Generate the Xcode project with XcodeGen (`ios/project.yml`) so it's + reviewable in git. +- **No WKWebView for the emulator.** +- If the Mac's Xcode can't build for the iPhone, add a GitHub Actions + workflow on `macos-latest`. It builds the unsigned app and uploads it as an + artifact: never game files, never signed builds with credentials. +- Signing happens on the Mac with the owner's **free Apple ID**: + - Builds expire after 7 days. + - Add an in-app reminder showing the days left, read from + `embedded.mobileprovision`. + +**Entitlements** +- `com.apple.developer.kernel.increased-memory-limit` and + `com.apple.developer.kernel.extended-virtual-addressing`. +- **Verify which ones a free (non-paid) account can actually use.** + Extended Virtual Addressing may need the paid program. Report what works; + don't assume. + +**Graphics** + +| Option | How | Tradeoff | +| --- | --- | --- | +| **(a) wgpu-native**, preferred to start | Port `render360-webgpu-backend.mjs` to C++ against wgpu-native's `webgpu.h` | wgpu accepts SPIR-V directly, so Xenia's shaders need no Naga step, and push constants are a native wgpu feature, so Xenia's load and resolve shaders can use them unmodified. The renderer logic stays shared with the web version | +| **(b) Metal directly** | Reuse the owner's GTA V port lessons | Faster at the end, more work | + +Whichever you choose, carry over: +- **ASTC** for BC textures, with a self-test at startup that compares against + a decoded reference. Today's web path decompresses BC to RGBA8, which uses + 4–8× the memory. +- **RG/RGBA16F** for 32-bit float textures that must filter. +- A **memory guard**: watch `os_proc_available_memory()`, shrink caches + before iOS kills the app, and log it. + +**CPU and JIT** +- Ship the interpreter, plus a **persistent translation cache** on disk: + keep translated HIR or a lighter form so a function is translated once, + ever. +- Add an optional JIT mode that turns on only when the process can map + executable memory: + - Detect it at startup by trying `mmap` with `MAP_JIT` / a dual mapping + and executing a tiny stub. + - It works with StikDebug on a sideloaded build. +- **No arm64 JIT backend exists yet** (Xenia only has x64). Treat the JIT + mode as a later project and report the interpreter speed honestly. + +**Telemetry, overlay and controls** (as in the owner's GTA port) +- An HTTP `/status` endpoint on the phone that the Mac can poll over Wi-Fi. + JSON: FPS, emulation speed, MIPS, interpreted %, memory in use, available + memory, thermal state. +- Crash breadcrumbs written to a file that survives restarts. +- A **30 FPS cap**. +- MFi / Xbox / PlayStation controllers via `GameController.framework`. +- On-screen touch controls. +- Same overlay fields as `render360-perf-overlay.mjs`. + +### Step 3: game import (never in any repo) + +- An in-app **Import game** with three sources: + - the Files app (document picker); + - AirDrop (open-in); + - a download from the Mac over Wi-Fi. +- Write `tools/serve-games.py` for the Mac side. It serves a folder over + HTTP with **Range** support, and the app resumes interrupted downloads. +- Store games in the app's `Documents/Games/`, with + `isExcludedFromBackup = true` on each file so they are excluded from + iCloud backup. +- **Multi-disc** titles: group discs under one game entry and let the core's + VFS swap discs. Watch Dogs has two discs. + +### Step 4: tests on the iPhone 11 (report each separately) + +1. **Banjo-Tooie:** boot to gameplay. Report: + - FPS, 1% low, emulation speed %, interpreted %; + - peak memory and available memory; + - thermal state after 10 minutes; + - time to reach gameplay. + + If it isn't real time (expected with interpreter only), say by how much + and what limits it: CPU, GPU or memory. +2. **Watch Dogs, record mode:** boot as far as it goes, recording every guest + function entry and indirect-branch target. Export a **ReXGlue manifest** + for the owner's native recompile. + - Check ReXGlue's actual expected input format first. Don't invent one. + - The manifest is game-derived: keep it on the Mac. Do not commit it. + +### Step 5: documentation + +Write `docs/IOS_APP.md` covering: +- building, on the Mac and in CI; +- signing with a free Apple ID; +- installing on the paired iPhone; +- the 7-day re-sign; +- importing games; +- the telemetry endpoint; +- known limits. + +Commit everything except game data and push to the branch above. + +## The 30 FPS bar (definition of done for any game) + +A game counts as supported only when it holds this bar: + +| Requirement | Threshold | +| --- | --- | +| Average FPS | ≥ 30 | +| 1% low | ≥ 25 | +| Emulation speed | ≥ 100% | +| Stutters (frames over 50 ms) | no more than one per minute | +| Audio | in sync | + +- Devices, reported separately: desktop Chrome, the 2018 MBP, the iPhone 11. +- Ladder: Banjo-Tooie → another Arcade title → a light retail game → a + mid-weight game → GTA IV → Watch Dogs. +- Move to the next game only after the current one passes on desktop. + +## How to report back + +After each step, add to `PROGRESS.md`: +- what you ran (exact commands); +- the measured numbers; +- what broke, and what you'd do next. + +Never report a step as done that you haven't run on the real device. From 858290efaade14af3881a1f222b74b1a377e1a22 Mon Sep 17 00:00:00 2001 From: Conrad Milton Powell Date: Sat, 17 Oct 2026 13:29:39 -0500 Subject: [PATCH 52/65] Native core build for macOS/iOS (interpreter only), native boot port, game server - xenia-ppc-sources.sh: one source list shared by the wasm and native builds - native/build-native.sh: clang build of the same sources + overlays for macos-x86_64/arm64 and ios-arm64; package core merged with r360pkg_ exports - guest_fibers.cpp: native guest threads as pthreads with a baton (same scheduler policy as the Asyncify fibers) - pointer-carrying r360_* exports widened to uintptr_t (wasm32 ABI unchanged) - native/src/native_title.cpp: C++ port of handoffDefaultXex boot path - native/tools/run_title.cpp: native headless runner - tools/serve-games.py: Range-capable game server for the iOS app - ios/: XcodeGen project skeleton (work in progress) Co-Authored-By: Claude Opus 5.5 --- .gitignore | 17 + build-xenia-ppc-bootstrap.sh | 70 +- ios/Render360/PerfStats.swift | 103 ++ ios/Render360/R360Platform.h | 14 + ios/Render360/R360Platform.m | 64 + ios/Render360/Render360-Bridging-Header.h | 3 + ios/Signing.xcconfig | 6 + ios/project.yml | 78 + native/build-native.sh | 102 ++ native/include/r360_native_compat.h | 13 + native/include/render360_core.h | 103 ++ native/include/render360_core_exports.h | 534 ++++++ native/include/xenia/base/platform.h | 34 + native/src/native_jit.cpp | 77 + native/src/native_title.cpp | 1440 +++++++++++++++++ native/tools/gen_core_api.py | 41 + native/tools/run_title.cpp | 123 ++ prepare-xenia-web-overlay.py | 2 +- render360_xenia_core.cpp | 12 +- src/xenia_web_bootstrap/guest_fibers.cpp | 263 ++- .../hir_correctness_executor.h | 5 + .../kernel_import_probe.cpp | 2 +- .../kernel_xboxkrnl_services.cpp | 43 +- .../ppc_translation_probe.cpp | 4 +- src/xenia_web_bootstrap/probe_backend.cpp | 17 +- .../sparse_guest_memory.cpp | 5 +- src/xenia_web_bootstrap/title_gpu_runtime.cpp | 4 +- src/xenia_web_bootstrap/webgpu_backend.cpp | 4 +- .../xenos_gpu_foundation.cpp | 6 +- .../xenos_shader_interpreter_probe.cpp | 4 +- .../xenos_spirv_translation_probe.cpp | 12 +- src/xenia_web_bootstrap/xex_guest_mapper.cpp | 6 +- src/xenia_web_bootstrap/xex_guest_mapper.h | 4 +- .../xex_image_decoder_exports.cpp | 2 +- .../xex_image_preparer_exports.cpp | 2 +- .../xex_pe_guest_loader.cpp | 6 +- src/xenia_web_bootstrap/xex_pe_guest_loader.h | 4 +- src/xenia_web_bootstrap/xex_title_handoff.cpp | 4 +- tools/serve-games.py | 203 +++ xenia-ppc-sources.sh | 83 + 40 files changed, 3395 insertions(+), 124 deletions(-) create mode 100644 ios/Render360/PerfStats.swift create mode 100644 ios/Render360/R360Platform.h create mode 100644 ios/Render360/R360Platform.m create mode 100644 ios/Render360/Render360-Bridging-Header.h create mode 100644 ios/Signing.xcconfig create mode 100644 ios/project.yml create mode 100644 native/build-native.sh create mode 100644 native/include/r360_native_compat.h create mode 100644 native/include/render360_core.h create mode 100644 native/include/render360_core_exports.h create mode 100644 native/include/xenia/base/platform.h create mode 100644 native/src/native_jit.cpp create mode 100644 native/src/native_title.cpp create mode 100644 native/tools/gen_core_api.py create mode 100644 native/tools/run_title.cpp create mode 100644 tools/serve-games.py create mode 100644 xenia-ppc-sources.sh diff --git a/.gitignore b/.gitignore index bcfb06cc..e3a7cada 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,20 @@ node_modules/ *.log build/ upstream/ +# Game data never goes in git (owner rule): discs, packages, decrypted images, captures, manifests +*.iso +*.xex +*.xcp +*.god +*.stfs +*.con +*.r360cap +*.gpucap +rexglue-manifest* +/games-local/ + +# iOS: personal signing values, build products +/ios/Signing.local.xcconfig +/ios/Render360.xcodeproj/ +/ios/build/ +*.ipa diff --git a/build-xenia-ppc-bootstrap.sh b/build-xenia-ppc-bootstrap.sh index 2c7d5ff3..67db7dbc 100644 --- a/build-xenia-ppc-bootstrap.sh +++ b/build-xenia-ppc-bootstrap.sh @@ -81,18 +81,7 @@ if [ -n "$LLVM_INCLUDE" ] && [ -d "$LLVM_INCLUDE" ]; then echo "LLVM headers: $LLVM_INCLUDE" fi -SOURCES=( - "third_party/fmt/src/format.cc" - "src/xenia/base/arena.cc" "src/xenia/base/cvar.cc" "src/xenia/base/utf8.cc" "src/xenia/base/filesystem_posix.cc" "src/xenia/base/memory.cc" "src/xenia/base/memory_posix.cc" "src/xenia/base/mapped_memory_posix.cc" "src/xenia/base/mutex.cc" "src/xenia/base/string.cc" "src/xenia/base/string_buffer.cc" - "src/xenia/memory.cc" "src/xenia/cpu/cpu_flags.cc" "src/xenia/cpu/mmio_handler.cc" "src/xenia/cpu/entry_table.cc" "src/xenia/cpu/module.cc" "src/xenia/cpu/stack_walker_posix.cc" "src/xenia/cpu/thread_state.cc" "src/xenia/cpu/processor.cc" "src/xenia/cpu/lzx.cc" - "src/xenia/cpu/backend/backend.cc" "src/xenia/cpu/backend/assembler.cc" "src/xenia/cpu/function.cc" "src/xenia/cpu/function_debug_info.cc" - "src/xenia/cpu/hir/opcodes.cc" "src/xenia/cpu/hir/block.cc" "src/xenia/cpu/hir/instr.cc" "src/xenia/cpu/hir/value.cc" "src/xenia/cpu/hir/hir_builder.cc" - "src/xenia/cpu/compiler/compiler.cc" "src/xenia/cpu/compiler/compiler_pass.cc" - "src/xenia/cpu/compiler/passes/conditional_group_pass.cc" "src/xenia/cpu/compiler/passes/conditional_group_subpass.cc" "src/xenia/cpu/compiler/passes/constant_propagation_pass.cc" "src/xenia/cpu/compiler/passes/context_promotion_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_simplification_pass.cc" "src/xenia/cpu/compiler/passes/data_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/dead_code_elimination_pass.cc" "src/xenia/cpu/compiler/passes/finalization_pass.cc" "src/xenia/cpu/compiler/passes/memory_sequence_combination_pass.cc" "src/xenia/cpu/compiler/passes/register_allocation_pass.cc" "src/xenia/cpu/compiler/passes/simplification_pass.cc" "src/xenia/cpu/compiler/passes/validation_pass.cc" "src/xenia/cpu/compiler/passes/value_reduction_pass.cc" - "src/xenia/cpu/ppc/ppc_context.cc" "src/xenia/cpu/ppc/ppc_opcode_table_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_lookup_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm.cc" "src/xenia/cpu/ppc/ppc_opcode_info.cc" "src/xenia/cpu/ppc/ppc_emit_alu.cc" "src/xenia/cpu/ppc/ppc_emit_control.cc" "src/xenia/cpu/ppc/ppc_emit_memory.cc" "src/xenia/cpu/ppc/ppc_emit_fpu.cc" "src/xenia/cpu/ppc/ppc_emit_altivec.cc" "src/xenia/cpu/ppc/ppc_scanner.cc" "src/xenia/cpu/ppc/ppc_hir_builder.cc" "src/xenia/cpu/ppc/ppc_translator.cc" "src/xenia/cpu/ppc/ppc_frontend.cc" - "src/xenia/kernel/util/xdbf_utils.cc" "src/xenia/gpu/gpu_flags.cc" "src/xenia/gpu/register_file.cc" "src/xenia/gpu/ucode.cc" "src/xenia/gpu/shader.cc" "src/xenia/gpu/shader_translator.cc" "src/xenia/gpu/shader_translator_disasm.cc" "src/xenia/gpu/shader_interpreter.cc" "src/xenia/gpu/draw_util.cc" "src/xenia/gpu/registers.cc" "src/xenia/gpu/xenos.cc" "src/xenia/gpu/texture_util.cc" "src/xenia/gpu/texture_info.cc" "src/xenia/gpu/texture_info_formats.cc" "src/xenia/ui/graphics_util.cc" "src/xenia/gpu/spirv_builder.cc" "src/xenia/gpu/spirv_shader.cc" "src/xenia/gpu/spirv_shader_translator.cc" - "third_party/glslang/SPIRV/SpvBuilder.cpp" -) +source "$ROOT/xenia-ppc-sources.sh" classify_failure() { local log="$1" @@ -170,59 +159,7 @@ queue_c() { } phase "Compiling wasm32 source matrix with $JOBS parallel job(s)" -for rel in "${SOURCES[@]}"; do - case "$rel" in - "src/xenia/base/arena.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/arena.cc" ;; - "src/xenia/base/cvar.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/cvar.cc" ;; - "src/xenia/base/utf8.cc") queue_cpp "$rel" "$OVERLAY/xenia/base/utf8.cc" ;; - "src/xenia/memory.cc") queue_cpp "$rel" "$OVERLAY/xenia/memory.cc" ;; - "src/xenia/cpu/mmio_handler.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/mmio_handler.cc" ;; - "src/xenia/cpu/processor.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/processor.cc" ;; - "src/xenia/cpu/hir/value.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/hir/value.cc" ;; - "src/xenia/cpu/ppc/ppc_scanner.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_scanner.cc" ;; - "src/xenia/cpu/ppc/ppc_translator.cc") queue_cpp "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_translator.cc" ;; - "src/xenia/gpu/draw_util.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/draw_util.cc" ;; - "src/xenia/gpu/shader_translator.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/shader_translator.cc" ;; - "src/xenia/gpu/shader_interpreter.cc") queue_cpp "$rel" "$OVERLAY/xenia/gpu/shader_interpreter.cc" ;; - *) queue_cpp "$rel" "$XENIA/$rel" ;; - esac -done - -queue_c "third_party/mspack/lzxd.c" "$XENIA/third_party/mspack/lzxd.c" -queue_c "third_party/crypto/rijndael-alg-fst.c" "$XENIA/third_party/crypto/rijndael-alg-fst.c" -queue_cpp "render360/browser_logging.cpp" "$ROOT/src/xenia_web_bootstrap/browser_logging.cpp" -queue_cpp "render360/browser_threading_sleep.cpp" "$ROOT/src/xenia_web_bootstrap/browser_threading_sleep.cpp" -queue_cpp "render360/hir_correctness_executor.cpp" "$OVERLAY/render360/hir_correctness_executor_vmx.cpp" -queue_cpp "render360/kernel_import_probe.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_import_probe.cpp" -queue_cpp "render360/kernel_runtime_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_runtime_foundation.cpp" -queue_cpp "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibers.cpp" -queue_cpp "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" -queue_cpp "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" -queue_cpp "render360/webgpu_backend.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_backend.cpp" -queue_cpp "render360/webgpu_draws.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_draws.cpp" -queue_cpp "render360/webgpu_textures.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_textures.cpp" -queue_cpp "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" -queue_cpp "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" -queue_cpp "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" -queue_cpp "render360/xenos_gpu_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp" -queue_cpp "render360/xenos_shader_interpreter_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp" -queue_cpp "render360/xenos_spirv_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp" -queue_cpp "render360/wasm_backend_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_probe.cpp" -queue_cpp "render360/wasm_backend_cfg_probe.cpp" "$OVERLAY/render360/wasm_backend_cfg_probe.cpp" -queue_cpp "render360/wasm_backend_memory_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_memory_probe.cpp" -queue_cpp "render360/wasm_backend_call_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_call_probe.cpp" -queue_cpp "render360/wasm_backend_fpu_probe.cpp" "$OVERLAY/render360/wasm_backend_fpu_probe_v2.cpp" -queue_cpp "render360/wasm_backend_vmx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_vmx_probe.cpp" -queue_cpp "render360/sparse_guest_memory.cpp" "$ROOT/src/xenia_web_bootstrap/sparse_guest_memory.cpp" -queue_cpp "render360/xex_guest_mapper.cpp" "$ROOT/src/xenia_web_bootstrap/xex_guest_mapper.cpp" -queue_cpp "render360/xex_pe_image.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_image.cpp" -queue_cpp "render360/xex_pe_guest_loader.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp" -queue_cpp "render360/xex_title_handoff.cpp" "$ROOT/src/xenia_web_bootstrap/xex_title_handoff.cpp" -queue_cpp "render360/xex_lzx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_lzx_probe.cpp" -queue_cpp "render360/xex_crypto_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_crypto_probe.cpp" -queue_cpp "render360/probe_backend.cpp" "$ROOT/src/xenia_web_bootstrap/probe_backend.cpp" -queue_cpp "render360/ppc_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_translation_probe.cpp" -queue_cpp "render360/ppc_context_abi_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_context_abi_probe.cpp" +r360_for_each_source queue_cpp queue_c wait || true @@ -235,7 +172,8 @@ done passed="$(awk -F '\t' '$2=="PASS"{n++} END{print n+0}' "$OUT/report.tsv")" failed="$(awk -F '\t' '$2=="BLOCKED"{n++} END{print n+0}' "$OUT/report.tsv")" -expected=$(( ${#SOURCES[@]} + 2 + 33 )) +r360_source_count +expected=$R360_SOURCE_COUNT actual=$(( passed + failed )) echo diff --git a/ios/Render360/PerfStats.swift b/ios/Render360/PerfStats.swift new file mode 100644 index 00000000..9d3d5c57 --- /dev/null +++ b/ios/Render360/PerfStats.swift @@ -0,0 +1,103 @@ +import Foundation + +/// Swift port of PerfStats (render360-perf-overlay.mjs) so the phone reports +/// the same numbers as the web overlay and the 30 FPS bar means the same thing: +/// judged on guest frames (VdSwap presents per second), average >= 30 and +/// 1% low >= 25 over the last 60 s, emulation speed >= 100%, at most one frame +/// over 50 ms per minute. Emulation speed is 100% plus the headroom when the +/// guest had idle time; without idle time it is game FPS / 30. +final class PerfStats { + struct Snapshot: Codable { + var gameFps: Double = 0 + var gameAverageFps: Double = 0 + var gameLow1Fps: Double = 0 + var stuttersPerMinute: Double = 0 + var emulationSpeedPercent: Double = 0 + var idlePercent: Double = 0 + var mips: Double = 0 + var interpretedPercent: Double = 0 + var presentedFps: Double = 0 + var barAverage = false, barLow1 = false, barSpeed = false, barStutter = false, barPass = false + var windowSeconds: Double = 0 + } + + private let windowMs: Double + private var guestFrameTimes: [Double] = [] // ms, one per new guest frame + private var presentTimes: [Double] = [] + private var counterSamples: [(t: Double, instructions: Double, interpreted: Double, idleMs: Double)] = [] + private var lastSubmitted: UInt32 = 0 + private let lock = NSLock() + + init(windowMs: Double = 60000) { self.windowMs = windowMs } + + static func nowMs() -> Double { Double(DispatchTime.now().uptimeNanoseconds) / 1e6 } + + /// Guest frames submitted so far (cumulative VdSwap count). + func submitted(_ t: Double, frames: UInt32) { + lock.lock(); defer { lock.unlock() } + if frames > lastSubmitted { + for _ in 0..= cutoff }), i > 0 { guestFrameTimes.removeFirst(i) } + if let i = presentTimes.firstIndex(where: { $0 >= cutoff }), i > 0 { presentTimes.removeFirst(i) } + if let i = counterSamples.firstIndex(where: { $0.t >= t - 5000 }), i > 0 { counterSamples.removeFirst(i) } + } + + func snapshot(_ t: Double = PerfStats.nowMs()) -> Snapshot { + lock.lock(); defer { lock.unlock() } + var s = Snapshot() + let g = guestFrameTimes + s.gameFps = Double(g.filter { $0 > t - 1000 }.count) + s.presentedFps = Double(presentTimes.filter { $0 > t - 1000 }.count) + let span = g.count > 1 ? max(1, t - g[0]) : 0 + s.windowSeconds = span / 1000 + s.gameAverageFps = span > 0 ? Double(g.count - 1) * 1000 / span : s.gameFps + var deltas: [Double] = [] + if g.count > 1 { for i in 1.. g[i - 1] { deltas.append(g[i] - g[i - 1]) } } + if !deltas.isEmpty { + let worst = deltas.sorted(by: >).prefix(max(1, Int(ceil(Double(deltas.count) / 100)))) + s.gameLow1Fps = 1000 / (worst.reduce(0, +) / Double(worst.count)) + } + let stutters = Double(deltas.filter { $0 > 50 }.count) + let minutes = max(1.0 / 60, min(windowMs, span > 0 ? span : 1000) / 60000) + s.stuttersPerMinute = stutters / minutes + let cs = counterSamples + if cs.count > 1 { + let last = cs[cs.count - 1] + var first = cs.first(where: { $0.t >= t - 1000 }) ?? cs[0] + if first.t == last.t { first = cs[cs.count - 2] } + let dt = max(1, last.t - first.t) + let di = last.instructions - first.instructions + s.mips = di / dt / 1000 + s.interpretedPercent = di > 0 ? 100 * (last.interpreted - first.interpreted) / di : 0 + s.idlePercent = min(100, 100 * (last.idleMs - first.idleMs) / dt) + } + s.emulationSpeedPercent = s.idlePercent > 0 ? 100 / max(0.01, 1 - s.idlePercent / 100) + : min(100, 100 * s.gameFps / 30) + s.barAverage = s.gameAverageFps >= 30 + s.barLow1 = s.gameLow1Fps >= 25 + s.barSpeed = s.emulationSpeedPercent >= 100 + s.barStutter = s.stuttersPerMinute <= 1 + s.barPass = s.barAverage && s.barLow1 && s.barSpeed && s.barStutter && span >= 10000 + return s + } +} diff --git a/ios/Render360/R360Platform.h b/ios/Render360/R360Platform.h new file mode 100644 index 00000000..e332c909 --- /dev/null +++ b/ios/Render360/R360Platform.h @@ -0,0 +1,14 @@ +// Small C helpers Swift cannot call directly. +#pragma once +#include +#include + +// Bytes the process may still allocate before iOS jetsams it +// (os_proc_available_memory), and the current physical footprint. +uint64_t r360_platform_available_memory(void); +uint64_t r360_platform_footprint(void); +// Breadcrumbs: append one line and fsync, so the last lines survive a crash. +void r360_breadcrumb_open(const char* path); +void r360_breadcrumb(const char* line); +// Installs signal handlers that write a final breadcrumb on a crash. +void r360_install_crash_handlers(void); diff --git a/ios/Render360/R360Platform.m b/ios/Render360/R360Platform.m new file mode 100644 index 00000000..a06950a4 --- /dev/null +++ b/ios/Render360/R360Platform.m @@ -0,0 +1,64 @@ +#import "R360Platform.h" + +#include +#include +#include +#include +#include +#include +#include + +uint64_t r360_platform_available_memory(void) { return (uint64_t)os_proc_available_memory(); } + +uint64_t r360_platform_footprint(void) { + task_vm_info_data_t info; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count) != KERN_SUCCESS) return 0; + return info.phys_footprint; +} + +static int g_breadcrumb_fd = -1; + +void r360_breadcrumb_open(const char* path) { + if (g_breadcrumb_fd >= 0) close(g_breadcrumb_fd); + g_breadcrumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644); +} + +static void write_line(const char* line) { + if (g_breadcrumb_fd < 0) return; + char stamp[32]; + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + const int n = snprintf(stamp, sizeof(stamp), "%lld.%03ld ", (long long)ts.tv_sec, ts.tv_nsec / 1000000); + write(g_breadcrumb_fd, stamp, (size_t)n); + write(g_breadcrumb_fd, line, strlen(line)); + write(g_breadcrumb_fd, "\n", 1); +} + +void r360_breadcrumb(const char* line) { + write_line(line); + if (g_breadcrumb_fd >= 0) fsync(g_breadcrumb_fd); +} + +static void crash_handler(int sig) { + // Async-signal-safe only: write + fsync, then re-raise for the system report. + char line[64]; + const char* name = sig == SIGSEGV ? "SIGSEGV" : sig == SIGBUS ? "SIGBUS" : sig == SIGILL ? "SIGILL" + : sig == SIGABRT ? "SIGABRT" : sig == SIGFPE ? "SIGFPE" : sig == SIGTRAP ? "SIGTRAP" : "signal"; + size_t n = 0; + const char* prefix = "CRASH "; + for (const char* p = prefix; *p; ++p) line[n++] = *p; + for (const char* p = name; *p && n < sizeof(line) - 2; ++p) line[n++] = *p; + line[n++] = '\n'; + if (g_breadcrumb_fd >= 0) { + write(g_breadcrumb_fd, line, n); + fsync(g_breadcrumb_fd); + } + signal(sig, SIG_DFL); + raise(sig); +} + +void r360_install_crash_handlers(void) { + const int signals[] = {SIGSEGV, SIGBUS, SIGILL, SIGABRT, SIGFPE, SIGTRAP}; + for (size_t i = 0; i < sizeof(signals) / sizeof(signals[0]); ++i) signal(signals[i], crash_handler); +} diff --git a/ios/Render360/Render360-Bridging-Header.h b/ios/Render360/Render360-Bridging-Header.h new file mode 100644 index 00000000..e8116281 --- /dev/null +++ b/ios/Render360/Render360-Bridging-Header.h @@ -0,0 +1,3 @@ +// Exposes the Render360 C core (native/include) to Swift. +#import "render360_core.h" +#import "R360Platform.h" diff --git a/ios/Signing.xcconfig b/ios/Signing.xcconfig new file mode 100644 index 00000000..d94fd394 --- /dev/null +++ b/ios/Signing.xcconfig @@ -0,0 +1,6 @@ +// Shared signing settings. Personal values go in Signing.local.xcconfig +// (git-ignored): DEVELOPMENT_TEAM = and +// R360_BUNDLE_ID = com..render360 (free teams need a +// bundle ID nobody else registered). +R360_BUNDLE_ID = com.render360.app +#include? "Signing.local.xcconfig" diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 00000000..5ac09d77 --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,78 @@ +# Render360 native iOS app. Generate the Xcode project with XcodeGen: +# cd ios && xcodegen generate +# The Render360 core is a static library built by native/build-native.sh +# (R360_NATIVE_TARGET=ios-arm64). See docs/IOS_APP.md. +name: Render360 +options: + bundleIdPrefix: com.render360 + deploymentTarget: + iOS: "16.0" + createIntermediateGroups: true +settings: + base: + # Free Apple ID ("Personal Team") signing: set your team in + # ios/Signing.local.xcconfig (git-ignored), see docs/IOS_APP.md. + CODE_SIGN_STYLE: Automatic + SWIFT_VERSION: "5.0" + IPHONEOS_DEPLOYMENT_TARGET: "16.0" + TARGETED_DEVICE_FAMILY: "1,2" + ENABLE_BITCODE: NO + CLANG_CXX_LANGUAGE_STANDARD: c++20 + ARCHS: arm64 +configFiles: + Debug: Signing.xcconfig + Release: Signing.xcconfig +targets: + Render360: + type: application + platform: iOS + sources: + - path: Render360 + excludes: + - "*.entitlements" + info: + path: Render360/Info.plist + properties: + CFBundleDisplayName: Render360 + CFBundleShortVersionString: "1.0" + CFBundleVersion: "1" + UILaunchScreen: {} + UIRequiresFullScreen: true + UIStatusBarHidden: true + UISupportedInterfaceOrientations: [UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight, UIInterfaceOrientationPortrait] + UIFileSharingEnabled: true + LSSupportsOpeningDocumentsInPlace: false + UISupportsDocumentBrowser: false + GCSupportsControllerUserInteraction: true + GCSupportedGameControllers: + - ProfileName: ExtendedGamepad + NSLocalNetworkUsageDescription: "Render360 downloads your own game files from your Mac and serves live performance telemetry to it over Wi-Fi." + NSBonjourServices: [_render360._tcp] + CFBundleDocumentTypes: + - CFBundleTypeName: Xbox 360 game + CFBundleTypeRole: Viewer + LSHandlerRank: Alternate + LSItemContentTypes: [public.data, public.disk-image, com.render360.xbox360-game] + UTImportedTypeDeclarations: + - UTTypeIdentifier: com.render360.xbox360-game + UTTypeDescription: Xbox 360 game + UTTypeConformsTo: [public.data] + UTTypeTagSpecification: + public.filename-extension: [iso, xex, god, stfs, con] + entitlements: + path: Render360/Render360.entitlements + properties: + com.apple.developer.kernel.increased-memory-limit: true + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(R360_BUNDLE_ID) + SWIFT_OBJC_BRIDGING_HEADER: Render360/Render360-Bridging-Header.h + HEADER_SEARCH_PATHS: ["$(SRCROOT)/../native/include"] + LIBRARY_SEARCH_PATHS: ["$(SRCROOT)/../build/native-ios-arm64"] + OTHER_LDFLAGS: ["-lrender360core", "-lc++", "-Wl,-dead_strip"] + ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon + dependencies: + - sdk: Metal.framework + - sdk: MetalKit.framework + - sdk: GameController.framework + - sdk: Network.framework diff --git a/native/build-native.sh b/native/build-native.sh new file mode 100644 index 00000000..08813e89 --- /dev/null +++ b/native/build-native.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Native (non-wasm) build of the Render360 core as a static library. +# R360_NATIVE_TARGET=macos-x86_64 | macos-arm64 | ios-arm64 (default: host macOS) +# Uses the exact same source list and overlays as the wasm build +# (xenia-ppc-sources.sh). bash 3.2 compatible. +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +XENIA="$ROOT/upstream/xenia" +OVERLAY="$ROOT/build/xenia-web-overlay" +TARGET="${R360_NATIVE_TARGET:-macos-$(uname -m)}" +OUT="$ROOT/build/native-$TARGET" +JOBS="${R360_BUILD_JOBS:-$(sysctl -n hw.ncpu 2>/dev/null || echo 2)}" +R360_OPT="${R360_OPT:--O3}" +case "$TARGET" in + macos-x86_64) SDK=macosx; ARCHFLAGS=(-arch x86_64 -mmacosx-version-min=12.0) ;; + macos-arm64) SDK=macosx; ARCHFLAGS=(-arch arm64 -mmacosx-version-min=12.0) ;; + ios-arm64) SDK=iphoneos; ARCHFLAGS=(-arch arm64 -miphoneos-version-min=16.0) ;; + *) echo "ERROR: unknown R360_NATIVE_TARGET=$TARGET" >&2; exit 2 ;; +esac +SYSROOT="$(xcrun --sdk "$SDK" --show-sdk-path)" +CXX="$(xcrun --sdk "$SDK" -f clang++)" +CC="$(xcrun --sdk "$SDK" -f clang)" +[ -d "$XENIA/src/xenia" ] || { echo "ERROR: run fetch-xenia.sh first" >&2; exit 2; } + +if [ "${R360_SKIP_OVERLAYS:-0}" != 1 ]; then # R360_SKIP_OVERLAYS=1 reuses build/xenia-web-overlay + git -C "$XENIA" checkout -- . + # Same overlay order as build-xenia-ppc-bootstrap.sh. + for s in $(sed -n 's#^python3 "\$ROOT/\(prepare-[a-z0-9-]*\.py\)"$#\1#p' "$ROOT/build-xenia-ppc-bootstrap.sh"); do + python3 "$ROOT/$s" >/dev/null + done +fi + +NATIVE_DEFS=(-DR360_NATIVE=1 -DNDEBUG) +COMMON=(-std=c++20 "$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" + -I"$ROOT/native/include" -I"$OVERLAY" -I"$ROOT/src/xenia_web_shims" -I"$ROOT/src/xenia_web_bootstrap" + -I"$XENIA/src" -I"$XENIA" -I"$XENIA/third_party/mspack" -I"$XENIA/third_party/fmt/include" + -I"$XENIA/third_party/utfcpp/source" -I"$XENIA/third_party/capstone/include" + -I"$XENIA/third_party/cpptoml/include" -I"$XENIA/third_party/cxxopts/include" -I"$XENIA/third_party/glslang" + -I"$XENIA/third_party/llvm/include" -include "$ROOT/native/include/r360_native_compat.h" + -Wno-everything) +COMMON_C=("$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" + -I"$XENIA/third_party/mspack" -I"$XENIA/third_party/crypto" -Wno-everything) + +mkdir -p "$OUT"; rm -f "$OUT"/*.o "$OUT"/*.log "$OUT"/*.fail +obj_for() { printf '%s/%s.o' "$OUT" "$(printf '%s' "$1" | tr '/' '_')"; } +throttle() { while [ "$(jobs -pr | wc -l | tr -d ' ')" -ge "$JOBS" ]; do sleep 0.2; done; } +cpp() { throttle; ( o="$(obj_for "$1")"; "$CXX" "${COMMON[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +cc() { throttle; ( o="$(obj_for "$1")"; "$CC" "${COMMON_C[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +# Native-only translation units (fiber baton, C API, JIT stub). +native_units() { + local f + for f in "$ROOT"/native/src/*.cpp; do [ -e "$f" ] && "$1" "native/$(basename "$f")" "$f"; done + return 0 +} + +source "$ROOT/xenia-ppc-sources.sh" +skip_wasm_only() { # wasm-only units replaced by native/src equivalents + case "$1" in render360/hir_wasm_jit.cpp) return 0 ;; esac + return 1 +} +cpp_filtered() { skip_wasm_only "$1" || cpp "$1" "$2"; } +r360_for_each_source cpp_filtered cc +native_units cpp +wait + +fails=$(find "$OUT" -maxdepth 1 -name '*.fail' | wc -l | tr -d ' ') +total=$(find "$OUT" -maxdepth 1 -name '*.o.log' | wc -l | tr -d ' ') +echo "native $TARGET: $((total - fails))/$total compiled" +if [ "$fails" -ne 0 ]; then + for f in "$OUT"/*.fail; do echo "----- ${f%.o.fail} -----"; grep -m5 'error:' "${f%.fail}.log" || head -5 "${f%.fail}.log"; done + exit 1 +fi +# Package core (render360_xenia_core.wasm: STFS mount/extract, XEX decode and +# image preparation; build-core.sh). It is a freestanding module whose names +# overlap the bootstrap's, so merge it into one relocatable object in which +# only its exports survive, renamed r360_* -> r360pkg_*. +PKG="$OUT/package-core" +rm -rf "$PKG"; mkdir -p "$PKG" +for f in "$ROOT/package-core.cpp" \ + "$ROOT"/src/xenia_web_bootstrap/xex_image_decoder.cpp "$ROOT"/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp \ + "$ROOT"/src/xenia_web_bootstrap/xex_image_preparer.cpp "$ROOT"/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp \ + "$ROOT"/src/xenia_web_bootstrap/xex_pe_image.cpp "$ROOT"/src/xenia_web_bootstrap/xex_pe_image_exports.cpp; do + "$CXX" -std=c++20 -O2 -g -fno-builtin "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" -I"$ROOT" -I"$ROOT/src/xenia_web_bootstrap" \ + -c "$f" -o "$PKG/$(basename "$f").o" +done +sed -n '/^EXPORTS=(/,/^)/p' "$ROOT/build-core.sh" | tr ' ' '\n' | grep '^r360_' | sort -u > "$PKG/names.txt" +awk '{print "_"$1" _r360pkg_"substr($1,6)}' "$PKG/names.txt" > "$PKG/aliases.txt" +awk '{print "_r360pkg_"substr($1,6)}' "$PKG/names.txt" > "$PKG/exports.txt" +xcrun --sdk "$SDK" ld -r "${ARCHFLAGS[@]:0:2}" "$PKG"/*.cpp.o -alias_list "$PKG/aliases.txt" \ + -exported_symbols_list "$PKG/exports.txt" -o "$OUT/zz_package_core.o" + +rm -f "$OUT/librender360core.a" +xcrun --sdk "$SDK" libtool -static -o "$OUT/librender360core.a" "$OUT"/*.o 2>&1 | grep -v 'has no symbols' || true +echo "built $OUT/librender360core.a" + +case "$TARGET" in + macos-*) + "$CXX" -std=c++20 "$R360_OPT" -g "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" -I"$ROOT/native/include" \ + "$ROOT/native/tools/run_title.cpp" "$OUT/librender360core.a" -Wl,-dead_strip -o "$OUT/run-title" + echo "built $OUT/run-title" + ;; +esac diff --git a/native/include/r360_native_compat.h b/native/include/r360_native_compat.h new file mode 100644 index 00000000..262fbc0e --- /dev/null +++ b/native/include/r360_native_compat.h @@ -0,0 +1,13 @@ +// Force-included by native/build-native.sh. Darwin's off_t is always 64-bit, +// so Xenia's glibc *64 POSIX names map directly onto the plain ones. +#pragma once +#if defined(__APPLE__) +#define off64_t off_t +#define ftello64 ftello +#define fseeko64 fseeko +#define ftruncate64 ftruncate +#define mmap64 mmap +#define lseek64 lseek +#define pread64 pread +#define pwrite64 pwrite +#endif diff --git a/native/include/render360_core.h b/native/include/render360_core.h new file mode 100644 index 00000000..3fa59de3 --- /dev/null +++ b/native/include/render360_core.h @@ -0,0 +1,103 @@ +// Render360 native core: the C API the iOS app (ios/) and the native headless +// runner (native/tools/run_title.cpp) use. +// +// The browser build drives the same core from JavaScript +// (render360-title-controller.mjs handoffDefaultXex, render360-guest-fibers.mjs, +// render360-guest-vfs.mjs, wasm-core.js). native/src/native_title.cpp is a +// line-for-line C++ port of that boot path, so both builds boot a title the +// same way and their deterministic runs can be compared. +// +// Every individual core entry point is also declared in +// render360_core_exports.h (generated by native/tools/gen_core_api.py). +#pragma once + +#include +#include + +#include "render360_core_exports.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// What a title is booted from. Game files never leave the device: the core +// reads them in place (pread on disc images and folders, STFS extraction into +// memory for packages). +typedef enum R360SourceKind { + R360_SOURCE_UNKNOWN = 0, + R360_SOURCE_FOLDER = 1, // extracted game folder with default.xex + R360_SOURCE_XEX = 2, // bare default.xex (its folder is the game root) + R360_SOURCE_STFS = 3, // LIVE / PIRS / CON package (XBLA titles) + R360_SOURCE_DISC = 4, // XISO / XGD1-3 disc image +} R360SourceKind; + +typedef struct R360BootOptions { + // Disc 1 (or the only file). For multi-disc titles the other discs are + // listed in `discs`; r360_native_select_disc() switches between them. + const char* path; + const char* const* discs; + uint32_t disc_count; + uint32_t license_full; // XAM license mask: 0 trial (Xenia default), 1 full + uint32_t deterministic_ps; // >0: guest clock from instructions (replayable runs) + uint32_t max_minstr; // >0: stop after this many million guest instructions + uint32_t function_budget; // per-function HIR fuel (run-title --budget), 0 = default 1<<30 + int32_t dialog_button; // >=0: answer every XamShowMessageBoxUI with this button + // Host slices: on_slice(user) runs on the guest thread about every slice_ms + // of host time (present frames, poll input, telemetry). Return nonzero to + // stop the run. slice_ms = 0 runs without slices. + uint32_t slice_ms; + uint32_t (*on_slice)(void* user); + void* user; +} R360BootOptions; + +typedef struct R360BootResult { + uint32_t ok; // 1: the title ran (see runtime_boundary for why it stopped) + R360SourceKind kind; + char title[128]; // STFS display name when known + uint32_t vfs_files, vfs_directories; + uint32_t entry, pe_entry; + uint32_t hir; // root result of the run + uint32_t stopped_by_host; // on_slice asked to stop + char runtime_boundary[48]; // same strings as handoffDefaultXex + uint32_t execution_status, execution_instructions; + uint32_t blocker_kind, blocker_opcode, blocker_address; + uint32_t memory_fault_code, memory_fault_address; + uint32_t kernel_calls, kernel_last_status, kernel_last_module, kernel_last_ordinal; + char kernel_boundary[192]; // readKernelBoundaryTelemetry, as text + uint32_t kernel_imports, kernel_registered, kernel_variables_relocated; + double elapsed_ms; + char error[256]; // set when ok == 0 +} R360BootResult; + +// Boots `options->path` and runs the title until it stops (exit, blocker, +// instruction limit, or on_slice returning nonzero). Blocking; call it from +// a background thread. Returns 1 on a completed run (ok), 0 on a boot error. +// A run that was stopped mid-call leaves its guest threads parked: start a +// new process (the iOS app relaunches) before booting another title. +uint32_t r360_native_boot(const R360BootOptions* options, R360BootResult* result); + +// Writes the run-title JSON report (tools/run-title.mjs fields that apply to +// the native build) for the last boot. Returns the length written. +size_t r360_native_report_json(const R360BootResult* result, char* out, size_t capacity); + +// Name of a kernel export (Xenia xboxkrnl_table.inc / xam_table.inc); module +// 1 = xboxkrnl.exe, 2 = xam.xex. Falls back to "module!0xORDINAL". +const char* r360_native_kernel_export_name(uint32_t module, uint32_t ordinal, char* buf, size_t size); + +// Multi-disc titles: re-registers \Device\Cdrom0 with disc `index` of the +// last boot's disc list (the title's next file open sees the new disc). +uint32_t r360_native_select_disc(uint32_t index); +uint32_t r360_native_current_disc(void); + +// 1 when this process can map and run executable memory (JIT-capable: on iOS +// a sideloaded build with StikDebug). The core is interpreter-only today. +uint32_t r360_native_jit_available(void); + +// Native guest-thread scheduler (src/xenia_web_bootstrap/guest_fibers.cpp). +uint32_t r360_native_run_with_fibers(uint32_t (*primary)(void*), void* user, uint32_t slice_ms, + uint32_t (*on_slice)(void*), void* slice_user, + uint32_t* stopped); + +#ifdef __cplusplus +} +#endif diff --git a/native/include/render360_core_exports.h b/native/include/render360_core_exports.h new file mode 100644 index 00000000..3e16de2e --- /dev/null +++ b/native/include/render360_core_exports.h @@ -0,0 +1,534 @@ +// Generated by native/tools/gen_core_api.py - do not edit. +// Every r360_* entry point of the Render360 core (browser: wasm exports). +#pragma once +#include +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +uint32_t r360_audio_client_callback(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_callback_arg(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_frames(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_audio_client_last_samples(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_cfg_export_continuation_ptr(uint32_t slot); // ppc_context_abi_probe.cpp +void r360_cfg_export_continuation_reset(uint32_t slot); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_slot_count(void); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_state_size(void); // ppc_context_abi_probe.cpp +uint32_t r360_cfg_export_continuation_status(uint32_t slot); // ppc_context_abi_probe.cpp +uint32_t r360_content_package_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_debug_watch(uint32_t address); // hir_correctness_executor_vmx.cpp +uint32_t r360_debug_watch_address(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_fiber_asyncify_data(void); // guest_fibers.cpp +uint32_t r360_fiber_count(void); // guest_fibers.cpp +uint32_t r360_fiber_current(void); // guest_fibers.cpp +uint32_t r360_fiber_entry(void); // guest_fibers.cpp +uint32_t r360_fiber_host_yields(void); // guest_fibers.cpp +double r360_fiber_idle_ms(void); // guest_fibers.cpp +uint32_t r360_fiber_instructions_millions(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_leave(uint32_t index, uint32_t field); // guest_fibers.cpp +uint32_t r360_fiber_preemptions(void); // guest_fibers.cpp +uint32_t r360_fiber_prepare(void); // guest_fibers.cpp +uint32_t r360_fiber_reset(uint32_t enable); // guest_fibers.cpp +uint32_t r360_fiber_resumes(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_set_host_slice(uint32_t milliseconds); // guest_fibers.cpp +uint32_t r360_fiber_stack_pointer(void); // guest_fibers.cpp +uint32_t r360_fiber_state(uint32_t index); // guest_fibers.cpp +uint32_t r360_fiber_switch_pending(void); // guest_fibers.cpp +uint32_t r360_fiber_switches(void); // guest_fibers.cpp +uint32_t r360_fiber_take_host_yield(void); // guest_fibers.cpp +uint32_t r360_fiber_thread(uint32_t index); // guest_fibers.cpp +uint64_t r360_generated_guest_load_scalar(uint32_t virtual_address, uint32_t size, uint32_t flags); // sparse_guest_memory.cpp +uint32_t r360_generated_guest_load_status(void); // sparse_guest_memory.cpp +uint32_t r360_gpu_draw_stat(uint32_t index); // webgpu_draws.cpp +uint32_t r360_gpu_set_mode(uint32_t mode); // webgpu_draws.cpp +void r360_gpu_shared_memory_clear(void); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_request(uint32_t start, uint32_t length); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_upload_ranges(void); // webgpu_backend.cpp +uint32_t r360_gpu_shared_memory_uploaded_kb(void); // webgpu_backend.cpp +void r360_gpu_shared_memory_written_by_gpu(uint32_t start, uint32_t length); // webgpu_backend.cpp +uintptr_t r360_gpu_stream_data(void); // webgpu_backend.cpp +void r360_gpu_stream_reset(void); // webgpu_backend.cpp +uint32_t r360_gpu_stream_words(void); // webgpu_backend.cpp +uint32_t r360_gpu_texture_stat(uint32_t index); // webgpu_textures.cpp +uint32_t r360_guest_clock_deterministic(void); // hir_correctness_executor_vmx.cpp +uint64_t r360_guest_clock_ns(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_guest_runtime_status(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_arg1(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_context(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_create(uint32_t entry, uint32_t context, uint32_t stack_size, uint32_t flags); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_current(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_entry(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_exit_code(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_external(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_find_by_kthread(uint32_t kthread); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_flags(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_id(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_kthread(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_next_runnable(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_pcr(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_register_external(uint32_t entry, uint32_t stack_base, uint32_t stack_limit, uint32_t pcr, uint32_t kthread, uint32_t thread_id); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_resume(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_runnable_list(uint32_t* out, uint32_t capacity); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_set_current(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_set_guest_objects(uint32_t handle, uint32_t pcr, uint32_t kthread, uint32_t arg1, uint32_t thread_id); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_base(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_mapped(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_size(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_stack_top(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_state(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_suspend(uint32_t handle); // kernel_runtime_foundation.cpp +uint32_t r360_guest_thread_terminate(uint32_t handle, uint32_t exit_code); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_alloc(void); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_free(uint32_t slot); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_get(uint32_t handle, uint32_t slot); // kernel_runtime_foundation.cpp +uint32_t r360_guest_tls_set(uint32_t handle, uint32_t slot, uint32_t value); // kernel_runtime_foundation.cpp +uint32_t r360_hir_cache_compiled_only_entries(void); // probe_backend.cpp +uint32_t r360_hir_cache_compiled_only_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_entries(void); // probe_backend.cpp +uint32_t r360_hir_cache_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_kilobytes(void); // probe_backend.cpp +uint32_t r360_hir_cache_memo_hits(void); // probe_backend.cpp +uint32_t r360_hir_cache_miss_dump(void); // probe_backend.cpp +uint32_t r360_hir_cache_misses(void); // probe_backend.cpp +uint32_t r360_hir_cache_set_budget_mb(uint32_t megabytes); // probe_backend.cpp +uint32_t r360_hir_correctness_supported_opcode_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_correctness_supports_opcode(uint32_t opcode); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_instruction_budget(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_last_source(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_opcode_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_opcode_histogram_k(uint32_t op); // hir_correctness_executor_vmx.cpp +const char* r360_hir_opcode_name(uint32_t opcode); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_set_instruction_budget(uint32_t budget); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_set_total_instruction_budget(uint32_t millions); // hir_correctness_executor_vmx.cpp +uint32_t r360_hir_total_instructions_millions(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_input_set_gamepad(uint32_t user_index, uint32_t connected, uint32_t buttons, uint32_t triggers, uint32_t left_stick, uint32_t right_stick); // kernel_xboxkrnl_services.cpp +uint32_t r360_jit_diag(uint32_t on); // hir_correctness_executor_vmx.cpp +uint32_t r360_jit_h_spill_alloc(uint32_t bytes); // guest_fibers.cpp +uint32_t r360_jit_h_spill_pop(uint32_t bytes); // guest_fibers.cpp +uint32_t r360_jit_osr_entries(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_jit_profile(uint32_t command); // hir_correctness_executor_vmx.cpp +uint32_t r360_kernel_audio_callbacks(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_cp_interrupts(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_read(uint32_t index, uintptr_t out, uint32_t capacity); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_debug_log_total(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_determinism_every(uint32_t n); // kernel_import_probe.cpp +uint32_t r360_kernel_export_calls(uint32_t module, uint32_t ordinal); // kernel_import_probe.cpp +uint32_t r360_kernel_gpu_address_to_virtual(uint32_t address); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_graphics_interrupt_callback(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_import_calls(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_count(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_dispatch_context(uint32_t thunk_address, uintptr_t context_ptr); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_module(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_ordinal(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_status(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_last_thunk(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_register(uint32_t a, uint32_t m, uint32_t o, uint32_t i, uint32_t r); // kernel_import_probe.cpp +void r360_kernel_import_reset(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_arg(uint32_t index, uint32_t arg_index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_count(void); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_handled(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_module(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_ordinal(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_result(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_sequence(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_status(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_thunk(uint32_t index); // kernel_import_probe.cpp +uint32_t r360_kernel_import_trace_total(void); // kernel_import_probe.cpp +uint32_t r360_kernel_object_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_pool_alloc(uint32_t size, uint32_t alignment); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_prepare_thread_objects(uint32_t native_handle, uint32_t start_address, uint32_t creation_flags); // kernel_xboxkrnl_services.cpp +void r360_kernel_runtime_reset(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_call(uint32_t module, uint32_t ordinal, uint32_t r3, uint32_t r4, uint32_t r5, uint32_t r6, uint32_t r7, uint32_t r8, uint32_t r9, uint32_t r10); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_calls(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_last_module(void); // kernel_runtime_foundation.cpp +uint32_t r360_kernel_service_last_ordinal(void); // kernel_runtime_foundation.cpp +void r360_kernel_service_reset(void); // kernel_runtime_foundation.cpp +void r360_kernel_service_set_caller(uint32_t r13, uint32_t lr, uint32_t r1); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_service_status(void); // kernel_runtime_foundation.cpp +void r360_kernel_services_reset(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_set_executable_module(uint32_t hmodule, uint32_t xex_header, uint32_t process_info_block); // kernel_xboxkrnl_services.cpp +void r360_kernel_set_timestamp_bundle(uint32_t address); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_arg(uint32_t index); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_code(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_kind(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_lr(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_module(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_terminal_ordinal(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_thread_poll(uint32_t thread, uint32_t field); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_thread_wait(uint32_t thread, uint32_t field); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_vblank_interrupts(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_handle(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_module(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_object(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_object_type(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_ordinal(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_wait_reason(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_kernel_watch_arg(uint32_t slot, uint32_t value); // kernel_import_probe.cpp +uint32_t r360_lzx_decompress(uint32_t input_size, uint32_t output_size, uint32_t window_size); // xex_lzx_probe.cpp +uint8_t* r360_lzx_input_buffer(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_input_capacity(void); // xex_lzx_probe.cpp +uint8_t* r360_lzx_output_buffer(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_output_capacity(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_output_size(void); // xex_lzx_probe.cpp +void r360_lzx_reset(void); // xex_lzx_probe.cpp +uint32_t r360_lzx_status(void); // xex_lzx_probe.cpp +uint32_t r360_native_fiber_finish(void); // guest_fibers.cpp +uint32_t r360_pe_guest_entry_address(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_pe_entry_address(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_raw_bytes(void); // xex_pe_guest_loader.cpp +void r360_pe_guest_reset(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_begin(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_end(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_runtime_function_prolog_bytes(uint32_t address); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_section_count(void); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_set_xex_pages(uintptr_t words_ptr, uint32_t count, uint32_t page_size); // xex_pe_guest_loader.cpp +uint32_t r360_pe_guest_status(void); // xex_pe_guest_loader.cpp +double r360_perf_counter(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_context_offset_ctr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_fpr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_gpr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_lr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_reserved_val(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_offset_vr(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_context_size(void); // ppc_context_abi_probe.cpp +uint32_t r360_ppc_probe_assembled_functions(void); // probe_backend.cpp +uint32_t r360_ppc_probe_compare_register(const char* name, const char* value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_correctness_blocker_address(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_blocker_kind(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_blocker_opcode(void); // probe_backend.cpp +uint64_t r360_ppc_probe_correctness_gpr(uint32_t index); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_correctness_instructions(void); // probe_backend.cpp +uint64_t r360_ppc_probe_correctness_r3(void); // probe_backend.cpp +uint32_t r360_ppc_probe_correctness_status(void); // probe_backend.cpp +uint32_t r360_ppc_probe_execute_on_translate(void); // probe_backend.cpp +uint32_t r360_ppc_probe_guest_base(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_hir_block_count(void); // probe_backend.cpp +uint32_t r360_ppc_probe_hir_instruction_count(void); // probe_backend.cpp +uint64_t r360_ppc_probe_initial_lr(void); // ppc_translation_probe.cpp +uintptr_t r360_ppc_probe_input_buffer(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_input_capacity(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_last_guest_address(void); // probe_backend.cpp +uint32_t r360_ppc_probe_load(const uint8_t* bytes, uint32_t length); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_load_at(uint32_t address, const uint8_t* bytes, uint32_t length); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_loaded_size(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_page_sparse_code(uint32_t target_address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_read_guest_u32_be(uint32_t address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_register_actual(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_register_save_rest(uint32_t start, uint32_t end); // ppc_translation_probe.cpp +void r360_ppc_probe_reset(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_address(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_diagnostic(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_function_end(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_hir_instructions(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_scan_window_end(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_execute_on_translate(uint32_t enabled); // probe_backend.cpp +uint32_t r360_ppc_probe_set_initial_gpr(uint32_t index, uint64_t value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_initial_lr(uint64_t value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_set_initial_register(const char* name, const char* value); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_stack_blocker_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_depth(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_flags(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_sequence(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_source(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_call_target(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_initial_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_depth(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_source(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_call_target(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_new_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_old_r1(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_write_address(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_last_write_depth(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_address(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_count(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_depth(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_new_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_old_r1(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_stack_write_sequence(uint32_t index); // hir_correctness_executor_vmx.cpp +uint32_t r360_ppc_probe_status(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_translate(void); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_translate_scanned_at(uint32_t address); // ppc_translation_probe.cpp +uint32_t r360_ppc_probe_write_guest_u32_be(uint32_t address, uint32_t value); // ppc_translation_probe.cpp +const uint8_t* r360_prepare_staged_bytes(uint32_t staged_header_length); // xex_image_preparer_exports.cpp +uint32_t r360_set_deterministic_clock(uint32_t ps_per_instruction); // hir_correctness_executor_vmx.cpp +uint32_t r360_sparse_guest_memory_alloc(uint32_t page_count); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_backing_pages(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_last_fault_address(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_last_fault_code(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_map(uint32_t virtual_address, uint32_t page_count, uint32_t backing_id, uint32_t backing_page_offset, uint32_t protection); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_mapped_pages(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_protect(uint32_t virtual_address, uint32_t page_count, uint32_t protection); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_read_u32_be(uint32_t virtual_address, uint32_t* out_value); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_read_u8(uint32_t virtual_address); // sparse_guest_memory.cpp +void r360_sparse_guest_memory_reset(void); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_unmap(uint32_t virtual_address, uint32_t page_count); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_write_u32_be(uint32_t virtual_address, uint32_t value); // sparse_guest_memory.cpp +uint32_t r360_sparse_guest_memory_write_u8(uint32_t virtual_address, uint32_t value); // sparse_guest_memory.cpp +uint32_t r360_title_gpu_last_vd_swap_buffer(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_frontbuffer(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_height(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_last_vd_swap_width(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_read(uint32_t address, uint32_t* out_value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_write(uint32_t address, uint32_t value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_mmio_writes(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_pumps(void); // title_gpu_runtime.cpp +void r360_title_gpu_reset(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_base(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_bytes(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_size_log2(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_word(uint32_t index, uint32_t* out_value); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_ring_word_capacity(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_rptr_block_size_log2(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_rptr_writeback(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_stalled(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_status(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_vd_swap_calls(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_vd_swap_failures(void); // title_gpu_runtime.cpp +uint32_t r360_title_gpu_write_pointer(void); // title_gpu_runtime.cpp +uint32_t r360_title_handoff_bytes(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_entry_address(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_hir_instructions(void); // xex_title_handoff.cpp +void r360_title_handoff_reset(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_status(void); // xex_title_handoff.cpp +uint32_t r360_title_handoff_translate_entry(uint32_t byte_count); // xex_title_handoff.cpp +uint32_t r360_title_handoff_translate_scanned_entry(void); // xex_title_handoff.cpp +uint32_t r360_trace_set_verbose(uint32_t enabled); // hir_correctness_executor_vmx.cpp +uint32_t r360_trace_verbose(void); // hir_correctness_executor_vmx.cpp +uint32_t r360_trace_verbose_from(uint32_t millions); // guest_fibers.cpp +uint32_t r360_trap_address(void); // probe_backend.cpp +uint32_t r360_trap_depth(void); // probe_backend.cpp +uint32_t r360_trap_phase(void); // probe_backend.cpp +uintptr_t r360_trap_reason(void); // probe_backend.cpp +uint32_t r360_trap_reason_length(void); // probe_backend.cpp +void r360_trap_reset(void); // probe_backend.cpp +uint32_t r360_trap_stack_exhausted(void); // probe_backend.cpp +uint32_t r360_trap_stack_headroom(void); // probe_backend.cpp +uintptr_t r360_vfs_data_buffer(uint32_t id); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_entry_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_entry_path(uint32_t id); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_entry(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_errno(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_length(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_host_io_offset(void); // kernel_xboxkrnl_services.cpp +uintptr_t r360_vfs_path_buffer(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_reads(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_vfs_register(uint32_t path_length, uint32_t size_lo, uint32_t size_hi, uint32_t attributes, uint32_t host_fd, uint32_t host_offset_lo, uint32_t host_offset_hi); // kernel_xboxkrnl_services.cpp +void r360_vfs_reset(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_wasm_backend_call_cache_hits(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_cache_misses(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_cache_rebuilds(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_context_ptr(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_address(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_count(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_function_generation(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_invalidations(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_lowered_instructions(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_module_ptr(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_module_size(uint32_t i); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_call_status(void); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_cfg_context_ptr(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_ptr(uint32_t slot); // wasm_backend_cfg_probe.cpp +void r360_wasm_backend_cfg_continuation_reset(uint32_t slot); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_slot_count(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_state_size(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_continuation_status(uint32_t slot); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_lowered_instructions(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_module_ptr(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_module_size(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_cfg_status(void); // wasm_backend_cfg_probe.cpp +uint32_t r360_wasm_backend_context_ptr(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_executable_content_generation(uint32_t address); // sparse_guest_memory.cpp +uint32_t r360_wasm_backend_executable_page_generation(uint32_t address); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_fpu_context_ptr(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_lowered_instructions(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_module_ptr(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_module_size(void); // wasm_backend_fpu_probe_v2.cpp +uint32_t r360_wasm_backend_fpu_status(void); // wasm_backend_fpu_probe_v2.cpp +void r360_wasm_backend_invalidate_executable_range(uint32_t address, uint32_t size); // wasm_backend_call_probe.cpp +uint32_t r360_wasm_backend_lowered_instructions(void); // wasm_backend_probe.cpp +void r360_wasm_backend_mark_executable_content_changed_range(uint32_t address, uint32_t size); // sparse_guest_memory.cpp +uint32_t r360_wasm_backend_memory_context_ptr(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_lowered_instructions(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_module_ptr(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_module_size(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_memory_status(void); // wasm_backend_memory_probe.cpp +uint32_t r360_wasm_backend_module_ptr(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_module_size(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_status(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_supported_opcode_count(void); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_supports_hir_opcode(uint32_t opcode); // wasm_backend_probe.cpp +uint32_t r360_wasm_backend_vmx_context_ptr(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_lowered_instructions(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_module_ptr(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_module_size(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_native_simd_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_scalarized_lane_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_status(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_wasm_backend_vmx_vector_ops(void); // wasm_backend_vmx_probe.cpp +uint32_t r360_xam_dialog_active_button(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_answer(uint32_t button); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_button_count(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_pending(void); // kernel_xboxkrnl_services.cpp +int32_t r360_xam_dialog_set_auto_answer(int32_t button); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_set_host_answers(uint32_t on); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_dialog_string_len(uint32_t which); // kernel_xboxkrnl_services.cpp +uintptr_t r360_xam_dialog_string_ptr(uint32_t which); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_license_mask(void); // kernel_xboxkrnl_services.cpp +uint32_t r360_xam_set_license_mask(uint32_t mask); // kernel_xboxkrnl_services.cpp +uint32_t r360_xenos_arm_resume(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_debug_draws(uint32_t n); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_draws(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_edram_tile_address(uint32_t b,uint32_t p,uint32_t x,uint32_t y); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_fetch_constant_word(uint32_t g,uint32_t w); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_frame_buffer(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_generation(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_hash(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_height(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_provenance(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_size(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frame_width(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frontbuffer_height(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_frontbuffer_ptr(void); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_frontbuffer_snapshot_buffer(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_capture(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_format(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_generation(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_hash(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_height(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_pitch(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_size(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_source_address(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_source_bytes(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_status(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_tiled(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_snapshot_width(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_frontbuffer_width(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_indirect_buffers(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_interrupts(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_fault_depth(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_fault_word(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_interrupt_mask(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_invalidate_mask(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_last_opcode(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_memory_writes(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_packets(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_presents(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_real_title_frame_ready(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_register(uint32_t i); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_register_writes(void); // xenos_gpu_foundation.cpp +void r360_xenos_reset(void); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_ring_buffer(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_ring_capacity(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_set_register(uint32_t i,uint32_t v); // xenos_gpu_foundation.cpp +uintptr_t r360_xenos_shader_buffer(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_dwords(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_guest_address(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_hash(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_interpreter_alloc_exports(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_analyze(uint32_t shader_type); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_cf_pair_bound(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_execute(uint32_t shader_type); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_execution_count(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_component_bits(uint32_t component); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_mask(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_last_export_register(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_register_bound(void); // xenos_shader_interpreter_probe.cpp +void r360_xenos_shader_interpreter_reset(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_shader_type(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_status(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_temp_component_bits(uint32_t reg, uint32_t component); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_texture_bindings(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_texture_fetches(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_ucode_dwords(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_uses_texture_fetch(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_value_exports(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_vertex_bindings(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_writes_color_targets(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_interpreter_writes_interpolators(void); // xenos_shader_interpreter_probe.cpp +uint32_t r360_xenos_shader_loads(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_shader_source(uint32_t t); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_soft_clear_ksamples(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_draws(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_resolve_info(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_skip(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_last_texture_format(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_pixels(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_render_us(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_resolve_kpixels(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_resolves(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_set_rasterize(uint32_t on); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_skipped(void); // xenos_soft_renderer.cpp +uint32_t r360_xenos_soft_texture_failures(void); // xenos_soft_renderer.cpp +uintptr_t r360_xenos_spirv_buffer(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_error_count(void); // xenos_spirv_translation_probe.cpp +void r360_xenos_spirv_reset(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_shader_type(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_size(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_status(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_translate(uint32_t shader_type); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_translation_count(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_ucode_dwords(void); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_spirv_word(uint32_t index); // xenos_spirv_translation_probe.cpp +uint32_t r360_xenos_stall_ready(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_stall_ring_offset(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_stall_wait(uint32_t i); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_status(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_submit(uint32_t n); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_swap_fetch_word(uint32_t w); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_swaps(void); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_trace_ibs(uint32_t on); // xenos_gpu_foundation.cpp +uint32_t r360_xenos_waits(void); // xenos_gpu_foundation.cpp +uint32_t r360_xex_crypto_begin_session(uint32_t use_devkit_key); // xex_crypto_probe.cpp +uint8_t* r360_xex_crypto_buffer(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_bytes_done(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_capacity(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_decrypt_chunk(uint32_t chunk_length); // xex_crypto_probe.cpp +void r360_xex_crypto_reset(void); // xex_crypto_probe.cpp +uint32_t r360_xex_crypto_status(void); // xex_crypto_probe.cpp +uint32_t r360_xex_decode(uint32_t length); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_address(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_bytes(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_count(uint32_t index); // xex_image_decoder_exports.cpp +uint32_t r360_xex_decode_page_type(uint32_t index); // xex_image_decoder_exports.cpp +void r360_xex_decode_reset(void); // xex_image_decoder_exports.cpp +uint32_t r360_xex_guest_mapper_entry_address(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_finalize(void); // xex_guest_mapper.cpp +uintptr_t r360_xex_guest_mapper_input_buffer(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_input_capacity(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_input_max_capacity(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, uintptr_t source_ptr, uint32_t size); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, uint32_t virtual_size, uint32_t final_protection); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_mapped_bytes(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_patch_u32_be(uint32_t address, uint32_t value); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_reserve_input(uint32_t required_capacity); // xex_guest_mapper.cpp +void r360_xex_guest_mapper_reset(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_section_count(void); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_set_entry(uint32_t entry_address); // xex_guest_mapper.cpp +uint32_t r360_xex_guest_mapper_status(void); // xex_guest_mapper.cpp +uint32_t r360_xex_pe_decode(uint32_t length); // xex_pe_image_exports.cpp +void r360_xex_pe_reset(void); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_characteristics(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_raw_address(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_raw_size(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_virtual_address(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_pe_section_virtual_size(uint32_t index); // xex_pe_image_exports.cpp +uint32_t r360_xex_prepare_basic_accept_data(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_consume_zero(uint32_t max_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_data_remaining(void); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_basic_zero_remaining(void); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_none_accept(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_none_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_normal_frame_accept(uint32_t chunk_length); // xex_image_preparer_exports.cpp +uint32_t r360_xex_prepare_normal_frame_begin(uint32_t staged_header_length, uint32_t file_length); // xex_image_preparer_exports.cpp +void r360_xex_prepare_reset(void); // xex_image_preparer_exports.cpp +#ifdef __cplusplus +} +#endif diff --git a/native/include/xenia/base/platform.h b/native/include/xenia/base/platform.h new file mode 100644 index 00000000..1c778754 --- /dev/null +++ b/native/include/xenia/base/platform.h @@ -0,0 +1,34 @@ +/** + * Render360 native (macOS / iOS) host shim for Xenia's platform switch. + * + * The native build deliberately takes the same portable code paths as the + * browser build (sparse guest memory, no host page mapping tricks, no x64 + * backend) so that native and wasm runs stay deterministic and comparable. + * XE_ARCH_WASM32 therefore means "Render360 portable host" here; + * R360_NATIVE marks the places where 64-bit host pointers differ. + */ +#ifndef XENIA_BASE_PLATFORM_H_ +#define XENIA_BASE_PLATFORM_H_ + +#if !defined(R360_NATIVE) +#error native/include must only be used by native/build-native.sh +#endif + +#define XE_PLATFORM_WEB 1 +#define XE_COMPILER_CLANG 1 +#define XE_ARCH_WASM32 1 + +#define _XEPACKEDSCOPE(body) \ + _Pragma("pack(push, 1)") body; \ + _Pragma("pack(pop)"); + +#define XEPACKEDSTRUCT(name, value) _XEPACKEDSCOPE(struct name value) +#define XEPACKEDSTRUCTANONYMOUS(value) _XEPACKEDSCOPE(struct value) +#define XEPACKEDUNION(name, value) _XEPACKEDSCOPE(union name value) + +namespace xe { +const char kPathSeparator = '/'; +const char kGuestPathSeparator = '\\'; +} // namespace xe + +#endif // XENIA_BASE_PLATFORM_H_ diff --git a/native/src/native_jit.cpp b/native/src/native_jit.cpp new file mode 100644 index 00000000..fac07820 --- /dev/null +++ b/native/src/native_jit.cpp @@ -0,0 +1,77 @@ +// Native build: the HIR -> WebAssembly guest JIT (hir_wasm_jit.cpp) does not +// apply, and no arm64/x64 backend exists yet (Xenia only ships x64), so every +// guest function runs on the HIR interpreter. These definitions keep the +// translation cache's JIT hooks inert ("JIT off", JitLastDecision() == 5). +// +// r360_native_jit_available() reports whether this process could run a JIT +// at all: on iOS that needs the debugger-attached / JIT-enabled state that a +// sideloaded build gets from StikDebug. It maps a MAP_JIT page, writes a tiny +// "return 42" stub and calls it. +#include +#include +#include +#if defined(__APPLE__) +#include +#include +#endif + +#include "hir_wasm_jit.h" + +namespace render360::xenia_web { +bool JitEnabled() { return false; } +void JitSetCandidate(xe::cpu::hir::HIRBuilder*, JitSlot*) {} +uint32_t JitTakeFunction(xe::cpu::hir::HIRBuilder*) { return 0; } +uint32_t JitLastDecision() { return 5; } +uint32_t JitRejectOpcode(xe::cpu::hir::HIRBuilder*) { return 0; } +JitSlot* JitTakeOsrSlot(xe::cpu::hir::HIRBuilder*) { return nullptr; } +uint32_t JitOsrFunction(xe::cpu::hir::HIRBuilder*, JitSlot*, bool) { return 0; } +uint32_t JitSegmentOfBlock(xe::cpu::hir::HIRBuilder*, const xe::cpu::hir::Block*) { return 0; } +void JitReleaseSlot(JitSlot*) {} +} // namespace render360::xenia_web + +namespace { +// 0 not probed, 1 available, 2 unavailable. +uint32_t g_jit_probe = 0; + +uint32_t ProbeExecutableMemory() { +#if defined(__aarch64__) || defined(__x86_64__) + const size_t size = 16384; +#if defined(__APPLE__) + void* page = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_JIT, -1, 0); +#else + void* page = mmap(nullptr, size, PROT_READ | PROT_WRITE | PROT_EXEC, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); +#endif + if (page == MAP_FAILED) return 2; +#if defined(__aarch64__) + static const uint32_t kStub[] = {0x52800540u /* mov w0, #42 */, 0xD65F03C0u /* ret */}; +#else + static const uint8_t kStub[] = {0xB8, 42, 0, 0, 0 /* mov eax, 42 */, 0xC3 /* ret */}; +#endif +#if defined(__APPLE__) && defined(__aarch64__) + pthread_jit_write_protect_np(0); +#endif + std::memcpy(page, kStub, sizeof(kStub)); +#if defined(__APPLE__) && defined(__aarch64__) + pthread_jit_write_protect_np(1); + sys_icache_invalidate(page, sizeof(kStub)); +#endif + // Without the JIT entitlement / debugger state the kernel kills the + // process on the call instead of failing the mmap on some iOS versions; + // the app only probes when the user enables JIT mode, and records a + // breadcrumb first so a crash here is attributed correctly. + using Fn = int (*)(); + const int value = reinterpret_cast(page)(); + munmap(page, size); + return value == 42 ? 1 : 2; +#else + return 2; +#endif +} +} // namespace + +extern "C" uint32_t r360_native_jit_available() { + if (!g_jit_probe) g_jit_probe = ProbeExecutableMemory(); + return g_jit_probe == 1 ? 1u : 0u; +} diff --git a/native/src/native_title.cpp b/native/src/native_title.cpp new file mode 100644 index 00000000..ae5a82fb --- /dev/null +++ b/native/src/native_title.cpp @@ -0,0 +1,1440 @@ +// Native title boot: a C++ port of the browser's JavaScript boot path, so the +// iOS app and the native runner start titles exactly like the web player. +// +// render360-title-controller.mjs handoffDefaultXex and its helpers +// retail-xex-image-pipeline.mjs prepareRetailXexImage (AES + NONE/BASIC/NORMAL) +// render360-xex-imports.mjs decodeXexImportLibraries +// render360-kernel-imports.mjs buildKernelImportPlan +// render360-guest-vfs.mjs registerGuestVfs, listStfsVfsFiles +// render360-xdvdfs.mjs mountXdvdfs +// render360-iso-title-controller extractXex2EncryptedImageKey +// wasm-core.js mountStfs / extractStfsEntry +// tools/run-title.mjs openTitle, the JSON report +// +// Function names below match the JavaScript ones; keep them in step. +#include "render360_core.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Package core (render360_xenia_core.wasm in the browser), linked as one +// object whose exports are renamed r360_* -> r360pkg_* (native/build-native.sh). +extern "C" { +uintptr_t r360pkg_io_ptr(); +uint32_t r360pkg_io_capacity(); +uint32_t r360pkg_stfs_mount_begin(uint32_t size_lo, uint32_t size_hi); +uint32_t r360pkg_stfs_submit_read(uint32_t length); +uint32_t r360pkg_stfs_request_pending(); +uint32_t r360pkg_stfs_request_offset_lo(); +uint32_t r360pkg_stfs_request_offset_hi(); +uint32_t r360pkg_stfs_request_size(); +uint32_t r360pkg_stfs_mount_status(); +uint32_t r360pkg_stfs_entry_count(); +uintptr_t r360pkg_stfs_entry_name_ptr(uint32_t index); +uint32_t r360pkg_stfs_entry_name_length(uint32_t index); +uint32_t r360pkg_stfs_entry_is_directory(uint32_t index); +uint32_t r360pkg_stfs_entry_parent_index(uint32_t index); +uint32_t r360pkg_stfs_entry_length(uint32_t index); +uintptr_t r360pkg_stfs_display_name_ptr(); +uint32_t r360pkg_stfs_display_name_length(); +uint32_t r360pkg_stfs_extract_begin(uint32_t entry_index); +uint32_t r360pkg_stfs_extract_status(); +uint32_t r360pkg_stfs_extract_bytes_done(); +uint32_t r360pkg_stfs_extract_bytes_total(); +void r360pkg_stfs_extract_reset(); +uint32_t r360pkg_xex_decode(uint32_t length); +uint32_t r360pkg_xex_decode_encryption_type(); +uint32_t r360pkg_xex_decode_compression_type(); +uint32_t r360pkg_xex_decode_image_size(); +uint32_t r360pkg_xex_prepare_none_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_none_accept(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_basic_accept_data(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_consume_zero(uint32_t length); +uint32_t r360pkg_xex_prepare_basic_data_remaining(); +uint32_t r360pkg_xex_prepare_basic_zero_remaining(); +uint32_t r360pkg_xex_prepare_status(); +uint32_t r360pkg_xex_prepare_last_output_kind(); +uint32_t r360pkg_xex_prepare_last_output_bytes(); +uint32_t r360pkg_xex_prepare_normal_frame_begin(uint32_t header_length, uint32_t source_length); +uint32_t r360pkg_xex_prepare_normal_frame_accept(uint32_t length); +uint32_t r360pkg_xex_prepare_normal_window_size(); +} + +namespace { + +using Bytes = std::vector; + +[[noreturn]] void Fail(const char* format, ...) { + char text[256]; + va_list args; + va_start(args, format); + std::vsnprintf(text, sizeof(text), format, args); + va_end(args); + throw std::runtime_error(text); +} + +uint32_t be32(const uint8_t* b, size_t o) { + return (uint32_t(b[o]) << 24) | (uint32_t(b[o + 1]) << 16) | (uint32_t(b[o + 2]) << 8) | b[o + 3]; +} +uint32_t be16(const uint8_t* b, size_t o) { return (uint32_t(b[o]) << 8) | b[o + 1]; } +uint32_t le16(const uint8_t* b, size_t o) { return b[o] | (uint32_t(b[o + 1]) << 8); } +uint32_t le32(const uint8_t* b, size_t o) { + return b[o] | (uint32_t(b[o + 1]) << 8) | (uint32_t(b[o + 2]) << 16) | (uint32_t(b[o + 3]) << 24); +} + +// --- Host files ------------------------------------------------------------- + +struct HostFile { + int fd = -1; + uint64_t size = 0; + bool Open(const std::string& path) { + fd = ::open(path.c_str(), O_RDONLY); + if (fd < 0) return false; + struct stat st {}; + if (fstat(fd, &st) != 0) return false; + size = uint64_t(st.st_size); + return true; + } + void Read(uint64_t offset, void* out, size_t length) const { + size_t done = 0; + while (done < length) { + const ssize_t n = ::pread(fd, static_cast(out) + done, length - done, off_t(offset + done)); + if (n <= 0) Fail("short read at 0x%llx (%zu/%zu)", (unsigned long long)(offset + done), done, length); + done += size_t(n); + } + } + Bytes ReadBytes(uint64_t offset, size_t length) const { + Bytes out(length); + Read(offset, out.data(), length); + return out; + } +}; +// Descriptors stay open for the process lifetime: the kernel VFS reads them. +std::vector> g_host_files; +HostFile* OpenHostFile(const std::string& path) { + auto file = std::make_unique(); + if (!file->Open(path)) Fail("cannot open %s", path.c_str()); + g_host_files.push_back(std::move(file)); + return g_host_files.back().get(); +} + +// --- Guest VFS (render360-guest-vfs.mjs) ---------------------------------------- + +struct VfsFile { + std::string path; // relative to \Device\Cdrom0, '\' separated + bool directory = false; + uint64_t size = 0; + int host_fd = 0; + uint64_t host_offset = 0; + Bytes data; // attached up front (STFS extraction) + bool has_data = false; +}; + +constexpr uint32_t FILE_ATTRIBUTE_READONLY = 0x01; +constexpr uint32_t FILE_ATTRIBUTE_DIRECTORY = 0x10; +constexpr uint32_t FILE_ATTRIBUTE_NORMAL = 0x80; + +uint32_t registerGuestVfs(const std::vector& files) { + r360_vfs_reset(); + auto* path_buffer = reinterpret_cast(r360_vfs_path_buffer()); + uint32_t registered = 0; + for (const auto& file : files) { + std::string path = file.path; + std::replace(path.begin(), path.end(), '/', '\\'); + while (!path.empty() && path[0] == '\\') path.erase(0, 1); + if (path.empty()) continue; + if (path.size() >= 1024) Fail("guest path too long for VFS: %s", path.c_str()); + std::memcpy(path_buffer, path.data(), path.size()); + const uint64_t size = file.directory ? 0 : file.size; + const uint32_t attributes = file.directory ? (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_READONLY) + : (FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_READONLY); + const uint32_t id = r360_vfs_register(uint32_t(path.size()), uint32_t(size), uint32_t(size >> 32), attributes, + uint32_t(file.host_fd), uint32_t(file.host_offset), + uint32_t(file.host_offset >> 32)); + if (!id) Fail("native VFS rejected %s", path.c_str()); + ++registered; + if (file.has_data && !file.directory) { + auto* ptr = reinterpret_cast(r360_vfs_data_buffer(id)); + if (!ptr) Fail("native VFS could not allocate %zu bytes for %s", file.data.size(), path.c_str()); + if (!file.data.empty()) std::memcpy(ptr, file.data.data(), file.data.size()); + } + } + return registered; +} + +// --- XDVDFS (render360-xdvdfs.mjs) ------------------------------------------------ + +constexpr uint32_t kSector = 2048; +const char kXdvdfsMagic[] = "MICROSOFT*XBOX*MEDIA"; + +struct XdvdfsEntry { + std::string name; + uint32_t left = 0, right = 0, start_sector = 0, size = 0, attributes = 0; + bool directory = false; +}; + +struct XdvdfsVolume { + const HostFile* file = nullptr; + std::string layout; + uint64_t partition_offset = 0; + uint32_t root_sector = 0, root_size = 0; + + Bytes Table(uint32_t sector, uint32_t size) const { + if (!size) return {}; + if (size > 16u * 1024u * 1024u) Fail("XDVDFS directory table too large %u", size); + return file->ReadBytes(partition_offset + uint64_t(sector) * kSector, size); + } + static std::vector WalkTree(const Bytes& table) { + std::vector out; + if (table.empty()) return out; + std::vector stack{0}; + std::vector seen(table.size() / 4 + 1, false); + size_t visited = 0; + while (!stack.empty()) { + const uint32_t off = stack.back(); + stack.pop_back(); + if (seen[off / 4]) Fail("XDVDFS directory tree cycle at 0x%x", off); + seen[off / 4] = true; + if (++visited > 65536) Fail("XDVDFS directory entry guard exceeded"); + if (off + 14 > table.size()) Fail("XDVDFS directory entry out of bounds 0x%x", off); + const uint32_t name_len = table[off + 13]; + if (!name_len || off + 14 + name_len > table.size()) Fail("XDVDFS directory filename out of bounds 0x%x", off); + XdvdfsEntry e; + e.left = le16(table.data(), off); + e.right = le16(table.data(), off + 2); + e.start_sector = le32(table.data(), off + 4); + e.size = le32(table.data(), off + 8); + e.attributes = table[off + 12]; + e.directory = (e.attributes & 0x10) != 0; + e.name.assign(reinterpret_cast(table.data() + off + 14), name_len); + if (e.name.find_first_of(std::string("\0/\\", 3)) != std::string::npos) Fail("invalid XDVDFS filename"); + out.push_back(e); + for (uint32_t d : {e.right, e.left}) { + if (!d) continue; + if (d * 4 >= table.size()) Fail("XDVDFS child pointer out of bounds 0x%x", d * 4); + stack.push_back(d * 4); + } + } + return out; + } +}; + +XdvdfsVolume mountXdvdfs(const HostFile* file) { + static const std::pair kPartitions[] = { + {"XISO", 0x00000000ull}, {"XGD3", 0x02080000ull}, {"XGD2", 0x0FD90000ull}, {"XGD1", 0x18300000ull}}; + for (const auto& [layout, partition_offset] : kPartitions) { + const uint64_t descriptor = partition_offset + 32ull * kSector; + if (descriptor + kSector > file->size) continue; + Bytes d = file->ReadBytes(descriptor, kSector); + if (std::memcmp(d.data(), kXdvdfsMagic, 20) || std::memcmp(d.data() + 0x7EC, kXdvdfsMagic, 20)) continue; + XdvdfsVolume volume; + volume.file = file; + volume.layout = layout; + volume.partition_offset = partition_offset; + volume.root_sector = le32(d.data(), 0x14); + volume.root_size = le32(d.data(), 0x18); + if (!volume.root_sector || !volume.root_size) Fail("XDVDFS root directory is empty"); + if (volume.root_size > 16u * 1024u * 1024u) Fail("XDVDFS root directory size unreasonable"); + if (partition_offset + uint64_t(volume.root_sector) * kSector + volume.root_size > file->size) + Fail("XDVDFS root directory outside image"); + return volume; + } + Fail("XDVDFS volume not found (XISO/XGD1/XGD2/XGD3)"); +} + +// listXdvdfsVfsFiles: every file is a contiguous extent of the image. +void listXdvdfsVfsFiles(const XdvdfsVolume& volume, uint32_t sector, uint32_t size, const std::string& prefix, + std::vector& files, int depth = 0) { + if (depth > 64) Fail("XDVDFS directory nesting too deep"); + for (const auto& entry : XdvdfsVolume::WalkTree(volume.Table(sector, size))) { + const std::string path = prefix.empty() ? entry.name : prefix + "\\" + entry.name; + VfsFile f; + f.path = path; + if (entry.directory) { + f.directory = true; + files.push_back(f); + listXdvdfsVfsFiles(volume, entry.start_sector, entry.size, path, files, depth + 1); + } else { + f.size = entry.size; + f.host_fd = volume.file->fd; + f.host_offset = volume.partition_offset + uint64_t(entry.start_sector) * kSector; + files.push_back(f); + } + } +} + +// --- STFS packages (wasm-core.js mountStfs / extractStfsEntry) -------------------- + +void StageSlice(const HostFile* file, uint64_t offset, uint32_t size) { + if (!size || size > r360pkg_io_capacity()) Fail("invalid native STFS read size %u", size); + file->Read(offset, reinterpret_cast(r360pkg_io_ptr()), size); +} +uint64_t RequestOffset() { + return (uint64_t(r360pkg_stfs_request_offset_hi()) << 32) | r360pkg_stfs_request_offset_lo(); +} + +std::string mountStfs(const HostFile* file) { + r360pkg_stfs_mount_begin(uint32_t(file->size), uint32_t(file->size >> 32)); + uint32_t requests = 0; + while (r360pkg_stfs_request_pending()) { + if (++requests > 4096) Fail("STFS mount exceeded 4096 native read requests"); + const uint32_t size = r360pkg_stfs_request_size(); + StageSlice(file, RequestOffset(), size); + r360pkg_stfs_submit_read(size); + } + const uint32_t status = r360pkg_stfs_mount_status(); + if (status != 2 && status != 3) Fail("STFS package did not mount (status %u)", status); + return std::string(reinterpret_cast(r360pkg_stfs_display_name_ptr()), + r360pkg_stfs_display_name_length()); +} + +Bytes extractStfsEntry(const HostFile* file, uint32_t index) { + r360pkg_stfs_extract_begin(index); + Bytes out(r360pkg_stfs_extract_bytes_total()); + uint32_t requests = 0; + while (r360pkg_stfs_request_pending()) { + if (++requests > (1u << 20)) { + r360pkg_stfs_extract_reset(); + Fail("STFS extraction exceeded native read request limit"); + } + const uint32_t size = r360pkg_stfs_request_size(); + const uint32_t dest = r360pkg_stfs_extract_bytes_done(); + StageSlice(file, RequestOffset(), size); + if (dest < out.size()) { + std::memcpy(out.data() + dest, reinterpret_cast(r360pkg_io_ptr()), + std::min(size, out.size() - dest)); + } + r360pkg_stfs_submit_read(size); + } + if (r360pkg_stfs_extract_status() != 2) Fail("STFS extraction of entry %u failed (status %u)", index, + r360pkg_stfs_extract_status()); + return out; +} + +// listStfsVfsFiles + run-title's eager extraction of every file. +std::vector listStfsVfsFiles(const HostFile* file, Bytes* default_xex) { + const uint32_t count = r360pkg_stfs_entry_count(); + std::vector names(count); + std::vector parents(count); + for (uint32_t i = 0; i < count; ++i) { + names[i].assign(reinterpret_cast(r360pkg_stfs_entry_name_ptr(i)), r360pkg_stfs_entry_name_length(i)); + parents[i] = r360pkg_stfs_entry_parent_index(i); + } + auto path_of = [&](uint32_t i) { + std::string path = names[i]; + for (uint32_t p = parents[i], depth = 0; p < count && p != i; p = parents[p]) { + if (++depth > 64) Fail("STFS directory chain too deep"); + path = names[p] + "\\" + path; + if (parents[p] == p) break; + } + return path; + }; + std::vector files; + for (uint32_t i = 0; i < count; ++i) { + VfsFile f; + f.path = path_of(i); + f.directory = r360pkg_stfs_entry_is_directory(i) != 0; + if (!f.directory) { + f.size = r360pkg_stfs_entry_length(i); + f.data = extractStfsEntry(file, i); + f.has_data = true; + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "default.xex") *default_xex = f.data; + } + files.push_back(std::move(f)); + } + return files; +} + +// --- Folders --------------------------------------------------------------------- + +void walkFolder(const std::string& root, const std::string& prefix, std::vector& files) { + DIR* dir = opendir(root.c_str()); + if (!dir) Fail("cannot list %s", root.c_str()); + std::vector names; + while (dirent* e = readdir(dir)) { + if (!std::strcmp(e->d_name, ".") || !std::strcmp(e->d_name, "..")) continue; + names.push_back(e->d_name); + } + closedir(dir); + std::sort(names.begin(), names.end()); // fs.readdirSync order on APFS/HFS+ + for (const auto& name : names) { + const std::string full = root + "/" + name; + const std::string guest = prefix.empty() ? name : prefix + "\\" + name; + struct stat st {}; + if (stat(full.c_str(), &st) != 0) continue; + VfsFile f; + f.path = guest; + if (S_ISDIR(st.st_mode)) { + f.directory = true; + files.push_back(f); + walkFolder(full, guest, files); + } else if (S_ISREG(st.st_mode)) { + f.size = uint64_t(st.st_size); + f.host_fd = OpenHostFile(full)->fd; + files.push_back(f); + } + } +} + +// --- openTitle (tools/run-title.mjs) ------------------------------------------------ + +struct OpenedTitle { + R360SourceKind kind = R360_SOURCE_UNKNOWN; + Bytes default_xex; + std::vector files; + std::string title; +}; + +OpenedTitle openTitle(const std::string& input) { + OpenedTitle title; + struct stat st {}; + if (stat(input.c_str(), &st) != 0) Fail("cannot stat %s", input.c_str()); + if (S_ISDIR(st.st_mode)) { + const std::string xex = input + "/default.xex"; + title.kind = R360_SOURCE_FOLDER; + walkFolder(input, "", title.files); + const HostFile* file = OpenHostFile(xex); + title.default_xex = file->ReadBytes(0, size_t(file->size)); + return title; + } + const HostFile* file = OpenHostFile(input); + uint8_t magic[4] = {}; + if (file->size >= 4) file->Read(0, magic, 4); + if (!std::memcmp(magic, "XEX2", 4)) { + // A bare XEX: its folder is the game root, as when launched from a HDD. + title.kind = R360_SOURCE_XEX; + std::string root = input.substr(0, input.find_last_of('/')); + if (root == input) root = "."; + walkFolder(root, "", title.files); + bool has_default = false; + for (const auto& f : title.files) { + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + has_default |= lower == "default.xex"; + } + if (!has_default) { + VfsFile f; + f.path = "default.xex"; + f.size = file->size; + f.host_fd = file->fd; + title.files.push_back(f); + } + title.default_xex = file->ReadBytes(0, size_t(file->size)); + return title; + } + if (!std::memcmp(magic, "LIVE", 4) || !std::memcmp(magic, "PIRS", 4) || !std::memcmp(magic, "CON ", 4)) { + title.kind = R360_SOURCE_STFS; + title.title = mountStfs(file); + title.files = listStfsVfsFiles(file, &title.default_xex); + if (title.default_xex.empty()) Fail("package has no default.xex"); + return title; + } + // Otherwise try an Xbox game disc image (XISO / XGD1-3). + title.kind = R360_SOURCE_DISC; + const XdvdfsVolume volume = mountXdvdfs(file); + listXdvdfsVfsFiles(volume, volume.root_sector, volume.root_size, "", title.files); + for (const auto& f : title.files) { + std::string lower = f.path; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "default.xex" && !f.directory) title.default_xex = file->ReadBytes(f.host_offset, size_t(f.size)); + } + if (title.default_xex.empty()) Fail("disc has no default.xex"); + return title; +} + +// --- XEX helpers (render360-title-controller.mjs) ------------------------------------ + +constexpr uint32_t XEX_HEADER_ENTRY_POINT = 0x00010100; +constexpr uint32_t XENIA_KERNEL_DATA_BASE = 0x50010000; +constexpr uint32_t XENIA_EXECUTABLE_MODULE_VAR = XENIA_KERNEL_DATA_BASE; +constexpr uint32_t XENIA_KE_DEBUG_MONITOR_DATA = XENIA_KERNEL_DATA_BASE + 0x004; +constexpr uint32_t XENIA_KE_CERT_MONITOR_DATA = XENIA_KERNEL_DATA_BASE + 0x008; +constexpr uint32_t XENIA_EXECUTABLE_HMODULE = XENIA_KERNEL_DATA_BASE + 0x100; +constexpr uint32_t XENIA_XEX_HEADER_BASE = XENIA_KERNEL_DATA_BASE + 0x1000; +constexpr uint32_t XENIA_PROCESS_INFO_BLOCK = XENIA_KERNEL_DATA_BASE + 0x200; + +struct KernelVariableSpec { + uint32_t ordinal; + const char* name; + uint32_t address; + std::vector words; + const char* text = nullptr; + uint32_t bytes = 0; +}; +// Every xboxkrnl variable export Xenia backs with real guest storage +// (XboxkrnlModule constructor + RegisterVideoExports), in the kernel data page. +const std::vector& KernelVariableLayout() { + static const std::vector kLayout = { + {0x0C, "ExConsoleGameRegion", XENIA_KERNEL_DATA_BASE + 0x00C, {0xFFFFFFFFu}}, + {0x59, "KeDebugMonitorData", XENIA_KE_DEBUG_MONITOR_DATA, {0}}, + {0xAD, "KeTimeStampBundle", XENIA_KERNEL_DATA_BASE + 0x040, {0, 0, 0, 0, 0, 0}}, + {0x156, "XboxHardwareInfo", XENIA_KERNEL_DATA_BASE + 0x010, {0x20, 0x06000000, 0, 0}}, + {0x158, "XboxKrnlVersion", XENIA_KERNEL_DATA_BASE + 0x020, {0x0002FFFF, 0xFFFF8000}}, + {0x193, "XexExecutableModuleHandle", XENIA_EXECUTABLE_MODULE_VAR, {}}, + {0x1AE, "ExLoadedCommandLine", XENIA_KERNEL_DATA_BASE + 0x800, {}, "\"default.xex\"", 0x400}, + {0x1AF, "ExLoadedImageName", XENIA_KERNEL_DATA_BASE + 0x400, {}, "\\Device\\Cdrom0\\default.xex", 0x100}, + {0x1BE, "VdGlobalDevice", XENIA_KERNEL_DATA_BASE + 0x028, {0}}, + {0x1BF, "VdGlobalXamDevice", XENIA_KERNEL_DATA_BASE + 0x02C, {0}}, + {0x1C0, "VdGpuClockInMHz", XENIA_KERNEL_DATA_BASE + 0x030, {500}}, + // X_RTL_CRITICAL_SECTION initialized with spin count 10000 (Xenia). + {0x1C1, "VdHSIOCalibrationLock", XENIA_KERNEL_DATA_BASE + 0x060, {0x01280000, 0, 0, 0, 0xFFFFFFFFu, 0, 0}}, + {0x266, "KeCertMonitorData", XENIA_KE_CERT_MONITOR_DATA, {0}}, + }; + return kLayout; +} +const KernelVariableSpec* FindKernelVariable(uint32_t ordinal) { + for (const auto& spec : KernelVariableLayout()) { + if (spec.ordinal == ordinal) return &spec; + } + return nullptr; +} +// Xenia XexModule::SetupLibraryImports placeholder for unbacked variables. +uint32_t xeniaUnmappedVariableValue(uint32_t ordinal) { return 0xD000BEEFu | ((ordinal & 0xFFFu) << 16); } + +uint32_t readXexEntryPoint(const Bytes& xex, uint32_t header_size) { + const uint32_t count = be32(xex.data(), 0x14); + if (header_size < 0x18 || count > ((header_size - 0x18) >> 3)) Fail("XEX optional-header table out of bounds"); + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (be32(xex.data(), p) != XEX_HEADER_ENTRY_POINT) continue; + const uint32_t entry = be32(xex.data(), p + 4); + if (!entry) Fail("XEX entry point is zero"); + return entry; + } + Fail("XEX entry point optional header missing"); +} + +// {inline value} for key&0xff == 0, {offset p+4} for 1, else {offset value}. +bool readXexOptionalHeader(const Bytes& xex, uint32_t header_size, uint32_t key, uint32_t* inline_value, + uint32_t* offset) { + const uint32_t count = be32(xex.data(), 0x14); + if (header_size < 0x18 || count > ((header_size - 0x18) >> 3)) return false; + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (be32(xex.data(), p) != key) continue; + const uint32_t value = be32(xex.data(), p + 4); + *inline_value = (key & 0xFF) == 0 ? value : 0; + *offset = (key & 0xFF) == 0 ? 0 : (key & 0xFF) == 1 ? p + 4 : value; + return true; + } + return false; +} + +struct XexTlsInfo { + uint32_t slot_count = 0, raw_data_address = 0, data_size = 0, raw_data_size = 0; +}; +bool readXexTlsInfo(const Bytes& xex, uint32_t header_size, XexTlsInfo* info) { + uint32_t value = 0, o = 0; + if (!readXexOptionalHeader(xex, header_size, 0x00020104, &value, &o) || !o || o + 16 > header_size) return false; + info->slot_count = be32(xex.data(), o); + info->raw_data_address = be32(xex.data(), o + 4); + info->data_size = be32(xex.data(), o + 8); + info->raw_data_size = be32(xex.data(), o + 12); + return true; +} +uint32_t readXexDefaultStackSize(const Bytes& xex, uint32_t header_size) { + uint32_t value = 0, o = 0; + return readXexOptionalHeader(xex, header_size, 0x00020200, &value, &o) ? value : 0; +} + +struct XexPages { + std::vector words; + uint32_t page_size = 0, load_address = 0; +}; +bool readXexPageDescriptors(const Bytes& xex, XexPages* pages) { + if (xex.size() < 0x18) return false; + const uint32_t sec = be32(xex.data(), 0x10); + if (uint64_t(sec) + 0x184 > xex.size()) return false; + pages->load_address = be32(xex.data(), sec + 0x110); + const uint32_t count = be32(xex.data(), sec + 0x180); + if (!count || count > 4096 || uint64_t(sec) + 0x184 + uint64_t(count) * 0x18 > xex.size()) return false; + pages->words.resize(count); + for (uint32_t i = 0; i < count; ++i) pages->words[i] = be32(xex.data(), sec + 0x184 + i * 0x18); + pages->page_size = pages->load_address <= 0x90000000u ? 0x10000 : 0x1000; + return true; +} + +Bytes extractXex2EncryptedImageKey(const Bytes& xex) { + if (xex.size() < 0x18 || std::memcmp(xex.data(), "XEX2", 4)) Fail("default.xex is not XEX2"); + const uint32_t header_size = be32(xex.data(), 8), security = be32(xex.data(), 0x10); + if (header_size < 0x18 || header_size > xex.size()) Fail("XEX header size out of bounds"); + if (!security || security > header_size - 0x160) Fail("XEX2 security info is too small for AES key"); + return Bytes(xex.begin() + security + 0x150, xex.begin() + security + 0x160); +} + +// --- prepareRetailXexImage (retail-xex-image-pipeline.mjs) ---------------------------- + +void coreStage(const uint8_t* bytes, size_t length) { + if (length > r360pkg_io_capacity()) Fail("XEX core staging overflow"); + std::memcpy(reinterpret_cast(r360pkg_io_ptr()), bytes, length); +} + +Bytes normalizeDecryptedHeader(const Bytes& header) { + Bytes out = header; + const uint32_t count = be32(out.data(), 0x14); + uint32_t ffi = 0; + bool found = false; + for (uint32_t i = 0, p = 0x18; i < count; ++i, p += 8) { + if (p + 8 > out.size()) Fail("XEX optional-header table truncated"); + if (be32(out.data(), p) == 0x3FF) { + ffi = be32(out.data(), p + 4); + found = true; + break; + } + } + if (!found) Fail("XEX file-format info missing"); + if (ffi + 8 > out.size()) Fail("XEX file-format info out of range"); + out[ffi + 4] = 0; + out[ffi + 5] = 0; + return out; +} + +Bytes decryptBody(const Bytes& key, const uint8_t* body, size_t length) { + auto* ptr = r360_xex_crypto_buffer(); + const uint32_t cap = r360_xex_crypto_capacity(); + if (key.size() != 16) Fail("encrypted XEX security key must be 16 bytes"); + if (!length || (length & 15)) Fail("encrypted XEX body must be non-empty and AES-block aligned"); + r360_xex_crypto_reset(); + std::memcpy(ptr, key.data(), 16); + if (r360_xex_crypto_begin_session(0) != 1) Fail("XEX session derivation failed %u", r360_xex_crypto_status()); + Bytes out(length); + size_t off = 0; + while (off < length) { + const uint32_t n = uint32_t(std::min(cap, length - off)) & ~15u; + if (!n) Fail("XEX AES chunk accounting failed"); + std::memcpy(ptr, body + off, n); + if (r360_xex_crypto_decrypt_chunk(n) != 1) Fail("XEX AES decrypt failed %u", r360_xex_crypto_status()); + std::memcpy(out.data() + off, ptr, n); + off += n; + } + if (r360_xex_crypto_bytes_done() != length) Fail("XEX AES byte accounting mismatch"); + return out; +} + +Bytes prepareNone(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_none_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st != 1) Fail("NONE begin failed %u", st); + Bytes out; + size_t off = 0; + while (off < body.size()) { + const size_t n = std::min(body.size() - off, 0x7000); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_none_accept(uint32_t(n)); + out.insert(out.end(), body.begin() + off, body.begin() + off + n); + off += n; + } + if (st != 2) Fail("NONE preparation failed %u", st); + return out; +} + +Bytes prepareBasic(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_basic_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st != 1) Fail("BASIC begin failed %u", st); + Bytes out; + size_t off = 0, guard = 0; + while (r360pkg_xex_prepare_status() == 1) { + if (++guard > 100000) Fail("BASIC preparation loop runaway"); + const uint32_t zero = r360pkg_xex_prepare_basic_zero_remaining(); + if (zero) { + st = r360pkg_xex_prepare_basic_consume_zero(std::min(zero, 0x4000)); + const uint32_t outn = r360pkg_xex_prepare_last_output_bytes(); + if (!outn || r360pkg_xex_prepare_last_output_kind() != 2) Fail("BASIC zero event mismatch"); + out.insert(out.end(), outn, 0); + continue; + } + const uint32_t data = r360pkg_xex_prepare_basic_data_remaining(); + if (!data) Fail("BASIC state has no work"); + const size_t n = std::min({size_t(data), body.size() - off, size_t(0x7000)}); + if (!n) Fail("BASIC encrypted source truncated"); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_basic_accept_data(uint32_t(n)); + if (r360pkg_xex_prepare_last_output_bytes() != n || r360pkg_xex_prepare_last_output_kind() != 1) + Fail("BASIC data event mismatch"); + out.insert(out.end(), body.begin() + off, body.begin() + off + n); + off += n; + } + if (st != 2 || off != body.size()) Fail("BASIC preparation failed status=%u source=%zu/%zu", st, off, body.size()); + return out; +} + +Bytes prepareNormal(const Bytes& header, const Bytes& body) { + coreStage(header.data(), header.size()); + uint32_t st = r360pkg_xex_prepare_normal_frame_begin(uint32_t(header.size()), uint32_t(header.size() + body.size())); + if (st >= 100) Fail("NORMAL begin failed %u", st); + Bytes stream; + size_t off = 0, pi = 0; + static const size_t kPattern[] = {17, 31, 67, 127, 251, 509}; + while (off < body.size() && st != 2 && st < 100) { + const size_t n = std::min(body.size() - off, kPattern[pi++ % 6]); + coreStage(body.data() + off, n); + st = r360pkg_xex_prepare_normal_frame_accept(uint32_t(n)); + const uint32_t outn = r360pkg_xex_prepare_last_output_bytes(); + if (outn) { + const auto* io = reinterpret_cast(r360pkg_io_ptr()); + stream.insert(stream.end(), io, io + outn); + } + off += n; + } + if (st != 2) Fail("NORMAL framing failed %u", st); + const uint32_t expected = r360pkg_xex_decode_image_size(); + if (stream.empty() || stream.size() > r360_lzx_input_capacity() || !expected || expected > r360_lzx_output_capacity()) + Fail("NORMAL LZX bounds"); + r360_lzx_reset(); + std::memcpy(r360_lzx_input_buffer(), stream.data(), stream.size()); + const uint32_t ls = r360_lzx_decompress(uint32_t(stream.size()), expected, r360pkg_xex_prepare_normal_window_size()); + if (ls != 0 || r360_lzx_output_size() != expected) Fail("NORMAL LZX failed %u", ls); + return Bytes(r360_lzx_output_buffer(), r360_lzx_output_buffer() + expected); +} + +Bytes prepareRetailXexImage(const Bytes& header, const Bytes& body, const Bytes& key) { + coreStage(header.data(), header.size()); + const uint32_t decode = r360pkg_xex_decode(uint32_t(header.size())); + if (decode != 1) Fail("XEX metadata decode failed status=%u", decode); + const uint32_t enc = r360pkg_xex_decode_encryption_type(); + const uint32_t comp = r360pkg_xex_decode_compression_type(); + if (comp > 2) Fail("unsupported XEX patch/delta compression %u", comp); + Bytes plain = body, effective = header; + if (enc == 1) { + plain = decryptBody(key, body.data(), body.size()); + effective = normalizeDecryptedHeader(header); + } else if (enc != 0) { + Fail("unsupported XEX encryption %u", enc); + } + if (comp == 0) return prepareNone(effective, plain); + if (comp == 1) return prepareBasic(effective, plain); + return prepareNormal(effective, plain); +} + +// --- Kernel import plan (render360-xex-imports.mjs, render360-kernel-imports.mjs) --- + +struct ImportLibrary { + std::string name; + std::vector imports; +}; + +std::vector decodeXexImportLibraries(const Bytes& x) { + const uint32_t header_size = be32(x.data(), 8), header_count = be32(x.data(), 0x14); + if (header_size < 0x18 || header_size > x.size() || header_count > ((header_size - 0x18) >> 3)) + Fail("XEX optional header table out of bounds"); + uint32_t offset = 0; + for (uint32_t i = 0; i < header_count; ++i) { + if (be32(x.data(), 0x18 + i * 8) == 0x000103FF) { + offset = be32(x.data(), 0x18 + i * 8 + 4); + break; + } + } + std::vector libraries; + if (!offset) return libraries; + if (offset > header_size - 12) Fail("XEX import header out of bounds"); + const uint32_t total = be32(x.data(), offset), string_bytes = be32(x.data(), offset + 4), + string_count = be32(x.data(), offset + 8); + if (total < 12 || offset + total > header_size || 12 + string_bytes > total || string_count > 256) + Fail("XEX import header size invalid"); + std::vector strings; + for (uint32_t s = 0; s < string_bytes && strings.size() < string_count;) { + const uint32_t start = offset + 12 + s, limit = offset + 12 + string_bytes; + uint32_t end = start; + while (end < limit && x[end]) ++end; + if (end == limit) Fail("unterminated XEX import string"); + strings.emplace_back(reinterpret_cast(x.data() + start), end - start); + s += (end - start) + 1; + if (s & 3) s += 4 - (s & 3); + } + if (strings.size() != string_count) Fail("XEX import string count mismatch"); + uint32_t p = offset + 12 + string_bytes; + const uint32_t end = offset + total; + while (p < end) { + if (end - p < 0x28) Fail("truncated XEX import library"); + const uint32_t size = be32(x.data(), p); + if (!size) break; + if (size < 0x28 || size > end - p) Fail("XEX import library size invalid"); + const uint32_t name_index = be16(x.data(), p + 0x24) & 0xFF, count = be16(x.data(), p + 0x26); + if (name_index >= strings.size()) Fail("XEX import library name index invalid"); + if (0x28 + count * 4 > size) Fail("XEX import table exceeds library record"); + ImportLibrary lib; + lib.name = strings[name_index]; + for (uint32_t i = 0; i < count; ++i) lib.imports.push_back(be32(x.data(), p + 0x28 + i * 4)); + libraries.push_back(std::move(lib)); + p += size; + } + return libraries; +} + +uint32_t imageBaseFromXex(const Bytes& x) { + const uint32_t header_count = be32(x.data(), 0x14); + for (uint32_t i = 0; i < header_count; ++i) { + if (be32(x.data(), 0x18 + i * 8) == 0x00010201) return be32(x.data(), 0x18 + i * 8 + 4); + } + Fail("XEX image base optional header missing"); +} + +struct PeSection { + uint32_t virtual_size, virtual_address, raw_size, raw_pointer, virtual_span; +}; +struct PreparedPe { + const Bytes* bytes; + uint32_t size_of_image = 0, size_of_headers = 0; + std::vector sections; +}; + +PreparedPe parsePreparedPe(const Bytes& p) { + if (p.size() < 0x40 || p[0] != 0x4D || p[1] != 0x5A) Fail("kernel import prepared image is not PE"); + const uint32_t nt = le32(p.data(), 0x3C); + if (nt > p.size() - 24 || le32(p.data(), nt) != 0x00004550) Fail("kernel import PE NT header invalid"); + const uint32_t section_count = le16(p.data(), nt + 6), optional_size = le16(p.data(), nt + 20), optional = nt + 24; + if (optional > p.size() || optional_size > p.size() - optional) Fail("kernel import PE optional header out of bounds"); + if (optional_size < 64) Fail("kernel import PE optional header too small"); + PreparedPe pe; + pe.bytes = &p; + pe.size_of_image = le32(p.data(), optional + 56); + pe.size_of_headers = le32(p.data(), optional + 60); + if (!pe.size_of_image || pe.size_of_headers > p.size()) Fail("kernel import PE image/header size invalid"); + const uint32_t table = optional + optional_size; + if (section_count > (p.size() - table) / 40) Fail("kernel import PE section table out of bounds"); + for (uint32_t i = 0; i < section_count; ++i) { + const uint32_t s = table + i * 40; + PeSection sec{le32(p.data(), s + 8), le32(p.data(), s + 12), le32(p.data(), s + 16), le32(p.data(), s + 20), 0}; + sec.virtual_span = std::max(sec.virtual_size, sec.raw_size); + const uint64_t vend = uint64_t(sec.virtual_address) + sec.virtual_span; + if (vend > 0x100000000ull || vend > pe.size_of_image) Fail("kernel import PE section RVA wraps/exceeds image"); + pe.sections.push_back(sec); + } + return pe; +} + +bool rvaInsideMappedPe(const PreparedPe& pe, uint64_t rva, uint64_t size) { + const uint64_t len = pe.bytes->size(); + if (rva < pe.size_of_headers) return rva + size <= pe.size_of_headers && rva + size <= len; + for (const auto& s : pe.sections) { + if (rva < s.virtual_address) continue; + const uint64_t delta = rva - s.virtual_address; + if (delta >= s.virtual_span) continue; + return rva + size <= len && delta + size <= s.virtual_span; + } + return false; +} + +bool rawOffsetForRva(const PreparedPe& pe, uint64_t rva, uint64_t size, uint64_t* out) { + const uint64_t len = pe.bytes->size(); + if (rva < pe.size_of_headers) { + if (rva + size <= pe.size_of_headers && rva + size <= len) { + *out = rva; + return true; + } + return false; + } + for (const auto& s : pe.sections) { + if (rva < s.virtual_address) continue; + const uint64_t delta = rva - s.virtual_address; + if (delta >= s.virtual_span) continue; + if (int64_t(delta) > int64_t(s.raw_size) - int64_t(size)) return false; + const uint64_t raw = s.raw_pointer + delta; + if (raw + size > len) return false; + *out = raw; + return true; + } + return false; +} + +bool isMappedImageLayout(const PreparedPe& pe) { + const uint64_t len = pe.bytes->size(); + if (len >= pe.size_of_image) return true; + uint64_t disk_end = pe.size_of_headers; + for (const auto& s : pe.sections) disk_end = std::max(disk_end, uint64_t(s.raw_pointer) + s.raw_size); + if (len > disk_end) return true; + if (pe.sections.empty()) return false; + for (const auto& s : pe.sections) { + if (uint64_t(s.virtual_address) + std::min(s.raw_size, s.virtual_span) > len) return false; + } + return true; +} + +struct ResolvedDescriptor { + bool mapped; + uint64_t offset; + uint32_t descriptor, type, ordinal; +}; +ResolvedDescriptor resolveImportDescriptor(const PreparedPe& pe, uint64_t rva) { + std::vector candidates; + if (rvaInsideMappedPe(pe, rva, 4)) candidates.push_back({true, rva, 0, 0, 0}); + uint64_t raw = 0; + if (rawOffsetForRva(pe, rva, 4, &raw)) { + bool dup = false; + for (const auto& c : candidates) dup |= c.offset == raw; + if (!dup) candidates.push_back({false, raw, 0, 0, 0}); + } + if (candidates.empty()) Fail("XEX import descriptor RVA is outside PE mappings"); + for (auto& c : candidates) { + c.descriptor = be32(pe.bytes->data(), size_t(c.offset)); + c.type = (c.descriptor >> 24) & 0xFF; + c.ordinal = c.descriptor & 0xFFFF; + } + std::vector valid; + for (const auto& c : candidates) { + if (c.type == 0 || c.type == 1) valid.push_back(c); + } + if (valid.size() == 1) return valid[0]; + if (valid.size() > 1) { + const bool want_mapped = isMappedImageLayout(pe); + for (const auto& c : valid) { + if (c.mapped == want_mapped) return c; + } + return valid[0]; + } + Fail("unsupported XEX import descriptor type %u", candidates[0].type); +} + +struct KernelImport { + std::string module; + uint32_t ordinal = 0; + bool function = false; + bool kernel_module = false; + uint32_t value_address = 0, thunk_address = 0; +}; +struct KernelImportPlan { + uint32_t image_base = 0; + std::vector plan; +}; + +KernelImportPlan buildKernelImportPlan(const Bytes& xex, const Bytes& prepared) { + KernelImportPlan out; + const auto libraries = decodeXexImportLibraries(xex); + const PreparedPe pe = parsePreparedPe(prepared); + out.image_base = imageBaseFromXex(xex); + for (const auto& lib : libraries) { + std::string lower = lib.name; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + const bool kernel = lower == "xboxkrnl.exe" || lower == "xam.xex"; + std::vector imports; + for (uint32_t record : lib.imports) { + if (record < out.image_base) Fail("XEX import descriptor below image base: %s@0x%x", lib.name.c_str(), record); + const ResolvedDescriptor d = resolveImportDescriptor(pe, uint64_t(record) - out.image_base); + if (d.type == 0) { + KernelImport item; + item.module = lib.name; + item.ordinal = d.ordinal; + item.kernel_module = kernel; + item.value_address = record; + imports.push_back(item); + continue; + } + if (imports.empty() || imports.back().ordinal != d.ordinal || imports.back().thunk_address) + Fail("XEX import thunk has no matching descriptor: %s ordinal 0x%x", lib.name.c_str(), d.ordinal); + imports.back().function = true; + imports.back().thunk_address = record; + } + out.plan.insert(out.plan.end(), imports.begin(), imports.end()); + } + return out; +} + +uint32_t moduleId(const std::string& name) { + std::string lower = name; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + return lower == "xboxkrnl.exe" ? 1 : lower == "xam.xex" ? 2 : 0; +} + +// registerKernelImportPlan: no browser HLE in the native build (the native +// title-GPU runtime is always present), so no function import is +// "implemented" by a relocated shim. +uint32_t registerKernelImportPlan(const KernelImportPlan& imports) { + r360_kernel_import_reset(); + uint32_t registered = 0; + for (const auto& item : imports.plan) { + if (!item.kernel_module || !item.function || !item.thunk_address) continue; + const uint32_t id = moduleId(item.module); + if (!id) continue; + if (r360_kernel_import_register(item.thunk_address, id, item.ordinal, 0, 0) != 1) + Fail("failed to register kernel import %s ordinal 0x%x", item.module.c_str(), item.ordinal); + ++registered; + } + return registered; +} + +void put8(uint32_t address, uint32_t value) { + if (r360_sparse_guest_memory_write_u8(address, value & 0xFF) != 1) + Fail("unable to initialize guest memory @ 0x%x", address); +} +void put32(uint32_t address, uint32_t value) { + for (int i = 0; i < 4; ++i) put8(address + i, (value >> (24 - i * 8)) & 0xFF); +} + +uint32_t installKernelVariableImports(const KernelImportPlan& imports, const Bytes& xex, uint32_t entry, + uint32_t header_size) { + bool any = false; + for (const auto& item : imports.plan) any |= item.kernel_module && !item.function; + if (!any) return 0; + const uint32_t page = 4096, read_write = 3; + const uint32_t pages = 1 + (header_size + page - 1) / page; + const uint32_t backing = r360_sparse_guest_memory_alloc(pages); + if (!backing || r360_sparse_guest_memory_map(XENIA_KERNEL_DATA_BASE, pages, backing, 0, read_write) != 1) + Fail("unable to map Xenia kernel variable/module state"); + for (uint32_t i = 0; i < header_size; ++i) put8(XENIA_XEX_HEADER_BASE + i, xex[i]); + const uint32_t security = be32(xex.data(), 0x10); + if (security > header_size - 8) Fail("XEX security header is outside copied guest header"); + const uint32_t image_size = be32(xex.data(), security + 4); + // X_LDR_DATA_TABLE_ENTRY fields used by Xenia UserModule::LoadXexContinue. + put32(XENIA_EXECUTABLE_HMODULE + 0x18, 0); + put32(XENIA_EXECUTABLE_HMODULE + 0x1C, imports.image_base); + put32(XENIA_EXECUTABLE_HMODULE + 0x38, image_size); + put32(XENIA_EXECUTABLE_HMODULE + 0x3C, entry); + put32(XENIA_EXECUTABLE_HMODULE + 0x58, XENIA_XEX_HEADER_BASE); + put32(XENIA_EXECUTABLE_MODULE_VAR, XENIA_EXECUTABLE_HMODULE); + for (const auto& spec : KernelVariableLayout()) { + for (size_t i = 0; i < spec.words.size(); ++i) put32(spec.address + uint32_t(i) * 4, spec.words[i]); + if (spec.text) { + const size_t n = std::strlen(spec.text); + for (uint32_t i = 0; i < spec.bytes; ++i) put8(spec.address + i, i < n ? uint8_t(spec.text[i]) : 0); + } + } + // ProcessInfoBlock (KernelState::SetExecutableModule). + XexTlsInfo tls; + const bool has_tls = readXexTlsInfo(xex, header_size, &tls); + for (uint32_t i = 0; i < 0x60; i += 4) put32(XENIA_PROCESS_INFO_BLOCK + i, 0); + put32(XENIA_PROCESS_INFO_BLOCK + 0x0C, 0x0000007F); + put32(XENIA_PROCESS_INFO_BLOCK + 0x10, 0x001F0000); + put8(XENIA_PROCESS_INFO_BLOCK + 0x1B, 0x06); + put32(XENIA_PROCESS_INFO_BLOCK + 0x1C, 16 * 1024); + if (has_tls) { + put32(XENIA_PROCESS_INFO_BLOCK + 0x24, tls.data_size); + put32(XENIA_PROCESS_INFO_BLOCK + 0x28, tls.raw_data_size); + put8(XENIA_PROCESS_INFO_BLOCK + 0x2C, ((tls.slot_count * 4) >> 8) & 0xFF); + put8(XENIA_PROCESS_INFO_BLOCK + 0x2D, (tls.slot_count * 4) & 0xFF); + } + put8(XENIA_PROCESS_INFO_BLOCK + 0x2F, 1); // X_PROCTYPE_USER + if (r360_kernel_set_executable_module(XENIA_EXECUTABLE_HMODULE, XENIA_XEX_HEADER_BASE, XENIA_PROCESS_INFO_BLOCK) != 1) + Fail("native kernel rejected the guest XEX header"); + r360_kernel_set_timestamp_bundle(XENIA_KERNEL_DATA_BASE + 0x040); + uint32_t relocated = 0; + for (const auto& item : imports.plan) { + if (!item.kernel_module || item.function) continue; + std::string lower = item.module; + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + const KernelVariableSpec* spec = lower == "xboxkrnl.exe" ? FindKernelVariable(item.ordinal) : nullptr; + const uint32_t target = spec ? spec->address : xeniaUnmappedVariableValue(item.ordinal); + if (r360_xex_guest_mapper_patch_u32_be(item.value_address, target) != 1) + Fail("failed to relocate %s ordinal 0x%x at 0x%x (mapper 0x%x)", item.module.c_str(), item.ordinal, + item.value_address, r360_xex_guest_mapper_status()); + if (spec) ++relocated; + } + return relocated; +} + +struct MainThreadContext { + uint32_t stack_top = 0, pcr = 0; +}; + +MainThreadContext prepareBrowserMainThreadContext(uint32_t entry, const Bytes& xex, uint32_t header_size) { + const uint32_t page = 4096, stack_slot_base = 0x70000000, stack_limit = stack_slot_base + page; + const uint32_t xex_stack = readXexDefaultStackSize(xex, header_size); + const uint32_t stack_pages = std::max(128, std::min(0x0F00, (xex_stack + 4095) / 4096)); + const uint32_t stack_base = stack_limit + stack_pages * page; + MainThreadContext ctx; + ctx.stack_top = (stack_base - (64 + 112)) & ~0xFu; + ctx.pcr = 0x50000000; + const uint32_t tls_address = 0x50001000, thread = 0x50002000, context_pages = 3, read_write = 3; + const uint32_t stack_backing = r360_sparse_guest_memory_alloc(stack_pages); + if (!stack_backing || r360_sparse_guest_memory_map(stack_limit, stack_pages, stack_backing, 0, read_write) != 1) + Fail("unable to map Xbox main-thread stack"); + const uint32_t context_backing = r360_sparse_guest_memory_alloc(context_pages); + if (!context_backing || r360_sparse_guest_memory_map(ctx.pcr, context_pages, context_backing, 0, read_write) != 1) + Fail("unable to map Xbox main-thread PCR/TLS"); + put32(ctx.pcr + 0x000, tls_address); + put32(ctx.pcr + 0x030, ctx.pcr); + put32(ctx.pcr + 0x070, stack_base); + put32(ctx.pcr + 0x074, stack_limit); + put32(ctx.pcr + 0x100, thread); + put32(ctx.pcr + 0x150, 0); + put32(thread + 0x05C, stack_base); + put32(thread + 0x060, stack_limit); + put32(thread + 0x068, tls_address); + put32(thread + 0x0D0, stack_base); + put32(thread + 0x14C, 1); + put32(thread + 0x150, entry); + // XThread::InitializeGuestObject: dispatcher header type 6, self-linked + // list heads, process info block, creation time, flags. + put8(thread + 0x000, 6); + static const uint32_t kLinks[][2] = {{0x008, 0x008}, {0x00C, 0x008}, {0x010, 0x010}, {0x014, 0x010}, + {0x040, 0x020}, {0x044, 0x020}, {0x048, 0x000}, {0x04C, 0x018}, + {0x074, 0x074}, {0x078, 0x074}, {0x07C, 0x07C}, {0x080, 0x07C}, + {0x144, 0x144}, {0x148, 0x144}, {0x154, 0x154}, {0x158, 0x154}}; + for (const auto& link : kLinks) put32(thread + link[0], thread + link[1]); + put32(thread + 0x054, 0x01020001); + put32(thread + 0x084, XENIA_PROCESS_INFO_BLOCK); + put8(thread + 0x08B, 1); + put32(thread + 0x09C, 0xFDFFD7FF); + put32(thread + 0x17C, 1); + // TLS: slots*4 + extended data, with the XEX TLS template copied in. + XexTlsInfo tls; + if (readXexTlsInfo(xex, header_size, &tls)) { + const uint32_t slots = tls.slot_count ? tls.slot_count : 1024; + const uint32_t total = slots * 4 + tls.data_size; + uint32_t block = tls_address; + if (total > page) { + block = r360_kernel_pool_alloc(total, 16); + if (!block) Fail("unable to allocate %u-byte Xbox TLS block", total); + } + const uint32_t copy = std::min(tls.raw_data_size, tls.data_size); + for (uint32_t i = 0; copy && tls.raw_data_address && i < copy; ++i) + put8(block + i, r360_sparse_guest_memory_read_u8(tls.raw_data_address + i)); + put32(ctx.pcr + 0x000, block); + put32(thread + 0x068, block); + } + r360_guest_thread_register_external(entry, stack_base, stack_limit, ctx.pcr, thread, 1); + return ctx; +} + +void stagePreparedPeImage(const Bytes& prepared, uint32_t xex_entry, const Bytes& xex) { + uintptr_t input = r360_xex_guest_mapper_input_buffer(); + uint32_t cap = r360_xex_guest_mapper_input_capacity(); + if (prepared.size() > cap) { + const uint32_t max = r360_xex_guest_mapper_input_max_capacity(); + if (max && prepared.size() > max) Fail("prepared image exceeds bounded PE staging ceiling %zu/%u", prepared.size(), max); + if (r360_xex_guest_mapper_reserve_input(uint32_t(prepared.size())) != 1) + Fail("unable to reserve PE staging for prepared image %zu bytes (status 0x%x)", prepared.size(), + r360_xex_guest_mapper_status()); + input = r360_xex_guest_mapper_input_buffer(); + cap = r360_xex_guest_mapper_input_capacity(); + } + if (!input || prepared.size() > cap) Fail("prepared image exceeds current PE staging capacity %zu/%u", prepared.size(), cap); + XexPages pages; + if (readXexPageDescriptors(xex, &pages) && pages.words.size() * 4 <= cap) { + std::memcpy(reinterpret_cast(input), pages.words.data(), pages.words.size() * 4); + r360_pe_guest_set_xex_pages(input, uint32_t(pages.words.size()), pages.page_size); + } + std::memcpy(reinterpret_cast(input), prepared.data(), prepared.size()); + if (r360_pe_guest_load_at_entry(input, uint32_t(prepared.size()), xex_entry) != 1) + Fail("prepared PE guest load failed 0x%x", r360_pe_guest_status()); +} + +uint32_t RunScannedEntry(void*) { return r360_title_handoff_translate_scanned_entry(); } + +// Mirrors the runtimeBoundary expression in handoffDefaultXex. +const char* RuntimeBoundary(bool stopped, uint32_t exec_status, uint32_t kernel_status, uint32_t blocker_kind) { + if (stopped) return "stopped-by-user"; + if (exec_status == 3) return "guest-return"; + if (kernel_status == 2) return "kernel-import-unimplemented"; + if (kernel_status == 3) return "kernel-import-abi-failed"; + if (kernel_status == 4) return "title-requested-exit"; + if (kernel_status == 5) return "guest-wait-blocked"; + if (exec_status == 2) return "no-return-boundary"; + if (exec_status == 1) { + return blocker_kind == 2 ? "unresolved-guest-call" + : blocker_kind == 3 ? "instruction-limit" + : blocker_kind == 5 ? "guest-memory-dependency" + : "unsupported-hir"; + } + return "execution-not-observed"; +} + +const char* const kTerminalKinds[] = {"none", "HalReturnToFirmware", "KeBugCheck", "ExTerminateThread", + "XamLoaderTerminateTitle", "XamLoaderLaunchTitle", "title process exit"}; +const char* const kWaitReasons[] = {"none", + "infinite wait on an unsignalled object", + "bounded wait spinning without progress", + "lock held by another guest thread", + "game file bytes not yet available to the synchronous kernel", + "XMA audio buffers waiting for a decoder (not implemented yet)"}; + +// Disc list of the last boot (multi-disc titles). +std::vector g_discs; +uint32_t g_current_disc = 0; + +void handoffDefaultXex(const Bytes& xex, const Bytes& key, const R360BootOptions& options, R360BootResult* r) { + if (xex.size() < 0x18 || std::memcmp(xex.data(), "XEX2", 4)) Fail("default.xex is not XEX2"); + const uint32_t header_size = be32(xex.data(), 8); + if (header_size < 0x18 || header_size > xex.size()) Fail("default.xex header size out of bounds"); + const uint32_t xex_entry = readXexEntryPoint(xex, header_size); + const Bytes header(xex.begin(), xex.begin() + header_size), body(xex.begin() + header_size, xex.end()); + const Bytes prepared = prepareRetailXexImage(header, body, key); + + // Each handoff is a fresh title boot (the registered guest VFS is kept). + r360_kernel_runtime_reset(); + r360_kernel_services_reset(); + r360_xam_set_license_mask(options.license_full ? 1 : 0); + r360_kernel_service_reset(); + stagePreparedPeImage(prepared, xex_entry, xex); + // XexModule::FindSaveRest. + XexPages pages; + if (readXexPageDescriptors(xex, &pages)) { + uint32_t address = pages.load_address; + for (uint32_t word : pages.words) { + const uint32_t size = (word >> 4) * pages.page_size; + if ((word & 0xF) == 1 && r360_ppc_probe_register_save_rest(address, address + size) == 3) break; + address += size; + } + } + const uint32_t entry = r360_pe_guest_entry_address(); + r->pe_entry = r360_pe_guest_pe_entry_address(); + if (entry != xex_entry) Fail("XEX entry selection mismatch 0x%x/0x%x", entry, xex_entry); + r->entry = entry; + + const KernelImportPlan imports = buildKernelImportPlan(xex, prepared); + r->kernel_imports = uint32_t(imports.plan.size()); + r->kernel_registered = registerKernelImportPlan(imports); + r->kernel_variables_relocated = installKernelVariableImports(imports, xex, entry, header_size); + + r360_title_handoff_reset(); + if (r360_ppc_probe_page_sparse_code(entry) == 0) Fail("unable to initialize Xenia title decoder before main-thread context"); + r360_title_handoff_reset(); + const MainThreadContext ctx = prepareBrowserMainThreadContext(entry, xex, header_size); + // R360_XENIA_ENTRY_ABI_V51: upstream Processor::Execute special state. + if (r360_ppc_probe_set_initial_lr(0xBCBCBCBCull) != 1) Fail("unable to initialize Xenia title-entry LR"); + if (uint32_t(r360_ppc_probe_initial_lr()) != 0xBCBCBCBCu) Fail("Xenia title-entry LR verification failed"); + if (r360_ppc_probe_set_initial_gpr(1, ctx.stack_top) != 1 || r360_ppc_probe_set_initial_gpr(13, ctx.pcr) != 1) + Fail("failed to set startup GPRs"); + // A sliced run lifts the per-function HIR instruction guard (as the browser). + if (options.slice_ms) r360_hir_set_instruction_budget(0xFFFFFFFFu); + + uint32_t stopped = 0; + const uint32_t hir = r360_native_run_with_fibers(RunScannedEntry, nullptr, options.slice_ms, options.on_slice, + options.user, &stopped); + r->stopped_by_host = stopped == 1; + r->hir = r->stopped_by_host ? 1 : hir; + if (!r->hir) { + Fail("title entry handoff failed 0x%x probe=0x%x entry=0x%x", r360_title_handoff_status(), r360_ppc_probe_status(), + entry); + } + r->execution_status = r360_ppc_probe_correctness_status(); + r->execution_instructions = r360_ppc_probe_correctness_instructions(); + r->blocker_kind = r360_ppc_probe_correctness_blocker_kind(); + r->blocker_opcode = r360_ppc_probe_correctness_blocker_opcode(); + r->blocker_address = r360_ppc_probe_correctness_blocker_address(); + r->memory_fault_address = r360_sparse_guest_memory_last_fault_address(); + r->memory_fault_code = r360_sparse_guest_memory_last_fault_code(); + r->kernel_calls = r360_kernel_import_calls(); + r->kernel_last_status = r360_kernel_import_last_status(); + r->kernel_last_module = r360_kernel_import_last_module(); + r->kernel_last_ordinal = r360_kernel_import_last_ordinal(); + std::snprintf(r->runtime_boundary, sizeof(r->runtime_boundary), "%s", + RuntimeBoundary(r->stopped_by_host, r->execution_status, r->kernel_last_status, r->blocker_kind)); + char name[96]; + if (r->kernel_last_status == 4) { + const uint32_t kind = r360_kernel_terminal_kind(); + std::snprintf(r->kernel_boundary, sizeof(r->kernel_boundary), "title-requested-exit: %s via %s code 0x%X lr 0x%08X", + kind < 7 ? kTerminalKinds[kind] : "terminal", + r360_native_kernel_export_name(r360_kernel_terminal_module(), r360_kernel_terminal_ordinal(), name, + sizeof(name)), + r360_kernel_terminal_code(), r360_kernel_terminal_lr()); + } else if (r->kernel_last_status == 5) { + const uint32_t reason = r360_kernel_wait_reason(); + std::snprintf(r->kernel_boundary, sizeof(r->kernel_boundary), "guest-wait-blocked: %s via %s object 0x%08X", + reason < 6 ? kWaitReasons[reason] : "wait", + r360_native_kernel_export_name(r360_kernel_wait_module(), r360_kernel_wait_ordinal(), name, + sizeof(name)), + r360_kernel_wait_object()); + } +} + +struct ExportName { + uint32_t ordinal; + const char* name; +}; +const ExportName kXboxkrnl[] = { +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name}, +#include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc" +#undef XE_EXPORT +}; +const ExportName kXam[] = { +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name}, +#include "xenia/kernel/xam/xam_table.inc" +#undef XE_EXPORT +}; + +void JsonString(std::string& out, const char* s) { + out += '"'; + for (; *s; ++s) { + const unsigned char c = static_cast(*s); + if (c == '"' || c == '\\') { + out += '\\'; + out += char(c); + } else if (c < 0x20) { + char esc[8]; + std::snprintf(esc, sizeof(esc), "\\u%04x", c); + out += esc; + } else { + out += char(c); + } + } + out += '"'; +} + +std::chrono::steady_clock::time_point g_boot_started; + +} // namespace + +extern "C" const char* r360_native_kernel_export_name(uint32_t module, uint32_t ordinal, char* buf, size_t size) { + const ExportName* table = module == 1 ? kXboxkrnl : module == 2 ? kXam : nullptr; + const size_t count = module == 1 ? sizeof(kXboxkrnl) / sizeof(kXboxkrnl[0]) : sizeof(kXam) / sizeof(kXam[0]); + for (size_t i = 0; table && i < count; ++i) { + if (table[i].ordinal == ordinal) { + std::snprintf(buf, size, "%s", table[i].name); + return buf; + } + } + std::snprintf(buf, size, "%s!0x%X", module == 1 ? "xboxkrnl.exe" : module == 2 ? "xam.xex" : "module", ordinal); + return buf; +} + +extern "C" uint32_t r360_native_boot(const R360BootOptions* options, R360BootResult* result) { + *result = R360BootResult{}; + g_boot_started = std::chrono::steady_clock::now(); + try { + if (!options || !options->path) Fail("no title path"); + g_discs.clear(); + g_discs.push_back(options->path); + for (uint32_t i = 0; options->discs && i < options->disc_count; ++i) { + if (options->discs[i] && g_discs[0] != options->discs[i]) g_discs.push_back(options->discs[i]); + } + g_current_disc = 0; + OpenedTitle title = openTitle(options->path); + result->kind = title.kind; + std::snprintf(result->title, sizeof(result->title), "%s", title.title.c_str()); + for (const auto& f : title.files) (f.directory ? result->vfs_directories : result->vfs_files)++; + registerGuestVfs(title.files); + title.files.clear(); // attached STFS data now lives in the kernel VFS + const Bytes key = extractXex2EncryptedImageKey(title.default_xex); + r360_hir_set_instruction_budget(options->function_budget ? options->function_budget : (1u << 30)); + r360_trace_set_verbose(0); + if (options->deterministic_ps) r360_set_deterministic_clock(options->deterministic_ps); + r360_hir_set_total_instruction_budget(options->max_minstr); + if (options->dialog_button >= 0) r360_xam_dialog_set_auto_answer(options->dialog_button); + r360_ppc_probe_set_execute_on_translate(1); + handoffDefaultXex(title.default_xex, key, *options, result); + result->ok = 1; + } catch (const std::exception& e) { + std::snprintf(result->error, sizeof(result->error), "%s", e.what()); + result->ok = 0; + } + result->elapsed_ms = + std::chrono::duration(std::chrono::steady_clock::now() - g_boot_started).count(); + return result->ok; +} + +extern "C" uint32_t r360_native_current_disc() { return g_current_disc; } + +extern "C" uint32_t r360_native_select_disc(uint32_t index) { + if (index >= g_discs.size()) return 0; + try { + OpenedTitle disc = openTitle(g_discs[index]); + registerGuestVfs(disc.files); + g_current_disc = index; + return 1; + } catch (const std::exception& e) { + std::fprintf(stderr, "R360_DISC select %u failed: %s\n", index, e.what()); + return 0; + } +} + +extern "C" size_t r360_native_report_json(const R360BootResult* r, char* out, size_t capacity) { + static const char* const kKinds[] = {"unknown", "folder", "xex", "stfs", "iso"}; + std::string j = "{"; + char buf[512]; + auto field = [&](const char* name, const char* format, auto... values) { + std::snprintf(buf, sizeof(buf), format, values...); + if (j.size() > 1) j += ','; + j += '"'; + j += name; + j += "\":"; + j += buf; + }; + auto text = [&](const char* name, const char* value) { + if (j.size() > 1) j += ','; + j += '"'; + j += name; + j += "\":"; + JsonString(j, value); + }; + text("build", "native"); + text("kind", kKinds[r->kind < 5 ? r->kind : 0]); + if (r->title[0]) text("title", r->title); + field("elapsedMs", "%.0f", r->elapsed_ms); + field("vfs", "{\"files\":%u,\"directories\":%u,\"reads\":%u}", r->vfs_files, r->vfs_directories, r360_vfs_reads()); + if (!r->ok) { + if (j.size() > 1) j += ','; + j += "\"error\":{\"message\":"; + JsonString(j, r->error); + j += '}'; + } else { + field("error", "null"); + field("entry", "\"0x%08X\"", r->entry); + text("runtimeBoundary", r->runtime_boundary); + field("executionStatus", "%u", r->execution_status); + field("instructions", "%u", r->execution_instructions); + field("kernelCalls", "%u", r->kernel_calls); + if (r->kernel_boundary[0]) text("kernelBoundary", r->kernel_boundary); + if (r->blocker_kind) + field("hirBlocker", "{\"kind\":%u,\"opcode\":%u,\"address\":\"0x%08X\"}", r->blocker_kind, r->blocker_opcode, + r->blocker_address); + if (r->memory_fault_code) + field("memoryFault", "{\"code\":%u,\"address\":\"0x%08X\"}", r->memory_fault_code, r->memory_fault_address); + if (r->kernel_last_status == 2) { + char name[96]; + if (j.size() > 1) j += ','; + j += "\"unsupportedKernelCall\":"; + JsonString(j, r360_native_kernel_export_name(r->kernel_last_module, r->kernel_last_ordinal, name, sizeof(name))); + } + field("guestFibers", "{\"threads\":%u,\"switches\":%u,\"preemptions\":%u,\"endedOn\":%u}", + r360_fiber_count() ? r360_fiber_count() - 1 : 0, r360_fiber_switches(), r360_fiber_preemptions(), + r360_fiber_current()); + // The 30 FPS bar inputs (same definitions as run-title.mjs perf). + const double wall = r->elapsed_ms / 1000.0; + const double instr = r360_perf_counter(0), interp = r360_perf_counter(1); + const uint32_t frames = r360_title_gpu_vd_swap_calls(); + field("perf", + "{\"wallSeconds\":%.1f,\"guestFrames\":%u,\"gameFpsWall\":%.2f,\"mips\":%.1f,\"interpretedPercent\":%.3f," + "\"guestIdleMs\":%.0f}", + wall, frames, frames / std::max(wall, 0.001), instr / std::max(wall, 0.001) / 1e6, + instr ? 100.0 * interp / instr : 0.0, r360_fiber_idle_ms()); + field("framesPresented", + "{\"vdSwapCalls\":%u,\"vblankInterrupts\":%u,\"cpInterrupts\":%u,\"gpuPackets\":%u,\"gpuDraws\":%u," + "\"softDraws\":%u,\"cacheHits\":%u,\"cacheMisses\":%u,\"cacheEntries\":%u,\"cacheKB\":%u," + "\"vdSwapFailures\":%u,\"width\":%u,\"height\":%u}", + frames, r360_kernel_vblank_interrupts(), r360_kernel_cp_interrupts(), r360_xenos_packets(), + r360_xenos_draws(), r360_xenos_soft_draws(), r360_hir_cache_hits(), r360_hir_cache_misses(), + r360_hir_cache_entries(), r360_hir_cache_kilobytes(), r360_title_gpu_vd_swap_failures(), + r360_title_gpu_last_vd_swap_width(), r360_title_gpu_last_vd_swap_height()); + // Last kernel calls (readKernelServiceTrace). + j += ",\"kernelTrace\":["; + const uint32_t n = r360_kernel_import_trace_count(); + for (uint32_t i = n > 48 ? n - 48 : 0, first = 1; i < n; ++i, first = 0) { + char name[96]; + if (!first) j += ','; + std::snprintf(buf, sizeof(buf), + "{\"sequence\":%u,\"name\":\"%s\",\"args\":[%u,%u,%u,%u],\"result\":%u,\"status\":%u}", + r360_kernel_import_trace_sequence(i), + r360_native_kernel_export_name(r360_kernel_import_trace_module(i), + r360_kernel_import_trace_ordinal(i), name, sizeof(name)), + r360_kernel_import_trace_arg(i, 0), r360_kernel_import_trace_arg(i, 1), + r360_kernel_import_trace_arg(i, 2), r360_kernel_import_trace_arg(i, 3), + r360_kernel_import_trace_result(i), r360_kernel_import_trace_status(i)); + j += buf; + } + j += ']'; + field("totalInstructionsMillions", "%u", r360_hir_total_instructions_millions()); + field("hostStackHeadroom", "%u", r360_trap_stack_headroom()); + } + j += '}'; + if (capacity) { + const size_t n = std::min(j.size(), capacity - 1); + std::memcpy(out, j.data(), n); + out[n] = 0; + } + return j.size(); +} diff --git a/native/tools/gen_core_api.py b/native/tools/gen_core_api.py new file mode 100644 index 00000000..d2a1040a --- /dev/null +++ b/native/tools/gen_core_api.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Generates native/include/render360_core_exports.h: C declarations of every +extern "C" r360_* function the Render360 bootstrap core defines (the same +surface the browser build exports to JavaScript). Run after changing exports: + python3 native/tools/gen_core_api.py +""" +import pathlib, re, sys +ROOT = pathlib.Path(__file__).resolve().parents[2] +SRC = ROOT / "src" / "xenia_web_bootstrap" +TYPES = r"(?:const\s+)?(?:void|bool|double|float|int|int32_t|uint8_t|uint16_t|uint32_t|uint64_t|int64_t|size_t|uintptr_t|char)\s*\**" +DEF = re.compile(r"^(?:extern\s+\"C\"\s+)?(?:__attribute__\(\([^;{]*?\)\)\s*)?(?:R360_WASM_EXPORT\([^)]*\)\s*)?(?:static\s+)?(?P" + TYPES + r")\s*(?Pr360_[A-Za-z0-9_]+)\s*\((?P[^)]*)\)\s*(?:noexcept\s*)?\{", re.M) +SKIP_FILES = {"hir_wasm_jit.cpp"} +found = {} +# Overlay-generated units (prepare-*.py) replace some sources at build time. +OVERLAY = ROOT / "build" / "xenia-web-overlay" / "render360" +paths = sorted(SRC.glob("*.cpp")) + sorted(SRC.glob("*.inc")) +if OVERLAY.is_dir(): + paths = sorted(OVERLAY.glob("*.cpp")) + paths +for path in paths: + if path.name in SKIP_FILES: + continue + text = path.read_text(errors="replace") + # Join attribute lines with the definition that follows them. + text = re.sub(r"(extern\s+\"C\"\s*)\n", r"\1 ", text) + text = re.sub(r"(__attribute__\(\([^\n]*\)\)|R360_WASM_EXPORT\([^)]*\))\s*\n", r"\1 ", text) + for m in DEF.finditer(text): + name = m.group("name") + args = " ".join(m.group("args").split()) + ret = " ".join(m.group("ret").split()) + found.setdefault(name, (ret, args, path.name)) +out = ["// Generated by native/tools/gen_core_api.py - do not edit.", + "// Every r360_* entry point of the Render360 core (browser: wasm exports).", + "#pragma once", "#include ", "#include ", "#include ", + "#ifdef __cplusplus", 'extern "C" {', "#endif"] +for name in sorted(found): + ret, args, src = found[name] + out.append(f"{ret} {name}({args or 'void'}); // {src}") +out += ["#ifdef __cplusplus", "}", "#endif", ""] +dest = ROOT / "native" / "include" / "render360_core_exports.h" +dest.write_text("\n".join(out)) +print(f"{len(found)} r360_* functions -> {dest.relative_to(ROOT)}", file=sys.stderr) diff --git a/native/tools/run_title.cpp b/native/tools/run_title.cpp new file mode 100644 index 00000000..f393833c --- /dev/null +++ b/native/tools/run_title.cpp @@ -0,0 +1,123 @@ +// Native headless title runner (macOS): the native counterpart of +// tools/run-title.mjs, built by native/build-native.sh as build/native-/run-title. +// +// run-title [--json out.json] +// [--max-minstr N] [--deterministic PS] [--budget N] [--license trial|full] +// [--dialog-button N] [--progress] [--slice-ms N] [--disc FILE]... +// +// Interpreter only (no guest JIT natively). Game files are read in place. +#include +#include +#include +#include +#include +#include +#include + +#include "render360_core.h" + +namespace { +struct Progress { + std::chrono::steady_clock::time_point started, last; + bool enabled = false; +}; + +uint32_t OnSlice(void* user) { + auto* p = static_cast(user); + const auto now = std::chrono::steady_clock::now(); + if (p->enabled && now - p->last >= std::chrono::seconds(5)) { + p->last = now; + const double wall = std::chrono::duration(now - p->started).count(); + std::printf("progress %uM instr · %u kernel calls · %u frames · %u fibers · %u switches · %.1f MIPS · %.0fs\n", + r360_hir_total_instructions_millions(), r360_kernel_import_calls(), r360_title_gpu_vd_swap_calls(), + r360_fiber_count(), r360_fiber_switches(), r360_perf_counter(0) / wall / 1e6, wall); + std::fflush(stdout); + } + return 0; +} +} // namespace + +int main(int argc, char** argv) { + R360BootOptions options{}; + options.dialog_button = -1; + const char* json = nullptr; + std::vector discs; + Progress progress; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + auto next = [&]() -> const char* { + if (i + 1 >= argc) { + std::fprintf(stderr, "%s needs a value\n", a.c_str()); + std::exit(2); + } + return argv[++i]; + }; + if (a == "--json") json = next(); + else if (a == "--max-minstr") options.max_minstr = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--deterministic") options.deterministic_ps = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--budget") options.function_budget = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--license") options.license_full = std::strcmp(next(), "full") == 0; + else if (a == "--dialog-button") options.dialog_button = int32_t(std::strtol(next(), nullptr, 0)); + else if (a == "--slice-ms") options.slice_ms = uint32_t(std::strtoul(next(), nullptr, 0)); + else if (a == "--progress") progress.enabled = true; + else if (a == "--disc") discs.push_back(next()); + else if (a == "--help" || a == "-h") { + std::printf("usage: run-title [--json out.json] [--max-minstr N] " + "[--deterministic PS] [--budget N] [--license trial|full] [--dialog-button N] [--progress] " + "[--slice-ms N] [--disc FILE]...\n"); + return 0; + } else if (!options.path) options.path = argv[i]; + else { + std::fprintf(stderr, "unexpected argument %s\n", argv[i]); + return 2; + } + } + if (!options.path) { + std::fprintf(stderr, "usage: run-title [--json out.json] ... (--help)\n"); + return 2; + } + // Same rule as run-title.mjs: progress (and frame/press work) runs in 200 ms slices. + if (progress.enabled && !options.slice_ms) options.slice_ms = 200; + progress.started = progress.last = std::chrono::steady_clock::now(); + if (options.slice_ms) { + options.on_slice = OnSlice; + options.user = &progress; + } + options.discs = discs.data(); + options.disc_count = uint32_t(discs.size()); + std::printf("Render360 native title runner · JIT-capable process: %s (interpreter only)\n", + r360_native_jit_available() ? "yes" : "no"); + + R360BootResult result{}; + r360_native_boot(&options, &result); + + if (!result.ok) { + std::printf("FAILED BEFORE EXECUTION: %s\n", result.error); + } else { + std::printf("entry 0x%08X · %u PPC instructions (native HIR) · %u kernel calls\n", result.entry, + result.execution_instructions, result.kernel_calls); + std::printf("stopped at: %s\n", result.runtime_boundary); + if (result.kernel_boundary[0]) std::printf(" %s\n", result.kernel_boundary); + const double wall = result.elapsed_ms / 1000.0; + const double instr = r360_perf_counter(0), interp = r360_perf_counter(1); + std::printf(" frames (VdSwap): %u at %ux%u · %.2f fps wall · %.1f MIPS · interpreted %.1f%% · %.1fs\n", + r360_title_gpu_vd_swap_calls(), r360_title_gpu_last_vd_swap_width(), + r360_title_gpu_last_vd_swap_height(), r360_title_gpu_vd_swap_calls() / wall, + instr / wall / 1e6, instr ? 100.0 * interp / instr : 0.0, wall); + std::printf(" guest threads: %u title-created, %u switches\n", r360_fiber_count() ? r360_fiber_count() - 1 : 0, + r360_fiber_switches()); + } + if (json) { + std::vector report(1 << 20); + const size_t n = r360_native_report_json(&result, report.data(), report.size()); + FILE* f = std::fopen(json, "w"); + if (f) { + std::fwrite(report.data(), 1, std::min(n, report.size() - 1), f); + std::fclose(f); + std::printf("report written to %s\n", json); + } + } + std::fflush(stdout); + // Guest threads of the run may still be parked; exit without unwinding them. + std::_Exit(result.ok ? 0 : 1); +} diff --git a/prepare-xenia-web-overlay.py b/prepare-xenia-web-overlay.py index 77499315..ef3f8944 100644 --- a/prepare-xenia-web-overlay.py +++ b/prepare-xenia-web-overlay.py @@ -44,7 +44,7 @@ if needle not in text: raise SystemExit("Upstream PPCContext layout drifted: reserved_val anchor not found") replacement = needle + ( - "\n#if defined(__EMSCRIPTEN__) || defined(XE_ARCH_WASM32)\n" + "\n#if (defined(__EMSCRIPTEN__) || defined(XE_ARCH_WASM32)) && !defined(R360_NATIVE)\n" " // Render360 web ABI: compensate for 32-bit host pointers without\n" " // moving any existing PPCContext field. Keep this as tail padding.\n" " uint8_t render360_wasm32_tail_padding[16];\n" diff --git a/render360_xenia_core.cpp b/render360_xenia_core.cpp index d5070bcb..dd365f8d 100644 --- a/render360_xenia_core.cpp +++ b/render360_xenia_core.cpp @@ -642,8 +642,8 @@ __attribute__((visibility("default"))) uint32_t r360_io_capacity() { return R360_IO_CAPACITY; } __attribute__((visibility("default"))) -uint32_t r360_io_ptr() { - return static_cast(reinterpret_cast(io_buffer)); +uintptr_t r360_io_ptr() { + return reinterpret_cast(io_buffer); } __attribute__((visibility("default"))) @@ -820,8 +820,8 @@ R360_STFS_GETTER(r360_stfs_request_kind, request_kind) #undef R360_STFS_GETTER __attribute__((visibility("default"))) -uint32_t r360_stfs_display_name_ptr() { - return static_cast(reinterpret_cast(stfs_display_name)); +uintptr_t r360_stfs_display_name_ptr() { + return reinterpret_cast(stfs_display_name); } __attribute__((visibility("default"))) uint32_t r360_stfs_display_name_length() { return stfs_display_name_length; } @@ -836,9 +836,9 @@ __attribute__((visibility("default"))) uint32_t r360_stfs_request_offset_hi() { return static_cast(stfs_state.request_offset >> 32); } __attribute__((visibility("default"))) -uint32_t r360_stfs_entry_name_ptr(uint32_t index) { +uintptr_t r360_stfs_entry_name_ptr(uint32_t index) { if (index >= stfs_state.entry_count) return 0u; - return static_cast(reinterpret_cast(stfs_entries[index].name)); + return reinterpret_cast(stfs_entries[index].name); } __attribute__((visibility("default"))) uint32_t r360_stfs_entry_name_length(uint32_t index) { diff --git a/src/xenia_web_bootstrap/guest_fibers.cpp b/src/xenia_web_bootstrap/guest_fibers.cpp index 18e9c572..ff193155 100644 --- a/src/xenia_web_bootstrap/guest_fibers.cpp +++ b/src/xenia_web_bootstrap/guest_fibers.cpp @@ -21,6 +21,22 @@ extern "C" char __stack_low; // The R360_FIBER_LOCAL section bounds (wasm-ld start/stop symbols). extern "C" char __start_r360_fiber[]; extern "C" char __stop_r360_fiber[]; +#define R360_FIBER_SWITCHING 1 +#elif defined(R360_NATIVE) +// Native build (native/build-native.sh): every guest thread is a pthread, and +// a baton (one mutex + condition variable) lets exactly one of them run at a +// time, so scheduling stays cooperative and deterministic like the browser's. +// What the JS driver (render360-guest-fibers.mjs) does after an Asyncify +// unwind is done in place by the thread that leaves (NativeDriveSwitch), and +// a resumed thread re-enters the function it left from, exactly as an +// Asyncify rewind would. The R360_FIBER_LOCAL block is a Mach-O section that +// is swapped the same way as the wasm section. +#include +#include +#include +extern "C" char __start_r360_fiber[] __asm("section$start$__DATA$r360_fiber"); +extern "C" char __stop_r360_fiber[] __asm("section$end$__DATA$r360_fiber"); +#define R360_FIBER_SWITCHING 1 #endif extern "C" { @@ -111,19 +127,19 @@ uint64_t HostMillis() { } size_t LocalsSize() { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) return size_t(__stop_r360_fiber - __start_r360_fiber); #else return 0; #endif } void SaveLocals(Fiber& fiber) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) fiber.locals.assign(__start_r360_fiber, __stop_r360_fiber); #endif } void RestoreLocals(const Fiber& fiber) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) const auto& image = fiber.locals.empty() ? g_pristine_locals : fiber.locals; if (image.size() == LocalsSize()) { std::memcpy(__start_r360_fiber, image.data(), image.size()); @@ -241,6 +257,12 @@ bool PickTarget(uint32_t from, uint32_t* target, bool preempting = false) { } bool EnsureFiberMemory(Fiber& fiber, bool needs_stack) { +#if defined(R360_NATIVE) + // Each native fiber is a pthread with its own stack; no Asyncify buffer. + (void)fiber; + (void)needs_stack; + return true; +#endif if (!fiber.asyncify) { fiber.asyncify = static_cast(std::malloc(kFiberAsyncifyBytes)); if (!fiber.asyncify) return false; @@ -258,6 +280,153 @@ void ArmAsyncifyBuffer(Fiber& fiber) { header[1] = static_cast(reinterpret_cast(fiber.asyncify + kFiberAsyncifyBytes)); } +#if defined(R360_NATIVE) +// --- Native baton (see the comment at the top of this file) --------------- +inline void r360_asyncify_stop_rewind() {} +} // namespace +} // namespace render360::xenia_web +extern "C" uint32_t r360_fiber_prepare(); +extern "C" uint32_t r360_fiber_entry(); +namespace render360::xenia_web { +namespace { +// Guest call chains live on the host stack (the browser gives each fiber its +// own C stack); native frames are larger, so give every guest thread plenty. +// Pages are only committed when touched. +constexpr size_t kNativeFiberStackBytes = 64u * 1024u * 1024u; +std::mutex g_native_mutex; +std::condition_variable g_native_cv; +uint32_t g_native_baton = 0; // fiber index allowed to run +uint64_t g_native_generation = 0; // one per title run +bool g_native_run_done = false; +uint32_t g_native_run_result = 0; +uint32_t g_native_run_stopped = 0; +uint32_t g_native_slice_ms = 0; +uint32_t (*g_native_on_slice)(void*) = nullptr; +void* g_native_slice_user = nullptr; + +// Blocks until fiber `index` holds the baton in run `generation`. A thread +// left behind when a run ends never wakes again (its generation is over). +void NativeWaitForBaton(uint32_t index, uint64_t generation) { + std::unique_lock lock(g_native_mutex); + g_native_cv.wait(lock, [&] { + return g_native_generation == generation && g_native_baton == index && !g_native_run_done; + }); +} + +void NativeEndRun(uint32_t result, uint32_t stopped) { + std::lock_guard lock(g_native_mutex); + g_native_run_done = true; + g_native_run_result = result; + g_native_run_stopped = stopped; + g_native_baton = UINT32_MAX; + g_native_cv.notify_all(); +} + +void NativePassBaton(uint32_t index) { + std::lock_guard lock(g_native_mutex); + g_native_baton = index; + g_native_cv.notify_all(); +} + +struct NativeThreadStart { + uint32_t index; + uint64_t generation; + uint32_t (*primary)(void*); + void* user; +}; + +bool NativeSpawn(NativeThreadStart* start, void* (*body)(void*)) { + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setstacksize(&attr, kNativeFiberStackBytes); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_t thread; + const bool ok = pthread_create(&thread, &attr, body, start) == 0; + pthread_attr_destroy(&attr); + return ok; +} + +void NativeDriveSwitch(); + +// Root of a title-created guest thread (the JS driver's r360_fiber_entry call). +void* NativeFiberThreadMain(void* raw) { + auto* start = static_cast(raw); + const uint32_t index = start->index; + const uint64_t generation = start->generation; + delete start; + pthread_setname_np("r360-guest"); + NativeWaitForBaton(index, generation); + const uint32_t result = r360_fiber_entry(); + // As in the JS driver: a title thread that finished queued the next fiber; + // one that stopped on a blocker ends the run. + if (g_current == 0 || !g_switch_pending) { + NativeEndRun(result, 0); + return nullptr; + } + NativeDriveSwitch(); + return nullptr; +} + +// The JS driver's step after an unwind: prepare the switch target and start +// (fresh fiber: a new thread) or resume it (pass the baton). +void NativeDriveSwitch() { + const uint32_t kind = r360_fiber_prepare(); + if (kind == 0) { + std::fprintf(stderr, "R360_FIBER_STOP native: switch without a target\n"); + NativeEndRun(0, 2); + return; + } + const uint32_t next = g_current; + if (kind == 1) { + { + std::lock_guard lock(g_native_mutex); + g_native_baton = next; + } + auto* start = new NativeThreadStart{next, g_native_generation, nullptr, nullptr}; + if (!NativeSpawn(start, NativeFiberThreadMain)) { + delete start; + std::fprintf(stderr, "R360_FIBER_STOP native: pthread_create failed\n"); + NativeEndRun(0, 2); + } + return; + } + NativePassBaton(next); +} + +// Called by the running guest thread when it leaves (SwitchTo): gives the +// host its slice callback if a host yield is due, hands over, and waits until +// it is scheduled again. Returns with this fiber's state restored. +void NativeLeave() { + const uint32_t me = g_current; + const uint64_t generation = g_native_generation; + if (g_host_yield) { + g_host_yield = false; + if (g_native_on_slice && g_native_on_slice(g_native_slice_user)) { + // The host stopped the run. This thread is abandoned mid-call. + NativeEndRun(0, 1); + NativeWaitForBaton(me, generation); + return; + } + if (g_native_slice_ms) g_host_slice_deadline_ms = HostMillis() + g_native_slice_ms; + } + NativeDriveSwitch(); + NativeWaitForBaton(me, generation); +} + +void* NativePrimaryThreadMain(void* raw) { + auto* start = static_cast(raw); + const uint64_t generation = start->generation; + uint32_t (*primary)(void*) = start->primary; + void* user = start->user; + delete start; + pthread_setname_np("r360-guest-primary"); + NativeWaitForBaton(0, generation); + const uint32_t result = primary(user); + NativeEndRun(result, 0); + return nullptr; +} +#endif + // Leaves the current fiber for `target`: snapshot its state and unwind the // wasm stack back to the JS driver, which then starts or rewinds the target. void SwitchTo(uint32_t target, FiberState leaving_state, uint32_t kind) { @@ -279,6 +448,22 @@ void SwitchTo(uint32_t target, FiberState leaving_state, uint32_t kind) { g_switch_pending = true; ++g_switches; r360_asyncify_start_unwind(current.asyncify); +#elif defined(R360_NATIVE) + Fiber& current = g_fibers[g_current]; + current.leave_kind = kind; + if (kind < 5) ++current.leave_counts[kind]; + current.leave_pc = HIRLastSourceAddress(); + current.leave_call = (r360_kernel_import_last_module() << 16) | + (r360_kernel_import_last_ordinal() & 0xFFFFu); + current.instructions += HIRTotalInstructions() - g_run_start; + current.vruntime += HIRTotalInstructions() - g_run_start; + current.state = leaving_state; + current.progress_mark = g_progress; + SaveLocals(current); + g_target = target; + g_switch_pending = true; + ++g_switches; + NativeLeave(); #else (void)target; (void)leaving_state; @@ -295,13 +480,16 @@ void GuestFiberNoteProgress() { ++g_progress; } uintptr_t GuestFiberStackLow() { #if defined(__wasm__) return g_stack_low ? g_stack_low : reinterpret_cast(&__stack_low); +#elif defined(R360_NATIVE) + pthread_t self = pthread_self(); + return reinterpret_cast(pthread_get_stackaddr_np(self)) - pthread_get_stacksize_np(self); #else return 0; #endif } bool GuestFiberYield(bool blocked) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { // Resumed: the driver restored this fiber's state and rewound into here. g_rewinding = false; @@ -321,6 +509,9 @@ bool GuestFiberYield(bool blocked) { return false; } SwitchTo(target, blocked ? kFiberBlocked : kFiberReady, blocked ? 1u : 2u); +#if defined(R360_NATIVE) + return GuestFiberYield(blocked); // resumed: re-enter as a rewind would +#endif return false; // unwinding; the value is not observed #else (void)blocked; @@ -358,7 +549,7 @@ void GuestFiberDiagnostic(char* out, size_t size) { // fiber runs. Returns true when resumed (the caller re-checks its condition), // false when no other fiber can run now (the caller idles: GuestFiberIdle). bool GuestFiberSleepUntil(uint64_t deadline_ns) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { g_rewinding = false; r360_asyncify_stop_rewind(); @@ -378,6 +569,9 @@ bool GuestFiberSleepUntil(uint64_t deadline_ns) { return false; } SwitchTo(target, kFiberBlocked, 1u); +#if defined(R360_NATIVE) + return GuestFiberSleepUntil(deadline_ns); // resumed +#endif return false; // unwinding; the value is not observed #else (void)deadline_ns; @@ -419,7 +613,7 @@ void GuestFiberHostYieldIfDue() { g_trace_from_instructions = 0; g_r360_verbose_trace = true; } -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (g_rewinding) { // Resumed after the page got its turn. g_rewinding = false; @@ -437,6 +631,9 @@ void GuestFiberHostYieldIfDue() { EnsureFiberMemory(g_fibers[target], target != 0)) { ++g_preemptions; SwitchTo(target, kFiberReady, 3u); +#if defined(R360_NATIVE) + GuestFiberHostYieldIfDue(); // resumed +#endif return; } } @@ -451,12 +648,15 @@ void GuestFiberHostYieldIfDue() { g_host_yield = true; ++g_host_yields; SwitchTo(g_current, kFiberReady, 4u); +#if defined(R360_NATIVE) + GuestFiberHostYieldIfDue(); // resumed after the host's turn +#endif #endif } bool RunGuestInterrupt(uint32_t address, uint32_t r3, uint32_t r4, uint32_t stack_top, uint32_t pcr) { -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) if (!g_enabled || g_in_interrupt || g_pristine_locals.size() != LocalsSize() || !address || !stack_top) { return false; @@ -510,7 +710,7 @@ uint32_t r360_fiber_reset(uint32_t enable) { rx::g_preemptions = 0; rx::g_enabled = enable != 0; if (!rx::g_enabled) return 0; -#if defined(__wasm__) +#if defined(R360_FIBER_SWITCHING) rx::g_pristine_locals.assign(__start_r360_fiber, __stop_r360_fiber); #endif rx::Fiber primary; @@ -677,4 +877,51 @@ uint32_t r360_fiber_entry() { return hir ? hir : 1u; } +#if defined(R360_NATIVE) +// Native equivalent of runWithGuestFibers (render360-guest-fibers.mjs): runs +// `primary` (enters the title's primary thread) with guest-thread scheduling +// and returns its result, or the root result of the title thread the run +// ended on. slice_ms > 0 calls on_slice about every slice_ms of host time on +// the running guest thread (frames, input, telemetry); a nonzero return stops +// the run (*stopped = 1). Threads of a stopped run are abandoned, so the host +// should end the process before booting another title. +uint32_t r360_native_run_with_fibers(uint32_t (*primary)(void*), void* user, uint32_t slice_ms, + uint32_t (*on_slice)(void*), void* slice_user, + uint32_t* stopped) { + r360_fiber_reset(1); + uint64_t generation; + { + std::lock_guard lock(rx::g_native_mutex); + generation = ++rx::g_native_generation; + rx::g_native_baton = 0; + rx::g_native_run_done = false; + rx::g_native_run_result = 0; + rx::g_native_run_stopped = 0; + } + rx::g_native_slice_ms = on_slice ? slice_ms : 0; + rx::g_native_on_slice = on_slice; + rx::g_native_slice_user = slice_user; + r360_fiber_set_host_slice(rx::g_native_slice_ms); + auto* start = new rx::NativeThreadStart{0, generation, primary, user}; + if (!rx::NativeSpawn(start, rx::NativePrimaryThreadMain)) { + delete start; + r360_fiber_reset(0); + if (stopped) *stopped = 2; + return 0; + } + uint32_t result; + { + std::unique_lock lock(rx::g_native_mutex); + rx::g_native_cv.wait(lock, [] { return rx::g_native_run_done; }); + result = rx::g_native_run_result; + if (stopped) *stopped = rx::g_native_run_stopped; + } + r360_fiber_set_host_slice(0); + rx::g_native_on_slice = nullptr; + // Fiber bookkeeping stays readable (r360_fiber_*) until the next reset. + return result; +} +uint32_t r360_native_fiber_finish() { return r360_fiber_reset(0); } +#endif + } // extern "C" diff --git a/src/xenia_web_bootstrap/hir_correctness_executor.h b/src/xenia_web_bootstrap/hir_correctness_executor.h index d87dc9a9..a8435e8b 100644 --- a/src/xenia_web_bootstrap/hir_correctness_executor.h +++ b/src/xenia_web_bootstrap/hir_correctness_executor.h @@ -11,6 +11,11 @@ // its own host thread and thread_local state). #if defined(__wasm__) #define R360_FIBER_LOCAL __attribute__((section("r360_fiber"))) +#elif defined(R360_NATIVE) && defined(__APPLE__) +// Native build: guest threads are pthreads that run one at a time (a baton, +// guest_fibers.cpp), and the block is swapped exactly as in the browser so +// both builds schedule identically. Mach-O section syntax. +#define R360_FIBER_LOCAL __attribute__((section("__DATA,r360_fiber"))) #else #define R360_FIBER_LOCAL thread_local #endif diff --git a/src/xenia_web_bootstrap/kernel_import_probe.cpp b/src/xenia_web_bootstrap/kernel_import_probe.cpp index 9dfd8c6c..9f392d9a 100644 --- a/src/xenia_web_bootstrap/kernel_import_probe.cpp +++ b/src/xenia_web_bootstrap/kernel_import_probe.cpp @@ -362,7 +362,7 @@ uint32_t r360_kernel_import_register(uint32_t a, uint32_t m, uint32_t o, : 0u; } uint32_t r360_kernel_import_dispatch_context(uint32_t thunk_address, - uint32_t context_ptr) { + uintptr_t context_ptr) { if (!context_ptr || (context_ptr & (alignof(xe::cpu::ppc::PPCContext) - 1u)) != 0u) { return 0; diff --git a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp index 0142b48c..d49cbf3e 100644 --- a/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp +++ b/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp @@ -65,6 +65,9 @@ __attribute__((weak)) uint32_t TitleGpuTakePendingInterrupts(uint32_t* mask) { i #if defined(__wasm__) #include +#elif defined(R360_NATIVE) +#include +#include #endif #if defined(__wasm__) @@ -1715,6 +1718,32 @@ uint32_t ReadVfs(VfsEntry& entry, uint32_t entry_index, uint64_t offset, g_vfs_bytes_read += done; return X_STATUS_SUCCESS; } +#elif defined(R360_NATIVE) + // Native host: host_fd is a real POSIX descriptor opened by the app/runner. + if (entry.host_fd) { + std::vector chunk(std::min(count, 1u << 20)); + uint32_t done = 0; + while (done < count) { + const uint32_t want = std::min(count - done, uint32_t(chunk.size())); + const ssize_t got = ::pread(int(entry.host_fd), chunk.data(), want, + off_t(entry.host_offset + offset + done)); + if (got <= 0) { + if (done) break; + g_host_io = {entry_index, offset, count, uint32_t(got < 0 ? errno : 0)}; + g_wait = {}; + g_wait.object = entry_index; + g_wait.reason = kWaitReasonHostIo; + g_status = kKernelServiceWouldBlock; + return 0; + } + if (!Wr(guest_buffer + done, chunk.data(), uint32_t(got))) return X_STATUS_ACCESS_VIOLATION; + done += uint32_t(got); + } + *read = done; + ++g_vfs_reads; + g_vfs_bytes_read += done; + return X_STATUS_SUCCESS; + } #endif g_host_io = {entry_index, offset, count, 0}; g_wait = {}; @@ -6072,7 +6101,7 @@ uint32_t r360_kernel_debug_log_count() { } // Copies debug log entry |index| into wasm memory at |out| (capacity bytes). R360_WASM_EXPORT("r360_kernel_debug_log_read") -uint32_t r360_kernel_debug_log_read(uint32_t index, uint32_t out, +uint32_t r360_kernel_debug_log_read(uint32_t index, uintptr_t out, uint32_t capacity) { if (index >= r360k::DebugLogEntries().size() || !out || !capacity) return 0; const std::string& text = r360k::DebugLogEntries()[index]; @@ -6111,9 +6140,9 @@ static const std::string* DialogString(uint32_t which) { return nullptr; } R360_WASM_EXPORT("r360_xam_dialog_string_ptr") -uint32_t r360_xam_dialog_string_ptr(uint32_t which) { +uintptr_t r360_xam_dialog_string_ptr(uint32_t which) { const std::string* s = DialogString(which); - return s ? uint32_t(reinterpret_cast(s->data())) : 0u; + return s ? (reinterpret_cast(s->data())) : 0u; } R360_WASM_EXPORT("r360_xam_dialog_string_len") uint32_t r360_xam_dialog_string_len(uint32_t which) { @@ -6180,8 +6209,8 @@ void r360_vfs_reset() { } // 1 KiB scratch buffer in wasm memory for passing a UTF-8 guest path. R360_WASM_EXPORT("r360_vfs_path_buffer") -uint32_t r360_vfs_path_buffer() { - return uint32_t(uintptr_t(r360k::g_vfs_path_buffer)); +uintptr_t r360_vfs_path_buffer() { + return (uintptr_t(r360k::g_vfs_path_buffer)); } // Registers a file or directory relative to \Device\Cdrom0 (the game disc). // Returns the 1-based entry id. host_fd/host_offset let WASI fd_pread supply @@ -6203,12 +6232,12 @@ uint32_t r360_vfs_register(uint32_t path_length, uint32_t size_lo, // Allocates an in-memory buffer holding the whole file for entry |id| and // returns its wasm address for the loader to fill (0 on failure). R360_WASM_EXPORT("r360_vfs_data_buffer") -uint32_t r360_vfs_data_buffer(uint32_t id) { +uintptr_t r360_vfs_data_buffer(uint32_t id) { auto* entry = r360k::VfsEntryAt(id); if (!entry || entry->size > 0x7FFFFFFFull) return 0; entry->data.assign(size_t(entry->size), 0); entry->has_data = true; - return entry->size ? uint32_t(uintptr_t(entry->data.data())) : 1u; + return entry->size ? (uintptr_t(entry->data.data())) : 1u; } R360_WASM_EXPORT("r360_vfs_entry_count") uint32_t r360_vfs_entry_count() { return uint32_t(r360k::VfsEntries().size()); } diff --git a/src/xenia_web_bootstrap/ppc_translation_probe.cpp b/src/xenia_web_bootstrap/ppc_translation_probe.cpp index 558a4d9f..ea566426 100644 --- a/src/xenia_web_bootstrap/ppc_translation_probe.cpp +++ b/src/xenia_web_bootstrap/ppc_translation_probe.cpp @@ -320,8 +320,8 @@ uint32_t r360_ppc_probe_read_guest_u32_be(uint32_t address) { (uint32_t(bytes[2]) << 8) | uint32_t(bytes[3]); } -uint32_t r360_ppc_probe_input_buffer() { - return static_cast( +uintptr_t r360_ppc_probe_input_buffer() { + return ( reinterpret_cast(render360::xenia_web::g_input_buffer)); } diff --git a/src/xenia_web_bootstrap/probe_backend.cpp b/src/xenia_web_bootstrap/probe_backend.cpp index 5bb6b3d6..ab20523f 100644 --- a/src/xenia_web_bootstrap/probe_backend.cpp +++ b/src/xenia_web_bootstrap/probe_backend.cpp @@ -85,7 +85,18 @@ uint32_t CurrentStackPointer() { } uint32_t StackHeadroom() { -#if defined(__wasm__) +#if defined(R360_NATIVE) + // Native guest threads run on their own pthread stacks; measure the + // distance to the current thread's stack limit (64-bit addresses, so keep + // the low-water mark relative to the stack base). + const uintptr_t low = GuestFiberStackLow(); + const uintptr_t sp = reinterpret_cast(__builtin_frame_address(0)); + if (!low || sp <= low) return low ? 0 : UINT32_MAX; + const uint64_t room = sp - low; + const uint32_t headroom = room > UINT32_MAX ? UINT32_MAX : uint32_t(room); + if (!g_trap_stack_low_water || headroom < g_trap_stack_low_water) g_trap_stack_low_water = headroom; + return headroom; +#elif defined(__wasm__) const uint32_t sp = CurrentStackPointer(); const uint32_t low = static_cast(GuestFiberStackLow()); if (!g_trap_stack_low_water || sp < g_trap_stack_low_water) g_trap_stack_low_water = sp; @@ -1220,8 +1231,8 @@ void render360_wasi_initialize() { #endif R360_WASM_EXPORT("r360_trap_reason") -uint32_t r360_trap_reason() { - return static_cast(reinterpret_cast(render360::xenia_web::g_trap_reason)); +uintptr_t r360_trap_reason() { + return reinterpret_cast(render360::xenia_web::g_trap_reason); } R360_WASM_EXPORT("r360_trap_reason_length") uint32_t r360_trap_reason_length() { diff --git a/src/xenia_web_bootstrap/sparse_guest_memory.cpp b/src/xenia_web_bootstrap/sparse_guest_memory.cpp index 2497074a..9da9bdfc 100644 --- a/src/xenia_web_bootstrap/sparse_guest_memory.cpp +++ b/src/xenia_web_bootstrap/sparse_guest_memory.cpp @@ -70,11 +70,14 @@ constexpr uint32_t kDirectoryEntries = 1u << (32u - kDirectoryShift); std::vector g_backings; std::array g_page_directory{}; -// Generated guest code (hir_wasm_jit.cpp) walks this table inline. +// Generated guest code (hir_wasm_jit.cpp) walks this table inline. The +// native build has no wasm JIT and 64-bit host pointers. +#if !defined(R360_NATIVE) static_assert(sizeof(PageEntry) == 20 && offsetof(PageEntry, host) == 0 && offsetof(PageEntry, executable_aliases) == 4 && offsetof(PageEntry, protection) == 16, "guest JIT inline page walk layout"); +#endif uint32_t g_mapped_pages = 0; // Executable virtual pages aliasing each physical sparse backing page. Guest // RAM writes are extremely hot; they check the per-page alias count and only diff --git a/src/xenia_web_bootstrap/title_gpu_runtime.cpp b/src/xenia_web_bootstrap/title_gpu_runtime.cpp index 60068c81..daede5db 100644 --- a/src/xenia_web_bootstrap/title_gpu_runtime.cpp +++ b/src/xenia_web_bootstrap/title_gpu_runtime.cpp @@ -10,7 +10,7 @@ extern "C" __attribute__((weak)) uint64_t r360_guest_clock_ns() { return 0; } extern "C" __attribute__((weak)) uint32_t r360_kernel_vblank_interrupts() { return 0; } extern "C" { void r360_xenos_reset(); -uint32_t r360_xenos_ring_buffer(); +uintptr_t r360_xenos_ring_buffer(); uint32_t r360_xenos_ring_capacity(); uint32_t r360_xenos_submit(uint32_t words); uint32_t r360_xenos_status(); @@ -229,7 +229,7 @@ bool DrainPendingRingToXenos() { ? g_write_pointer - g_read_pointer : (capacity - g_read_pointer) + g_write_pointer; const uint32_t decoder_capacity = r360_xenos_ring_capacity(); - const uint32_t decoder_ptr = r360_xenos_ring_buffer(); + const uintptr_t decoder_ptr = r360_xenos_ring_buffer(); if (!pending || !decoder_ptr || pending > decoder_capacity) { ++g_xenos_rejections; g_last_xenos_status = r360_xenos_status(); diff --git a/src/xenia_web_bootstrap/webgpu_backend.cpp b/src/xenia_web_bootstrap/webgpu_backend.cpp index 5a5eaa9f..87535cb6 100644 --- a/src/xenia_web_bootstrap/webgpu_backend.cpp +++ b/src/xenia_web_bootstrap/webgpu_backend.cpp @@ -109,8 +109,8 @@ namespace rx = render360::xenia_web; extern "C" { // The recorded command stream (words) for render360-webgpu-xenos.mjs. __attribute__((used, export_name("r360_gpu_stream_data"))) -uint32_t r360_gpu_stream_data() { - return uint32_t(reinterpret_cast(rx::GpuStream().words().data())); +uintptr_t r360_gpu_stream_data() { + return (reinterpret_cast(rx::GpuStream().words().data())); } __attribute__((used, export_name("r360_gpu_stream_words"))) uint32_t r360_gpu_stream_words() { return uint32_t(rx::GpuStream().words().size()); } diff --git a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp index a5d1c8dc..a6a9f2de 100644 --- a/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp +++ b/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp @@ -692,7 +692,7 @@ const ShaderCapture* ShaderForExport(uint32_t type) { extern "C" { void r360_xenos_reset(){render360::xenia_web::Reset();} -uint32_t r360_xenos_ring_buffer(){return uint32_t(reinterpret_cast(render360::xenia_web::g_ring.data()));} +uintptr_t r360_xenos_ring_buffer(){return (reinterpret_cast(render360::xenia_web::g_ring.data()));} uint32_t r360_xenos_ring_capacity(){return render360::xenia_web::kRingCapacity;} uint32_t r360_xenos_submit(uint32_t n){if(n>render360::xenia_web::kRingCapacity){render360::xenia_web::g_status=render360::xenia_web::kStatusInvalid;return 0;}render360::xenia_web::g_ring_words=n;return render360::xenia_web::Execute()?1u:0u;} uint32_t r360_xenos_status(){return render360::xenia_web::g_status;} @@ -729,7 +729,7 @@ uint32_t r360_xenos_frame_provenance(){return render360::xenia_web::FrameProvena uint32_t r360_xenos_real_title_frame_ready(){const uint32_t need=render360::xenia_web::kFrameProvSwap|render360::xenia_web::kFrameProvVertexShader|render360::xenia_web::kFrameProvPixelShader|render360::xenia_web::kFrameProvFetchResources;const uint32_t p=render360::xenia_web::FrameProvenance();return((p&need)==need&&!(p&render360::xenia_web::kFrameProvBoundedRaster))?1u:0u;} uint32_t r360_xenos_register(uint32_t i){return i=render360::xenia_web::g_regs.size())return 0;render360::xenia_web::g_regs[i]=v;return 1;} -uint32_t r360_xenos_shader_buffer(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?uint32_t(reinterpret_cast(s->words.data())):0u;} +uintptr_t r360_xenos_shader_buffer(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?(reinterpret_cast(s->words.data())):0u;} uint32_t r360_xenos_shader_dwords(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->dword_count:0u;} uint32_t r360_xenos_shader_hash(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->hash:0u;} uint32_t r360_xenos_shader_guest_address(uint32_t t){const auto*s=render360::xenia_web::ShaderForExport(t);return s?s->guest_address:0u;} @@ -738,7 +738,7 @@ uint32_t r360_xenos_debug_draws(uint32_t n){render360::xenia_web::g_draw_log_rem uint32_t r360_xenos_swap_fetch_word(uint32_t w){return w<6u?render360::xenia_web::g_swap_fetch[w]:0u;} uint32_t r360_xenos_fetch_constant_word(uint32_t g,uint32_t w){if(w>=6u)return 0u;const uint64_t i=0x4800ull+uint64_t(g)*6u+w;return i(render360::xenia_web::g_frame.data()));} +uintptr_t r360_xenos_frame_buffer(){return (reinterpret_cast(render360::xenia_web::g_frame.data()));} uint32_t r360_xenos_frame_size(){return render360::xenia_web::kFrameBytes;} uint32_t r360_xenos_frame_width(){return render360::xenia_web::kFrameWidth;} uint32_t r360_xenos_frame_height(){return render360::xenia_web::kFrameHeight;} diff --git a/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp b/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp index 7c167968..baf0ff41 100644 --- a/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp +++ b/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp @@ -14,7 +14,7 @@ extern "C" { uint32_t r360_xenos_register(uint32_t index); -uint32_t r360_xenos_shader_buffer(uint32_t shader_type); +uintptr_t r360_xenos_shader_buffer(uint32_t shader_type); uint32_t r360_xenos_shader_dwords(uint32_t shader_type); uint32_t r360_xenos_shader_hash(uint32_t shader_type); } @@ -98,7 +98,7 @@ std::unique_ptr AnalyzeCurrentShader(uint32_t type) { return nullptr; } const uint32_t count = r360_xenos_shader_dwords(type); - const uint32_t ptr = r360_xenos_shader_buffer(type); + const uintptr_t ptr = r360_xenos_shader_buffer(type); if (!count || !ptr) { g_status = kStatusNoShader; return nullptr; diff --git a/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp b/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp index a52fed92..e89aa282 100644 --- a/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp +++ b/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp @@ -36,7 +36,7 @@ #include "third_party/glslang/SPIRV/InReadableOrder.cpp" extern "C" { -uint32_t r360_xenos_shader_buffer(uint32_t shader_type); +uintptr_t r360_xenos_shader_buffer(uint32_t shader_type); uint32_t r360_xenos_shader_dwords(uint32_t shader_type); uint32_t r360_xenos_shader_hash(uint32_t shader_type); uint32_t r360_xenos_fetch_constant_word(uint32_t group, uint32_t word); @@ -115,7 +115,7 @@ uint32_t Translate(uint32_t type) { } const uint32_t count = r360_xenos_shader_dwords(type); - const uint32_t ptr = r360_xenos_shader_buffer(type); + const uintptr_t ptr = r360_xenos_shader_buffer(type); if (!count || !ptr) { g_status = kStatusNoShader; return 0; @@ -414,10 +414,10 @@ uint32_t r360_xenos_spirv_translation_count() { uint32_t r360_xenos_spirv_error_count() { return render360::xenia_web::g_error_count; } -uint32_t r360_xenos_spirv_buffer() { +uintptr_t r360_xenos_spirv_buffer() { return render360::xenia_web::g_spirv.empty() ? 0u - : static_cast(reinterpret_cast( + : (reinterpret_cast( render360::xenia_web::g_spirv.data())); } uint32_t r360_xenos_spirv_size() { @@ -443,10 +443,10 @@ uint32_t r360_xenos_frontbuffer_snapshot_status() { return render360::xenia_web::g_frontbuffer_snapshot_status; } R360_WASM_EXPORT("r360_xenos_frontbuffer_snapshot_buffer") -uint32_t r360_xenos_frontbuffer_snapshot_buffer() { +uintptr_t r360_xenos_frontbuffer_snapshot_buffer() { return render360::xenia_web::g_frontbuffer_snapshot.empty() ? 0u - : static_cast(reinterpret_cast( + : (reinterpret_cast( render360::xenia_web::g_frontbuffer_snapshot.data())); } R360_WASM_EXPORT("r360_xenos_frontbuffer_snapshot_size") diff --git a/src/xenia_web_bootstrap/xex_guest_mapper.cpp b/src/xenia_web_bootstrap/xex_guest_mapper.cpp index 0e438931..81d470a8 100644 --- a/src/xenia_web_bootstrap/xex_guest_mapper.cpp +++ b/src/xenia_web_bootstrap/xex_guest_mapper.cpp @@ -276,7 +276,7 @@ uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, : 0u; } uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, - uint32_t source_ptr, uint32_t size) { + uintptr_t source_ptr, uint32_t size) { const void* source = reinterpret_cast(uintptr_t(source_ptr)); return render360::xenia_web::LoadXexGuestSectionData(virtual_address, source, size) @@ -310,8 +310,8 @@ uint32_t r360_xex_guest_mapper_section_count() { uint32_t r360_xex_guest_mapper_mapped_bytes() { return render360::xenia_web::XexGuestMappedBytes(); } -uint32_t r360_xex_guest_mapper_input_buffer() { - return static_cast( +uintptr_t r360_xex_guest_mapper_input_buffer() { + return ( reinterpret_cast(render360::xenia_web::XexGuestInputBuffer())); } uint32_t r360_xex_guest_mapper_input_capacity() { diff --git a/src/xenia_web_bootstrap/xex_guest_mapper.h b/src/xenia_web_bootstrap/xex_guest_mapper.h index 5fd6ec8c..93b133a6 100644 --- a/src/xenia_web_bootstrap/xex_guest_mapper.h +++ b/src/xenia_web_bootstrap/xex_guest_mapper.h @@ -42,7 +42,7 @@ uint32_t r360_xex_guest_mapper_map_section(uint32_t virtual_address, uint32_t virtual_size, uint32_t final_protection); uint32_t r360_xex_guest_mapper_load(uint32_t virtual_address, - uint32_t source_ptr, uint32_t size); + uintptr_t source_ptr, uint32_t size); uint32_t r360_xex_guest_mapper_set_entry(uint32_t entry_address); uint32_t r360_xex_guest_mapper_finalize(); uint32_t r360_xex_guest_mapper_patch_u32_be(uint32_t address, uint32_t value); @@ -51,7 +51,7 @@ uint32_t r360_xex_guest_mapper_status(); uint32_t r360_xex_guest_mapper_entry_address(); uint32_t r360_xex_guest_mapper_section_count(); uint32_t r360_xex_guest_mapper_mapped_bytes(); -uint32_t r360_xex_guest_mapper_input_buffer(); +uintptr_t r360_xex_guest_mapper_input_buffer(); uint32_t r360_xex_guest_mapper_input_capacity(); uint32_t r360_xex_guest_mapper_input_max_capacity(); } diff --git a/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp b/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp index 6f25452b..98c7a37b 100644 --- a/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp +++ b/src/xenia_web_bootstrap/xex_image_decoder_exports.cpp @@ -2,7 +2,7 @@ #include #include "xex_image_decoder.h" -extern "C" uint32_t r360_io_ptr(); +extern "C" uintptr_t r360_io_ptr(); extern "C" uint32_t r360_io_capacity(); namespace { diff --git a/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp b/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp index 4c9b1a93..5927dc48 100644 --- a/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp +++ b/src/xenia_web_bootstrap/xex_image_preparer_exports.cpp @@ -2,7 +2,7 @@ #include #include "xex_image_preparer.h" -extern "C" uint32_t r360_io_ptr(); +extern "C" uintptr_t r360_io_ptr(); extern "C" uint32_t r360_io_capacity(); namespace { diff --git a/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp b/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp index e30e78fb..91770589 100644 --- a/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp +++ b/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp @@ -295,7 +295,7 @@ void r360_pe_guest_reset() { } // Supplies the XEX page descriptors for the next r360_pe_guest_load*: count // big-endian-decoded words at words_ptr and the image page size. -uint32_t r360_pe_guest_set_xex_pages(uint32_t words_ptr, uint32_t count, +uint32_t r360_pe_guest_set_xex_pages(uintptr_t words_ptr, uint32_t count, uint32_t page_size) { auto& words = render360::xenia_web::g_xex_page_words; words.clear(); @@ -310,13 +310,13 @@ uint32_t r360_pe_guest_set_xex_pages(uint32_t words_ptr, uint32_t count, render360::xenia_web::g_xex_page_size = page_size; return 1; } -uint32_t r360_pe_guest_load(uint32_t source_ptr, uint32_t length) { +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length) { const auto* source = reinterpret_cast(static_cast(source_ptr)); return render360::xenia_web::LoadPreparedPeImageToGuest(source, length) ? 1u : 0u; } -uint32_t r360_pe_guest_load_at_entry(uint32_t source_ptr, uint32_t length, +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address) { const auto* source = reinterpret_cast(static_cast(source_ptr)); diff --git a/src/xenia_web_bootstrap/xex_pe_guest_loader.h b/src/xenia_web_bootstrap/xex_pe_guest_loader.h index af29ab83..0863331b 100644 --- a/src/xenia_web_bootstrap/xex_pe_guest_loader.h +++ b/src/xenia_web_bootstrap/xex_pe_guest_loader.h @@ -35,8 +35,8 @@ bool PreparedPeGuestFindRuntimeFunction(uint32_t address, uint32_t* begin, extern "C" { void r360_pe_guest_reset(); -uint32_t r360_pe_guest_load(uint32_t source_ptr, uint32_t length); -uint32_t r360_pe_guest_load_at_entry(uint32_t source_ptr, uint32_t length, +uint32_t r360_pe_guest_load(uintptr_t source_ptr, uint32_t length); +uint32_t r360_pe_guest_load_at_entry(uintptr_t source_ptr, uint32_t length, uint32_t entry_address); uint32_t r360_pe_guest_status(); uint32_t r360_pe_guest_entry_address(); diff --git a/src/xenia_web_bootstrap/xex_title_handoff.cpp b/src/xenia_web_bootstrap/xex_title_handoff.cpp index ee3ff180..9e0c8850 100644 --- a/src/xenia_web_bootstrap/xex_title_handoff.cpp +++ b/src/xenia_web_bootstrap/xex_title_handoff.cpp @@ -7,7 +7,7 @@ extern "C" { void r360_ppc_probe_reset(); -uint32_t r360_ppc_probe_input_buffer(); +uintptr_t r360_ppc_probe_input_buffer(); uint32_t r360_ppc_probe_input_capacity(); uint32_t r360_ppc_probe_load_at(uint32_t address, const uint8_t* bytes, uint32_t length); @@ -53,7 +53,7 @@ uint32_t TranslatePreparedPeEntry(uint32_t byte_count) { } const uint32_t entry = PreparedPeGuestEntryAddress(); - const uint32_t input_ptr = r360_ppc_probe_input_buffer(); + const uintptr_t input_ptr = r360_ppc_probe_input_buffer(); auto* input = reinterpret_cast(static_cast(input_ptr)); if (!input || !ReadSparseGuestMemory(entry, input, byte_count)) { g_status = kPreparedEntryHandoffReadFailed; diff --git a/tools/serve-games.py b/tools/serve-games.py new file mode 100644 index 00000000..23cbb04e --- /dev/null +++ b/tools/serve-games.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Serve your own game files from the Mac to the Render360 iOS app over Wi-Fi. + + python3 tools/serve-games.py "/Volumes/EXTERNAL HD/Render360-games" [--port 8360] [--token SECRET] + +The app's Import > "From my Mac" lists /games.json and downloads files with +HTTP Range requests, so an interrupted download resumes where it stopped. + +* Read-only: GET/HEAD only, nothing outside the served folder (no symlink or + ".." escapes), no directory listings except the JSON catalogue. +* Optional --token: the app must send it as ?token= or the X-Render360-Token + header (prints a URL with the token to paste into the app). +* Game files never go into git: serve them from a folder outside the repo. + +Catalogue format (/games.json): {"games":[{"id","title","discs":[{"name","path","size"}]}]} +A game is a sub-folder (its files are its discs, sorted by name: Watch Dogs +Disc 1, Disc 2) or a single file at the top level. +""" +import argparse +import hashlib +import http.server +import json +import os +import socket +import socketserver +import sys +import urllib.parse + +GAME_EXTENSIONS = {".iso", ".xex", ".god", ".stfs", ".con", ".live", ""} +CHUNK = 1 << 20 + + +def is_game_file(name): + if name.startswith("."): + return False + ext = os.path.splitext(name)[1].lower() + # STFS packages are usually extension-less 42-hex-digit names (Banjo). + return ext in GAME_EXTENSIONS or ext in {".bin", ".img"} + + +def catalogue(root): + games = [] + for name in sorted(os.listdir(root)): + full = os.path.join(root, name) + if name.startswith("."): + continue + if os.path.isdir(full): + discs = [] + for disc in sorted(os.listdir(full)): + path = os.path.join(full, disc) + if os.path.isfile(path) and is_game_file(disc): + discs.append({"name": disc, "path": f"{name}/{disc}", "size": os.path.getsize(path)}) + if discs: + games.append({"id": hashlib.sha1(name.encode()).hexdigest()[:12], "title": name, "discs": discs}) + elif os.path.isfile(full) and is_game_file(name): + games.append({"id": hashlib.sha1(name.encode()).hexdigest()[:12], "title": name, + "discs": [{"name": name, "path": name, "size": os.path.getsize(full)}]}) + return {"games": games} + + +class Handler(http.server.BaseHTTPRequestHandler): + root = "." + token = None + server_version = "Render360GameServer/1" + + def log_message(self, fmt, *args): + sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args)) + + def authorized(self, query): + if not self.token: + return True + supplied = self.headers.get("X-Render360-Token") or query.get("token", [None])[0] + return supplied == self.token + + def resolve(self, rel): + rel = urllib.parse.unquote(rel).lstrip("/") + path = os.path.realpath(os.path.join(self.root, rel)) + if path != self.root and not path.startswith(self.root + os.sep): + return None + return path if os.path.isfile(path) else None + + def do_HEAD(self): + self.handle_request(head=True) + + def do_GET(self): + self.handle_request(head=False) + + def handle_request(self, head): + url = urllib.parse.urlsplit(self.path) + query = urllib.parse.parse_qs(url.query) + if not self.authorized(query): + self.send_error(403, "token required") + return + if url.path == "/games.json": + body = json.dumps(catalogue(self.root)).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + if not head: + self.wfile.write(body) + return + if not url.path.startswith("/files/"): + self.send_error(404) + return + path = self.resolve(url.path[len("/files/"):]) + if not path: + self.send_error(404) + return + size = os.path.getsize(path) + start, end = 0, size - 1 + status = 200 + rng = self.headers.get("Range") + if rng: + try: + unit, spec = rng.split("=", 1) + first, last = spec.split(",")[0].split("-") + if unit.strip() != "bytes": + raise ValueError + if first: + start = int(first) + end = int(last) if last else size - 1 + else: # suffix range: last N bytes + start = max(0, size - int(last)) + if start > end or start >= size: + raise ValueError + end = min(end, size - 1) + status = 206 + except ValueError: + self.send_response(416) + self.send_header("Content-Range", f"bytes */{size}") + self.end_headers() + return + length = end - start + 1 + self.send_response(status) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Accept-Ranges", "bytes") + self.send_header("Content-Length", str(length)) + stat = os.stat(path) + self.send_header("ETag", '"%x-%x"' % (stat.st_size, int(stat.st_mtime))) + if status == 206: + self.send_header("Content-Range", f"bytes {start}-{end}/{size}") + self.end_headers() + if head: + return + with open(path, "rb") as f: + f.seek(start) + remaining = length + try: + while remaining: + data = f.read(min(CHUNK, remaining)) + if not data: + break + self.wfile.write(data) + remaining -= len(data) + except (BrokenPipeError, ConnectionResetError): + pass # the app paused/cancelled; it resumes with a Range request + + +class Server(socketserver.ThreadingMixIn, http.server.HTTPServer): + daemon_threads = True + allow_reuse_address = True + + +def lan_address(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("10.255.255.255", 1)) + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + s.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("folder", help="folder with your game files (outside any git repository)") + parser.add_argument("--port", type=int, default=8360) + parser.add_argument("--bind", default="0.0.0.0") + parser.add_argument("--token", default=None, help="require this token from the app") + args = parser.parse_args() + root = os.path.realpath(args.folder) + if not os.path.isdir(root): + parser.error(f"{root} is not a folder") + probe = root + while probe != os.path.dirname(probe): + if os.path.isdir(os.path.join(probe, ".git")): + print(f"warning: {root} is inside a git repository ({probe}); keep game files out of git", file=sys.stderr) + break + probe = os.path.dirname(probe) + Handler.root = root + Handler.token = args.token + games = catalogue(root)["games"] + url = f"http://{lan_address()}:{args.port}" + print(f"Serving {len(games)} game(s) from {root}") + print(f"In the app: Import > From my Mac > {url}" + (f" (token {args.token})" if args.token else "")) + Server((args.bind, args.port), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/xenia-ppc-sources.sh b/xenia-ppc-sources.sh new file mode 100644 index 00000000..a8fe815e --- /dev/null +++ b/xenia-ppc-sources.sh @@ -0,0 +1,83 @@ +# Render360 Xenia PPC bootstrap source list, shared by the wasm build +# (build-xenia-ppc-bootstrap.sh) and the native macOS/iOS build +# (native/build-native.sh) so the two can never drift apart. +# Requires ROOT, XENIA and OVERLAY to be set. bash 3.2 compatible (macOS). + +SOURCES=( + "third_party/fmt/src/format.cc" + "src/xenia/base/arena.cc" "src/xenia/base/cvar.cc" "src/xenia/base/utf8.cc" "src/xenia/base/filesystem_posix.cc" "src/xenia/base/memory.cc" "src/xenia/base/memory_posix.cc" "src/xenia/base/mapped_memory_posix.cc" "src/xenia/base/mutex.cc" "src/xenia/base/string.cc" "src/xenia/base/string_buffer.cc" + "src/xenia/memory.cc" "src/xenia/cpu/cpu_flags.cc" "src/xenia/cpu/mmio_handler.cc" "src/xenia/cpu/entry_table.cc" "src/xenia/cpu/module.cc" "src/xenia/cpu/stack_walker_posix.cc" "src/xenia/cpu/thread_state.cc" "src/xenia/cpu/processor.cc" "src/xenia/cpu/lzx.cc" + "src/xenia/cpu/backend/backend.cc" "src/xenia/cpu/backend/assembler.cc" "src/xenia/cpu/function.cc" "src/xenia/cpu/function_debug_info.cc" + "src/xenia/cpu/hir/opcodes.cc" "src/xenia/cpu/hir/block.cc" "src/xenia/cpu/hir/instr.cc" "src/xenia/cpu/hir/value.cc" "src/xenia/cpu/hir/hir_builder.cc" + "src/xenia/cpu/compiler/compiler.cc" "src/xenia/cpu/compiler/compiler_pass.cc" + "src/xenia/cpu/compiler/passes/conditional_group_pass.cc" "src/xenia/cpu/compiler/passes/conditional_group_subpass.cc" "src/xenia/cpu/compiler/passes/constant_propagation_pass.cc" "src/xenia/cpu/compiler/passes/context_promotion_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/control_flow_simplification_pass.cc" "src/xenia/cpu/compiler/passes/data_flow_analysis_pass.cc" "src/xenia/cpu/compiler/passes/dead_code_elimination_pass.cc" "src/xenia/cpu/compiler/passes/finalization_pass.cc" "src/xenia/cpu/compiler/passes/memory_sequence_combination_pass.cc" "src/xenia/cpu/compiler/passes/register_allocation_pass.cc" "src/xenia/cpu/compiler/passes/simplification_pass.cc" "src/xenia/cpu/compiler/passes/validation_pass.cc" "src/xenia/cpu/compiler/passes/value_reduction_pass.cc" + "src/xenia/cpu/ppc/ppc_context.cc" "src/xenia/cpu/ppc/ppc_opcode_table_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_lookup_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm_gen.cc" "src/xenia/cpu/ppc/ppc_opcode_disasm.cc" "src/xenia/cpu/ppc/ppc_opcode_info.cc" "src/xenia/cpu/ppc/ppc_emit_alu.cc" "src/xenia/cpu/ppc/ppc_emit_control.cc" "src/xenia/cpu/ppc/ppc_emit_memory.cc" "src/xenia/cpu/ppc/ppc_emit_fpu.cc" "src/xenia/cpu/ppc/ppc_emit_altivec.cc" "src/xenia/cpu/ppc/ppc_scanner.cc" "src/xenia/cpu/ppc/ppc_hir_builder.cc" "src/xenia/cpu/ppc/ppc_translator.cc" "src/xenia/cpu/ppc/ppc_frontend.cc" + "src/xenia/kernel/util/xdbf_utils.cc" "src/xenia/gpu/gpu_flags.cc" "src/xenia/gpu/register_file.cc" "src/xenia/gpu/ucode.cc" "src/xenia/gpu/shader.cc" "src/xenia/gpu/shader_translator.cc" "src/xenia/gpu/shader_translator_disasm.cc" "src/xenia/gpu/shader_interpreter.cc" "src/xenia/gpu/draw_util.cc" "src/xenia/gpu/registers.cc" "src/xenia/gpu/xenos.cc" "src/xenia/gpu/texture_util.cc" "src/xenia/gpu/texture_info.cc" "src/xenia/gpu/texture_info_formats.cc" "src/xenia/ui/graphics_util.cc" "src/xenia/gpu/spirv_builder.cc" "src/xenia/gpu/spirv_shader.cc" "src/xenia/gpu/spirv_shader_translator.cc" + "third_party/glslang/SPIRV/SpvBuilder.cpp" +) + +# r360_for_each_source CPP_FN C_FN: calls CPP_FN/C_FN with "label" "path" for +# every translation unit of the bootstrap, in build order. +r360_for_each_source() { + local queue_cpp="$1" queue_c="$2" rel + for rel in "${SOURCES[@]}"; do + case "$rel" in + "src/xenia/base/arena.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/base/arena.cc" ;; + "src/xenia/base/cvar.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/base/cvar.cc" ;; + "src/xenia/base/utf8.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/base/utf8.cc" ;; + "src/xenia/memory.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/memory.cc" ;; + "src/xenia/cpu/mmio_handler.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/cpu/mmio_handler.cc" ;; + "src/xenia/cpu/processor.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/cpu/processor.cc" ;; + "src/xenia/cpu/hir/value.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/cpu/hir/value.cc" ;; + "src/xenia/cpu/ppc/ppc_scanner.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_scanner.cc" ;; + "src/xenia/cpu/ppc/ppc_translator.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/cpu/ppc/ppc_translator.cc" ;; + "src/xenia/gpu/draw_util.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/gpu/draw_util.cc" ;; + "src/xenia/gpu/shader_translator.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/gpu/shader_translator.cc" ;; + "src/xenia/gpu/shader_interpreter.cc") "$queue_cpp" "$rel" "$OVERLAY/xenia/gpu/shader_interpreter.cc" ;; + *) "$queue_cpp" "$rel" "$XENIA/$rel" ;; + esac + done + + "$queue_c" "third_party/mspack/lzxd.c" "$XENIA/third_party/mspack/lzxd.c" + "$queue_c" "third_party/crypto/rijndael-alg-fst.c" "$XENIA/third_party/crypto/rijndael-alg-fst.c" + "$queue_cpp" "render360/browser_logging.cpp" "$ROOT/src/xenia_web_bootstrap/browser_logging.cpp" + "$queue_cpp" "render360/browser_threading_sleep.cpp" "$ROOT/src/xenia_web_bootstrap/browser_threading_sleep.cpp" + "$queue_cpp" "render360/hir_correctness_executor.cpp" "$OVERLAY/render360/hir_correctness_executor_vmx.cpp" + "$queue_cpp" "render360/kernel_import_probe.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_import_probe.cpp" + "$queue_cpp" "render360/kernel_runtime_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_runtime_foundation.cpp" + "$queue_cpp" "render360/guest_fibers.cpp" "$ROOT/src/xenia_web_bootstrap/guest_fibers.cpp" + "$queue_cpp" "render360/hir_wasm_jit.cpp" "$ROOT/src/xenia_web_bootstrap/hir_wasm_jit.cpp" + "$queue_cpp" "render360/xenos_soft_renderer.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_soft_renderer.cpp" + "$queue_cpp" "render360/webgpu_backend.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_backend.cpp" + "$queue_cpp" "render360/webgpu_draws.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_draws.cpp" + "$queue_cpp" "render360/webgpu_textures.cpp" "$ROOT/src/xenia_web_bootstrap/webgpu_textures.cpp" + "$queue_cpp" "render360/kernel_xboxkrnl_services.cpp" "$ROOT/src/xenia_web_bootstrap/kernel_xboxkrnl_services.cpp" + "$queue_cpp" "render360/xam_xdbf.cpp" "$ROOT/src/xenia_web_bootstrap/xam_xdbf.cpp" + "$queue_cpp" "render360/title_gpu_runtime.cpp" "$ROOT/src/xenia_web_bootstrap/title_gpu_runtime.cpp" + "$queue_cpp" "render360/xenos_gpu_foundation.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_gpu_foundation.cpp" + "$queue_cpp" "render360/xenos_shader_interpreter_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_shader_interpreter_probe.cpp" + "$queue_cpp" "render360/xenos_spirv_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xenos_spirv_translation_probe.cpp" + "$queue_cpp" "render360/wasm_backend_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_probe.cpp" + "$queue_cpp" "render360/wasm_backend_cfg_probe.cpp" "$OVERLAY/render360/wasm_backend_cfg_probe.cpp" + "$queue_cpp" "render360/wasm_backend_memory_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_memory_probe.cpp" + "$queue_cpp" "render360/wasm_backend_call_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_call_probe.cpp" + "$queue_cpp" "render360/wasm_backend_fpu_probe.cpp" "$OVERLAY/render360/wasm_backend_fpu_probe_v2.cpp" + "$queue_cpp" "render360/wasm_backend_vmx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/wasm_backend_vmx_probe.cpp" + "$queue_cpp" "render360/sparse_guest_memory.cpp" "$ROOT/src/xenia_web_bootstrap/sparse_guest_memory.cpp" + "$queue_cpp" "render360/xex_guest_mapper.cpp" "$ROOT/src/xenia_web_bootstrap/xex_guest_mapper.cpp" + "$queue_cpp" "render360/xex_pe_image.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_image.cpp" + "$queue_cpp" "render360/xex_pe_guest_loader.cpp" "$ROOT/src/xenia_web_bootstrap/xex_pe_guest_loader.cpp" + "$queue_cpp" "render360/xex_title_handoff.cpp" "$ROOT/src/xenia_web_bootstrap/xex_title_handoff.cpp" + "$queue_cpp" "render360/xex_lzx_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_lzx_probe.cpp" + "$queue_cpp" "render360/xex_crypto_probe.cpp" "$ROOT/src/xenia_web_bootstrap/xex_crypto_probe.cpp" + "$queue_cpp" "render360/probe_backend.cpp" "$ROOT/src/xenia_web_bootstrap/probe_backend.cpp" + "$queue_cpp" "render360/ppc_translation_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_translation_probe.cpp" + "$queue_cpp" "render360/ppc_context_abi_probe.cpp" "$ROOT/src/xenia_web_bootstrap/ppc_context_abi_probe.cpp" +} + +# Number of r360_for_each_source callbacks (SOURCES + 2 C files + Render360 TUs). +r360_source_count() { + R360_SOURCE_COUNT=0 + _r360_count() { R360_SOURCE_COUNT=$((R360_SOURCE_COUNT + 1)); } + r360_for_each_source _r360_count _r360_count +} From e10ff9635498838c3b7b4fd9642415e6b65f8bc7 Mon Sep 17 00:00:00 2001 From: Conrad Milton Powell Date: Sat, 17 Oct 2026 14:20:12 -0500 Subject: [PATCH 53/65] Native Banjo-Tooie boot on macOS; iOS app sources; telemetry server - Memory::LookupVirtualMappedRange: no MMIO handler on the portable host (wasm read zeros at 0x20; native faulted) - incremental native rebuilds with R360_SKIP_OVERLAYS=1 - ios/Render360: SwiftUI app (library, Files/AirDrop/Mac import with Range resume, Metal frontbuffer presenter capped at 30 FPS, touch + GameController input, PerfStats port, breadcrumbs, memory guard, signing expiry) - tools/telemetry-server.py: phone telemetry -> /status on the Mac Measured (2018 MBP, deterministic 1000, interpreter only): Banjo-Tooie 5B instructions, 132 VdSwap frames at 1280x720, 9.0 MIPS. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + ios/Render360/Controls.swift | 199 ++++++++++++++++++++ ios/Render360/Diagnostics.swift | 172 +++++++++++++++++ ios/Render360/EmulatorSession.swift | 166 +++++++++++++++++ ios/Render360/GameLibrary.swift | 137 ++++++++++++++ ios/Render360/MacImport.swift | 154 ++++++++++++++++ ios/Render360/MetalFrameView.swift | 93 ++++++++++ ios/Render360/Render360App.swift | 276 ++++++++++++++++++++++++++++ native/build-native.sh | 10 +- native/src/native_title.cpp | 4 +- prepare-xenia-web-overlay.py | 12 ++ tools/telemetry-server.py | 150 +++++++++++++++ 12 files changed, 1369 insertions(+), 5 deletions(-) create mode 100644 ios/Render360/Controls.swift create mode 100644 ios/Render360/Diagnostics.swift create mode 100644 ios/Render360/EmulatorSession.swift create mode 100644 ios/Render360/GameLibrary.swift create mode 100644 ios/Render360/MacImport.swift create mode 100644 ios/Render360/MetalFrameView.swift create mode 100644 ios/Render360/Render360App.swift create mode 100644 tools/telemetry-server.py diff --git a/.gitignore b/.gitignore index e3a7cada..9f8205b5 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ rexglue-manifest* /ios/Render360.xcodeproj/ /ios/build/ *.ipa +/logs/ diff --git a/ios/Render360/Controls.swift b/ios/Render360/Controls.swift new file mode 100644 index 00000000..3cd3a5bb --- /dev/null +++ b/ios/Render360/Controls.swift @@ -0,0 +1,199 @@ +import GameController +import SwiftUI + +/// XInput gamepad bits (XINPUT_GAMEPAD_*), as render360-guest-fibers.mjs. +enum XButton: UInt32 { + case up = 0x1, down = 0x2, left = 0x4, right = 0x8, start = 0x10, back = 0x20, ls = 0x40, rs = 0x80 + case lb = 0x100, rb = 0x200, a = 0x1000, b = 0x2000, x = 0x4000, y = 0x8000 +} + +/// Merges a hardware controller (MFi / Xbox / PlayStation via +/// GameController.framework) with the on-screen touch controls and feeds the +/// result to the emulator 60 times a second. +final class InputHub: ObservableObject { + @Published private(set) var controllerName: String? + var touch = PadState() + private weak var session: EmulatorSession? + private var link: CADisplayLink? + + init() { + NotificationCenter.default.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] _ in self?.refresh() } + NotificationCenter.default.addObserver(forName: .GCControllerDidDisconnect, object: nil, queue: .main) { [weak self] _ in self?.refresh() } + GCController.startWirelessControllerDiscovery {} + refresh() + } + + func attach(_ session: EmulatorSession) { + self.session = session + link?.invalidate() + let l = CADisplayLink(target: self, selector: #selector(tick)) + l.preferredFramesPerSecond = 60 + l.add(to: .main, forMode: .common) + link = l + } + + func detach() { link?.invalidate(); link = nil } + + private func refresh() { + let pad = GCController.controllers().first { $0.extendedGamepad != nil } + controllerName = pad?.vendorName ?? (pad != nil ? "Controller" : nil) + Breadcrumbs.shared.log("controller \(controllerName ?? "none")") + } + + @objc private func tick() { + var p = touch + if let g = GCController.controllers().first(where: { $0.extendedGamepad != nil })?.extendedGamepad { + func on(_ b: GCControllerButtonInput?, _ x: XButton) { if b?.isPressed == true { p.buttons |= x.rawValue } } + on(g.buttonA, .a); on(g.buttonB, .b); on(g.buttonX, .x); on(g.buttonY, .y) + on(g.leftShoulder, .lb); on(g.rightShoulder, .rb) + on(g.buttonMenu, .start); on(g.buttonOptions, .back) + on(g.leftThumbstickButton, .ls); on(g.rightThumbstickButton, .rs) + on(g.dpad.up, .up); on(g.dpad.down, .down); on(g.dpad.left, .left); on(g.dpad.right, .right) + p.leftTrigger = max(p.leftTrigger, UInt8(g.leftTrigger.value * 255)) + p.rightTrigger = max(p.rightTrigger, UInt8(g.rightTrigger.value * 255)) + if abs(g.leftThumbstick.xAxis.value) + abs(g.leftThumbstick.yAxis.value) > 0.05 { + p.lx = g.leftThumbstick.xAxis.value; p.ly = g.leftThumbstick.yAxis.value // Y up, as XInput + } + if abs(g.rightThumbstick.xAxis.value) + abs(g.rightThumbstick.yAxis.value) > 0.05 { + p.rx = g.rightThumbstick.xAxis.value; p.ry = g.rightThumbstick.yAxis.value + } + } + session?.setPad(p) + } +} + +/// On-screen controls: left stick, d-pad, A/B/X/Y, shoulders, triggers, +/// Start/Back. Hidden while a hardware controller is connected. +struct TouchControls: View { + @ObservedObject var input: InputHub + @State private var held: Set = [] + @State private var stick = CGSize.zero + @State private var lt = false + @State private var rt = false + + private func sync() { + var p = PadState() + for b in held { p.buttons |= b.rawValue } + p.leftTrigger = lt ? 255 : 0; p.rightTrigger = rt ? 255 : 0 + p.lx = Float(stick.width); p.ly = Float(-stick.height) + input.touch = p + } + + var body: some View { + GeometryReader { geo in + let s = min(geo.size.width, geo.size.height) + ZStack { + HStack(alignment: .bottom) { + VStack(spacing: s * 0.03) { + HStack { pad("LT", trigger: true, left: true); pad("LB", .lb) } + Stick(value: $stick, onChange: sync).frame(width: s * 0.34, height: s * 0.34) + DPad(held: $held, onChange: sync).frame(width: s * 0.26, height: s * 0.26) + } + Spacer() + VStack(spacing: s * 0.03) { + HStack { pad("RB", .rb); pad("RT", trigger: true, left: false) } + FaceButtons(held: $held, onChange: sync).frame(width: s * 0.36, height: s * 0.36) + } + } + .padding(.horizontal, s * 0.05).padding(.bottom, s * 0.04) + VStack { + Spacer() + HStack(spacing: s * 0.08) { pad("Back", .back); pad("Start", .start) }.padding(.bottom, s * 0.04) + } + } + } + .opacity(input.controllerName == nil ? 0.55 : 0) + .allowsHitTesting(input.controllerName == nil) + } + + @ViewBuilder private func pad(_ label: String, _ b: XButton? = nil, trigger: Bool = false, left: Bool = true) -> some View { + HoldButton(label: label) { down in + if trigger { if left { lt = down } else { rt = down } } + else if let b { if down { held.insert(b) } else { held.remove(b) } } + sync() + } + } +} + +struct HoldButton: View { + let label: String + var round = false + let changed: (Bool) -> Void + @State private var down = false + var body: some View { + Text(label) + .font(.system(size: 15, weight: .semibold, design: .rounded)) + .foregroundStyle(.white) + .frame(minWidth: round ? 52 : 64, minHeight: round ? 52 : 34) + .background(down ? Color.white.opacity(0.45) : Color.black.opacity(0.45), in: round ? AnyShape(Circle()) : AnyShape(Capsule())) + .overlay((round ? AnyShape(Circle()) : AnyShape(Capsule())).stroke(.white.opacity(0.6), lineWidth: 1)) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { _ in if !down { down = true; changed(true) } } + .onEnded { _ in down = false; changed(false) }) + .accessibilityLabel(label) + } +} + +struct FaceButtons: View { + @Binding var held: Set + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let d = g.size.width / 3 + ZStack { + face("Y", .y).position(x: g.size.width / 2, y: d / 2) + face("X", .x).position(x: d / 2, y: g.size.height / 2) + face("B", .b).position(x: g.size.width - d / 2, y: g.size.height / 2) + face("A", .a).position(x: g.size.width / 2, y: g.size.height - d / 2) + } + } + } + private func face(_ l: String, _ b: XButton) -> some View { + HoldButton(label: l, round: true) { down in if down { held.insert(b) } else { held.remove(b) }; onChange() } + } +} + +struct DPad: View { + @Binding var held: Set + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let d = g.size.width / 3 + ZStack { + dir("▲", .up).position(x: g.size.width / 2, y: d / 2) + dir("◀", .left).position(x: d / 2, y: g.size.height / 2) + dir("▶", .right).position(x: g.size.width - d / 2, y: g.size.height / 2) + dir("▼", .down).position(x: g.size.width / 2, y: g.size.height - d / 2) + } + } + } + private func dir(_ l: String, _ b: XButton) -> some View { + HoldButton(label: l, round: true) { down in if down { held.insert(b) } else { held.remove(b) }; onChange() } + } +} + +/// Analog stick: drag inside the circle; value is -1...1 per axis (y down). +struct Stick: View { + @Binding var value: CGSize + let onChange: () -> Void + var body: some View { + GeometryReader { g in + let r = g.size.width / 2 + ZStack { + Circle().fill(.black.opacity(0.4)).overlay(Circle().stroke(.white.opacity(0.6))) + Circle().fill(.white.opacity(0.6)).frame(width: r * 0.8, height: r * 0.8) + .offset(x: value.width * r * 0.6, y: value.height * r * 0.6) + } + .contentShape(Circle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { v in + var dx = (v.location.x - r) / (r * 0.6), dy = (v.location.y - r) / (r * 0.6) + let len = sqrt(dx * dx + dy * dy) + if len > 1 { dx /= len; dy /= len } + value = CGSize(width: dx, height: dy); onChange() + } + .onEnded { _ in value = .zero; onChange() }) + } + .accessibilityLabel("Left stick") + } +} diff --git a/ios/Render360/Diagnostics.swift b/ios/Render360/Diagnostics.swift new file mode 100644 index 00000000..b4eae420 --- /dev/null +++ b/ios/Render360/Diagnostics.swift @@ -0,0 +1,172 @@ +import Foundation +import UIKit + +/// Crash breadcrumbs: Documents/Diagnostics/breadcrumbs.log, one fsynced line +/// per event, so the last lines survive a crash or a jetsam kill (which +/// writes no crash report for the app). running.flag marks a live session; if +/// it is still there at the next launch, the previous run did not end cleanly. +final class Breadcrumbs { + static let shared = Breadcrumbs() + let folder: URL + let file: URL + private let flag: URL + private(set) var previousRunCrashed = false + private(set) var previousTail: [String] = [] + + init() { + folder = GameLibrary.documents.appendingPathComponent("Diagnostics", isDirectory: true) + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + file = folder.appendingPathComponent("breadcrumbs.log") + flag = folder.appendingPathComponent("running.flag") + } + + func startSession() { + let fm = FileManager.default + previousRunCrashed = fm.fileExists(atPath: flag.path) + if let text = try? String(contentsOf: file) { + previousTail = Array(text.split(separator: "\n").suffix(40).map(String.init)) + // Keep the log bounded: last ~2000 lines. + let lines = text.split(separator: "\n") + if lines.count > 4000 { try? lines.suffix(2000).joined(separator: "\n").appending("\n").write(to: file, atomically: true, encoding: .utf8) } + } + try? Data().write(to: flag) + r360_breadcrumb_open(file.path) + r360_install_crash_handlers() + log("launch \(Bundle.main.bundleIdentifier ?? "") \(UIDevice.current.model) iOS \(UIDevice.current.systemVersion) previousCrashed=\(previousRunCrashed)") + } + + func endSession() { + log("clean exit") + try? FileManager.default.removeItem(at: flag) + } + + func log(_ line: String) { r360_breadcrumb(line) } +} + +/// Watches os_proc_available_memory() and logs/acts before iOS kills the app. +/// The interpreter-only core has no large GPU caches yet; its big consumer is +/// the HIR translation cache, which the core already bounds. Under pressure +/// the guard records breadcrumbs (so a jetsam kill is attributed) and tells +/// the UI; the lowest free memory of a run is kept for telemetry. +final class MemoryGuard { + private(set) var lowestAvailableMB: Double = .infinity + private var lastWarnMB = Double.infinity + private var lastCheck = 0.0 + var onPressure: ((Double) -> Void)? + + static var availableMB: Double { Double(r360_platform_available_memory()) / 1048576 } + static var footprintMB: Double { Double(r360_platform_footprint()) / 1048576 } + + func check() { + let t = PerfStats.nowMs() + guard t - lastCheck > 250 else { return } + lastCheck = t + let avail = Self.availableMB + lowestAvailableMB = min(lowestAvailableMB, avail) + // Same thresholds as the GTA V port's phone budget: act below 240 MB free. + if avail < 240, avail < lastWarnMB - 32 { + lastWarnMB = avail + Breadcrumbs.shared.log(String(format: "memory low: %.0f MB free, footprint %.0f MB", avail, Self.footprintMB)) + onPressure?(avail) + } else if avail > lastWarnMB + 96 { + lastWarnMB = .infinity + } + } +} + +/// Free Apple ID builds expire after 7 days: read the expiry from +/// embedded.mobileprovision to show the days left. +enum SigningInfo { + static var expiry: Date? { + guard let url = Bundle.main.url(forResource: "embedded", withExtension: "mobileprovision"), + let data = try? Data(contentsOf: url) else { return nil } + // The profile is CMS-signed; the plist sits in it as plain XML. + let text = String(decoding: data, as: UTF8.self) + guard let start = text.range(of: "") else { return nil } + let xml = Data(text[start.lowerBound.. [String: Any] { + let s = emulator?.perf.snapshot() ?? PerfStats.Snapshot() + let thermal = ["nominal", "fair", "serious", "critical"][min(3, ProcessInfo.processInfo.thermalState.rawValue)] + var game = "", state = "idle" + if let e = emulator { + game = e.game?.title ?? "" + switch e.state { + case .idle: state = "idle" + case .booting: state = "booting" + case .running: state = "running" + case .stopped(let b): state = "stopped: \(b)" + case .failed(let m): state = "failed: \(m)" + } + } + return [ + "session": sessionID, "time": Date().timeIntervalSince1970, "device": "iPhone 11", + "game": game, "state": state, + "fps": s.gameFps, "fpsAvg": s.gameAverageFps, "low1": s.gameLow1Fps, "presentedFps": s.presentedFps, + "stuttersPerMin": s.stuttersPerMinute, "speedPercent": s.emulationSpeedPercent, "idlePercent": s.idlePercent, + "mips": s.mips, "interpretedPercent": s.interpretedPercent, "bar30": s.barPass, + "guestInstructionsM": Double(r360_hir_total_instructions_millions()), "guestFrames": Double(r360_title_gpu_vd_swap_calls()), + "memFootprintMB": MemoryGuard.footprintMB, "memAvailableMB": MemoryGuard.availableMB, + "memLowestAvailableMB": memory?.lowestAvailableMB.isFinite == true ? memory!.lowestAvailableMB : MemoryGuard.availableMB, + "thermal": thermal, "battery": Double(UIDevice.current.batteryLevel), + "jit": r360_native_jit_available() == 1, "signingDaysLeft": SigningInfo.daysLeft ?? -1, + ] + } + + private func tick() { + guard let data = try? JSONSerialization.data(withJSONObject: status()) else { return } + log?.write(data); log?.write(Data("\n".utf8)) + guard !macURL.isEmpty, var comps = URLComponents(string: macURL + "/telemetry") else { return } + comps.queryItems = [URLQueryItem(name: "s", value: sessionID)] + guard let url = comps.url else { return } + var r = URLRequest(url: url, timeoutInterval: 2) + r.httpMethod = "POST" + r.setValue("application/json", forHTTPHeaderField: "Content-Type") + r.httpBody = data + URLSession.shared.dataTask(with: r).resume() + } + + /// Sends the previous run's breadcrumbs to the Mac (after a crash). + func sendCrashReport(_ lines: [String]) { + guard !macURL.isEmpty, let url = URL(string: macURL + "/crash?s=\(sessionID)") else { return } + var r = URLRequest(url: url, timeoutInterval: 5) + r.httpMethod = "POST" + r.httpBody = Data(lines.joined(separator: "\n").utf8) + URLSession.shared.dataTask(with: r).resume() + } +} diff --git a/ios/Render360/EmulatorSession.swift b/ios/Render360/EmulatorSession.swift new file mode 100644 index 00000000..3070c268 --- /dev/null +++ b/ios/Render360/EmulatorSession.swift @@ -0,0 +1,166 @@ +import Foundation +import Combine + +/// Latest guest frame (RGBA8), handed from the guest thread to the Metal view. +final class FrameStore { + private let lock = NSLock() + private var pixels = [UInt8]() + private(set) var width = 0, height = 0, generation: UInt64 = 0 + + func store(_ src: UnsafeRawPointer, width: Int, height: Int) { + lock.lock(); defer { lock.unlock() } + let count = width * height * 4 + if pixels.count != count { pixels = [UInt8](repeating: 0, count: count) } + pixels.withUnsafeMutableBytes { $0.baseAddress!.copyMemory(from: src, byteCount: count) } + self.width = width; self.height = height + generation &+= 1 + } + + /// Runs `body` with the newest frame if it is newer than `since`. + func withFrame(newerThan since: UInt64, _ body: (UnsafeRawPointer, Int, Int, UInt64) -> Void) { + lock.lock(); defer { lock.unlock() } + guard generation != since, width > 0 else { return } + pixels.withUnsafeBytes { body($0.baseAddress!, width, height, generation) } + } +} + +/// Gamepad state shared between the UI (touch / GameController) and the guest thread. +struct PadState: Equatable { + var buttons: UInt32 = 0 // XINPUT_GAMEPAD_* bits + var leftTrigger: UInt8 = 0, rightTrigger: UInt8 = 0 + var lx: Float = 0, ly: Float = 0, rx: Float = 0, ry: Float = 0 +} + +/// One running title. The core runs on its own threads; this object only +/// starts it and reacts in the host slices (frames, input, stats, stop). +final class EmulatorSession: ObservableObject { + enum State: Equatable { case idle, booting, running, stopped(String), failed(String) } + + @Published private(set) var state: State = .idle + @Published private(set) var stats = PerfStats.Snapshot() + @Published var dialog: GuestDialog? + + let frames = FrameStore() + let perf = PerfStats() + private(set) var game: GameEntry? + private var stopRequested = false + private var padLock = NSLock() + private var pad = PadState() + private var lastSentPad = PadState(buttons: .max) + private var lastFrames: UInt32 = 0 + private var dialogAnswer: Int? + private var statsTimer: Timer? + private(set) var bootResult = R360BootResult() + var memory: MemoryGuard? + + struct GuestDialog: Identifiable { + let id = UUID() + let title: String, text: String + let buttons: [String] + let focused: Int + } + + func setPad(_ newPad: PadState) { + padLock.lock(); pad = newPad; padLock.unlock() + } + + func answerDialog(_ button: Int) { + padLock.lock(); dialogAnswer = button; padLock.unlock() + dialog = nil + } + + func stop() { stopRequested = true } + + func start(game: GameEntry) { + guard state == .idle else { return } + self.game = game + state = .booting + Breadcrumbs.shared.log("boot \(game.title) discs=\(game.discs.count)") + let thread = Thread { [weak self] in self?.runCore(game) } + thread.name = "r360-boot" + thread.stackSize = 16 << 20 + thread.qualityOfService = .userInteractive + thread.start() + statsTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in + guard let self else { return } + self.stats = self.perf.snapshot() + } + } + + private func runCore(_ game: GameEntry) { + let paths = game.discURLs.map { $0.path } + var cStrings = paths.map { strdup($0) } + defer { cStrings.forEach { free($0) } } + var result = R360BootResult() + let ok: UInt32 = cStrings.withUnsafeMutableBufferPointer { buf -> UInt32 in + var options = R360BootOptions() + options.path = UnsafePointer(buf[0]) + let discs = buf.map { UnsafePointer($0) } + return discs.withUnsafeBufferPointer { dbuf -> UInt32 in + options.discs = UnsafePointer(dbuf.baseAddress.map { UnsafeRawPointer($0).assumingMemoryBound(to: UnsafePointer?.self) }) + options.disc_count = UInt32(discs.count) + options.license_full = game.ownedFullLicense ? 1 : 0 + options.dialog_button = -1 + options.slice_ms = 20 + options.on_slice = { user in + Unmanaged.fromOpaque(user!).takeUnretainedValue().onSlice() + } + options.user = Unmanaged.passUnretained(self).toOpaque() + // Host answers for XamShowMessageBoxUI (the player picks). + r360_xam_dialog_set_host_answers(1) + DispatchQueue.main.async { self.state = .running } + return r360_native_boot(&options, &result) + } + } + bootResult = result + let boundary = withUnsafeBytes(of: result.runtime_boundary) { String(cString: $0.bindMemory(to: CChar.self).baseAddress!) } + let error = withUnsafeBytes(of: result.error) { String(cString: $0.bindMemory(to: CChar.self).baseAddress!) } + Breadcrumbs.shared.log("run ended ok=\(ok) boundary=\(boundary) error=\(error)") + DispatchQueue.main.async { + self.statsTimer?.invalidate() + self.state = ok == 1 ? .stopped(boundary) : .failed(error) + } + } + + /// Called on the running guest thread about every 20 ms of host time. + private func onSlice() -> UInt32 { + let t = PerfStats.nowMs() + // Frames: decode the VdSwap frontbuffer (as render360-title-frontbuffer.mjs). + let swaps = r360_title_gpu_vd_swap_calls() + perf.submitted(t, frames: swaps) + if swaps != lastFrames { + lastFrames = swaps + if r360_xenos_frontbuffer_snapshot_capture() == 1, + let ptr = UnsafeRawPointer(bitPattern: r360_xenos_frontbuffer_snapshot_buffer()) { + let w = Int(r360_xenos_frontbuffer_snapshot_width()), h = Int(r360_xenos_frontbuffer_snapshot_height()) + if w > 0, h > 0, Int(r360_xenos_frontbuffer_snapshot_size()) == w * h * 4 { + frames.store(ptr, width: w, height: h) + } + } + } + perf.counters(t, instructions: r360_perf_counter(0), interpreted: r360_perf_counter(1), idleMs: r360_fiber_idle_ms()) + // Input: XInput state for user 0. + padLock.lock(); let p = pad; let answer = dialogAnswer; dialogAnswer = nil; padLock.unlock() + if p != lastSentPad { + lastSentPad = p + func axis(_ v: Float) -> UInt32 { UInt32(bitPattern: Int32(max(-32768, min(32767, (v * 32767).rounded())))) & 0xFFFF } + let left = axis(p.lx) | (axis(p.ly) << 16), right = axis(p.rx) | (axis(p.ry) << 16) + let triggers = UInt32(p.leftTrigger) | (UInt32(p.rightTrigger) << 8) + r360_input_set_gamepad(0, 1, p.buttons, triggers, left, right) + } + // System message boxes. + if let answer { r360_xam_dialog_answer(UInt32(answer)) } + if r360_xam_dialog_pending() != 0, dialog == nil { + func str(_ w: UInt32) -> String { + guard let ptr = UnsafeRawPointer(bitPattern: r360_xam_dialog_string_ptr(w)) else { return "" } + return String(decoding: UnsafeRawBufferPointer(start: ptr, count: Int(r360_xam_dialog_string_len(w))), as: UTF8.self) + } + let count = r360_xam_dialog_button_count() + let d = GuestDialog(title: str(0), text: str(1), buttons: (0../: its discs (Watch Dogs has two) plus a +/// small game.json. Game files stay on the device; every file is excluded +/// from iCloud/iTunes backup. +struct GameEntry: Codable, Identifiable, Equatable { + var id: String + var title: String + var discs: [String] // file names inside the game folder, disc order + var ownedFullLicense = false // XAM license mask (Xenia default: trial) + var addedAt = Date() + + var folder: URL { GameLibrary.gamesRoot.appendingPathComponent(id, isDirectory: true) } + var discURLs: [URL] { discs.map { folder.appendingPathComponent($0) } } + var totalBytes: Int64 { + discURLs.reduce(0) { $0 + ((try? $1.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) ?? 0) } + } +} + +final class GameLibrary: ObservableObject { + static let shared = GameLibrary() + static var documents: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } + static var gamesRoot: URL { documents.appendingPathComponent("Games", isDirectory: true) } + + @Published private(set) var games: [GameEntry] = [] + + init() { reload() } + + func reload() { + let fm = FileManager.default + try? fm.createDirectory(at: Self.gamesRoot, withIntermediateDirectories: true) + Self.excludeFromBackup(Self.gamesRoot) + var found: [GameEntry] = [] + for dir in (try? fm.contentsOfDirectory(at: Self.gamesRoot, includingPropertiesForKeys: nil)) ?? [] { + let meta = dir.appendingPathComponent("game.json") + if let data = try? Data(contentsOf: meta), let entry = try? JSONDecoder().decode(GameEntry.self, from: data), + entry.discURLs.allSatisfy({ fm.fileExists(atPath: $0.path) }) { + found.append(entry) + } + } + games = found.sorted { $0.title.localizedCaseInsensitiveCompare($1.title) == .orderedAscending } + } + + static func excludeFromBackup(_ url: URL) { + var u = url + var values = URLResourceValues() + values.isExcludedFromBackup = true + try? u.setResourceValues(values) + } + + /// Disc order from names ("Disc 1", "disc2", "_d1"...), else alphabetical. + static func discOrder(_ names: [String]) -> [String] { + func discNumber(_ s: String) -> Int? { + let lower = s.lowercased() + for marker in ["disc", "disk", "cd", "_d"] { + if let r = lower.range(of: marker) { + let digits = lower[r.upperBound...].drop { $0 == " " || $0 == "_" || $0 == "-" }.prefix { $0.isNumber } + if let n = Int(digits) { return n } + } + } + return nil + } + return names.sorted { a, b in + switch (discNumber(a), discNumber(b)) { + case let (x?, y?) where x != y: return x < y + default: return a.localizedStandardCompare(b) == .orderedAscending + } + } + } + + /// Creates (or extends, for another disc of the same title) a game entry + /// from files already moved into its folder. + @discardableResult + func register(id: String, title: String, discFiles: [String]) -> GameEntry { + let folder = Self.gamesRoot.appendingPathComponent(id, isDirectory: true) + var entry = games.first { $0.id == id } ?? GameEntry(id: id, title: title, discs: []) + entry.discs = Self.discOrder(Array(Set(entry.discs + discFiles))) + for disc in entry.discs { Self.excludeFromBackup(folder.appendingPathComponent(disc)) } + Self.excludeFromBackup(folder) + if let data = try? JSONEncoder().encode(entry) { try? data.write(to: folder.appendingPathComponent("game.json")) } + reload() + return entry + } + + func update(_ entry: GameEntry) { + if let data = try? JSONEncoder().encode(entry) { try? data.write(to: entry.folder.appendingPathComponent("game.json")) } + reload() + } + + func delete(_ entry: GameEntry) { + try? FileManager.default.removeItem(at: entry.folder) + reload() + } + + static func makeID(_ title: String) -> String { + let base = title.lowercased().map { $0.isLetter || $0.isNumber ? $0 : "-" } + return String(base).split(separator: "-").joined(separator: "-").prefix(40) + "-" + String(UUID().uuidString.prefix(6)) + } + + /// Imports files from the Files app or AirDrop (open-in). Files that look + /// like discs of one title ("Watch Dogs Disc 1/2") become one entry. + /// `addTo` adds the files as further discs of an existing game. + func importFiles(_ urls: [URL], addTo existing: GameEntry? = nil) throws -> GameEntry { + guard !urls.isEmpty else { throw CocoaError(.fileNoSuchFile) } + let title = existing?.title ?? Self.titleFromDiscName(urls[0].deletingPathExtension().lastPathComponent) + let id = existing?.id ?? Self.makeID(title) + let folder = Self.gamesRoot.appendingPathComponent(id, isDirectory: true) + let fm = FileManager.default + try fm.createDirectory(at: folder, withIntermediateDirectories: true) + var names: [String] = [] + for url in urls { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let dest = folder.appendingPathComponent(url.lastPathComponent) + if fm.fileExists(atPath: dest.path) { try fm.removeItem(at: dest) } + // Inbox files (AirDrop/open-in) can be moved; picked files are copied. + if url.path.contains("/Inbox/") { try fm.moveItem(at: url, to: dest) } else { try fm.copyItem(at: url, to: dest) } + names.append(dest.lastPathComponent) + Breadcrumbs.shared.log("import \(dest.lastPathComponent)") + } + return register(id: id, title: title, discs: names) + } + + private func register(id: String, title: String, discs: [String]) -> GameEntry { + register(id: id, title: title, discFiles: discs) + } + + /// "Watch Dogs (Disc 1)" -> "Watch Dogs". + static func titleFromDiscName(_ name: String) -> String { + var t = name + for pattern in ["\\s*[\\(\\[]?\\s*(disc|disk|cd)\\s*\\d+\\s*[\\)\\]]?", "_d\\d+$"] { + t = t.replacingOccurrences(of: pattern, with: "", options: [.regularExpression, .caseInsensitive]) + } + t = t.trimmingCharacters(in: .whitespaces) + return t.isEmpty ? name : t + } +} diff --git a/ios/Render360/MacImport.swift b/ios/Render360/MacImport.swift new file mode 100644 index 00000000..b741d64f --- /dev/null +++ b/ios/Render360/MacImport.swift @@ -0,0 +1,154 @@ +import Foundation + +/// "Import from my Mac": lists tools/serve-games.py's /games.json and +/// downloads a game's discs with HTTP Range requests into Documents/Games. +/// A download writes .part and continues from its size, so an +/// interrupted download (Wi-Fi drop, app killed) resumes where it stopped. +final class MacImporter: NSObject, ObservableObject, URLSessionDataDelegate { + struct Catalogue: Decodable { let games: [RemoteGame] } + struct RemoteGame: Decodable, Identifiable { + let id: String, title: String + let discs: [RemoteDisc] + var totalBytes: Int64 { discs.reduce(0) { $0 + $1.size } } + } + struct RemoteDisc: Decodable { let name: String, path: String, size: Int64 } + + @Published var serverURL: String = UserDefaults.standard.string(forKey: "r360.macServer") ?? "http://192.168.1.2:8360" + @Published var token: String = UserDefaults.standard.string(forKey: "r360.macToken") ?? "" + @Published private(set) var games: [RemoteGame] = [] + @Published private(set) var status = "" + @Published private(set) var progress: Double = 0 + @Published private(set) var busy = false + + private var session: URLSession! + private var handle: FileHandle? + private var expected: Int64 = 0, received: Int64 = 0, total: Int64 = 0, doneBefore: Int64 = 0 + private var completion: ((Error?) -> Void)? + private var cancelled = false + + override init() { + super.init() + let config = URLSessionConfiguration.default + config.timeoutIntervalForRequest = 60 + config.waitsForConnectivity = true + session = URLSession(configuration: config, delegate: self, delegateQueue: nil) + } + + private func request(_ path: String) -> URLRequest? { + guard var comps = URLComponents(string: serverURL.trimmingCharacters(in: .whitespaces) + path) else { return nil } + if !token.isEmpty { comps.queryItems = (comps.queryItems ?? []) + [URLQueryItem(name: "token", value: token)] } + guard let url = comps.url else { return nil } + var r = URLRequest(url: url) + if !token.isEmpty { r.setValue(token, forHTTPHeaderField: "X-Render360-Token") } + return r + } + + func refresh() { + UserDefaults.standard.set(serverURL, forKey: "r360.macServer") + UserDefaults.standard.set(token, forKey: "r360.macToken") + guard let r = request("/games.json") else { status = "Invalid address"; return } + status = "Connecting…" + URLSession.shared.dataTask(with: r) { data, response, error in + DispatchQueue.main.async { + if let error { self.status = "Can't reach the Mac: \(error.localizedDescription)"; return } + guard (response as? HTTPURLResponse)?.statusCode == 200, let data, + let cat = try? JSONDecoder().decode(Catalogue.self, from: data) else { + self.status = "The Mac answered with an error (wrong token?)"; return + } + self.games = cat.games + self.status = cat.games.isEmpty ? "No games in the served folder" : "\(cat.games.count) game(s) on the Mac" + } + }.resume() + } + + func cancel() { cancelled = true; session.getAllTasks { $0.forEach { $0.cancel() } } } + + func download(_ game: RemoteGame, into library: GameLibrary) { + guard !busy else { return } + busy = true; cancelled = false + let id = "mac-" + game.id + let folder = GameLibrary.gamesRoot.appendingPathComponent(id, isDirectory: true) + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + GameLibrary.excludeFromBackup(folder) + total = game.totalBytes; doneBefore = 0 + Breadcrumbs.shared.log("mac download \(game.title) \(total) bytes") + func next(_ index: Int) { + if index == game.discs.count { + DispatchQueue.main.async { + library.register(id: id, title: game.title, discFiles: game.discs.map { $0.name }) + self.busy = false; self.status = "Imported \(game.title)"; self.progress = 1 + } + return + } + let disc = game.discs[index] + let dest = folder.appendingPathComponent(disc.name) + if let size = try? dest.resourceValues(forKeys: [.fileSizeKey]).fileSize, Int64(size) == disc.size { + doneBefore += disc.size; next(index + 1); return + } + fetch(disc, to: dest) { error in + if let error { + DispatchQueue.main.async { + self.busy = false + self.status = self.cancelled ? "Paused – tap Download to resume" : "Download stopped: \(error.localizedDescription) – tap Download to resume" + } + return + } + self.doneBefore += disc.size + next(index + 1) + } + } + next(0) + } + + private func fetch(_ disc: RemoteDisc, to dest: URL, completion: @escaping (Error?) -> Void) { + let part = dest.appendingPathExtension("part") + let fm = FileManager.default + if !fm.fileExists(atPath: part.path) { fm.createFile(atPath: part.path, contents: nil) } + GameLibrary.excludeFromBackup(part) + guard let h = try? FileHandle(forWritingTo: part) else { completion(CocoaError(.fileWriteUnknown)); return } + let have = (try? h.seekToEnd()).map(Int64.init) ?? 0 + handle = h; received = have; expected = disc.size + self.completion = { error in + try? h.close() + if error == nil { + try? fm.removeItem(at: dest) + do { try fm.moveItem(at: part, to: dest) } catch { completion(error); return } + GameLibrary.excludeFromBackup(dest) + } + completion(error) + } + if have >= disc.size { self.completion?(nil); return } + guard var r = request("/files/" + (disc.path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? disc.path)) else { + completion(URLError(.badURL)); return + } + r.setValue("bytes=\(have)-", forHTTPHeaderField: "Range") + session.dataTask(with: r).resume() + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + let code = (response as? HTTPURLResponse)?.statusCode ?? 0 + if code == 200, received > 0 { + // Server ignored Range: start the file over. + try? handle?.truncate(atOffset: 0); received = 0 + } + completionHandler(code == 200 || code == 206 ? .allow : .cancel) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + handle?.write(data) + received += Int64(data.count) + let p = total > 0 ? Double(doneBefore + received) / Double(total) : 0 + DispatchQueue.main.async { + self.progress = p + self.status = String(format: "Downloading… %.0f%% (%.0f / %.0f MB)", p * 100, + Double(self.doneBefore + self.received) / 1e6, Double(self.total) / 1e6) + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + let done = completion; completion = nil + if error == nil, received != expected { done?(URLError(.networkConnectionLost)); return } + done?(error) + } +} diff --git a/ios/Render360/MetalFrameView.swift b/ios/Render360/MetalFrameView.swift new file mode 100644 index 00000000..887c251f --- /dev/null +++ b/ios/Render360/MetalFrameView.swift @@ -0,0 +1,93 @@ +import MetalKit +import SwiftUI + +/// Presents the guest frontbuffer (FrameStore) with Metal: upload RGBA8 into a +/// texture, draw an aspect-fit quad. Presentation is capped at 30 FPS +/// (preferredFramesPerSecond), the target of the 30 FPS bar. +struct MetalFrameView: UIViewRepresentable { + let frames: FrameStore + let perf: PerfStats + + func makeCoordinator() -> Renderer { Renderer(frames: frames, perf: perf) } + + func makeUIView(context: Context) -> MTKView { + let view = MTKView(frame: .zero, device: context.coordinator.device) + view.colorPixelFormat = .bgra8Unorm + view.preferredFramesPerSecond = 30 + view.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1) + view.delegate = context.coordinator + view.framebufferOnly = true + view.contentScaleFactor = UIScreen.main.nativeScale + return view + } + + func updateUIView(_ uiView: MTKView, context: Context) {} + + final class Renderer: NSObject, MTKViewDelegate { + let device = MTLCreateSystemDefaultDevice()! + private let queue: MTLCommandQueue + private let pipeline: MTLRenderPipelineState + private let sampler: MTLSamplerState + private var texture: MTLTexture? + private var shown: UInt64 = 0 + private let frames: FrameStore + private let perf: PerfStats + + init(frames: FrameStore, perf: PerfStats) { + self.frames = frames + self.perf = perf + queue = device.makeCommandQueue()! + let source = """ + #include + using namespace metal; + struct VOut { float4 pos [[position]]; float2 uv; }; + vertex VOut vmain(uint vid [[vertex_id]], constant float2& scale [[buffer(0)]]) { + float2 p = float2(vid & 1, vid >> 1); + VOut o; o.pos = float4((p * 2.0 - 1.0) * scale, 0, 1); o.uv = float2(p.x, 1.0 - p.y); return o; + } + fragment float4 fmain(VOut in [[stage_in]], texture2d t [[texture(0)]], sampler s [[sampler(0)]]) { + return float4(t.sample(s, in.uv).rgb, 1.0); + } + """ + let library = try! device.makeLibrary(source: source, options: nil) + let desc = MTLRenderPipelineDescriptor() + desc.vertexFunction = library.makeFunction(name: "vmain") + desc.fragmentFunction = library.makeFunction(name: "fmain") + desc.colorAttachments[0].pixelFormat = .bgra8Unorm + pipeline = try! device.makeRenderPipelineState(descriptor: desc) + let sd = MTLSamplerDescriptor() + sd.minFilter = .linear; sd.magFilter = .linear + sampler = device.makeSamplerState(descriptor: sd)! + } + + func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} + + func draw(in view: MTKView) { + frames.withFrame(newerThan: shown) { ptr, w, h, gen in + if texture?.width != w || texture?.height != h { + let td = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: w, height: h, mipmapped: false) + td.usage = .shaderRead + texture = device.makeTexture(descriptor: td) + } + texture?.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0, withBytes: ptr, bytesPerRow: w * 4) + shown = gen + perf.framePresented(PerfStats.nowMs()) + } + guard let pass = view.currentRenderPassDescriptor, let drawable = view.currentDrawable, + let cmd = queue.makeCommandBuffer(), let enc = cmd.makeRenderCommandEncoder(descriptor: pass) else { return } + if let texture { + let vw = Float(view.drawableSize.width), vh = Float(view.drawableSize.height) + let fa = Float(texture.width) / Float(texture.height), va = vw / max(vh, 1) + var scale = fa > va ? SIMD2(1, va / fa) : SIMD2(fa / va, 1) + enc.setRenderPipelineState(pipeline) + enc.setVertexBytes(&scale, length: MemoryLayout>.size, index: 0) + enc.setFragmentTexture(texture, index: 0) + enc.setFragmentSamplerState(sampler, index: 0) + enc.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) + } + enc.endEncoding() + cmd.present(drawable) + cmd.commit() + } + } +} diff --git a/ios/Render360/Render360App.swift b/ios/Render360/Render360App.swift new file mode 100644 index 00000000..a3c6b465 --- /dev/null +++ b/ios/Render360/Render360App.swift @@ -0,0 +1,276 @@ +import SwiftUI +import UniformTypeIdentifiers + +@main +struct Render360App: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate + @StateObject private var library = GameLibrary.shared + @StateObject private var input = InputHub() + + var body: some Scene { + WindowGroup { + RootView() + .environmentObject(library) + .environmentObject(input) + .preferredColorScheme(.dark) + // AirDrop / "Open in Render360" / Files "Share" deliveries. + .onOpenURL { url in + _ = try? library.importFiles([url]) + } + } + } +} + +final class AppDelegate: NSObject, UIApplicationDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + Breadcrumbs.shared.startSession() + UIDevice.current.isBatteryMonitoringEnabled = true + // JIT is only usable when the process may map executable memory + // (sideloaded build + StikDebug). The core is interpreter-only today; + // the result is reported in telemetry and Settings. + Breadcrumbs.shared.log("jit probe start") + Breadcrumbs.shared.log("jit available=\(r360_native_jit_available())") + Telemetry.shared.start() + if Breadcrumbs.shared.previousRunCrashed { Telemetry.shared.sendCrashReport(Breadcrumbs.shared.previousTail) } + return true + } + func applicationWillTerminate(_ application: UIApplication) { Breadcrumbs.shared.endSession() } +} + +struct RootView: View { + @EnvironmentObject var library: GameLibrary + @EnvironmentObject var input: InputHub + @State private var playing: GameEntry? + @State private var showImport = false + @State private var showSettings = false + @State private var showCrash = Breadcrumbs.shared.previousRunCrashed + + var body: some View { + NavigationStack { + List { + if let days = SigningInfo.daysLeft, days <= 2 { + Label(days <= 0 ? "This build has expired. Rebuild and reinstall from the Mac (docs/IOS_APP.md)." + : "This build expires in \(days) day\(days == 1 ? "" : "s"). Re-sign from the Mac to keep playing.", + systemImage: "clock.badge.exclamationmark") + .foregroundStyle(.orange) + } + if library.games.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("No games yet").font(.headline) + Text("Import your own dumped games from the Files app, AirDrop, or your Mac over Wi-Fi.") + .font(.subheadline).foregroundStyle(.secondary) + }.padding(.vertical, 8) + } + ForEach(library.games) { game in + Button { playing = game } label: { GameRow(game: game) } + .swipeActions { + Button(role: .destructive) { library.delete(game) } label: { Label("Delete", systemImage: "trash") } + } + .contextMenu { + Button(game.ownedFullLicense ? "Mark as trial" : "I own the full game") { + var g = game; g.ownedFullLicense.toggle(); library.update(g) + } + } + } + } + .navigationTitle("Render360") + .toolbar { + ToolbarItem(placement: .topBarLeading) { Button { showSettings = true } label: { Image(systemName: "gearshape") } } + ToolbarItem(placement: .topBarTrailing) { Button { showImport = true } label: { Label("Import game", systemImage: "plus") } } + } + .sheet(isPresented: $showImport) { ImportView().environmentObject(library) } + .sheet(isPresented: $showSettings) { SettingsView() } + .alert("The last session ended unexpectedly", isPresented: $showCrash) { + Button("OK", role: .cancel) {} + } message: { + Text((Breadcrumbs.shared.previousTail.suffix(4)).joined(separator: "\n")) + } + } + .fullScreenCover(item: $playing) { game in PlayView(game: game).environmentObject(input) } + } +} + +struct GameRow: View { + let game: GameEntry + var body: some View { + VStack(alignment: .leading, spacing: 3) { + Text(game.title).font(.headline) + Text("\(game.discs.count) disc\(game.discs.count == 1 ? "" : "s") · \(ByteCountFormatter.string(fromByteCount: game.totalBytes, countStyle: .file))\(game.ownedFullLicense ? " · full license" : "")") + .font(.caption).foregroundStyle(.secondary) + } + } +} + +struct ImportView: View { + @EnvironmentObject var library: GameLibrary + @Environment(\.dismiss) private var dismiss + @StateObject private var mac = MacImporter() + @State private var picking = false + @State private var addDiscsTo: GameEntry? + @State private var message = "" + + var body: some View { + NavigationStack { + Form { + Section("From the Files app") { + Button("Choose files…") { addDiscsTo = nil; picking = true } + Text("Pick every disc of a multi-disc game together (for example Watch Dogs disc 1 and 2); they become one game.") + .font(.caption).foregroundStyle(.secondary) + if !library.games.isEmpty { + Menu("Add a disc to an existing game") { + ForEach(library.games) { g in Button(g.title) { addDiscsTo = g; picking = true } } + } + } + } + Section("AirDrop") { + Text("AirDrop the file from your Mac and choose Render360 in the share sheet.").font(.caption).foregroundStyle(.secondary) + } + Section("From my Mac (Wi-Fi)") { + TextField("http://mac-address:8360", text: $mac.serverURL) + .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() + TextField("Token (optional)", text: $mac.token).textInputAutocapitalization(.never).autocorrectionDisabled() + Button("Show games on the Mac") { mac.refresh() }.disabled(mac.busy) + if !mac.status.isEmpty { Text(mac.status).font(.caption) } + if mac.busy { ProgressView(value: mac.progress); Button("Pause", role: .cancel) { mac.cancel() } } + ForEach(mac.games) { g in + Button { mac.download(g, into: library) } label: { + VStack(alignment: .leading) { + Text(g.title) + Text("\(g.discs.count) disc(s) · \(ByteCountFormatter.string(fromByteCount: g.totalBytes, countStyle: .file))") + .font(.caption).foregroundStyle(.secondary) + } + }.disabled(mac.busy) + } + } + if !message.isEmpty { Section { Text(message) } } + Section { + Text("Only import games you dumped from your own discs or console. Files stay on this iPhone and are excluded from iCloud backup.") + .font(.caption).foregroundStyle(.secondary) + } + } + .navigationTitle("Import game") + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } + .fileImporter(isPresented: $picking, allowedContentTypes: [.data, .diskImage, .item], allowsMultipleSelection: true) { result in + do { + let urls = try result.get() + let entry = try library.importFiles(urls, addTo: addDiscsTo) + message = "Imported \(entry.title) (\(entry.discs.count) disc\(entry.discs.count == 1 ? "" : "s"))" + } catch { + message = "Import failed: \(error.localizedDescription)" + } + } + } + } +} + +struct PlayView: View { + let game: GameEntry + @EnvironmentObject var input: InputHub + @StateObject private var session = EmulatorSession() + @Environment(\.dismiss) private var dismiss + @State private var showOverlay = true + @State private var memoryWarning: Double? + private let memory = MemoryGuard() + + var body: some View { + ZStack { + Color.black.ignoresSafeArea() + MetalFrameView(frames: session.frames, perf: session.perf).ignoresSafeArea() + TouchControls(input: input).ignoresSafeArea() + VStack { + HStack(alignment: .top) { + if showOverlay { PerfOverlay(stats: session.stats, state: session.state, memory: memory) } + Spacer() + Button { showOverlay.toggle() } label: { Image(systemName: "speedometer") }.padding(6) + Button { + session.stop() + // Guest threads of a stopped run cannot be unwound; the + // app exits to release them (next launch starts clean). + Breadcrumbs.shared.endSession() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { exit(0) } + } label: { Image(systemName: "xmark.circle.fill").font(.title2) }.padding(6) + } + Spacer() + } + .padding(8) + if case .failed(let message) = session.state { + Text("Could not start: \(message)").padding().background(.red.opacity(0.8), in: RoundedRectangle(cornerRadius: 10)) + .onTapGesture { dismiss() } + } + } + .statusBarHidden() + .persistentSystemOverlays(.hidden) + .alert(session.dialog?.title ?? "", isPresented: Binding(get: { session.dialog != nil }, set: { _ in })) { + ForEach(Array((session.dialog?.buttons ?? []).enumerated()), id: \.offset) { i, label in + Button(label) { session.answerDialog(i) } + } + } message: { Text(session.dialog?.text ?? "") } + .onAppear { + UIApplication.shared.isIdleTimerDisabled = true + memory.onPressure = { mb in DispatchQueue.main.async { memoryWarning = mb } } + session.memory = memory + Telemetry.shared.emulator = session + Telemetry.shared.memory = memory + input.attach(session) + session.start(game: game) + } + .onDisappear { input.detach(); UIApplication.shared.isIdleTimerDisabled = false } + } +} + +struct PerfOverlay: View { + let stats: PerfStats.Snapshot + let state: EmulatorSession.State + let memory: MemoryGuard + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text(String(format: "Game FPS %.0f avg %.1f 1%% low %.1f stutters %.1f/min", stats.gameFps, stats.gameAverageFps, stats.gameLow1Fps, stats.stuttersPerMinute)) + Text(String(format: "Emulation speed %.0f%% idle %.0f%% %.0f MIPS interpreted %.1f%%", stats.emulationSpeedPercent, stats.idlePercent, stats.mips, stats.interpretedPercent)) + Text(String(format: "Memory %.0f MB used · %.0f MB free (lowest %.0f)", MemoryGuard.footprintMB, MemoryGuard.availableMB, + memory.lowestAvailableMB.isFinite ? memory.lowestAvailableMB : MemoryGuard.availableMB)) + Text("30 FPS bar: \(stats.barPass ? "PASS" : "not met") · \(stateText) · thermal \(["nominal", "fair", "serious", "critical"][min(3, ProcessInfo.processInfo.thermalState.rawValue)])") + } + .font(.system(size: 11, design: .monospaced)) + .foregroundStyle(.white) + .padding(6) + .background(.black.opacity(0.6), in: RoundedRectangle(cornerRadius: 6)) + } + private var stateText: String { + switch state { + case .idle: return "idle" + case .booting: return "booting" + case .running: return "running (interpreter)" + case .stopped(let b): return "stopped: \(b)" + case .failed: return "failed" + } + } +} + +struct SettingsView: View { + @Environment(\.dismiss) private var dismiss + @State private var telemetry = UserDefaults.standard.string(forKey: "r360.telemetryServer") ?? "" + var body: some View { + NavigationStack { + Form { + Section("Telemetry to the Mac") { + TextField("http://mac-address:8361", text: $telemetry) + .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() + .onSubmit { UserDefaults.standard.set(telemetry, forKey: "r360.telemetryServer") } + Text("Run tools/telemetry-server.py on the Mac, then open /status there.").font(.caption).foregroundStyle(.secondary) + } + Section("This build") { + LabeledContent("Signing expires", value: SigningInfo.expiry.map { $0.formatted(date: .abbreviated, time: .shortened) } ?? "unknown") + LabeledContent("JIT", value: r360_native_jit_available() == 1 ? "available (not used yet)" : "not available — interpreter") + LabeledContent("Free memory", value: String(format: "%.0f MB", MemoryGuard.availableMB)) + } + Section("Diagnostics") { + ShareLink(item: Breadcrumbs.shared.file) { Label("Share breadcrumbs", systemImage: "square.and.arrow.up") } + } + } + .navigationTitle("Settings") + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { + UserDefaults.standard.set(telemetry, forKey: "r360.telemetryServer"); dismiss() + } } } + } + } +} diff --git a/native/build-native.sh b/native/build-native.sh index 08813e89..26436b86 100644 --- a/native/build-native.sh +++ b/native/build-native.sh @@ -41,11 +41,15 @@ COMMON=(-std=c++20 "$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroo COMMON_C=("$R360_OPT" -g "${NATIVE_DEFS[@]}" "${ARCHFLAGS[@]}" -isysroot "$SYSROOT" -I"$XENIA/third_party/mspack" -I"$XENIA/third_party/crypto" -Wno-everything) -mkdir -p "$OUT"; rm -f "$OUT"/*.o "$OUT"/*.log "$OUT"/*.fail +mkdir -p "$OUT"; rm -f "$OUT"/*.fail +# Fresh overlays rewrite every source, so rebuild everything; with +# R360_SKIP_OVERLAYS=1 only units whose source is newer than the object. +[ "${R360_SKIP_OVERLAYS:-0}" = 1 ] || rm -f "$OUT"/*.o "$OUT"/*.log +up_to_date() { [ "${R360_SKIP_OVERLAYS:-0}" = 1 ] && [ -f "$1" ] && [ "$1" -nt "$2" ] && [ ! "$2" -nt "$1" ]; } obj_for() { printf '%s/%s.o' "$OUT" "$(printf '%s' "$1" | tr '/' '_')"; } throttle() { while [ "$(jobs -pr | wc -l | tr -d ' ')" -ge "$JOBS" ]; do sleep 0.2; done; } -cpp() { throttle; ( o="$(obj_for "$1")"; "$CXX" "${COMMON[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } -cc() { throttle; ( o="$(obj_for "$1")"; "$CC" "${COMMON_C[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +cpp() { up_to_date "$(obj_for "$1")" "$2" && { : > "$(obj_for "$1").log"; return 0; }; throttle; ( o="$(obj_for "$1")"; "$CXX" "${COMMON[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } +cc() { up_to_date "$(obj_for "$1")" "$2" && { : > "$(obj_for "$1").log"; return 0; }; throttle; ( o="$(obj_for "$1")"; "$CC" "${COMMON_C[@]}" -c "$2" -o "$o" >"$o.log" 2>&1 || touch "$o.fail" ) & } # Native-only translation units (fiber baton, C API, JIT stub). native_units() { local f diff --git a/native/src/native_title.cpp b/native/src/native_title.cpp index ae5a82fb..921a2904 100644 --- a/native/src/native_title.cpp +++ b/native/src/native_title.cpp @@ -1247,12 +1247,12 @@ struct ExportName { const char* name; }; const ExportName kXboxkrnl[] = { -#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name}, +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name} #include "xenia/kernel/xboxkrnl/xboxkrnl_table.inc" #undef XE_EXPORT }; const ExportName kXam[] = { -#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name}, +#define XE_EXPORT(module, ordinal, name, kind) {ordinal, #name} #include "xenia/kernel/xam/xam_table.inc" #undef XE_EXPORT }; diff --git a/prepare-xenia-web-overlay.py b/prepare-xenia-web-overlay.py index ef3f8944..b0aa6cf1 100644 --- a/prepare-xenia-web-overlay.py +++ b/prepare-xenia-web-overlay.py @@ -274,6 +274,18 @@ def write_narrow_utf8_overlay(source: Path, dest: Path, label: str) -> int: wasm_init += desktop_body_without_close + "#endif\n}\n\n" memory_cc = memory_cc[:init_start] + wasm_init + memory_cc[map_info_start:] MEMORY_DEST.parent.mkdir(parents=True, exist_ok=True) +# The portable host never installs an MMIOHandler (no host page faults), but +# the HIR constant-propagation pass still asks for MMIO ranges. Upstream +# dereferences the null handler; wasm32 happened to read zeros at address 0x20, +# a 64-bit native host faults. Report "no range" instead. +lookup_anchor = " return mmio_handler_->LookupRange(virtual_address);\n" +if lookup_anchor not in memory_cc: + raise SystemExit("Upstream Memory::LookupVirtualMappedRange drifted") +memory_cc = memory_cc.replace( + lookup_anchor, + " if (!mmio_handler_) return nullptr; // Render360 portable host\n" + lookup_anchor, + 1, +) MEMORY_DEST.write_text(memory_cc) # processor.cc: the debugger exception-resume path knows how to restore a diff --git a/tools/telemetry-server.py b/tools/telemetry-server.py new file mode 100644 index 00000000..fb122f0d --- /dev/null +++ b/tools/telemetry-server.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Receive Render360 iOS telemetry on the Mac and show it at /status. + + python3 tools/telemetry-server.py [--port 8361] [--logs logs/phone] + +In the app: Settings > Telemetry to the Mac > http://:8361 +The phone POSTs one JSON object per second to /telemetry?s= and, +after a crash, its last breadcrumbs to /crash?s=. This server keeps: + logs/phone/telemetry_.jsonl every line (game FPS, speed, MIPS, + interpreted %, memory, thermal...) + logs/phone/crash__