From 529d13f557a1619813b1220e70c97a534320decd Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:29:07 +0500 Subject: [PATCH 1/7] Shaders: share compiled DXIL across pipeline builds Return the cached Arc to pipeline builders so repeated shader requests reuse the compiled storage. Keep the VS and PS owners alive while the driver consumes their bytecode. Assisted-by: Codex (gpt-6.1-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 25 ++++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 20 ++++++++++---------- crates/xcl/tests/console_shaders.rs | 8 ++++---- 3 files changed, 34 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b6dd120ff..ec6fc8fbe 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -128,7 +128,7 @@ pub struct Compiled { /// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static /// samplers take registers from `sampler_base` (space 1). /// Fails when the blob is not a console shader or the program is not fully translated. -pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result { +pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result, String> { console_to_dxil_for(blob, stage, sampler_base, false) } @@ -136,7 +136,7 @@ pub fn console_to_dxil(blob: &[u8], stage: Stage, sampler_base: u32) -> Result Result { +pub fn console_to_dxil_for(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool) -> Result, String> { console_to_dxil_in(blob, stage, sampler_base, split_wave64, mem_windows()) } @@ -148,10 +148,10 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). -pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { +pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result, String> { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { - return compile_one(); + return compile_one().map(Arc::new); } let key = ShaderKey { hash: crate::gpu::shader::fnv64(blob), @@ -164,7 +164,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, // direct translator version, routing mode): never mixed with the HLSL path's entries let from_disk = || translated::cached(&dxc::cache_dir(), blob, stage, sampler_base, windows, split_wave64, compile_one); - cached_shader(shader_cache(), key, blob, from_disk).map(|shader| shader.as_ref().clone()) + cached_shader(shader_cache(), key, blob, from_disk) } /// Translations on disk: a console program's (DXIL, static samplers) by its bytes, so a run @@ -1566,6 +1566,21 @@ mod shader_cache_tests { mod compile_time_bench { use super::*; + #[test] + fn repeated_console_shader_requests_share_dxil() { + use crate::gpu::xbox::tests::{fssm, sample, CODE}; + let mut f = fssm(&CODE, &[(6, 0)]); + for offset in [0x13C, 0x140, 0x144] { + f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes()); + } + let blob = sample(5, &[f]); + let first = console_to_dxil(&blob, Stage::Compute, 0).unwrap(); + let second = console_to_dxil(&blob, Stage::Compute, 0).unwrap(); + assert_eq!(first.dxil, second.dxil); + assert_eq!(first.samplers, second.samplers); + assert_eq!(first.dxil.as_ptr(), second.dxil.as_ptr(), "a cache hit shares its compiled storage"); + } + #[test] #[ignore] fn repeated_pso_shader_compile() { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18..dac4fd3cb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3858,7 +3858,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } }; - let dxil = compiled.dxil; + let dxil = &compiled.dxil; // a big program: the driver's compile takes it seconds to a minute (a retail game's 1 MB // ray-tracing resolve programs ~30 s each, ~600 of them): built in the background like one // whose DXIL is missing – the title's loading does not wait for it, its first bind does @@ -4629,22 +4629,22 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } }; - let mut samplers = vs_c.samplers; - let vs_dxil = vs_c.dxil; - let ps_dxil = match shader_bytes(&d.PS) { + let mut samplers = vs_c.samplers.clone(); + let vs_dxil = &vs_c.dxil; + let ps_c = match shader_bytes(&d.PS) { Some(p) if is_console(p) => match console_to_dxil_for(p, Stage::Pixel, samplers.len() as u32, split) { Ok(b) => { - samplers.extend(b.samplers); - Some(b.dxil) + samplers.extend_from_slice(&b.samplers); + Some(b) } Err(e) => { note_translation_error(format!("PS: {e}")); return None; } }, - Some(p) => Some(p.to_vec()), - None => None, + _ => None, }; + let ps_dxil = ps_c.as_ref().map(|c| c.dxil.as_slice()).or_else(|| shader_bytes(&d.PS)); let rs = abi_rs_for(this, &samplers)?; let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -4669,7 +4669,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); + let bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.as_ref().map_or(0, Vec::len); let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); let mut cached = graphics_blob(gkey); let disk = driver_cache::graphics_path(gkey.0, gkey.1); @@ -5284,7 +5284,7 @@ mod two_pass_identity; fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; match ps { - Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil), c.samplers)).map_err(|e| format!("PS: {e}")), + Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil.clone()), c.samplers.clone())).map_err(|e| format!("PS: {e}")), Some(p) => Ok((Some(p.to_vec()), Vec::new())), None => Ok((None, Vec::new())), } diff --git a/crates/xcl/tests/console_shaders.rs b/crates/xcl/tests/console_shaders.rs index e2b96c6dc..9a0166081 100644 --- a/crates/xcl/tests/console_shaders.rs +++ b/crates/xcl/tests/console_shaders.rs @@ -524,8 +524,8 @@ fn console_compiled_graphics_reads_its_root_arguments() { let ps = format!("{common}ROOT float4 main(float4 p : SV_Position, float4 c : COLOR0) : SV_Target {{ return float4(k0, k1, m0.x + c.x, m0.y + c.y); }}\n"); let vs_blob = console_compile(&c, &vs, &["-E", "main", "-T", "vs_6_6"]).unwrap_or_else(|e| panic!("VS: {e}")); let ps_blob = console_compile(&c, &ps, &["-E", "main", "-T", "ps_6_6"]).unwrap_or_else(|e| panic!("PS: {e}")); - let vs_dxil = pso::console_to_dxil(&vs_blob, pso::Stage::Vertex, 0).unwrap_or_else(|e| panic!("VS translation: {e}")).dxil; - let ps_dxil = pso::console_to_dxil(&ps_blob, pso::Stage::Pixel, 0).unwrap_or_else(|e| panic!("PS translation: {e}")).dxil; + let vs_dxil = &pso::console_to_dxil(&vs_blob, pso::Stage::Vertex, 0).unwrap_or_else(|e| panic!("VS translation: {e}")).dxil; + let ps_dxil = &pso::console_to_dxil(&ps_blob, pso::Stage::Pixel, 0).unwrap_or_else(|e| panic!("PS translation: {e}")).dxil; // root arguments: 4 constants (0.25, 0.5, 2.0 – the position scale, 0.5), the CBV's address let (cbv, table_at) = (0x1000usize, 0x100usize); let layout = console_list::layout_from_blob(&vs_blob).expect("RTS0"); @@ -568,8 +568,8 @@ fn console_compiled_derivatives_hold_on_triangle_edges() { let ps = format!("{root}ROOT float4 main(float4 p : SV_Position, float2 uv : TEXCOORD0) : SV_Target {{ return float4(ddx_fine(uv.x), ddy_fine(uv.y), ddx_fine(uv.y), 1.0); }}\n"); let vs_blob = console_compile(&c, &vs, &["-E", "main", "-T", "vs_6_6"]).unwrap_or_else(|e| panic!("VS: {e}")); let ps_blob = console_compile(&c, &ps, &["-E", "main", "-T", "ps_6_6"]).unwrap_or_else(|e| panic!("PS: {e}")); - let vs_dxil = pso::console_to_dxil(&vs_blob, pso::Stage::Vertex, 0).unwrap_or_else(|e| panic!("VS translation: {e}")).dxil; - let ps_dxil = pso::console_to_dxil(&ps_blob, pso::Stage::Pixel, 0).unwrap_or_else(|e| panic!("PS translation: {e}")).dxil; + let vs_dxil = &pso::console_to_dxil(&vs_blob, pso::Stage::Vertex, 0).unwrap_or_else(|e| panic!("VS translation: {e}")).dxil; + let ps_dxil = &pso::console_to_dxil(&ps_blob, pso::Stage::Pixel, 0).unwrap_or_else(|e| panic!("PS translation: {e}")).dxil; // the whole 32x32 target as two triangles: uv steps by 1 per pixel in x, by −1 in y let quad = [-1.0f32, -1.0, 0.0, 1.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0]; let el = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32_FLOAT, offset: 0 }]; From 1c43107a1179d980d9dce934f388830188611fab Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:19:43 +0500 Subject: [PATCH 2/7] D3D12.X: prepare bounded native AS input snapshots Prepare native input copies with checked descriptor capture, packed vertex spans and a committed allocation cap. This preparatory module is not called by title execution yet. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- crates/xcl/src/hle/d3d12x/host_bvh.rs | 219 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 78 +++++++ crates/xcl/src/hle/d3d12x/mod.rs | 2 + 3 files changed, 299 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/host_bvh.rs create mode 100644 crates/xcl/src/hle/d3d12x/host_bvh/tests.rs diff --git a/crates/xcl/src/hle/d3d12x/host_bvh.rs b/crates/xcl/src/hle/d3d12x/host_bvh.rs new file mode 100644 index 000000000..adbad2819 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/host_bvh.rs @@ -0,0 +1,219 @@ +//! Bounded input preparation for a future opt-in native acceleration-structure path. +#![allow(dead_code, unused_imports)] + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{size_of, ManuallyDrop, MaybeUninit}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +use super::real; + +const LIMIT: u64 = 256 << 20; +const MAX_DESCS: usize = 8192; +// All T at the call sites are POD descriptor records or integer words. +unsafe fn read_items(address: usize, count: usize) -> Result, String> { + let bytes = count.checked_mul(size_of::()).ok_or("descriptor size overflow")?; + if count > MAX_DESCS || address.checked_add(bytes).is_none() { + return Err("descriptor capture limit exceeded".into()); + } + if bytes == 0 { + return Ok(Vec::new()); + } + let mut values = Vec::>::new(); + values.try_reserve_exact(count).map_err(|_| "descriptor allocation failed")?; + values.resize_with(count, MaybeUninit::uninit); + let mut done = 0; + if address == 0 || ReadProcessMemory( + GetCurrentProcess(), address as *const c_void, values.as_mut_ptr().cast(), bytes, &mut done, + ) == 0 || done != bytes { + return Err("descriptor memory is unreadable".into()); + } + let mut values = ManuallyDrop::new(values); + Ok(Vec::from_raw_parts(values.as_mut_ptr().cast(), values.len(), values.capacity())) +} + +unsafe fn native_vtable(object: &T) -> &T::Vtable { + if real::is_adopted(object.as_raw()) { + let table = *(object.as_raw() as *const *const usize); + &*(*table.sub(1) as *const T::Vtable) + } else { + object.vtable() + } +} + +#[derive(Clone)] +struct HostAs { + resource: ID3D12Resource, + bytes: u64, + kind: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE, +} + +struct Prepared { + resources: Vec, + copies: Vec<(ID3D12Resource, u64, ID3D12Resource, u64)>, + bytes: u64, + limit: u64, +} + +impl Prepared { + fn new(limit: u64) -> Self { + Self { resources: Vec::new(), copies: Vec::new(), bytes: 0, limit } + } + + unsafe fn buffer(&mut self, dev: &ID3D12Device5, bytes: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> Result { + let bytes = bytes.checked_add(255).map(|n| n & !255).filter(|&n| n > 0).ok_or("invalid native buffer size")?; + let committed = bytes.checked_add(65535).map(|n| n & !65535).ok_or("native allocation size overflow")?; + if committed > self.limit.saturating_sub(self.bytes) { + return Err("256 MiB shadow DXR capture budget reached".into()); + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, + DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if heap == D3D12_HEAP_TYPE_DEFAULT && state != D3D12_RESOURCE_STATE_COPY_DEST { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let properties = D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }; + let base = &*(native_vtable(dev) as *const _ as *const ID3D12Device_Vtbl); + let mut resource = None::; + (base.CreateCommittedResource)( + dev.as_raw(), &properties, D3D12_HEAP_FLAG_NONE, &desc, state, std::ptr::null(), + &ID3D12Resource::IID, (&mut resource as *mut Option).cast(), + ).ok().map_err(|e| e.to_string())?; + let resource = resource.ok_or("native buffer creation returned null")?; + self.bytes += committed; + self.resources.push(resource.clone()); + Ok(resource) + } + + unsafe fn input( + &mut self, dev: &ID3D12Device5, address: u64, bytes: u64, + source: &dyn Fn(u64, u64) -> Option<(ID3D12Resource, u64)>, + ) -> Result { + let (original, offset) = source(address, bytes).ok_or("geometry range is outside a mapped UMA window")?; + let buffer = self.buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST)?; + let address = buffer.GetGPUVirtualAddress(); + self.copies.push((original, offset, buffer, bytes)); + Ok(address) + } +} + +fn vertex_bytes(format: DXGI_FORMAT) -> Option { + match format { + DXGI_FORMAT_R32G32B32_FLOAT => Some(12), + DXGI_FORMAT_R32G32_FLOAT => Some(8), + // DXR ignores A16, and packed positions may use a six-byte stride. + DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_SNORM | + DXGI_FORMAT_R16G16B16A16_UNORM => Some(6), + DXGI_FORMAT_R16G16_FLOAT | DXGI_FORMAT_R16G16_SNORM | + DXGI_FORMAT_R16G16_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM => Some(4), + _ => None, + } +} + +fn vertex_span(triangle: &D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC) -> Result { + let element = vertex_bytes(triangle.VertexFormat).ok_or("unsupported DXR vertex format")?; + u64::from(triangle.VertexCount).checked_sub(1) + .and_then(|n| n.checked_mul(triangle.VertexBuffer.StrideInBytes)) + .and_then(|n| n.checked_add(element)).ok_or_else(|| "invalid DXR vertex span".into()) +} + +unsafe fn geometry( + prepared: &mut Prepared, dev: &ID3D12Device5, inputs: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + source: &dyn Fn(u64, u64) -> Option<(ID3D12Resource, u64)>, +) -> Result, String> { + let mut geometries = match inputs.DescsLayout { + D3D12_ELEMENTS_LAYOUT_ARRAY => read_items(inputs.Anonymous.pGeometryDescs as usize, inputs.NumDescs as usize)?, + D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS => { + let pointers: Vec = read_items(inputs.Anonymous.ppGeometryDescs as usize, inputs.NumDescs as usize)?; + pointers.into_iter().map(|p| read_items::(p, 1).map(|mut v| v.remove(0))).collect::, _>>()? + } + _ => return Err("unsupported geometry descriptor layout".into()), + }; + for geometry in &mut geometries { + if geometry.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("shadow DXR currently accepts triangle geometry".into()); + } + let triangle = &mut geometry.Anonymous.Triangles; + let bytes = vertex_span(triangle)?; + triangle.VertexBuffer.StartAddress = prepared.input(dev, triangle.VertexBuffer.StartAddress, bytes, source)?; + if triangle.IndexCount != 0 { + let width = match triangle.IndexFormat { + DXGI_FORMAT_R16_UINT => 2, + DXGI_FORMAT_R32_UINT => 4, + _ => return Err("unsupported DXR index format".into()), + }; + triangle.IndexBuffer = prepared.input(dev, triangle.IndexBuffer, u64::from(triangle.IndexCount) * width, source)?; + } + if triangle.Transform3x4 != 0 { + triangle.Transform3x4 = prepared.input(dev, triangle.Transform3x4, 48, source)?; + } + } + Ok(geometries) +} + +unsafe fn instances( + prepared: &mut Prepared, dev: &ID3D12Device5, inputs: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, + structures: &HashMap, +) -> Result { + if inputs.DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY { + return Err("shadow TLAS requires a contiguous instance array".into()); + } + let address = inputs.Anonymous.InstanceDescs as usize; + let mut instances: Vec<[u8; 64]> = read_items(address, inputs.NumDescs as usize).or_else(|error| { + let cpu = crate::hle::kernelx::mirrors::source(address).ok_or(error)?; + read_items(cpu, inputs.NumDescs as usize) + })?; + for instance in &mut instances { + let console = u64::from_le_bytes(instance[56..64].try_into().unwrap()); + let native = structures.get(&console) + .filter(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) + .ok_or("TLAS references a BLAS without a shadow build")?; + instance[56..64].copy_from_slice(&native.resource.GetGPUVirtualAddress().to_le_bytes()); + } + let bytes = size_of::<[u8; 64]>() * instances.len(); + let upload = prepared.buffer(dev, bytes as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut mapped = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).map_err(|e| e.to_string())?; + std::ptr::copy_nonoverlapping(instances.as_ptr().cast::(), mapped.cast(), bytes); + upload.Unmap(0, None); + Ok(upload.GetGPUVirtualAddress()) +} + +unsafe fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(resource), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, StateAfter: after, + }) }, + ..Default::default() + } +} + +unsafe fn uav_barrier(resource: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: ManuallyDrop::new(resource.map(|resource| std::mem::transmute_copy(resource))), + }) }, + ..Default::default() + } +} + +unsafe fn barriers(list: &ID3D12GraphicsCommandList4, barriers: &[D3D12_RESOURCE_BARRIER]) { + let base = &*(native_vtable(list) as *const _ as *const ID3D12GraphicsCommandList_Vtbl); + (base.ResourceBarrier)(list.as_raw(), barriers.len() as u32, barriers.as_ptr()); +} + +#[cfg(test)] +mod tests; diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs new file mode 100644 index 000000000..39792d093 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -0,0 +1,78 @@ +use super::*; + +#[test] +fn descriptor_capture_checks_spans_and_preserves_records() { + unsafe { + let data = [17u64, 29]; + assert_eq!(read_items::(data.as_ptr() as usize, 2).unwrap(), data); + assert!(read_items::(0, 1).is_err()); + assert!(read_items::(usize::MAX - 2, 2).is_err()); + assert!(read_items::(data.as_ptr() as usize, MAX_DESCS + 1).is_err()); + assert!(read_items::(0, 0).unwrap().is_empty()); + } +} + +#[test] +fn packed_vertex_spans_exclude_unused_alpha_and_check_overflow() { + let mut triangle = D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { + VertexFormat: DXGI_FORMAT_R16G16B16A16_FLOAT, + VertexCount: 3, + VertexBuffer: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { StartAddress: 256, StrideInBytes: 6 }, + ..Default::default() + }; + assert_eq!(vertex_span(&triangle).unwrap(), 18); + triangle.VertexCount = 0; + assert!(vertex_span(&triangle).is_err()); + triangle.VertexCount = 3; + triangle.VertexBuffer.StrideInBytes = u64::MAX; + assert!(vertex_span(&triangle).is_err()); +} + +#[test] +fn gpu_native_input_budget_and_adopted_device() { + use crate::gpu::recomp::{runner}; + use windows::Win32::Graphics::Direct3D::*; + use windows::Win32::Graphics::Dxgi::*; + + unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { + runner::skip_test("no DXGI factory"); + return; + }; + let selector = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((adapter, desc)) = crate::gpu::adapter::candidates(&factory, &selector).into_iter().next() else { + runner::skip_test("no GPU"); + return; + }; + let Ok(base) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_1) else { + runner::skip_test("no D3D12 device"); + return; + }; + let Ok(dev) = base.cast::() else { + runner::skip_test("no DXR interface"); + return; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS5::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, (&mut options as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS5).cast(), size_of::() as u32).unwrap(); + if options.RaytracingTier.0 < D3D12_RAYTRACING_TIER_1_1.0 { + runner::skip_test("no DXR 1.1"); + return; + } + println!("Host DXR fixture on {}", crate::gpu::adapter::name(&desc)); + let mut prepared = Prepared::new(2 * 65536); + let buffer = prepared.buffer(&dev, 36, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON).unwrap(); + assert_eq!(prepared.bytes, 65536); + let source = |address, bytes| (address == 17 && bytes == 36).then(|| (buffer.clone(), 0)); + let copied = prepared.input(&dev, 17, 36, &source).unwrap(); + assert_ne!(copied, buffer.GetGPUVirtualAddress()); + assert_eq!(prepared.bytes, 2 * 65536); + assert_eq!(prepared.copies.len(), 1); + assert!(prepared.input(&dev, 17, 36, &source).is_err()); + assert_eq!(prepared.bytes, 2 * 65536); + assert!(prepared.input(&dev, 18, 36, &source).is_err()); + let native = native_vtable(&dev) as *const _; + real::adopt(dev.as_raw(), real::Kind::Device); + assert_eq!(native_vtable(&dev) as *const _, native); + println!("Native input copies respect the committed allocation cap on an adopted device"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f035798..42fd6580b 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -250,3 +250,5 @@ pub unsafe extern "system" fn D3D12ConfigureVirtualMemoryX(config: *const c_void } S_OK } + +pub(crate) mod host_bvh; From d4d128f061a330c6be4b47dae5ecdb2f784de16c Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:21:18 +0500 Subject: [PATCH 3/7] D3D12.X: record bounded shadow BLAS and TLAS builds Build native acceleration structures from captured inputs and retain every referenced buffer within the allocation cap. The title-facing observer is connected in the next change. GPU fixtures cover build, compact-copy, traversal and budget failure. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- crates/xcl/src/hle/d3d12x/host_bvh.rs | 114 ++++++++++++ crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 188 ++++++++++++++++++-- 2 files changed, 288 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/host_bvh.rs b/crates/xcl/src/hle/d3d12x/host_bvh.rs index adbad2819..3279fabb9 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh.rs @@ -55,6 +55,35 @@ struct HostAs { kind: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE, } +#[derive(Default)] +struct State { + structures: HashMap, + // Buffers stay alive across command-list resets and submissions. The byte cap includes + // scratch, input snapshots and old generations, including failed or unsubmitted builds. + retained: Vec, + bytes: u64, + recorded: u64, +} + +impl State { + fn retain(&mut self, prepared: Prepared) { + self.bytes += prepared.bytes; + self.retained.extend(prepared.resources); + } +} + +static STATES: Mutex>> = Mutex::new(None); + +fn forget(dest: u64) { + if let Some(states) = STATES.lock().unwrap().as_mut() { + for state in states.values_mut() { + if state.structures.remove(&dest).is_some_and(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) { + state.structures.retain(|_, value| value.kind != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); + } + } + } +} + struct Prepared { resources: Vec, copies: Vec<(ID3D12Resource, u64, ID3D12Resource, u64)>, @@ -215,5 +244,90 @@ unsafe fn barriers(list: &ID3D12GraphicsCommandList4, barriers: &[D3D12_RESOURCE (base.ResourceBarrier)(list.as_raw(), barriers.len() as u32, barriers.as_ptr()); } +unsafe fn record_on( + state: &mut State, dev: &ID3D12Device5, list: &ID3D12GraphicsCommandList4, + desc: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + source: &dyn Fn(u64, u64) -> Option<(ID3D12Resource, u64)>, +) -> Result { + let previous = state.structures.remove(&desc.DestAccelerationStructureData); + if desc.Inputs.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL + || previous.is_some_and(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) { + state.structures.retain(|_, value| value.kind != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); + } + if desc.DestAccelerationStructureData == 0 || desc.Inputs.NumDescs == 0 { + return Err("empty acceleration structure".into()); + } + let mut prepared = Prepared::new(LIMIT - state.bytes); + let mut inputs = desc.Inputs; + inputs.Flags &= !D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; + let geometries; + match inputs.Type { + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL => { + geometries = geometry(&mut prepared, dev, &inputs, source)?; + inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + inputs.Anonymous.pGeometryDescs = geometries.as_ptr(); + } + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL => { + inputs.Anonymous.InstanceDescs = instances(&mut prepared, dev, &inputs, &state.structures)?; + } + _ => return Err("unsupported acceleration structure type".into()), + } + let mut info = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + (native_vtable(dev).GetRaytracingAccelerationStructurePrebuildInfo)(dev.as_raw(), &inputs, &mut info); + let result = prepared.buffer(dev, info.ResultDataMaxSizeInBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE)?; + let scratch = prepared.buffer(dev, info.ScratchDataSizeInBytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)?; + let copies = std::mem::take(&mut prepared.copies); + // Retain every referenced buffer before recording the first command. Failed preparation + // has emitted no commands and can release its allocations immediately. + state.retain(prepared); + barriers(list, &[uav_barrier(None)]); + let base = &*(native_vtable(list) as *const _ as *const ID3D12GraphicsCommandList_Vtbl); + for (original, offset, target, bytes) in copies { + barriers(list, &[transition(&original, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + (base.CopyBufferRegion)(list.as_raw(), target.as_raw(), 0, original.as_raw(), offset, bytes); + barriers(list, &[ + transition(&original, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON), + transition(&target, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + ]); + } + let native = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: result.GetGPUVirtualAddress(), Inputs: inputs, + ScratchAccelerationStructureData: scratch.GetGPUVirtualAddress(), ..Default::default() + }; + (native_vtable(list).BuildRaytracingAccelerationStructure)(list.as_raw(), &native, 0, std::ptr::null()); + barriers(list, &[uav_barrier(Some(&result))]); + let built = HostAs { resource: result, bytes: info.ResultDataMaxSizeInBytes, kind: inputs.Type }; + state.structures.insert(desc.DestAccelerationStructureData, built.clone()); + Ok(built) +} + +unsafe fn record_copy_on( + state: &mut State, dev: &ID3D12Device5, list: &ID3D12GraphicsCommandList4, + dest: u64, source: u64, mode: i32, +) -> Result { + let old = state.structures.get(&source).cloned(); + let previous = state.structures.remove(&dest); + if previous.is_some_and(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) + || old.as_ref().is_some_and(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) { + state.structures.retain(|_, value| value.kind != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); + } + if dest == 0 || (mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE.0 + && mode != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT.0) { + return Err("unsupported shadow copy mode or destination".into()); + } + let old = old.ok_or("shadow copy source is unavailable")?; + let mut prepared = Prepared::new(LIMIT - state.bytes); + let result = prepared.buffer(dev, old.bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE)?; + state.retain(prepared); + (native_vtable(list).CopyRaytracingAccelerationStructure)( + list.as_raw(), result.GetGPUVirtualAddress(), old.resource.GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, + ); + barriers(list, &[uav_barrier(Some(&result))]); + let copied = HostAs { resource: result, ..old }; + state.structures.insert(dest, copied.clone()); + Ok(copied) +} + #[cfg(test)] mod tests; diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs index 39792d093..9ac4662d4 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -1,4 +1,5 @@ use super::*; +use std::mem::size_of_val; #[test] fn descriptor_capture_checks_spans_and_preserves_records() { @@ -29,12 +30,16 @@ fn packed_vertex_spans_exclude_unused_alpha_and_check_overflow() { } #[test] -fn gpu_native_input_budget_and_adopted_device() { - use crate::gpu::recomp::{runner}; +fn gpu_shadow_dxr_builds_and_clones_blas_then_traces_a_tlas() { + use crate::gpu::recomp::{dxc, runner}; use windows::Win32::Graphics::Direct3D::*; use windows::Win32::Graphics::Dxgi::*; unsafe { + if dxc::location().is_err() { + runner::skip_test("no DXC"); + return; + } let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { runner::skip_test("no DXGI factory"); return; @@ -59,20 +64,175 @@ fn gpu_native_input_budget_and_adopted_device() { return; } println!("Host DXR fixture on {}", crate::gpu::adapter::name(&desc)); - let mut prepared = Prepared::new(2 * 65536); - let buffer = prepared.buffer(&dev, 36, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON).unwrap(); - assert_eq!(prepared.bytes, 65536); - let source = |address, bytes| (address == 17 && bytes == 36).then(|| (buffer.clone(), 0)); - let copied = prepared.input(&dev, 17, 36, &source).unwrap(); - assert_ne!(copied, buffer.GetGPUVirtualAddress()); - assert_eq!(prepared.bytes, 2 * 65536); - assert_eq!(prepared.copies.len(), 1); - assert!(prepared.input(&dev, 17, 36, &source).is_err()); - assert_eq!(prepared.bytes, 2 * 65536); - assert!(prepared.input(&dev, 18, 36, &source).is_err()); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList4 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let mut allocations = Prepared::new(LIMIT); + let vertices = [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let vertex_bytes = std::slice::from_raw_parts(vertices.as_ptr().cast::(), size_of_val(&vertices)); + let upload = allocations.buffer(&dev, vertex_bytes.len() as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ).unwrap(); + let mut mapped = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(vertex_bytes.as_ptr(), mapped.cast(), vertex_bytes.len()); + upload.Unmap(0, None); + let vertex_buffer = allocations.buffer(&dev, vertex_bytes.len() as u64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST).unwrap(); + list.CopyBufferRegion(&vertex_buffer, 0, &upload, 0, vertex_bytes.len() as u64); + list.ResourceBarrier(&[transition(&vertex_buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + + let console_vertices = 0x100000u64; + let console_blas = 0x200000u64; + let console_clone = 0x280000u64; + let console_tlas = 0x300000u64; + let geometry = D3D12_RAYTRACING_GEOMETRY_DESC { + Type: D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, + Flags: D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE, + Anonymous: D3D12_RAYTRACING_GEOMETRY_DESC_0 { + Triangles: D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { + VertexFormat: DXGI_FORMAT_R32G32B32_FLOAT, + VertexCount: 3, + VertexBuffer: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { StartAddress: console_vertices, StrideInBytes: 12 }, + ..Default::default() + }, + }, + }; + let bottom = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: console_blas, + Inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL, + NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { pGeometryDescs: &geometry }, + ..Default::default() + }, + ..Default::default() + }; + let source = |address, bytes| { + (address == console_vertices && bytes <= vertex_bytes.len() as u64).then(|| (vertex_buffer.clone(), 0)) + }; + let mut state = State::default(); + let blas = record_on(&mut state, &dev, &list, &bottom, &source).unwrap(); + assert_eq!(state.structures.len(), 1); + let cloned = record_copy_on(&mut state, &dev, &list, console_clone, console_blas, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT.0).unwrap(); + assert_ne!(blas.resource.GetGPUVirtualAddress(), cloned.resource.GetGPUVirtualAddress()); + + let mut instance = [0u8; 64]; + for i in 0..3 { + instance[(i * 4 + i) * 4..(i * 4 + i + 1) * 4].copy_from_slice(&1.0f32.to_le_bytes()); + } + instance[48..52].copy_from_slice(&(0xffu32 << 24).to_le_bytes()); + instance[56..64].copy_from_slice(&console_clone.to_le_bytes()); + let top = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: console_tlas, + Inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL, + NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { InstanceDescs: instance.as_ptr() as u64 }, + ..Default::default() + }, + ..Default::default() + }; + let tlas = record_on(&mut state, &dev, &list, &top, &source).unwrap(); + assert_eq!(state.structures.len(), 3); + let cs = dxc::compile(r#" +RaytracingAccelerationStructure scene : register(t0); +RWByteAddressBuffer output : register(u0); +[numthreads(1,1,1)] +void main(uint3 id : SV_DispatchThreadID) { + RayDesc ray; + ray.Origin = id.x == 0 ? float3(0.25, 0.25, 1) : float3(2, 2, 1); + ray.Direction = float3(0, 0, -1); + ray.TMin = 0; + ray.TMax = 10; + RayQuery q; + q.TraceRayInline(scene, RAY_FLAG_NONE, 0xff, ray); + while(q.Proceed()) {} + output.Store(id.x * 4, q.CommittedStatus() == COMMITTED_TRIANGLE_HIT ? asuint(q.CommittedRayT()) : 0xffffffff); +} +"#, "main", "cs_6_6", &[]).unwrap(); + let parameters = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ..Default::default() + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ..Default::default() + }, + ]; + let root_desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 2, pParameters: parameters.as_ptr(), ..Default::default() }; + let mut serialized = None; + D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut serialized, None).unwrap(); + let serialized = serialized.unwrap(); + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(serialized.GetBufferPointer().cast(), serialized.GetBufferSize())).unwrap(); + let pipeline: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(std::mem::transmute_copy(&root))), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr().cast(), BytecodeLength: cs.len() }, + ..Default::default() + }).unwrap(); + let output = allocations.buffer(&dev, 8, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS).unwrap(); + let readback = allocations.buffer(&dev, 8, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST).unwrap(); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetComputeRootShaderResourceView(0, tlas.resource.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, output.GetGPUVirtualAddress()); + list.Dispatch(2, 1, 1); + list.ResourceBarrier(&[transition(&output, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&readback, 0, &output, 0, 8); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &base, None, 30000).unwrap(); + let mut mapped = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let hits = std::slice::from_raw_parts(mapped.cast::(), 2); + let console = crate::gpu::bvh::build(&[vertices], 0); + let scene = crate::gpu::bvh::build_top(&[crate::gpu::bvh::Instance { + transform: [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]], + id: 0, mask: 0xff, contribution: 0, flags: 0, + blas_address: console_clone, blas_root: console.root, blas_bounds: console.bounds(), + }]); + let expected = [[0.25, 0.25, 1.], [2., 2., 1.]].map(|origin| { + scene.trace_scene(&|address| (address == console_clone).then_some(console.data.as_slice()), + origin, [0., 0., -1.], 10.).map_or(u32::MAX, |hit| hit.0.to_bits()) + }); + assert_eq!(expected, [1.0f32.to_bits(), u32::MAX]); + assert_eq!(hits, expected); + readback.Unmap(0, None); + assert!(blas.resource.GetGPUVirtualAddress() != console_blas); + assert!(state.bytes <= LIMIT); + let mut invalid = State { structures: state.structures.clone(), ..Default::default() }; + let mut empty = bottom; + empty.Inputs.NumDescs = 0; + assert!(record_on(&mut invalid, &dev, &list, &empty, &source).is_err()); + assert!(!invalid.structures.contains_key(&console_tlas)); + assert!(invalid.retained.is_empty()); + *STATES.lock().unwrap() = Some(HashMap::from([(usize::MAX, State { + structures: state.structures.clone(), ..Default::default() + })])); + forget(console_blas); + let mut captured = STATES.lock().unwrap().take().unwrap(); + let captured = captured.remove(&usize::MAX).unwrap(); + assert!(!captured.structures.contains_key(&console_blas)); + assert!(!captured.structures.contains_key(&console_tlas)); + assert!(captured.structures.contains_key(&console_clone)); + let mut full = State { structures: state.structures.clone(), bytes: LIMIT, ..Default::default() }; + assert!(record_on(&mut full, &dev, &list, &bottom, &source).is_err()); + assert!(!full.structures.contains_key(&console_blas)); + assert!(!full.structures.contains_key(&console_tlas)); + assert_eq!(full.bytes, LIMIT); + assert!(full.retained.is_empty()); let native = native_vtable(&dev) as *const _; real::adopt(dev.as_raw(), real::Kind::Device); + assert!(real::is_adopted(dev.as_raw())); assert_eq!(native_vtable(&dev) as *const _, native); - println!("Native input copies respect the committed allocation cap on an adopted device"); + let mut probe = Prepared::new(65536); + let buffer = probe.buffer(&dev, 256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ).unwrap(); + assert_eq!(probe.bytes, 65536); + assert!(!real::is_adopted(buffer.as_raw())); + assert!(probe.buffer(&dev, 256, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ).is_err()); + println!("Shadow BLAS, compact-copy and TLAS matched console BVH hit distance and miss"); } } From 16b46ee406b6aefa387497779197cc00a7f2c95e Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:25:18 +0500 Subject: [PATCH 4/7] D3D12.X: observe XboxBvhBuilder batched exports Forward the original builder calls, then record bounded shadow builds on the active recording segment. Rehydration invalidates captured mappings because its additional transforms are not reproduced. The observer is disabled unless explicitly requested. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- README.md | 8 + crates/xcl/src/hle/d3d12x/host_bvh.rs | 164 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 53 +++++++ crates/xcl/src/hle/d3d12x/title_list.rs | 11 ++ crates/xcl/src/resolver.rs | 5 +- 5 files changed, 237 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d9d151320..8b31eeb1d 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,14 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. +- `XCL_HOST_DXR=1` enables an experimental shadow-build capture of XboxBvhBuilder + build, rehydrate and copy calls on DXR 1.1 devices. It snapshots triangle inputs from + mapped UMA windows and rewrites readable CPU instance arrays to native BLAS addresses. + Compressed rehydration, command-buffer replay, procedural geometry and GPU-generated + instance arrays are not supported. Rehydration invalidates earlier shadow mappings. + Native buffers are retained until exit with a 256 MiB allocation budget + per device. Translated shaders still use the console BVH, so this diagnostic mode + adds GPU work and does not accelerate rendering yet. It is disabled by default. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/hle/d3d12x/host_bvh.rs b/crates/xcl/src/hle/d3d12x/host_bvh.rs index 3279fabb9..785a47eb1 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh.rs @@ -1,5 +1,7 @@ -//! Bounded input preparation for a future opt-in native acceleration-structure path. -#![allow(dead_code, unused_imports)] +//! Opt-in shadow DXR builds from XboxBvhBuilder calls. The title keeps its console BVH. +//! This build-only prototype retains at most 256 MiB of native buffers until process exit. +//! Geometry inputs are copied on the active recording list. TLAS capture requires readable +//! CPU instance descriptors. No translated shader consumes the shadow structures yet. use std::collections::HashMap; use std::ffi::c_void; @@ -13,10 +15,122 @@ use windows::Win32::Graphics::Dxgi::Common::*; use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; -use super::real; +use crate::modules::MappedModule; +use crate::pe::{ExportTarget, ImportName}; +use super::{console_list, real, title_list}; const LIMIT: u64 = 256 << 20; const MAX_DESCS: usize = 8192; +const BUILD: &str = "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +const REHYDRATE: &str = "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; +const COPY: &str = "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; + +static BUILD_FN: AtomicUsize = AtomicUsize::new(0); +static REHYDRATE_FN: AtomicUsize = AtomicUsize::new(0); +static COPY_FN: AtomicUsize = AtomicUsize::new(0); + +#[repr(C)] +#[derive(Clone, Copy)] +struct BatchedDesc { + build: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, + postbuild_count: u32, + _padding: u32, + postbuild: *const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, + _tail: [u64; 2], +} + +fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_HOST_DXR").is_ok_and(|v| v == "1")) +} + +fn replacement(name: &str, original: usize) -> Option { + let (saved, hook) = match name { + BUILD => (&BUILD_FN, build as usize), + REHYDRATE => (&REHYDRATE_FN, rehydrate as usize), + COPY => (©_FN, copy as usize), + _ => return None, + }; + match saved.compare_exchange(0, original, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + crate::xlog_info!("Host DXR: observing {} calls", name.split('@').next().unwrap_or(name)); + Some(hook) + } + Err(existing) => (existing == original).then_some(hook), + } +} + +/// The same path handles static imports, delay imports and GetProcAddress. +pub(crate) fn intercept(module: &MappedModule, what: &ImportName, rva: u32, original: usize) -> usize { + if module.name != "xboxbvhbuilder.dll" || !enabled() { + return original; + } + let name = match what { + ImportName::Name { name, .. } => Some(name.as_str()), + ImportName::Ordinal(_) => module.exports.by_name.iter().find_map(|(name, target)| { + matches!(target, ExportTarget::Rva(value) if *value == rva).then_some(name.as_str()) + }), + }; + name.and_then(|name| replacement(name, original)).unwrap_or(original) +} + +unsafe extern "system-unwind" fn build(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) { + let original: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u32, *const BatchedDesc) = + std::mem::transmute(BUILD_FN.load(Ordering::Acquire)); + original(this, list, count, descs); + observe(|| { + for desc in read_items::(descs as usize, count as usize)? { + observe(|| record(list, &desc.build)); + } + Ok(()) + }); +} + +unsafe extern "system-unwind" fn rehydrate( + this: *mut c_void, list: *mut c_void, count: u32, + descs: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, sources: *const u64, +) -> i32 { + let original: unsafe extern "system-unwind" fn( + *mut c_void, *mut c_void, u32, *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, *const u64, + ) -> i32 = std::mem::transmute(REHYDRATE_FN.load(Ordering::Acquire)); + let result = original(this, list, count, descs, sources); + if result >= 0 { + observe(|| { + for desc in read_items::(descs as usize, count as usize)? { + forget(desc.DestAccelerationStructureData); + } + // Rehydration applies scale, translation and format transforms from its compressed + // source header. Rebuilding the input geometry alone would produce a different BLAS. + if count == 0 { Ok(()) } else { Err("compressed rehydration transforms are not captured".into()) } + }); + } + result +} + +unsafe extern "system-unwind" fn copy(this: *mut c_void, list: *mut c_void, dest: u64, source: u64, mode: i32) { + let original: unsafe extern "system-unwind" fn(*mut c_void, *mut c_void, u64, u64, i32) = + std::mem::transmute(COPY_FN.load(Ordering::Acquire)); + original(this, list, dest, source, mode); + observe(|| { + let list = recording_list(list)?; + let dev = device(&list)?; + let mut states = STATES.lock().unwrap(); + let state = states.get_or_insert_with(HashMap::new).entry(dev.as_raw() as usize).or_default(); + record_copy_on(state, &dev, &list, dest, source, mode)?; + Ok(()) + }); +} + +fn observe(run: impl FnOnce() -> Result<(), String>) { + if let Err(error) = run() { + static ERRORS: AtomicU64 = AtomicU64::new(0); + let count = ERRORS.fetch_add(1, Ordering::Relaxed) + 1; + if count <= 8 || count.is_power_of_two() { + crate::xlog_info!("Host DXR: shadow build skipped ({count}): {error}"); + } + } +} + // All T at the call sites are POD descriptor records or integer words. unsafe fn read_items(address: usize, count: usize) -> Result, String> { let bytes = count.checked_mul(size_of::()).ok_or("descriptor size overflow")?; @@ -48,6 +162,32 @@ unsafe fn native_vtable(object: &T) -> &T::Vtable { } } +unsafe fn recording_list(list: *mut c_void) -> Result { + if list.is_null() || !crate::gpu::shader::readable(list as usize, size_of::()) { + return Err("command list is unavailable".into()); + } + if console_list::pc_list(list).is_some() { + return Err("command-buffer replay is not supported by shadow DXR".into()); + } + let raw = title_list::recording(list).unwrap_or(list); + ID3D12GraphicsCommandList::from_raw_borrowed(&raw).ok_or("invalid command list")? + .cast().map_err(|e| format!("command list has no DXR interface: {e}")) +} + +unsafe fn device(list: &ID3D12GraphicsCommandList4) -> Result { + let mut dev: Option = None; + list.GetDevice(&mut dev).map_err(|e| e.to_string())?; + let dev = dev.ok_or("command list has no device")?; + let base = &*(native_vtable(&dev) as *const _ as *const ID3D12Device_Vtbl); + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS5::default(); + (base.CheckFeatureSupport)(dev.as_raw(), D3D12_FEATURE_D3D12_OPTIONS5, (&mut options as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS5).cast(), size_of::() as u32) + .ok().map_err(|e| e.to_string())?; + if options.RaytracingTier.0 < D3D12_RAYTRACING_TIER_1_1.0 { + return Err("host does not support DXR 1.1".into()); + } + Ok(dev) +} + #[derive(Clone)] struct HostAs { resource: ID3D12Resource, @@ -244,6 +384,24 @@ unsafe fn barriers(list: &ID3D12GraphicsCommandList4, barriers: &[D3D12_RESOURCE (base.ResourceBarrier)(list.as_raw(), barriers.len() as u32, barriers.as_ptr()); } +unsafe fn record(list: *mut c_void, desc: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) -> Result<(), String> { + let list = recording_list(list)?; + let dev = device(&list)?; + let mut states = STATES.lock().unwrap(); + let state = states.get_or_insert_with(HashMap::new).entry(dev.as_raw() as usize).or_default(); + let source = |address: u64, bytes: u64| { + let (raw, offset) = real::uma_window_buffer(address as usize, usize::try_from(bytes).ok()?)?; + let raw = raw as *mut c_void; + Some((ID3D12Resource::from_raw_borrowed(&raw)?.clone(), offset)) + }; + record_on(state, &dev, &list, desc, &source)?; + state.recorded += 1; + if state.recorded <= 8 || state.recorded.is_power_of_two() { + crate::xlog_info!("Host DXR: {} shadow builds recorded, {} KiB retained", state.recorded, state.bytes >> 10); + } + Ok(()) +} + unsafe fn record_on( state: &mut State, dev: &ID3D12Device5, list: &ID3D12GraphicsCommandList4, desc: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs index 9ac4662d4..3daff1ea4 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -1,6 +1,15 @@ use super::*; use std::mem::size_of_val; +#[test] +fn captured_descriptors_follow_the_observed_abi() { + assert_eq!(size_of::(), 80); + assert_eq!(size_of::(), 48); + assert_eq!(std::mem::offset_of!(BatchedDesc, postbuild_count), 48); + assert_eq!(std::mem::offset_of!(BatchedDesc, postbuild), 56); + assert_eq!(size_of::(), 56); +} + #[test] fn descriptor_capture_checks_spans_and_preserves_records() { unsafe { @@ -13,6 +22,12 @@ fn descriptor_capture_checks_spans_and_preserves_records() { } } +#[test] +fn unsupported_exports_keep_the_native_target() { + assert!(replacement("BuildRaytracingAccelerationStructure", 1).is_none()); + assert!(replacement("?Unrelated@XboxBvhBuilder@@", 1).is_none()); +} + #[test] fn packed_vertex_spans_exclude_unused_alpha_and_check_overflow() { let mut triangle = D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { @@ -29,6 +44,44 @@ fn packed_vertex_spans_exclude_unused_alpha_and_check_overflow() { assert!(vertex_span(&triangle).is_err()); } +#[test] +fn hooks_forward_arguments_and_preserve_rehydrate_failure() { + unsafe extern "system-unwind" fn original_build(this: *mut c_void, list: *mut c_void, count: u32, descs: *const BatchedDesc) { + assert_eq!(list as usize, 17); + assert_eq!(count, 0); + assert!(descs.is_null()); + *(this as *mut u32) += 1; + } + unsafe extern "system-unwind" fn original_rehydrate(this: *mut c_void, list: *mut c_void, count: u32, + descs: *const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, sources: *const u64) -> i32 { + assert_eq!(list as usize, 29); + assert_eq!(count, 3); + assert_eq!(descs as usize, 41); + assert_eq!(sources as usize, 53); + *(this as *mut u32) += 1; + -7 + } + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { + BUILD_FN.store(0, Ordering::Release); + REHYDRATE_FN.store(0, Ordering::Release); + } + } + let _reset = Reset; + assert_eq!(replacement(BUILD, original_build as usize), Some(build as usize)); + assert_eq!(replacement(BUILD, original_build as usize), Some(build as usize)); + assert_eq!(replacement(BUILD, 1), None); + assert_eq!(replacement(REHYDRATE, original_rehydrate as usize), Some(rehydrate as usize)); + let mut calls = 0u32; + unsafe { + let this = (&mut calls as *mut u32).cast(); + build(this, 17usize as *mut c_void, 0, std::ptr::null()); + assert_eq!(rehydrate(this, 29usize as *mut c_void, 3, 41usize as *const _, 53usize as *const _), -7); + } + assert_eq!(calls, 2); +} + #[test] fn gpu_shadow_dxr_builds_and_clones_blas_then_traces_a_tlas() { use crate::gpu::recomp::{dxc, runner}; diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 05de94b66..874d00afc 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -213,6 +213,12 @@ pub fn backing(list: *mut c_void) -> Option<*mut c_void> { unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_PRIMARY) as *const *mut c_void)) } } +/// The PC list currently recording this wrapper, including a mid-list split. +pub(super) fn recording(list: *mut c_void) -> Option<*mut c_void> { + backing(list)?; + Some(unsafe { *((list as usize + F_BACKING) as *const *mut c_void) }) +} + /// Expand a console list object into all of its recorded PC command list segments (in exact /// recording order). Returns `false` if `list` is not a `title_list` wrapper. pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { @@ -417,6 +423,11 @@ mod tests { unsafe { let o = wrap(fake as *mut c_void); assert_eq!(backing(o), Some(fake as *mut c_void)); + assert_eq!(recording(o), Some(fake as *mut c_void)); + *((o as usize + F_BACKING) as *mut usize) = 17; + assert_eq!(recording(o), Some(17usize as *mut c_void)); + assert_eq!(backing(o), Some(fake as *mut c_void)); + *((o as usize + F_BACKING) as *mut usize) = fake as usize; assert_eq!(backing(fake as *mut c_void), None); let (w, e) = (*((o as usize + F_WRITE) as *const usize), *((o as usize + F_END) as *const usize)); assert!(w >= e && *((o as usize + F_DISPATCH_END) as *const usize) == w); diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index 7882042e3..8b95c4d13 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -175,7 +175,10 @@ fn resolve_export_of_mapped_inner( ImportName::Ordinal(o) => m.exports.by_ordinal.get(&(*o as u32))?, }; match t { - ExportTarget::Rva(r) => Some(m.base + *r as usize), + ExportTarget::Rva(r) => { + let original = m.base + *r as usize; + Some(crate::hle::d3d12x::host_bvh::intercept(m, what, *r, original)) + } ExportTarget::Forwarder(f) => { if depth > 8 { return None; From 95b1f11aafa381df9352e6860c7dffb5ff828ab5 Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:28:15 +0500 Subject: [PATCH 5/7] D3D12.X: scope native AS bindings to live recordings Track compatible native structures by UMA range and recording owner. Invalidate bindings on reset, release and page remapping; cross-recording consumers retain the console path. Shader consumption is added separately. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- crates/xcl/src/gpu/uma.rs | 6 + crates/xcl/src/hle/d3d12x/host_bvh.rs | 141 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 64 ++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 3 + crates/xcl/src/hle/d3d12x/title_list.rs | 2 + crates/xcl/src/hle/kernelx.rs | 6 + 6 files changed, 207 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b..37e4e3b6a 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -465,6 +465,8 @@ impl Uma { len += l; } g.0.insert(start, len); + drop(g); + crate::hle::d3d12x::host_bvh::forget_range(p, size); Some(size) } @@ -689,6 +691,8 @@ impl Uma { let mut g = self.pool.lock().unwrap(); if p >= g.0 && p < g.1 { g.2.push(p); + drop(g); + crate::hle::d3d12x::host_bvh::forget_range(p, ARENA_BLOCK); return true; } } @@ -708,6 +712,8 @@ impl Uma { len += l; } g.free.insert(start, len); + drop(g); + crate::hle::d3d12x::host_bvh::forget_range(p, orig); true } diff --git a/crates/xcl/src/hle/d3d12x/host_bvh.rs b/crates/xcl/src/hle/d3d12x/host_bvh.rs index 785a47eb1..7934bba84 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh.rs @@ -1,7 +1,7 @@ //! Opt-in shadow DXR builds from XboxBvhBuilder calls. The title keeps its console BVH. -//! This build-only prototype retains at most 256 MiB of native buffers until process exit. +//! This experimental capture retains at most 256 MiB of native buffers until process exit. //! Geometry inputs are copied on the active recording list. TLAS capture requires readable -//! CPU instance descriptors. No translated shader consumes the shadow structures yet. +//! CPU instance descriptors. Query bindings are prepared for a later shader consumer. use std::collections::HashMap; use std::ffi::c_void; @@ -41,7 +41,21 @@ struct BatchedDesc { fn enabled() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_HOST_DXR").is_ok_and(|v| v == "1")) + *ON.get_or_init(|| std::env::var("XCL_HOST_DXR").is_ok_and(|v| v == "1") || query_requested()) +} + +pub(crate) fn query_requested() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_HOST_RAYQUERY").is_ok_and(|v| v == "1")) +} + +pub(crate) fn query_supported() -> bool { + if !query_requested() { return false; } + unsafe { + let raw = real::device_raw(); + let Some(dev) = ID3D12Device::from_raw_borrowed(&raw) else { return false }; + dev.cast::().is_ok_and(|dev| supports_dxr(&dev).is_ok()) + } } fn replacement(name: &str, original: usize) -> Option { @@ -178,21 +192,30 @@ unsafe fn device(list: &ID3D12GraphicsCommandList4) -> Result = None; list.GetDevice(&mut dev).map_err(|e| e.to_string())?; let dev = dev.ok_or("command list has no device")?; - let base = &*(native_vtable(&dev) as *const _ as *const ID3D12Device_Vtbl); + supports_dxr(&dev)?; + Ok(dev) +} + +unsafe fn supports_dxr(dev: &ID3D12Device5) -> Result<(), String> { + let base = &*(native_vtable(dev) as *const _ as *const ID3D12Device_Vtbl); let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS5::default(); (base.CheckFeatureSupport)(dev.as_raw(), D3D12_FEATURE_D3D12_OPTIONS5, (&mut options as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS5).cast(), size_of::() as u32) .ok().map_err(|e| e.to_string())?; if options.RaytracingTier.0 < D3D12_RAYTRACING_TIER_1_1.0 { return Err("host does not support DXR 1.1".into()); } - Ok(dev) + Ok(()) } #[derive(Clone)] struct HostAs { resource: ID3D12Resource, bytes: u64, + guest_bytes: u64, kind: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE, + opaque: bool, + serial: u64, + owner: usize, } #[derive(Default)] @@ -203,6 +226,7 @@ struct State { retained: Vec, bytes: u64, recorded: u64, + serial: u64, } impl State { @@ -214,6 +238,66 @@ impl State { static STATES: Mutex>> = Mutex::new(None); +/// A reset or released recording no longer proves producer-before-consumer ordering. +pub(super) fn forget_list(list: usize) { + if let Some(states) = STATES.lock().unwrap().as_mut() { + for state in states.values_mut() { + let bottom_removed = state.structures.values().any(|s| s.owner == list + && s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL); + state.structures.retain(|_, s| s.owner != list + && !(bottom_removed && s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL)); + } + } +} + +/// Freed or remapped console memory cannot keep naming a previously captured AS. +pub(crate) fn forget_range(base: usize, bytes: usize) { + if bytes == 0 { return; } + let end = base.saturating_add(bytes) as u64; + if let Some(states) = STATES.lock().unwrap().as_mut() { + for state in states.values_mut() { + let mut bottom_removed = false; + state.structures.retain(|&address, value| { + let overlap = address < end && (base as u64) < address.saturating_add(value.guest_bytes); + bottom_removed |= overlap && value.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + !overlap + }); + if bottom_removed { state.structures.retain(|_, s| s.kind != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); } + } + } +} + +pub(super) struct QueryBinding { + pub console: u64, + pub native: u64, +} + +pub(super) unsafe fn query_binding(list: &ID3D12GraphicsCommandList) -> Option { + if !query_requested() { return None; } + let mut dev: Option = None; + list.GetDevice(&mut dev).ok()?; + let dev = dev?; + let states = STATES.lock().unwrap(); + let state = states.as_ref()?.get(&(dev.as_raw() as usize))?; + // Other addresses keep the original traversal; prefer the most recent compatible TLAS. + let (&console, value) = state.structures.iter().filter(|(_, value)| { + value.opaque && value.owner == list.as_raw() as usize + && value.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL + }).max_by_key(|(_, value)| value.serial)?; + static LAST: AtomicU64 = AtomicU64::new(0); + if LAST.swap(console, Ordering::Relaxed) != console { + crate::xlog_info!("Host RayQuery: native TLAS available at console {console:#x}, generation {}", value.serial); + } + Some(QueryBinding { console, native: value.resource.GetGPUVirtualAddress() }) +} + +fn managed_span(address: u64, bytes: u64) -> bool { + crate::gpu::uma::get().is_some_and(|u| { + bytes != 0 && u.contains(address as usize) + && address.checked_add(bytes - 1).is_some_and(|end| u.contains(end as usize)) + }) +} + fn forget(dest: u64) { if let Some(states) = STATES.lock().unwrap().as_mut() { for state in states.values_mut() { @@ -268,7 +352,8 @@ impl Prepared { &mut self, dev: &ID3D12Device5, address: u64, bytes: u64, source: &dyn Fn(u64, u64) -> Option<(ID3D12Resource, u64)>, ) -> Result { - let (original, offset) = source(address, bytes).ok_or("geometry range is outside a mapped UMA window")?; + let (original, offset) = source(address, bytes) + .ok_or_else(|| format!("geometry {address:#x} ({bytes} bytes) is outside a mapped UMA window"))?; let buffer = self.buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST)?; let address = buffer.GetGPUVirtualAddress(); self.copies.push((original, offset, buffer, bytes)); @@ -332,8 +417,8 @@ unsafe fn geometry( unsafe fn instances( prepared: &mut Prepared, dev: &ID3D12Device5, inputs: &D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, - structures: &HashMap, -) -> Result { + structures: &HashMap, owner: usize, +) -> Result<(u64, bool), String> { if inputs.DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY { return Err("shadow TLAS requires a contiguous instance array".into()); } @@ -342,11 +427,24 @@ unsafe fn instances( let cpu = crate::hle::kernelx::mirrors::source(address).ok_or(error)?; read_items(cpu, inputs.NumDescs as usize) })?; + let mut opaque = true; for instance in &mut instances { let console = u64::from_le_bytes(instance[56..64].try_into().unwrap()); let native = structures.get(&console) .filter(|s| s.kind == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) .ok_or("TLAS references a BLAS without a shadow build")?; + if native.owner != owner { + return Err("TLAS references a BLAS from another recording".into()); + } + opaque &= native.opaque && native.owner == owner && instance[51] == 0xff && instance[55] == 0; + // First consumer is verified for translation-only instances, without winding overrides. + for row in 0..3 { + for column in 0..4 { + let at = (row * 4 + column) * 4; + let value = f32::from_le_bytes(instance[at..at + 4].try_into().unwrap()); + opaque &= value.is_finite() && (column == 3 || value == if row == column { 1. } else { 0. }); + } + } instance[56..64].copy_from_slice(&native.resource.GetGPUVirtualAddress().to_le_bytes()); } let bytes = size_of::<[u8; 64]>() * instances.len(); @@ -355,7 +453,7 @@ unsafe fn instances( upload.Map(0, None, Some(&mut mapped)).map_err(|e| e.to_string())?; std::ptr::copy_nonoverlapping(instances.as_ptr().cast::(), mapped.cast(), bytes); upload.Unmap(0, None); - Ok(upload.GetGPUVirtualAddress()) + Ok((upload.GetGPUVirtualAddress(), opaque)) } unsafe fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { @@ -419,14 +517,25 @@ unsafe fn record_on( let mut inputs = desc.Inputs; inputs.Flags &= !D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE; let geometries; + let opaque; + let guest_bytes; match inputs.Type { D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL => { geometries = geometry(&mut prepared, dev, &inputs, source)?; + opaque = geometries.iter().all(|g| g.Flags.0 & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE.0 != 0 && g.Anonymous.Triangles.Transform3x4 == 0); + let triangles = geometries.iter().map(|g| { + let t = g.Anonymous.Triangles; + u64::from(if t.IndexCount == 0 { t.VertexCount } else { t.IndexCount }) / 3 + }).sum(); + guest_bytes = crate::gpu::bvh::prebuild_size(triangles, false); inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; inputs.Anonymous.pGeometryDescs = geometries.as_ptr(); } D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL => { - inputs.Anonymous.InstanceDescs = instances(&mut prepared, dev, &inputs, &state.structures)?; + let (address, compatible) = instances(&mut prepared, dev, &inputs, &state.structures, list.as_raw() as usize)?; + inputs.Anonymous.InstanceDescs = address; + opaque = compatible; + guest_bytes = crate::gpu::bvh::prebuild_size(inputs.NumDescs as u64, true); } _ => return Err("unsupported acceleration structure type".into()), } @@ -454,7 +563,10 @@ unsafe fn record_on( }; (native_vtable(list).BuildRaytracingAccelerationStructure)(list.as_raw(), &native, 0, std::ptr::null()); barriers(list, &[uav_barrier(Some(&result))]); - let built = HostAs { resource: result, bytes: info.ResultDataMaxSizeInBytes, kind: inputs.Type }; + // Only the UMA allocation/remapping hooks currently invalidate native query bindings. + let opaque = opaque && managed_span(desc.DestAccelerationStructureData, guest_bytes); + state.serial += 1; + let built = HostAs { resource: result, bytes: info.ResultDataMaxSizeInBytes, guest_bytes, kind: inputs.Type, opaque, serial: state.serial, owner: list.as_raw() as usize }; state.structures.insert(desc.DestAccelerationStructureData, built.clone()); Ok(built) } @@ -474,6 +586,9 @@ unsafe fn record_copy_on( return Err("unsupported shadow copy mode or destination".into()); } let old = old.ok_or("shadow copy source is unavailable")?; + if old.owner != list.as_raw() as usize { + return Err("shadow copy source belongs to another recording".into()); + } let mut prepared = Prepared::new(LIMIT - state.bytes); let result = prepared.buffer(dev, old.bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE)?; state.retain(prepared); @@ -482,7 +597,9 @@ unsafe fn record_copy_on( D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE, ); barriers(list, &[uav_barrier(Some(&result))]); - let copied = HostAs { resource: result, ..old }; + state.serial += 1; + let opaque = old.opaque && old.owner == list.as_raw() as usize && managed_span(dest, old.guest_bytes); + let copied = HostAs { resource: result, opaque, serial: state.serial, owner: list.as_raw() as usize, ..old }; state.structures.insert(dest, copied.clone()); Ok(copied) } diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs index 3daff1ea4..b4b7cd19a 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -133,9 +133,19 @@ fn gpu_shadow_dxr_builds_and_clones_blas_then_traces_a_tlas() { list.ResourceBarrier(&[transition(&vertex_buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); let console_vertices = 0x100000u64; - let console_blas = 0x200000u64; - let console_clone = 0x280000u64; - let console_tlas = 0x300000u64; + let uma = crate::gpu::uma::get().unwrap(); + let span = uma.alloc(3 * 65536, 65536).unwrap() as usize; + struct Span(usize); + impl Drop for Span { + fn drop(&mut self) { + forget_range(self.0, 3 * 65536); + crate::gpu::uma::get().unwrap().free(self.0); + } + } + let _span = Span(span); + let console_blas = span as u64; + let console_clone = console_blas + 65536; + let console_tlas = console_clone + 65536; let geometry = D3D12_RAYTRACING_GEOMETRY_DESC { Type: D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, Flags: D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE, @@ -186,6 +196,7 @@ fn gpu_shadow_dxr_builds_and_clones_blas_then_traces_a_tlas() { }; let tlas = record_on(&mut state, &dev, &list, &top, &source).unwrap(); assert_eq!(state.structures.len(), 3); + assert!(blas.opaque && cloned.opaque && tlas.opaque); let cs = dxc::compile(r#" RaytracingAccelerationStructure scene : register(t0); RWByteAddressBuffer output : register(u0); @@ -254,6 +265,53 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(expected, [1.0f32.to_bits(), u32::MAX]); assert_eq!(hits, expected); readback.Unmap(0, None); + if query_requested() { + *STATES.lock().unwrap() = Some(HashMap::from([(dev.as_raw() as usize, State { + structures: state.structures.clone(), ..Default::default() + })])); + let bound = query_binding(&list.cast().unwrap()).unwrap(); + assert_eq!(bound.console, console_tlas); + assert_eq!(bound.native, tlas.resource.GetGPUVirtualAddress()); + let other: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + assert!(query_binding(&other).is_none(), "another recording must not consume an unpublished build"); + let other_dxr: ID3D12GraphicsCommandList4 = other.cast().unwrap(); + let mut unpublished = State { structures: state.structures.clone(), ..Default::default() }; + assert!(record_on(&mut unpublished, &dev, &other_dxr, &top, &source).is_err(), "TLAS cannot read another recording's unpublished BLAS"); + assert!(record_copy_on(&mut unpublished, &dev, &other_dxr, console_blas + 3 * 65536, + console_clone, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE.0).is_err(), "clone cannot read another recording's unpublished AS"); + assert!(unpublished.retained.is_empty()); + other.Close().unwrap(); + forget_list(list.as_raw() as usize); + assert!(query_binding(&list.cast().unwrap()).is_none()); + *STATES.lock().unwrap() = Some(HashMap::from([(dev.as_raw() as usize, State { + structures: state.structures.clone(), ..Default::default() + })])); + // Touching a byte inside a BLAS, rather than just its base, invalidates its TLAS. + forget_range(console_blas as usize + 128, 1); + assert!(query_binding(&list.cast().unwrap()).is_none()); + let captured = STATES.lock().unwrap().take().unwrap(); + let captured = &captured[&(dev.as_raw() as usize)]; + assert!(!captured.structures.contains_key(&console_blas)); + assert!(captured.structures.contains_key(&console_clone)); + let released = uma.alloc(2 * 65536, 65536).unwrap() as usize; + *STATES.lock().unwrap() = Some(HashMap::from([(dev.as_raw() as usize, State { + structures: HashMap::from([(released as u64, blas.clone()), + (released as u64 + 65536, tlas.clone())]), ..Default::default() + })])); + assert!(query_binding(&list.cast().unwrap()).is_some()); + crate::hle::kernelx::XMemFreeDefault(released as *mut c_void, 1 << 29); + assert!(query_binding(&list.cast().unwrap()).is_none(), "XMemFree must invalidate native AS bindings"); + if let Some((released, _)) = uma.sparse_alloc(2 * 65536, 65536) { + *STATES.lock().unwrap() = Some(HashMap::from([(dev.as_raw() as usize, State { + structures: HashMap::from([(released as u64, blas.clone()), + (released as u64 + 65536, tlas.clone())]), ..Default::default() + })])); + assert!(query_binding(&list.cast().unwrap()).is_some()); + assert_eq!(uma.sparse_release(released), Some(2 * 65536)); + assert!(query_binding(&list.cast().unwrap()).is_none(), "sparse release must invalidate native AS bindings"); + } + println!("Runtime native TLAS binding and partial-range invalidation passed"); + } assert!(blas.resource.GetGPUVirtualAddress() != console_blas); assert!(state.bytes <= LIMIT); let mut invalid = State { structures: state.structures.clone(), ..Default::default() }; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 06cca160a..3abf11d7c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -791,6 +791,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { + super::host_bvh::forget_list(list); super::alloc_pool::forget_list(list); release_copy_scratch(list); super::title_textures::list_reset(list); @@ -2857,6 +2858,7 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { + super::host_bvh::forget_list(list as usize); reset_copy_scratch(list); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; @@ -3683,6 +3685,7 @@ pub unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, pso: usiz return hr; } + super::host_bvh::forget_list(this as usize); reset_copy_scratch(this); let is_bundle = { let mut g = LISTS.lock().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 874d00afc..fb8514fb9 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -153,6 +153,7 @@ unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> f(primary, alloc, pso) }; if hr >= 0 { + super::host_bvh::forget_list(primary as usize); *((this as usize + F_BACKING) as *mut usize) = primary as usize; let moved = { let mut sg = SEGMENTS.lock().unwrap(); @@ -357,6 +358,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2)); let n = f(pc); if n == 0 { + super::host_bvh::forget_list(pc as usize); let book = SEGMENTS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); { let mut wg = WRAPPER_OF.lock().unwrap(); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index afa86c30c..3f2eb77f2 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -437,6 +437,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } }; if n > 0 { + crate::hle::d3d12x::host_bvh::forget_range(a, n); // sparse first: under its lock, so no copy of CPU writes to video memory reads the // pages while they go (the submit thread's copy faulted on them) crate::hle::d3d12x::sparse::decommitted(a, n); @@ -455,6 +456,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 return u.free(addr as usize) as BOOL; } if t & 0x4000 != 0 && size > 0 { + crate::hle::d3d12x::host_bvh::forget_range(addr as usize, size); std::ptr::write_bytes(addr as *mut u8, 0, size); } return 1; @@ -907,6 +909,7 @@ pub fn gpu_view_map_gen() -> u64 { /// Pages are mapped or unmapped at `va`: a GPU view's mappings changed if it lies in one. fn note_mapping_at(va: usize) { + crate::hle::d3d12x::host_bvh::forget_range(va, PHYS_PAGE); if mirrors::source(va).is_some() { GPU_VIEW_MAP_GEN.fetch_add(1, Ordering::Release); } @@ -1030,6 +1033,7 @@ unsafe fn give_back_homes(away: &mut Away) { end += PHYS_PAGE; i += 1; } + crate::hle::d3d12x::host_bvh::forget_range(start, end - start); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(start)) { crate::hle::d3d12x::sparse::decommitted(start, end - start); } @@ -1265,10 +1269,12 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: if page >= first + count { continue; } + crate::hle::d3d12x::host_bvh::forget_range(home + (page - first) * PHYS_PAGE, PHYS_PAGE); let e = g.get_mut(&first).unwrap(); e.1 = e.1.saturating_sub(1); if e.1 == 0 { g.remove(&first); + crate::hle::d3d12x::host_bvh::forget_range(home, count * PHYS_PAGE); if u.is_sparse(home) { crate::hle::d3d12x::sparse::free(home); } else if u.contains(home) { From 190885bb24ee1b6cf18f5822b23786c57e654139 Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:29:52 +0500 Subject: [PATCH 6/7] Recompiler: identify a verified shadow traversal region Prepare an exact-program traversal matcher with control-flow guards, register-liveness assertions and sample-gated baseline GPU checks. Translation behavior is unchanged until the consumer is connected. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- crates/xcl/build.rs | 1 + crates/xcl/src/gpu/recomp/mod.rs | 4 +- crates/xcl/src/gpu/recomp/rayquery.rs | 150 ++++++++++++++++++ .../src/gpu/recomp/rayquery/test_support.rs | 91 +++++++++++ crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 2 + 5 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/gpu/recomp/rayquery.rs create mode 100644 crates/xcl/src/gpu/recomp/rayquery/test_support.rs diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index e5c182a42..d54e14f21 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -14,6 +14,7 @@ const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/recomp/emit.rs", "src/gpu/recomp/mesh_wave.rs", "src/gpu/recomp/mod.rs", + "src/gpu/recomp/rayquery.rs", "src/gpu/recomp/upper_lanes.rs", "src/gpu/recomp/x64_masks.rs", "src/gpu/shader.rs", diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4..2686e9405 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -88,6 +88,7 @@ pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) } pub mod upper_lanes; +pub(crate) mod rayquery; use std::collections::{BTreeMap, BTreeSet}; @@ -526,11 +527,12 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + pub host_rayquery: bool, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { host_rayquery: false, mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } } } diff --git a/crates/xcl/src/gpu/recomp/rayquery.rs b/crates/xcl/src/gpu/recomp/rayquery.rs new file mode 100644 index 000000000..6bae588f0 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/rayquery.rs @@ -0,0 +1,150 @@ +//! Opt-in replacement of verified whole traversal regions with inline RayQuery. + +use super::{Mode, Options}; +use crate::gpu::{rdna2, shader}; + +pub const MAGIC: u32 = 0x58445231; +pub const HOST_AS_ROOT: u32 = 6; +pub const SHADOW_RECORD: u64 = 0x9d51ce32ab9a9ab5; + +#[derive(Clone, Copy, Debug)] +pub(super) struct Region { + pub start: u64, + pub end: u64, +} + +pub(super) fn identify(code: &[u8], opt: &Options, insts: &[rdna2::Decoded]) -> Option { + if !opt.host_rayquery || !opt.structured { + return None; + } + let hash = shader::fnv64(code); + let region = if matches!(opt.mode, Mode::Compute(_)) && hash == 0x65cd3172658edef2 && code.len() == 9724 { + Region { start: 0x13d4, end: 0x1c6c } + } else { + #[cfg(test)] + if matches!(opt.mode, Mode::Kernel) && hash == 0x4f7800379203c280 && code.len() == 2204 { + return Some(Region { start: 0, end: 2200 }); + } + return None; + }; + // No entry into the middle of the replaced region, and a single continuation. + if insts.iter().any(|d| rdna2::branch_target(d).is_some_and(|target| { + let inside = d.pc >= region.start && d.pc < region.end; + (!inside && target > region.start && target < region.end) + || (inside && (target < region.start || target > region.end)) + })) { + return None; + } + Some(region) +} + + +#[cfg(test)] +pub(crate) mod test_support; + +#[cfg(test)] +mod tests { + use super::super::{dxc, runner, translate}; + use crate::gpu::{bvh, shader, xbox}; + + #[test] + fn gpu_retail_shadow_region_matches_console_scene() { + let Some(path) = std::env::var_os("XCL_SAMPLE_RAYQUERY") else { + runner::skip_test("no XCL_SAMPLE_RAYQUERY"); + return; + }; + if runner::adapter().is_err() || dxc::location().is_err() { + runner::skip_test("no GPU or DXC"); + return; + } + let blob = std::fs::read(path).unwrap(); + assert_eq!(shader::fnv64(&blob), 0x9d51ce32ab9a9ab5); + let sh = xbox::parse(&blob).unwrap(); + let f = sh.fssm.iter().find(|f| f.stages.iter().any(|s| s.hw == 6)).unwrap(); + let p = f.programs.first().unwrap(); + let full = &f.data[p.offset..p.offset + p.len]; + println!("retail program hash {:016x}, {} bytes", shader::fnv64(full), full.len()); + let mut insts = Vec::new(); + let mut at = 0; + while at < full.len() { + let d = crate::gpu::rdna2::decode(&full[at..], at as u64).unwrap(); + at += d.len; insts.push(d); + } + let cfg = super::super::cfg::Cfg::new(&insts).unwrap(); + for scalar in [false, true] { + use std::collections::BTreeSet; + let uses = |d: &crate::gpu::rdna2::Decoded| if scalar { crate::gpu::rdna2::sgpr_uses(d) } else { crate::gpu::rdna2::vgpr_uses(d) }; + let mut live = vec![BTreeSet::::new(); cfg.start.len()]; + loop { + let mut changed = false; + for b in (0..cfg.start.len()).rev() { + let mut next: BTreeSet = cfg.succ[b].iter().flat_map(|&s| live[s].iter().copied()).collect(); + for i in cfg.range(b).rev() { + let (r,w) = uses(&insts[i]); + for reg in w { next.remove(®); } + next.extend(r); + } + changed |= live[b] != next; live[b] = next; + } + if !changed { break; } + } + let end = insts.iter().position(|d| d.pc == 0x1c6c).unwrap(); + let written: BTreeSet = insts.iter().filter(|d| d.pc >= 0x13d4 && d.pc < 0x1c6c).flat_map(|d| uses(d).1).collect(); + let out: Vec<_> = written.intersection(&live[cfg.block_of[end]]).copied().collect(); + println!("retail region live {} outputs: {out:?}", if scalar { "scalar" } else { "vector" }); + assert_eq!(out, if scalar { vec![] } else { vec![28, 31] }); + } + let mode = super::super::interface(&blob, &sh, f).unwrap(); + let mut native = runner::options(mode); + native.host_rayquery = true; + native.mem_windows = 4; + let full_translation = translate(full, &native).unwrap(); + assert!(full_translation.complete(), "{:?}", full_translation.unsupported); + assert_eq!(full_translation.hlsl.matches("TraceRayInline").count(), 0); + assert!(super::identify(full, &native, &insts).is_some()); + let dxil = dxc::compile(&full_translation.hlsl, "main", "cs_6_6", &[]).unwrap(); + println!("Full retail shader baseline compiled: {} B DXIL", dxil.len()); + let mut altered = full.to_vec(); + altered[0] ^= 1; + assert!(super::identify(&altered, &native, &insts).is_none()); + native.host_rayquery = false; + assert!(super::identify(full, &native, &insts).is_none()); + let mut code = full[0x13d4..0x1c6c].to_vec(); + code.extend_from_slice(&0xbf810000u32.to_le_bytes()); + let opt = runner::options(super::super::Mode::Kernel); + let t = translate(&code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + let dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let triangle = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]]; + let bottom = bvh::build(&[triangle], 0); + let top = bvh::build_top(&[bvh::Instance { + transform: [[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.]], + id: 0, mask: 0xff, contribution: 0, flags: 0, + blas_address: 0x4000, blas_root: bottom.root, blas_bounds: bottom.bounds(), + }]); + let mut memory = vec![0u8; 0x8000]; + memory[0x1000..0x1000 + top.data.len()].copy_from_slice(&top.data); + memory[0x4000..0x4000 + bottom.data.len()].copy_from_slice(&bottom.data); + let memory: Vec = memory.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect(); + let mut state = runner::KernelState::default(); + state.sgpr[4] = 0x1000; + for (lane, v) in state.vgpr.iter_mut().enumerate() { + let origin = if lane % 2 == 0 { [0.25f32, 0.25, 1.] } else { [2., 2., 1.] }; + for (r, value) in [(6, origin[0]), (66, origin[1]), (62, origin[2]), + (47, origin[0]), (48, origin[1]), (49, origin[2]), + (11, 0.), (12, 0.), (52, -1.), (50, 0.), (51, 0.), (5, -1.), (8, 10.)] { + v[r] = value.to_bits(); + } + for r in [35, 36, 37] { v[r] = u32::MAX; } + } + let result = runner::run(&dxil, &state, &memory).unwrap(); + for lane in 0..4 { + println!("lane {lane}: limit {}, distance {}, flag {}", f32::from_bits(result.vgpr[lane][8]), + f32::from_bits(result.vgpr[lane][28]), f32::from_bits(result.vgpr[lane][31])); + } + for lane in (0..64).step_by(2) { + assert_eq!(f32::from_bits(result.vgpr[lane][8]), 1.); + assert_eq!(f32::from_bits(result.vgpr[lane][28]), 1.); + } + } +} diff --git a/crates/xcl/src/gpu/recomp/rayquery/test_support.rs b/crates/xcl/src/gpu/recomp/rayquery/test_support.rs new file mode 100644 index 000000000..014be00e8 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/rayquery/test_support.rs @@ -0,0 +1,91 @@ +//! Native scene fixtures for the upcoming sample-gated traversal comparison. +#![allow(dead_code, unused_imports)] + +use std::mem::{transmute_copy, ManuallyDrop}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use crate::gpu::bvh; +use super::super::{dxc, runner, translate, KERNEL_RES_DWORDS, KERNEL_SCC_SLOT, KERNEL_SGPRS}; + +unsafe fn buffer(dev: &ID3D12Device5, bytes: usize, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes.div_ceil(256) as u64 * 256, + Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if heap == D3D12_HEAP_TYPE_DEFAULT { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &desc, state, None, &mut resource).unwrap(); + resource.unwrap() +} + +unsafe fn upload(dev: &ID3D12Device5, words: &[u32]) -> ID3D12Resource { + let resource = buffer(dev, words.len() * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut mapped = std::ptr::null_mut(); + resource.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(words.as_ptr(), mapped.cast(), words.len()); + resource.Unmap(0, None); + resource +} + +unsafe fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: transmute_copy(resource), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, StateAfter: after, + }) }, + ..Default::default() + } +} + +pub(crate) unsafe fn scene(dev: &ID3D12Device5, queue: &ID3D12CommandQueue, triangles: &[bvh::Triangle]) -> (ID3D12Resource, Vec) { + let words: Vec = triangles.iter().flatten().flatten().map(|v| v.to_bits()).collect(); + let vertices = upload(dev, &words); + let geometry = D3D12_RAYTRACING_GEOMETRY_DESC { + Type: D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, Flags: D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE, + Anonymous: D3D12_RAYTRACING_GEOMETRY_DESC_0 { Triangles: D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { + VertexFormat: DXGI_FORMAT_R32G32B32_FLOAT, VertexCount: triangles.len() as u32 * 3, + VertexBuffer: D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { StartAddress: vertices.GetGPUVirtualAddress(), StrideInBytes: 12 }, + ..Default::default() + } }, + }; + let inputs = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL, NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { pGeometryDescs: &geometry }, ..Default::default() + }; + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList4 = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let mut retained = Vec::new(); + let mut build = |inputs: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS| { + let mut size = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + dev.GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &mut size); + let result = buffer(dev, size.ResultDataMaxSizeInBytes as usize, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE); + let scratch = buffer(dev, size.ScratchDataSizeInBytes as usize, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.BuildRaytracingAccelerationStructure(&D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: result.GetGPUVirtualAddress(), ScratchAccelerationStructureData: scratch.GetGPUVirtualAddress(), Inputs: inputs, ..Default::default() + }, None); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: transmute_copy(&result) }) }, ..Default::default() }]); + retained.push(scratch); retained.push(result.clone()); result + }; + let bottom = build(inputs); + let mut instance = [0u32; 16]; + for i in [0, 5, 10] { instance[i] = 1f32.to_bits(); } + instance[12] = 0xff000000; + instance[14] = bottom.GetGPUVirtualAddress() as u32; + instance[15] = (bottom.GetGPUVirtualAddress() >> 32) as u32; + let instances = upload(dev, &instance); + let top = build(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL, NumDescs: 1, DescsLayout: D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { InstanceDescs: instances.GetGPUVirtualAddress() }, ..Default::default() + }); + list.Close().unwrap(); queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev.cast().unwrap(), None, 30000).unwrap(); + // A TLAS references its BLAS even after the build has completed. + (top, retained) +} diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs index b4b7cd19a..7a277e831 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -312,6 +312,8 @@ void main(uint3 id : SV_DispatchThreadID) { } println!("Runtime native TLAS binding and partial-range invalidation passed"); } + let scene = crate::gpu::recomp::rayquery::test_support::scene(&dev, &queue, &[vertices]); + assert_ne!(scene.0.GetGPUVirtualAddress(), 0); assert!(blas.resource.GetGPUVirtualAddress() != console_blas); assert!(state.bytes <= LIMIT); let mut invalid = State { structures: state.structures.clone(), ..Default::default() }; From 24206a657b11ccde6884a3a6cb3bb7a262d18075 Mon Sep 17 00:00:00 2001 From: rison1337 <225131806+rison1337@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:32:20 +0500 Subject: [PATCH 7/7] Recompiler: bound a shadow traversal with native RayQuery Bind a compatible native TLAS directly and use hardware hits to shorten one exact-program traversal region. Preserve the console check for nearer and zero-distance intersections. The opt-in path remains disabled by default and has no demonstrated retail FPS benefit. Assisted-by: Codex (GPT-6 family; exact variant unavailable) --- README.md | 11 ++ crates/xcl/src/gpu/recomp/emit.rs | 52 +++++++ crates/xcl/src/gpu/recomp/mod.rs | 30 +++- crates/xcl/src/gpu/recomp/pso.rs | 29 +++- crates/xcl/src/gpu/recomp/rayquery.rs | 12 +- .../src/gpu/recomp/rayquery/test_support.rs | 133 +++++++++++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 10 ++ crates/xcl/src/hle/d3d12x/host_bvh/tests.rs | 5 +- 8 files changed, 270 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 8b31eeb1d..b92d8d3a0 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,17 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder Native buffers are retained until exit with a 256 MiB allocation budget per device. Translated shaders still use the console BVH, so this diagnostic mode adds GPU work and does not accelerate rendering yet. It is disabled by default. +- `XCL_HOST_RAYQUERY=1` additionally enables an experimental native consumer for one + verified full-resolution shadow compute shader. One compatible native TLAS is bound + directly per dispatch; mismatched addresses retain the original traversal. Only opaque + triangle BLASes without geometry transforms and translation-only instances with mask + `0xff` and no flags are eligible. A native hit tightens the maximum distance of the original + traversal; the guest still checks nearer intersections, including zero-distance hits, before merging the native + endpoint. A native miss leaves the original traversal unchanged. Freed or + remapped UMA ranges invalidate captured bindings. Producers and consumers must share the + same current command-list recording; Reset invalidates the bindings. Cross-list and + cross-queue publication is not supported. This is disabled by default; retail + scene coverage and a rendering performance improvement have not been established. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8f257a043..a975493ac 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -17,6 +17,8 @@ pub(super) enum Flow { } pub(super) struct Em { + pub rayquery_region: Option, + uses_rayquery: bool, opt: Options, out: String, pub indent: usize, @@ -567,6 +569,8 @@ fn to_f16_rounded_expr(dynamic_rm: bool, e: &str) -> String { impl Em { pub fn new(opt: Options) -> Self { Em { + rayquery_region: None, + uses_rayquery: false, opt, out: String::new(), indent: 1, @@ -975,6 +979,51 @@ impl Em { // ---------------------------------------------------------------- one instruction + /// Use a native hit as an upper bound, retaining the guest's boundary intersections. + pub fn emit_rayquery_branch(&mut self) { + self.uses_rayquery = true; + let active = self.act(); + self.line("bool xcl_q_ready = xcl_query_matches(s4, s5), xcl_q_hit = false;"); + self.line("uint xcl_q_t = 0u;"); + self.line("if (xcl_q_ready) {"); + self.indent += 1; + self.line(&format!("bool xcl_q_bad = and({active}, !and(and(all(isfinite(asfloat(uint3(v47,v48,v49)))), all(isfinite(asfloat(uint3(v50,v51,v5))))), and(isfinite(asfloat(v8)), and(asfloat(v8) > 0.0f, any(asfloat(uint3(v50,v51,v5)) != 0.0f)))));")); + if self.x64() { + self.line("uint2 xcl_q_invalid = xcl_x_ballot(xcl_q_bad);"); + self.line("xcl_q_ready = (xcl_q_invalid.x | xcl_q_invalid.y) == 0u;"); + } else { + self.line("xcl_q_ready = !WaveActiveAnyTrue(xcl_q_bad);"); + } + self.indent -= 1; + self.line("}"); + self.line(&format!("if (and(xcl_q_ready, {active})) {{")); + self.indent += 1; + self.line("RayDesc xcl_q_ray; xcl_q_ray.Origin = asfloat(uint3(v47,v48,v49)); xcl_q_ray.Direction = asfloat(uint3(v50,v51,v5));"); + self.line("xcl_q_ray.TMin = 0.0f; xcl_q_ray.TMax = asfloat(v8);"); + self.line("RayQuery xcl_q;"); + self.line("xcl_q.TraceRayInline(xcl_q_scene, RAY_FLAG_NONE, 0xffu, xcl_q_ray);"); + self.line("while (xcl_q.Proceed()) {}"); + self.line("xcl_q_hit = xcl_q.CommittedStatus() == COMMITTED_TRIANGLE_HIT;"); + self.line("xcl_q_t = xcl_q_hit ? asuint(xcl_q.CommittedRayT()) : 0u;"); + self.line("xcl_q_hit = and(xcl_q_hit, asfloat(xcl_q_t) < asfloat(v8));"); + #[cfg(test)] + if matches!(self.opt.mode, Mode::Kernel) { + self.line(&format!("res.InterlockedAdd({}u, 1u);", super::KERNEL_RES_DWORDS * 4)); + self.line(&format!("if (xcl_q_hit) res.InterlockedAdd({}u, 1u);", (super::KERNEL_RES_DWORDS + 1) * 4)); + } + self.indent -= 1; + self.line("}"); + self.line("v8 = xcl_q_hit ? xcl_q_t : v8;"); + // The guest can accept a t=0 intersection that native traversal omits. Search the + // shorter interval too, then merge the native endpoint only if it found no nearer hit. + self.line("{"); + } + + pub fn emit_rayquery_merge(&mut self) { + self.line("bool xcl_q_use = and(xcl_q_hit, v28 == 0xc47a0000u);"); + self.line("v8 = xcl_q_use ? xcl_q_t : v8; v28 = xcl_q_use ? xcl_q_t : v28; v31 = xcl_q_use ? 0u : v31;"); + } + /// Emit one basic block's instructions in order; stops at the first non-fallthrough flow. /// In split-wave64 mode, folds cross-half reduction tails (`v_readlane(v, L)` -> `v_op(v, s, v)` /// -> `v_readlane(v, L^32)`, 32-bit and 64-bit `v_add_f64`) into a single `xcl_x_meet()`. @@ -4694,6 +4743,9 @@ impl Em { let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); h.push_str(PRELUDE_MEM); + if self.uses_rayquery { + h.push_str(super::rayquery::LOOKUP); + } if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 2686e9405..284ecbcd9 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -61,6 +61,7 @@ pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; pub mod partition; +pub(crate) mod rayquery; pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; @@ -88,7 +89,6 @@ pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) } pub mod upper_lanes; -pub(crate) mod rayquery; use std::collections::{BTreeMap, BTreeSet}; @@ -203,6 +203,9 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +pub const IO_HOST_AS_LO: usize = 113; +pub const IO_HOST_AS_HI: usize = 114; +pub const IO_HOST_AS_MAGIC: usize = 115; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) @@ -498,6 +501,8 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss #[derive(Debug, Clone)] pub struct Options { + /// Opt-in whole-region inline RayQuery for the verified shadow traversal program. + pub host_rayquery: bool, pub mode: Mode, /// wave64 (64-bit EXEC/VCC) or wave32 program pub wave64: bool, @@ -527,7 +532,6 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, - pub host_rayquery: bool, } impl Default for Options { @@ -1019,6 +1023,23 @@ fn emit_structured( } let d = depth + guard.is_some() as usize; let ipad = " ".repeat(d); + if let Some(region) = em.rayquery_region.filter(|r| r.start == s && r.end <= hi) { + em.rayquery_region = None; + em.indent = d; + em.emit_rayquery_branch(); + body.push_str(&em.take()); + let raised = emit_structured(c, em, body, region.start, region.end, Some(region.end), nest + 1, + cont, &none, d + 1, blocks, flags); + body.push_str(&format!("{ipad}}}\n")); + em.indent = d; + em.emit_rayquery_merge(); + body.push_str(&em.take()); + em.rayquery_region = Some(region); + pending.extend(raised); + queued = None; + i = c.leaders.partition_point(|&l| l < region.end); + continue; + } if resolved { body.push_str(&format!("{ipad}{} = false;\n", skip_flag(s))); } @@ -1405,8 +1426,12 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { insts.push(d); } rdna2::resolve_far_jumps(&mut insts); + let query = rayquery::identify(program, opt, &insts); let starts: BTreeSet = insts.iter().map(|d| d.pc).collect(); let mut leaders: BTreeSet = BTreeSet::from([0]); + if let Some(region) = query { + leaders.extend([region.start, region.end]); + } let mut branches = 0usize; // geometry mode: the ES's s_setpc_b64 continues into the GS code (or ends the ES alone) let gs_jump = match &opt.mode { @@ -1435,6 +1460,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); + em.rayquery_region = query; em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ec6fc8fbe..222bce854 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -150,6 +150,11 @@ fn shader_cache() -> &'static Mutex { /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result, String> { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + // Keep the opt-in variant out of the legacy translation caches. DXC still caches by + // the generated HLSL, and only this one verified record takes this path. + if native_query_blob(blob, stage) { + return compile_one().map(Arc::new); + } if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(Arc::new); } @@ -365,7 +370,7 @@ mod translated { fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result { // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path // for what it cannot translate yet - if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { + if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() && !native_query_blob(blob, stage) { if dxc::defer() { return Err("DXIL not compiled yet".into()); } @@ -809,7 +814,10 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { host_rayquery: native_query_blob(blob, stage), mode, wave64: super::detect_wave64(code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + if t.hlsl.contains("TraceRayInline") { + crate::xlog_info!("Host RayQuery: verified shadow traversal translated (record {:016x})", super::rayquery::SHADOW_RECORD); + } if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -817,6 +825,12 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, Ok((t, profile)) } +fn native_query_blob(blob: &[u8], stage: Stage) -> bool { + stage == Stage::Compute && crate::hle::d3d12x::host_bvh::query_requested() + && crate::gpu::shader::fnv64(blob) == super::rayquery::SHADOW_RECORD + && crate::hle::d3d12x::host_bvh::query_supported() +} + /// A console geometry stage as XCL runs it, in two passes: the console program as a compute /// shader writes one record per thread group (vertices + primitives, `record`) into `res`, /// then a pass-through mesh shader rasterises the records with the pixel shader. @@ -1047,7 +1061,7 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) - let params: Vec = (0..6) + let mut params: Vec = (0..6) .map(|i| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -1056,6 +1070,15 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }) .collect(); + if crate::hle::d3d12x::host_bvh::query_requested() { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; if graphics { flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; diff --git a/crates/xcl/src/gpu/recomp/rayquery.rs b/crates/xcl/src/gpu/recomp/rayquery.rs index 6bae588f0..923c7801a 100644 --- a/crates/xcl/src/gpu/recomp/rayquery.rs +++ b/crates/xcl/src/gpu/recomp/rayquery.rs @@ -38,6 +38,13 @@ pub(super) fn identify(code: &[u8], opt: &Options, insts: &[rdna2::Decoded]) -> Some(region) } +pub(super) const LOOKUP: &str = r#" +RaytracingAccelerationStructure xcl_q_scene : register(t0, space2); +// One native TLAS is bound per dispatch. Other guest addresses use the original traversal. +bool xcl_query_matches(uint lo, uint hi) { + return io.Load(460u) == 0x58445231u && io.Load(452u) == lo && io.Load(456u) == (hi & 0xffffu); +} +"#; #[cfg(test)] pub(crate) mod test_support; @@ -100,10 +107,9 @@ mod tests { native.mem_windows = 4; let full_translation = translate(full, &native).unwrap(); assert!(full_translation.complete(), "{:?}", full_translation.unsupported); - assert_eq!(full_translation.hlsl.matches("TraceRayInline").count(), 0); - assert!(super::identify(full, &native, &insts).is_some()); + assert_eq!(full_translation.hlsl.matches("TraceRayInline").count(), 1); let dxil = dxc::compile(&full_translation.hlsl, "main", "cs_6_6", &[]).unwrap(); - println!("Full retail shader baseline compiled: {} B DXIL", dxil.len()); + println!("Full retail shader with RayQuery compiled: {} B DXIL", dxil.len()); let mut altered = full.to_vec(); altered[0] ^= 1; assert!(super::identify(&altered, &native, &insts).is_none()); diff --git a/crates/xcl/src/gpu/recomp/rayquery/test_support.rs b/crates/xcl/src/gpu/recomp/rayquery/test_support.rs index 014be00e8..9ed76d887 100644 --- a/crates/xcl/src/gpu/recomp/rayquery/test_support.rs +++ b/crates/xcl/src/gpu/recomp/rayquery/test_support.rs @@ -1,5 +1,4 @@ -//! Native scene fixtures for the upcoming sample-gated traversal comparison. -#![allow(dead_code, unused_imports)] +//! Local retail sample only; no title code or data is stored in the repository. use std::mem::{transmute_copy, ManuallyDrop}; use windows::core::Interface; @@ -89,3 +88,133 @@ pub(crate) unsafe fn scene(dev: &ID3D12Device5, queue: &ID3D12CommandQueue, tria // A TLAS references its BLAS even after the build has completed. (top, retained) } + +pub(crate) unsafe fn compare_native(dev: &ID3D12Device5, queue: &ID3D12CommandQueue, tlas: &ID3D12Resource) { + let path = std::env::var_os("XCL_SAMPLE_RAYQUERY").unwrap(); + let blob = std::fs::read(path).unwrap(); + assert_eq!(crate::gpu::shader::fnv64(&blob), super::SHADOW_RECORD); + let sh = crate::gpu::xbox::parse(&blob).unwrap(); + let f = sh.fssm.iter().find(|f| f.stages.iter().any(|s| s.hw == 6)).unwrap(); + let p = f.programs.first().unwrap(); + let mut code = f.data[p.offset + 0x13d4..p.offset + 0x1c6c].to_vec(); + code.extend_from_slice(&0xbf810000u32.to_le_bytes()); + let mut parameters: Vec = (0..6).map(|index| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: index, RegisterSpace: 0 } }, + ..Default::default() + }).collect(); + parameters.push(D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 2 } }, ..Default::default() }); + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: parameters.len() as u32, pParameters: parameters.as_ptr(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, + ..Default::default() + }; + let mut serialized = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut serialized, None).unwrap(); + let serialized = serialized.unwrap(); + let root: ID3D12RootSignature = if crate::hle::d3d12x::host_bvh::query_requested() { + super::super::pso::abi_root_signature(&dev.cast().unwrap(), false).unwrap() + } else { + dev.CreateRootSignature(0, std::slice::from_raw_parts(serialized.GetBufferPointer().cast(), serialized.GetBufferSize())).unwrap() + }; + let mut waves = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&mut waves as *mut D3D12_FEATURE_DATA_D3D12_OPTIONS1).cast(), std::mem::size_of_val(&waves) as u32).unwrap(); + let mut pipelines = Vec::new(); + for native in [false, true] { + let mut opt = super::super::Options { split_wave64: waves.WaveLaneCountMax < 64, ..Default::default() }; + opt.host_rayquery = native; + let translation = translate(&code, &opt).unwrap(); + assert!(translation.complete(), "{:?}", translation.unsupported); + assert_eq!(translation.hlsl.contains("TraceRayInline"), native); + let dxil = dxc::compile(&translation.hlsl, "main", "cs_6_6", &[]).unwrap(); + let pipeline: ID3D12PipelineState = dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }).unwrap(); + pipelines.push(pipeline); + } + let triangle = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.]]; + let lower = |z: f32| triangle.map(|mut p| { p[2] = z; p }); + for (scene_index, triangles) in [vec![triangle], vec![triangle, lower(-1.)], vec![lower(-1.), triangle], vec![triangle, lower(-0.5), lower(-2.)]].into_iter().enumerate() { + let built = (scene_index != 0).then(|| scene(dev, queue, &triangles)); + let tlas = built.as_ref().map_or(tlas, |built| &built.0); + let bottom = bvh::build(&triangles, 0); + let top = bvh::build_top(&[bvh::Instance { + transform: [[1.,0.,0.,0.], [0.,1.,0.,0.], [0.,0.,1.,0.]], id: 0, mask: 0xff, contribution: 0, flags: 0, + blas_address: 0x4000, blas_root: bottom.root, blas_bounds: bottom.bounds(), + }]); + let mut memory = vec![0u8; 0x8000]; + memory[0x1000..0x1000 + top.data.len()].copy_from_slice(&top.data); + memory[0x4000..0x4000 + bottom.data.len()].copy_from_slice(&bottom.data); + let mut memory: Vec = memory.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect(); + for case in 0..7 { + let mut state = runner::KernelState::default(); + state.sgpr[4] = 0x1000; + state.sgpr[super::super::IO_HOST_AS_LO] = if case == 5 { 0x2000 } else { 0x1000 }; + state.sgpr[super::super::IO_HOST_AS_HI] = 0; + state.sgpr[super::super::IO_HOST_AS_MAGIC] = if case == 1 { 0 } else { super::MAGIC }; + if case == 2 { state.sgpr[126] = 0xaaaaaaaa; state.sgpr[127] = 0xaaaaaaaa; } + for (lane,v) in state.vgpr.iter_mut().enumerate() { + let (origin, direction, limit) = match if case == 4 { 0 } else { lane % 8 } { + 0 => ([0.25f32,0.25,1.], [0.,0.,-1.], 10.), + 1 => ([2.,2.,1.], [0.,0.,-1.], 10.), + 2 => ([0.25,0.25,-1.], [0.,0.,1.], 10.), + 3 => ([0.25,0.25,1.], [0.,0.,-1.], 1.), + 4 => ([0.25,0.25,1.], [0.,0.,-1.], 0.5), + 5 => ([0.25,0.25,0.], [0.,0.,-1.], 10.), + 6 => ([0.75,0.25,1.], [0.,0.,-1.], 10.), + _ => ([0.25,0.25,1.], [0.,0.,-2.], 10.), + }; + for (r,x) in [(6,origin[0]),(66,origin[1]),(62,origin[2]),(47,origin[0]),(48,origin[1]),(49,origin[2]), + (11,direction[0]),(12,direction[1]),(52,direction[2]),(50,direction[0]),(51,direction[1]),(5,direction[2]),(8,limit)] { v[r] = x.to_bits(); } + for r in [35,36,37] { v[r] = u32::MAX; } + } + if case == 6 { state.sgpr[126] = 0; state.sgpr[127] = 0; } + if case == 3 { state.vgpr[17][47] = f32::NAN.to_bits(); state.vgpr[17][6] = f32::NAN.to_bits(); } + let mut io = state.sgpr.clone(); io.resize(KERNEL_SGPRS,0); io[KERNEL_SCC_SLOT] = state.scc; + for v in &state.vgpr { io.extend_from_slice(v); } + let mut results = Vec::new(); + for pipeline in &pipelines { + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let uploads = [upload(dev,&io),upload(dev,&memory),upload(dev,&vec![0;KERNEL_RES_DWORDS+2])]; + let sizes = [io.len()*4,memory.len()*4,(KERNEL_RES_DWORDS+2)*4]; + let buffers: Vec<_> = sizes.iter().map(|&bytes| buffer(dev,bytes,D3D12_HEAP_TYPE_DEFAULT,D3D12_RESOURCE_STATE_COPY_DEST)).collect(); + for i in 0..3 { + list.CopyBufferRegion(&buffers[i],0,&uploads[i],0,sizes[i] as u64); + list.ResourceBarrier(&[transition(&buffers[i],D3D12_RESOURCE_STATE_COPY_DEST,D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } + let readback = buffer(dev,sizes[2],D3D12_HEAP_TYPE_READBACK,D3D12_RESOURCE_STATE_COPY_DEST); + list.SetComputeRootSignature(&root); list.SetPipelineState(pipeline); + list.SetComputeRootUnorderedAccessView(0,buffers[0].GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1,buffers[2].GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2,buffers[1].GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView(6,tlas.GetGPUVirtualAddress()); + list.Dispatch(1,1,1); + list.ResourceBarrier(&[transition(&buffers[2],D3D12_RESOURCE_STATE_UNORDERED_ACCESS,D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&readback,0,&buffers[2],0,sizes[2] as u64); list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0,D3D12_FENCE_FLAG_NONE).unwrap(); queue.Signal(&fence,1).unwrap(); + crate::gpu::fence::wait(&fence,1,&dev.cast().unwrap(),None,30000).unwrap(); + let mut mapped = std::ptr::null_mut(); readback.Map(0,None,Some(&mut mapped)).unwrap(); + let words = std::slice::from_raw_parts(mapped.cast::(),sizes[2]/4).to_vec(); readback.Unmap(0,None); + results.push(words); + } + for lane in 0..64 { + for reg in [8,28,31] { + let at = KERNEL_SGPRS + lane * 256 + reg; + assert_eq!(results[1][at],results[0][at],"scene {scene_index}, case {case}, lane {lane}, v{reg}: native {} vs guest {}", + f32::from_bits(results[1][at]),f32::from_bits(results[0][at])); + } + } + let expected = [64,0,32,0,64,0,0][case]; + assert_eq!(results[1][KERNEL_RES_DWORDS],expected,"native trace count for case {case}"); + let limits = results[1][KERNEL_RES_DWORDS+1]; + let minimum = [24,0,8,0,64,0,0][case]; + assert!(limits >= minimum && limits <= expected, "case {case}: only {limits} native search limits, expected at least {minimum}"); + println!("Retail region vs RayQuery scene {scene_index}, case {case}: 64 lane results matched, {expected} hardware traces, {limits} native search limits"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef4..dca7eaeab 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -967,6 +967,13 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + let query = if gfx { None } else { super::host_bvh::query_binding(list) }; + io[crate::gpu::recomp::IO_HOST_AS_MAGIC] = 0; + if let Some(query) = &query { + io[crate::gpu::recomp::IO_HOST_AS_LO] = query.console as u32; + io[crate::gpu::recomp::IO_HOST_AS_HI] = (query.console >> 32) as u32; + io[crate::gpu::recomp::IO_HOST_AS_MAGIC] = crate::gpu::recomp::rayquery::MAGIC; + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); @@ -981,6 +988,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi } } else { list.SetComputeRootSignature(rs); + if super::host_bvh::query_requested() { + list.SetComputeRootShaderResourceView(crate::gpu::recomp::rayquery::HOST_AS_ROOT, query.map_or(0, |q| q.native)); + } for (k, v) in views.enumerate() { list.SetComputeRootUnorderedAccessView(k as u32, v); } diff --git a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs index 7a277e831..e0971d183 100644 --- a/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs +++ b/crates/xcl/src/hle/d3d12x/host_bvh/tests.rs @@ -265,6 +265,9 @@ void main(uint3 id : SV_DispatchThreadID) { assert_eq!(expected, [1.0f32.to_bits(), u32::MAX]); assert_eq!(hits, expected); readback.Unmap(0, None); + if std::env::var_os("XCL_SAMPLE_RAYQUERY").is_some() { + crate::gpu::recomp::rayquery::test_support::compare_native(&dev, &queue, &tlas.resource); + } if query_requested() { *STATES.lock().unwrap() = Some(HashMap::from([(dev.as_raw() as usize, State { structures: state.structures.clone(), ..Default::default() @@ -312,8 +315,6 @@ void main(uint3 id : SV_DispatchThreadID) { } println!("Runtime native TLAS binding and partial-range invalidation passed"); } - let scene = crate::gpu::recomp::rayquery::test_support::scene(&dev, &queue, &[vertices]); - assert_ne!(scene.0.GetGPUVirtualAddress(), 0); assert!(blas.resource.GetGPUVirtualAddress() != console_blas); assert!(state.bytes <= LIMIT); let mut invalid = State { structures: state.structures.clone(), ..Default::default() };