diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 477c6410..0b51e472 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1722,6 +1722,30 @@ fn buffer_srv( Some(HeldSource::Widened(widened, shadow.clone())), ))); } + let stride = u64::from(buffer.StructureByteStride); + if stride > 0 && raw_structured() { + // Scalar and offset-only buffer reads emit `rawBufferLoad` on a raw + // handle (`victory_shader::emit`), which D3D12 leaves undefined on a + // structured SRV (NVIDIA treats the byte offset as an element index, + // hanging `WindNew` loops). NVIDIA, WARP and D3DMetal all read both + // raw handles and structured handles accurately from a raw view of the + // same bytes; under Wine/D3DMetal any dword-aligned start (`+8B` or + // `+680B`) works too, while native D3D12 requires 16-byte alignment. + let (byte, dwords) = (first * stride, u64::from(count) * stride / 4); + let align = if crate::shader_cache::under_wine() { 4 } else { 16 }; + match u32::try_from(dwords) { + Ok(dwords) if byte.is_multiple_of(align) && stride.is_multiple_of(4) => { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: byte / 4, + NumElements: dwords, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + _ => once!(byte, stride, "structured buffer view not made raw: unaligned"), + } + } // SAFETY: a live buffer and a slot of our heap. unsafe { host.device @@ -1733,6 +1757,23 @@ fn buffer_srv( ))) } +/// Whether structured buffer views are made raw ([`buffer_srv`]): under Wine +/// (D3DMetal) and on NVIDIA hosts, both of which serve structured-handle and +/// raw-handle `rawBufferLoad`s from a raw view of the same bytes. +/// `VICTORY_RAW_STRUCTURED=0` or `=1` overrides. +fn raw_structured() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = match std::env::var("VICTORY_RAW_STRUCTURED").as_deref() { + Ok("0" | "false" | "off") => false, + Ok("1" | "true" | "on") => true, + _ => crate::shader_cache::under_wine() || crate::host::host_vendor() == 0x10DE, + }; + tracing::info!(on, "structured buffer views made raw"); + on + }) +} + /// Whether `count` elements of `element` bytes from element `first` lie in /// `buffer`. The console takes a view that is empty or runs past its /// memory; the host removes the device for one. @@ -3661,4 +3702,269 @@ void main(uint3 id : SV_DispatchThreadID) { "patterns unchanged, moved as unsigned integers" ); } + + /// End-to-end test of [`buffer_srv`] converting a structured buffer SRV + /// (`StructureByteStride = 680`, starting at `FirstElement = 1` = `+680` + /// bytes, `8 mod 16`) into a raw SRV and reading it through a translated + /// DXIL compute shader via MUBUF raw byte offset (`0xC4`), SMEM scalar + /// byte offset (`0xC4`), and MUBUF structured element+field (`[2] + 12`). + #[test] + fn structured_buffer_srv_made_raw_reads_byte_and_element_offsets() { + use crate::pipeline::{Shader, Translated, host::HostPipeline}; + use victory_shader::native::{ComputeIo, StageIo}; + use victory_shader::{ + Container, HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, + emit, io, ir, resource, structure, + }; + + let Some(host) = host() else { + return; + }; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: valid feature support query. + let ok = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + }; + if ok.is_err() || sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return; + } + + let code_words: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 (SRV slot 0) + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 (UAV slot 1) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF420_0404, + 0xFA00_00C4, // s_buffer_load_dword s16, s[8:11], 0xC4 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0210, // v_mov_b32 v4, s16 + 0xE030_00C4, + 0x8002_0100, // buffer_load_dword v1, off, s[8:11], 0 offset:196 + 0x7E04_0282, // v_mov_b32 v2, 2 + 0xE030_200C, + 0x8002_0302, // buffer_load_dword v3, v2, s[8:11], 0 idxen offset:12 + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_0000, + 0x8003_0100, // buffer_store_dword v1, off, s[12:15], 0 offset:0 + 0xE070_0004, + 0x8003_0400, // buffer_store_dword v4, off, s[12:15], 0 offset:4 + 0xE070_0008, + 0x8003_0300, // buffer_store_dword v3, off, s[12:15], 0 offset:8 + 0xBF81_0000, // s_endpgm + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: (0..2) + .map(|slot| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: slot, + slot, + }) + .collect(), + used: vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 680, + dwords: 4, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 1, + slot: 1, + }, + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: code_words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut container = vec![0; 32]; + container[..4].copy_from_slice(b"DXBC"); + container[20..24].copy_from_slice(&1u32.to_le_bytes()); + container[24..28].copy_from_slice(&32u32.to_le_bytes()); + let c = Container::parse(&container).unwrap(); + let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let hs = emit::emit(&c, &native, &p, &st, &io, &res).unwrap(); + let ud_spec = hs.user_data.clone(); + let shader = Shader::for_test( + "compute", + Translated { + host: hs, + used: native.used, + }, + ); + let Some(hp) = HostPipeline::new(&[shader], None, |_, _| {}) else { + panic!("synthetic structured-SRV pipeline"); + }; + + // Allocate 8 KiB of title memory (2048 dwords) filled with distinct words. + let bytes_len = 8192usize; + let mut backing: Vec = (0..(bytes_len / 4) as u32) + .map(|i| 0x2000_0000 + i) + .collect(); + let mem = backing.as_mut_ptr(); + crate::shadow::register(mem as usize, mem as u64, bytes_len as u64); + + // SAFETY: shader-visible heap with 2 slots. + let d3d_heap: ID3D12DescriptorHeap = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .unwrap() + }; + // SAFETY: live descriptor heap. + let cpu = unsafe { d3d_heap.GetCPUDescriptorHandleForHeapStart() }; + // SAFETY: plain device query. + let step = unsafe { + host.device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } as usize; + + // Structured SRV: stride = 680, FirstElement = 1 (+680B = +170 dwords), NumElements = 4. + let srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 1, + NumElements: 4, + StructureByteStride: 680, + Flags: D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, + }; + let _kept = buffer_srv(mem as u64, bytes_len as u64, srv_desc, cpu) + .expect("buffer_srv succeeds") + .expect("holds shadow buffer"); + + let list = host.new_list().unwrap(); + let shadow = crate::shadow::find(mem as u64, bytes_len as u64).expect("registered shadow"); + shadow.refresh(&list, mem as u64, bytes_len as u64); + + let mut uav_buf: Option = None; + // SAFETY: valid default UAV buffer description. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut uav_buf, + ) + .unwrap(); + } + let uav_buf = uav_buf.unwrap(); + let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 8, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: valid UAV slot 1. + unsafe { + host.device.CreateUnorderedAccessView( + &uav_buf, + None, + Some(&uav_desc), + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + step, + }, + ); + } + + let mut ud = vec![0u32; hp.stages[0].user_data.map_or(1, |(_, n)| n as usize)]; + for u in &ud_spec { + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let (readback, rb_ptr) = list.readback(host, 256).unwrap(); + // SAFETY: open list with heap, root signature, constants, and PSO bound. + unsafe { + list.list.SetDescriptorHeaps(&[Some(d3d_heap.clone())]); + list.list.SetComputeRootSignature(&hp.root); + list.list + .SetComputeRoot32BitConstants(0, ud.len() as u32, ud.as_ptr().cast(), 0); + list.list.SetPipelineState(&hp.pso); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[crate::host::transition( + &uav_buf, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.list.CopyResource(&readback, &uav_buf); + } + list.close(); + host.execute(&[&list]); + + // SAFETY: GPU execution finished; read 3 dwords from mapped readback. + let got = unsafe { *rb_ptr.cast::<[u32; 3]>() }; + // SAFETY: plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + crate::shadow::unregister(mem as usize, mem as u64); + drop(backing); + + let expected = [ + 0x2000_0000 + 170 + 49, // MUBUF raw @ 0xC4 + 0x2000_0000 + 170 + 49, // SMEM scalar raw @ 0xC4 + 0x2000_0000 + 170 + 343, // MUBUF structured [2] + 12 + ]; + assert_eq!(got, expected); + } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2cddd6d9..fdfffbc3 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -66,6 +66,10 @@ pub(crate) struct State { depth: usize, /// Last render target and depth keys set on the host list. host_targets: Option<(Vec, Option)>, + /// The formats of the views [`State::set_targets`] bound on the host + /// list: a draw's pipeline is one for them + /// (`crate::pipeline::host_pipeline_for`). + target_formats: crate::pipeline::host::TargetFormats, /// None leaves the host list's default bounds (0..1) in place. depth_bounds: Option<(f32, f32)>, /// The title's primitive topology (the host's may differ). @@ -261,6 +265,17 @@ fn set(roots: &mut Vec, slot: u32, root: Root) { roots[slot] = root; } +/// The format of a host view of `texture` whose description names +/// `described` (none without a description): that one, or the texture's +/// own, which is what the host gives a view without a format. +fn bound_format(texture: &ID3D12Resource, described: Option) -> u32 { + match described { + Some(format) if format.0 != 0 => format.0 as u32, + // SAFETY: a live texture. + _ => unsafe { texture.GetDesc() }.Format.0 as u32, + } +} + impl State { pub(crate) fn reset(&mut self, pipeline: This) { *self = State::default(); @@ -438,6 +453,8 @@ impl State { return; }; self.targets.clear(); + // The formats of the host views, for the draws' pipelines. + let mut formats = [0; 9]; let mut rtv_views = Vec::with_capacity(handles.len()); let mut rtv_keys = Vec::with_capacity(handles.len()); for &h in handles { @@ -454,8 +471,12 @@ impl State { self.targets.push(record.resource as usize); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); + let desc = record.desc(); + if rtv_views.len() < 8 { + formats[rtv_views.len()] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); + } rtv_keys.push((texture.as_raw() as usize, record.key())); - rtv_views.push((texture, record.desc())); + rtv_views.push((texture, desc)); } if self .hdr_rtvs @@ -471,11 +492,14 @@ impl State { && let Some(texture) = crate::resource::host_resource(record.resource) { self.depth = record.resource as usize; + let desc = record.depth_desc(); + formats[8] = bound_format(&texture, desc.as_ref().map(|d| d.Format)); #[cfg(feature = "diagnostics")] crate::capture::note_target(list, record.resource); dsv_key = Some((texture.as_raw() as usize, record.key())); - dsv_view = Some((texture, record.depth_desc())); + dsv_view = Some((texture, desc)); } + self.target_formats = formats; if bind_cache_enabled() && self .host_targets @@ -585,7 +609,8 @@ impl State { if crate::pipeline::is_skipped(self.pipeline as This) { return false; } - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; if p.compute || p.mesh != mesh { @@ -1947,7 +1972,8 @@ impl State { /// Binds vertex buffers holding the rectangles of vertices `first..first /// + count` as triangles, made when the list is submitted. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { - let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + let Some(p) = crate::pipeline::host_pipeline_for(self.pipeline as This, &self.target_formats) + else { return false; }; let rects = u64::from(count / 3); @@ -2332,10 +2358,10 @@ fn readable(list: &HostList, u: &UsedResource, view: &View, marked: bool) { (View::Shader(resource, _), ResourceType::Srv) => { // A view of memory the GPU writes through another title texture // whose host copy this one could not share reads that copy. - if let Some(a) = crate::resource::alias_source(*resource as This) { - crate::texture::alias_copy(list, a.get(), *resource as This); - } - if let Some(t) = crate::resource::host_copy(*resource as This) + let copied = crate::resource::alias_source(*resource as This) + .is_some_and(|a| crate::texture::alias_copy(list, a.get(), *resource as This)); + if !copied + && let Some(t) = crate::resource::host_copy(*resource as This) && t.title_written() { crate::texture::upload(list, *resource as This, &t.texture); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index f22a0859..230bed23 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -414,6 +414,25 @@ pub(crate) fn device_removed() -> bool { host().is_some_and(|h| unsafe { h.device.GetDeviceRemovedReason() }.is_err()) } +/// The PCI vendor id of the host device's adapter (NVIDIA 0x10DE), 0 if it +/// cannot be told. +pub(crate) fn host_vendor() -> u32 { + static VENDOR: OnceLock = OnceLock::new(); + *VENDOR.get_or_init(|| { + let Some(host) = host() else { return 0 }; + // SAFETY: plain DXGI queries for the device's own adapter. + let vendor = unsafe { + let luid = host.device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| f.EnumAdapterByLuid::(luid)) + .and_then(|a| a.GetDesc1()) + .map_or(0, |d| d.VendorId) + }; + tracing::info!(vendor = format_args!("{vendor:#x}"), "host adapter vendor"); + vendor + }) +} + /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { @@ -1590,6 +1609,8 @@ struct Deferred { slots: std::collections::HashSet<(usize, u32)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// Last GPU source copied into each aliased host texture in this list. + texture_aliases: std::collections::HashMap, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, @@ -3729,6 +3750,16 @@ impl HostList { self.deferred().textures.insert(key) } + pub(crate) fn alias_source_changed( + &self, + view: &ID3D12Resource, + source: &ID3D12Resource, + ) -> bool { + let view = view.as_raw() as usize; + let source = source.as_raw() as usize; + self.deferred().texture_aliases.insert(view, source) != Some(source) + } + /// Runs `work` on host memory at submission, in order with the copies. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Host(Box::new(work))); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index a8208ba7..50f68d67 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -530,6 +530,23 @@ pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { make::ready(&pipeline(this).host) } +/// As [`host_pipeline`], for a draw into render target and depth views of +/// the formats `bound`. +#[cfg(windows)] +pub(crate) fn host_pipeline_for<'a>( + this: This, + bound: &host::TargetFormats, +) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = &pipeline(this).host; + if p.formats != *bound && host::formats_differ(&p.formats, bound) { + return make::for_formats(p, bound); + } + make::ready(p) +} + /// Whether a dispatch with the title pipeline is held back: it is the /// acceleration-structure builder's, which does not run this frame /// ([`builder::runs`]). diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 0b043032..04b2f255 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -94,6 +94,44 @@ impl Default for GraphicsState { } } +#[cfg(test)] +impl GraphicsState { + /// A state that declares one render target, of format `format` (tests). + pub(crate) fn declaring(format: i32) -> Self { + let mut g = Self::default(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT(format); + g + } +} + +/// The formats of what a draw draws into, as the host has them: the eight +/// render targets (0 where there is none), then depth (0 for none). +pub(crate) type TargetFormats = [u32; 9]; + +/// Whether a draw into views of the formats `bound` cannot go to the host +/// with a pipeline that declares `declared`: a render target slot for which +/// the pipeline declares a format has a view of another format bound to it. +pub(crate) fn formats_differ(declared: &TargetFormats, bound: &TargetFormats) -> bool { + declared[..8] + .iter() + .zip(&bound[..8]) + .any(|(&d, &b)| d != 0 && b != 0 && b != d) +} + +/// The formats a pipeline for a draw into `bound` declares +/// ([`formats_differ`]): the title's own, except declared render target slots +/// with a bound view take the bound view's format. +pub(crate) fn formats_for(declared: &TargetFormats, bound: &TargetFormats) -> TargetFormats { + let mut formats = *declared; + for i in 0..8 { + if declared[i] != 0 && bound[i] != 0 { + formats[i] = bound[i]; + } + } + formats +} + /// Integer render target formats: D3D12 cannot blend into them. fn integer_format(f: DXGI_FORMAT) -> bool { matches!( @@ -154,6 +192,53 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1 } impl GraphicsState { + /// The formats the state declares ([`TargetFormats`]): nothing past its + /// count of render targets. + pub(crate) fn formats(&self) -> TargetFormats { + let mut formats = [0; 9]; + let n = (self.targets.NumRenderTargets as usize).min(8); + for (to, from) in formats.iter_mut().zip(&self.targets.RTFormats[..n]) { + *to = from.0 as u32; + } + formats[8] = self.depth_format.0 as u32; + formats + } + + /// The same state for a draw into views of the formats `bound` + /// ([`formats_differ`]): the render target formats come from `bound`, + /// everything else stays the title's. + pub(crate) fn with_formats(&self, bound: &TargetFormats) -> GraphicsState { + let names = self.names.clone(); + let inputs: Vec = self + .inputs + .iter() + .zip(&names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + ..*e + }) + .collect(); + let mut targets = self.targets; + let n = (targets.NumRenderTargets as usize).min(8); + for (to, &from) in targets.RTFormats[..n].iter_mut().zip(bound) { + *to = DXGI_FORMAT(from as i32); + } + GraphicsState { + blend: self.blend, + sample_mask: self.sample_mask, + rasterizer: self.rasterizer, + depth: self.depth, + depth_bounds: self.depth_bounds, + inputs, + names, + strip_cut: self.strip_cut, + topology: self.topology, + targets, + depth_format: self.depth_format, + samples: self.samples, + } + } + /// Takes in one subobject of a stream: its type, then its data at +4 /// (+8 for those holding pointers). /// @@ -1117,4 +1202,81 @@ mod tests { ]; let _ = offsets(&inputs); } + + #[test] + fn bound_formats_are_compared_slot_by_slot() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.targets.RTFormats[2] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + let declared = g.formats(); + assert_eq!(declared, [24, 28, 0, 0, 0, 0, 0, 0, 40]); + assert!(!formats_differ(&declared, &declared)); + assert!(!formats_differ(&declared, &[24, 0, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 0])); + assert!(!formats_differ(&declared, &[0; 9])); + assert!(formats_differ(&declared, &[26, 28, 0, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 28, 0, 0, 0, 0, 0, 40])); + assert!(!formats_differ(&declared, &[24, 28, 0, 0, 0, 0, 0, 0, 45])); + assert!(!formats_differ( + &[24, 0, 0, 0, 0, 0, 0, 0, 0], + &[24, 0, 0, 0, 0, 0, 0, 0, 40] + )); + assert_eq!( + formats_for(&declared, &[26, 28, 28, 0, 0, 0, 0, 0, 45]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!( + formats_for(&declared, &[26, 0, 0, 0, 0, 0, 0, 0, 0]), + [26, 28, 0, 0, 0, 0, 0, 0, 40] + ); + assert_eq!(formats_for(&declared, &declared), declared); + } + + #[test] + fn a_state_for_the_bound_formats() { + let mut g = GraphicsState::default(); + g.targets.NumRenderTargets = 2; + g.targets.RTFormats[0] = DXGI_FORMAT_R10G10B10A2_UNORM; + g.targets.RTFormats[1] = DXGI_FORMAT_R8_UINT; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + g.sample_mask = 0x55; + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.blend.RenderTarget[0].BlendEnable = true.into(); + g.blend.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; + g.names = vec![c"POSITION".to_owned()]; + g.inputs = vec![D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(g.names[0].as_ptr().cast()), + Format: DXGI_FORMAT_R32G32B32_FLOAT, + ..Default::default() + }]; + + let g_blend = host_blend(&g.blend, &g.targets); + assert!(!g_blend.RenderTarget[1].BlendEnable.as_bool()); + + let bound = formats_for(&g.formats(), &[26, 26, 0, 0, 0, 0, 0, 0, 0]); + assert_eq!(bound, [26, 26, 0, 0, 0, 0, 0, 0, 40]); + let v = g.with_formats(&bound); + assert_eq!(v.formats(), bound); + assert_eq!(v.targets.NumRenderTargets, 2); + assert_eq!(v.depth_format, DXGI_FORMAT_D32_FLOAT); + let v_blend = host_blend(&v.blend, &v.targets); + assert!(v_blend.RenderTarget[0].BlendEnable.as_bool()); + assert_ne!(v.describe(), g.describe()); + assert_eq!( + (v.sample_mask, v.rasterizer.CullMode), + (0x55, D3D12_CULL_MODE_NONE) + ); + assert_eq!(v.inputs.len(), 1); + assert_eq!(v.inputs[0].SemanticName.0, v.names[0].as_ptr().cast::()); + assert_ne!(v.inputs[0].SemanticName.0, g.inputs[0].SemanticName.0); + + let bound_int = [36, 24, 0, 0, 0, 0, 0, 0, 40]; + let v_int = g.with_formats(&bound_int); + let v_int_blend = host_blend(&v_int.blend, &v_int.targets); + assert!(!v_int_blend.RenderTarget[0].BlendEnable.as_bool()); + assert!(v_int_blend.RenderTarget[1].BlendEnable.as_bool()); + } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 38886e79..22a2577a 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -23,7 +23,7 @@ use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; use super::Shader; -use super::host::{GraphicsState, HostPipeline}; +use super::host::{GraphicsState, HostPipeline, TargetFormats}; use super::schedule::{ COMPUTE_BUDGET, Lane, PriorityQueue, WaitBudgets, lane_for, sync_compute_enabled, }; @@ -53,6 +53,13 @@ pub(crate) struct Pending { /// whether a draw has used it yet. pub(crate) key: String, used: AtomicBool, + /// The formats its state declares for what a draw draws into (zeros + /// without a graphics state). + pub(crate) formats: TargetFormats, + /// The same shaders and state for other formats, bound at a draw + /// ([`for_formats`]): a chain from the title's pipeline, one link per + /// set of formats met, never shortened. + variant: OnceLock>, } // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input @@ -85,6 +92,8 @@ impl Pending { && shaders.first().is_some_and(|s| s.stage == "compute") && sync_compute_enabled(); Pending { + formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), + variant: OnceLock::new(), key, shaders, graphics, @@ -240,6 +249,60 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { p.made.get()?.as_ref() } +/// Pipelines made again for the formats bound at a draw, since the start. +static VARIANTS: AtomicU64 = AtomicU64::new(0); + +/// Whether a draw into views of other formats than its pipeline declares +/// gets a host pipeline for those formats ([`for_formats`]). On by +/// default; `VICTORY_TARGET_VARIANTS=0` sends such a draw to the host with +/// the title's pipeline, as before. +fn variants_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_TARGET_VARIANTS").is_none_or(|v| v != "0")) +} + +/// The host pipeline for a draw with `p` into views of the formats +/// `bound`, which `p` does not declare (`host::formats_differ`). +#[cold] +pub(crate) fn for_formats<'a>( + p: &'a Arc, + bound: &TargetFormats, +) -> Option<&'a HostPipeline> { + match p.graphics.as_deref() { + Some(g) if variants_on() => { + ready(variant(p, g, &super::host::formats_for(&p.formats, bound))) + } + _ => ready(p), + } +} + +fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> &'a Arc { + let mut at = p; + for _ in 0..64 { + let next = at.variant.get_or_init(|| { + let so_far = VARIANTS.fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + pipeline = ?p.shaders, + declared = ?p.formats, + bound = ?bound, + so_far, + "a pipeline is made again for the render target formats bound at its draw (VICTORY_TARGET_VARIANTS=0 disables)" + ); + Arc::new(Pending::new( + p.shaders.clone(), + Some(Box::new(g.with_formats(bound))), + #[cfg(feature = "diagnostics")] + &[], + )) + }); + if next.formats == *bound { + return next; + } + at = next; + } + p +} + /// Starts making `p` now, without waiting for it. pub(crate) fn begin(p: &Arc) { if !p.shaders.is_empty() { @@ -533,6 +596,31 @@ mod tests { ); } + #[test] + fn a_pipeline_for_bound_formats_is_made_once() { + let p = Arc::new(Pending::new( + Vec::new(), + Some(Box::new(GraphicsState::declaring(24))), + #[cfg(feature = "diagnostics")] + &[], + )); + assert_eq!(p.formats, [24, 0, 0, 0, 0, 0, 0, 0, 0]); + let g = p.graphics.as_deref().unwrap(); + let (a, b) = ([26, 0, 0, 0, 0, 0, 0, 0, 0], [28, 0, 0, 0, 0, 0, 0, 0, 0]); + let first = variant(&p, g, &a); + assert_eq!(first.formats, a); + assert_ne!(first.key, p.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + let second = variant(&p, g, &b); + assert_eq!(second.formats, b); + assert!(!Arc::ptr_eq(first, second)); + assert_ne!(second.key, first.key); + assert!(Arc::ptr_eq(first, variant(&p, g, &a))); + assert!(Arc::ptr_eq(second, variant(&p, g, &b))); + assert!(!first.queued.load(Ordering::Relaxed)); + assert!(!p.queued.load(Ordering::Relaxed)); + } + #[cfg(feature = "diagnostics")] #[test] fn skipped_pipeline_stays_off_the_queue() { diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 6563bd19..ea698e26 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -3982,4 +3982,188 @@ mod tests { assert_eq!(slot::(heap, 0x10)(heap), 1); assert_eq!(slot::(placed, 0x10)(placed), 0); } + + /// An earlier title-memory upload in a command list must not suppress a + /// later alias copy from a GPU-written atlas (`R32_UINT` -> `R9G9B9E5`), + /// and a subsequent GPU write to the source in the same list must copy + /// again into the sampled view. + #[cfg(windows)] + #[test] + fn alias_after_title_upload_and_mid_list_gpu_write_copies_the_gpu_atlas() { + use crate::backend::{HostGpu, HostMemory}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let Some(host) = crate::host::host() else { + return; + }; + let null = std::ptr::null(); + let h = heap(1 << 20); + let place = |desc: &ResourceDesc| { + let mut out = null; + assert_eq!( + create_placed( + null, + h, + 0, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut out + ), + S_OK + ); + out + }; + // 4x4 R32G32_UINT (format 17, 8 bytes/texel) and 16x16 BC1_UNORM + // (format 71, 4x4 blocks of 8 bytes) cannot share a host texture + // across uncompressed/compressed families, so `alias_source` pairs them. + let source = place(&ResourceDesc { + flags: UNORDERED, + ..texture(4, 4, 17, 1) + }); + let view = place(&texture(16, 16, 71, 1)); + let written = host_resource(source).expect("written host texture"); + let sampled = host_resource(view).expect("sampled host texture"); + assert_eq!(alias_source(view).map(|a| a.get()), Some(source)); + + let (upload, data) = host.upload_buffer(2048).unwrap(); + let first_light = 0x8c02_0100_55aa_1122_u64; + let second_light = 0x9d04_0200_cc33_7788_u64; + // SAFETY: two 1024-byte 4-row footprints inside the 2048-byte upload buffer. + unsafe { + for row in 0..4 { + for x in 0..4 { + data.add(row * 256 + x * 8) + .cast::() + .write_unaligned(first_light); + data.add(1024 + row * 256 + x * 8) + .cast::() + .write_unaligned(second_light); + } + } + } + let copy_into_source = |list: &crate::host::HostList, offset: u64| { + // SAFETY: borrowed COM pointers live through CopyTextureRegion. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&written), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: written.GetDesc().Format, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + crate::list::ensure_state(list, source, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + }; + + let seed = host.new_list().unwrap(); + copy_into_source(&seed, 0); + seed.close(); + host.execute(&[&seed]); + + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + let list = host.new_list().unwrap(); + crate::texture::upload(&list, view, &sampled); + assert!(crate::texture::alias_copy(&list, source, view)); + copy_into_source(&list, 1024); + assert!(crate::texture::alias_copy(&list, source, view)); + + crate::list::ensure_state(&list, view, D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32); + // SAFETY: open list; valid readback footprint for 16x16 BC1 texture. + unsafe { + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: sampled.GetDesc().Format, + Width: 16, + Height: 16, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&sampled), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + list.close(); + host.execute(&[&list]); + + let mut mapped = std::ptr::null_mut(); + // SAFETY: completed GPU copy into a 1024-byte readback buffer. + let actual = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let texel = mapped.cast::().read_unaligned(); + readback.Unmap(0, None); + texel + }; + for r in [view, source, h] { + assert_eq!(slot::(r, 0x10)(r), 0); + } + assert_eq!( + actual, second_light, + "sampled alias view did not reflect the latest GPU-written atlas" + ); + } } diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 035ec1de..ce69a3d8 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -331,7 +331,7 @@ pub(crate) static ALIAS_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic /// subresource with its own format, as many as have the same bytes per /// row and rows in both; `to` no longer takes its contents from title /// memory. -pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { +pub(crate) fn alias_copy(list: &HostList, from: This, to: This) -> bool { const COPY_DEST: u32 = 0x400; const COPY_SOURCE: u32 = 0x800; let (Some(a), Some(b), Some(host)) = ( @@ -339,11 +339,26 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { crate::resource::host_resource(to), host(), ) else { - return; + return false; }; - // An odd key: textures' own first uses are keyed by the host texture. - if !list.first_use(to as usize | 1) { - return; + // An upload from title memory can have already used this view; only a + // copy from the same GPU source with no intervening state change on the + // source can satisfy this read. + list.first_use(to as usize | 1); + let new_source = list.alias_source_changed(&b, &a); + let before = list.transition(from, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(&texture, COPY_SOURCE); + let barrier = crate::host::transition( + &texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !new_source && before.is_none() { + return true; } // SAFETY: live resources. let (da, db) = unsafe { (a.GetDesc(), b.GetDesc()) }; @@ -377,12 +392,11 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { .count() as u32; if n == 0 { once!(?da, ?db, "an aliased texture not copied: its layouts differ on the host"); - return; + return false; } - let Some(buffer) = host.default_buffer(total) else { return }; + let Some(buffer) = host.default_buffer(total) else { return false }; list.keep(&buffer); crate::texture::host_writes(list, to); - crate::list::ensure_state(list, from, COPY_SOURCE); crate::list::ensure_state(list, to, COPY_DEST); let place = |r: &ID3D12Resource, f: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { // SAFETY: a borrowed pointer the copy does not release. @@ -418,6 +432,7 @@ pub(crate) fn alias_copy(list: &HostList, from: This, to: This) { logged.push((from as usize, to as usize)); tracing::info!(from = ?from, to = ?to, a = da.Format.0, b = db.Format.0, w = da.Width, h = da.Height, subresources = n, "aliased texture copied"); } + true } /// Has `resource`'s host copy brought up to date at the submission that