diff --git a/d3d12/crates/leonida-gpu/src/descriptor/host.rs b/d3d12/crates/leonida-gpu/src/descriptor/host.rs index 921dcc9dbf..de5ab08204 100644 --- a/d3d12/crates/leonida-gpu/src/descriptor/host.rs +++ b/d3d12/crates/leonida-gpu/src/descriptor/host.rs @@ -281,6 +281,13 @@ pub(crate) struct HostHeap { /// they were made from and when that was /// ([`HostHeap::texture_slot_gone`]). away: Mutex>, + /// For slots showing a placed `R9G9B9E5` view: the serial of the castable + /// source host texture shown (`0` when showing the placed view's own copy). + cast_serials: Mutex>, + /// [`crate::texture::alias_cast`] at this heap's last [`HostHeap::texture_views_remade`] + /// pass (`u8::MAX` before its first pass), so each view heap remakes its own + /// placed `R9G9B9E5` slots when `LEONIDA_AB` flips `LEONIDA_ALIAS_CAST`. + last_cast_on: std::sync::atomic::AtomicU8, /// The host resource each slot views, held while the slot does: shaders /// index heaps directly, so a slot the title has not rewritten since it /// released the resource may still be read, and a freed host resource @@ -479,10 +486,67 @@ fn begun_before(view: &View) -> Option { let View::Shader(resource, _) = shader else { return None; }; + if let Some((_, copy)) = crate::resource::cast_alias_of(resource as crate::object::This) { + return crate::pool::begun_before(©.texture); + } let texture = crate::resource::host_resource(resource as crate::object::This)?; crate::pool::begun_before(texture) } +/// For a placed `R9G9B9E5` shader view: the serial of the castable source host +/// texture it resolves to now (`0` when it uses its own host copy); `None` for +/// every other view. +pub(crate) fn view_cast_serial(view: &View) -> Option { + let resolved = placed_texture(view); + let View::Shader(resource, _) = resolved.as_ref().unwrap_or(view) else { + return None; + }; + crate::resource::cast_alias_serial(*resource as crate::object::This) +} + +/// Collects `(k, View)` for every placed `R9G9B9E5` shader view in the `n` +/// validated 32-byte descriptor slots starting at `table`, taking `views_read` +/// at most once for the whole table (zero times when every slot is null or an +/// inline constant buffer). +pub(crate) fn table_r9g9b9e5_views(table: u64, n: u32, out: &mut Vec<(u32, View)>) { + out.clear(); + let mut views = None; + for k in 0..n { + // SAFETY: caller verified `[table, table + n * 32)` lies in a bound view heap. + let words = unsafe { ((table + u64::from(k) * 32) as *const [u32; 3]).read_unaligned() }; + if words[0] != super::VIEW_TAG { + continue; + } + match words[2] >> super::KIND_SHIFT { + super::PLACED => { + let v = views.get_or_insert_with(super::views_read); + let payload = super::payload(words[1], words[2]); + if let Some(&(unordered, resource, _)) = + v.shapes.get((payload >> super::PLACED_ADDRESS_BITS) as usize) + && !unordered + && resource[0] != 1 + && resource[8] == 67 + && let Some(view) = v.placed_of(words[1], words[2]) + { + out.push((k, view)); + } + } + 0 => { + let v = views.get_or_insert_with(super::views_read); + if let Some((view, current)) = v.list.get(words[1] as usize) + && *current == words[2] + && let View::Placed(false, resource, _) = view + && resource[0] != 1 + && resource[8] == 67 + { + out.push((k, view.clone())); + } + } + _ => {} + } + } +} + /// Slots shown late ([`show_after`]), the frames they waited, the longest; /// those that were given the neutral texture meanwhile; those not shown any /// more when their time came. @@ -2267,6 +2331,8 @@ impl HostHeap { copied: Mutex::new(Vec::new()), waiting: Mutex::default(), away: Mutex::default(), + cast_serials: Mutex::default(), + last_cast_on: std::sync::atomic::AtomicU8::new(u8::MAX), kept: (0..count + extra).map(|_| Mutex::new(None)).collect(), next: Mutex::new((0, DynamicBits::new(extra as usize))), free: std::sync::atomic::AtomicU32::new(extra), @@ -2922,6 +2988,11 @@ impl HostHeap { if self.sampler { return 0; } + let cast_now = u8::from(crate::texture::alias_cast()); + let cast_flipped = { + let prev = self.last_cast_on.swap(cast_now, std::sync::atomic::Ordering::Relaxed); + prev != u8::MAX && prev != cast_now + }; { let mut after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); if !after.is_empty() { @@ -2936,13 +3007,20 @@ impl HostHeap { } } let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); - if starts.is_empty() { + if starts.is_empty() && !cast_flipped { return 0; } - let slots: Vec = { + let mut slots: Vec = if starts.is_empty() { + Vec::new() + } else { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); starts.iter().flat_map(|&start| placed.slots_at(start)).collect() }; + if cast_flipped { + slots.extend(self.cast_serials.lock().unwrap_or_else(|e| e.into_inner()).keys().copied()); + slots.sort_unstable(); + slots.dedup(); + } let mut remade = 0; for slot in slots { let _made = self.made.lock(slot); @@ -2952,9 +3030,14 @@ impl HostHeap { let Some(view) = view_at(key as u32, (key >> 32) as u32) else { continue; }; - if let Some(kept) = make(&view, self.at(slot)) { + let (kept, cast_serial) = make_twinned_info(&view, self.at(slot), None); + if let Some(kept) = kept { self.put(slot); self.keep(slot, kept); + self.note_cast_serial(slot, cast_serial); + if cast_serial.is_some() { + self.quick_is(slot, 0); + } remade += 1; } } @@ -3099,6 +3182,7 @@ impl HostHeap { && let Some((view, key)) = self.prepare_texture_slot(index, handle) && let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view)) && crate::resource::buffer_bytes(resource as crate::object::This).is_none() + && crate::resource::cast_alias_of(resource as crate::object::This).is_none() && crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource as crate::object::This) { @@ -3231,12 +3315,14 @@ impl HostHeap { return false; }; let stale = self.note_buffer(index, Some(&view), true); - if let Some(kept) = make(&view, self.at(index)) { + let (kept, cast_serial) = make_twinned_info(&view, self.at(index), None); + if let Some(kept) = kept { self.put(index); self.quick_is(index, 0); self.clear_twin(index); self.made.set(index, key); self.keep(index, kept); + self.note_cast_serial(index, cast_serial); (true, stale) } else { (false, stale) @@ -3300,7 +3386,8 @@ impl HostHeap { continue; } } - if let Some(kept) = make(&view, self.at(f.index)) { + let (kept, cast_serial) = make_twinned_info(&view, self.at(f.index), None); + if let Some(kept) = kept { #[cfg(feature = "diagnostics")] note_before(f.index, shown, if f.late.is_some() { "shown after its upload" } else { "flip" }); self.put(f.index); @@ -3309,6 +3396,7 @@ impl HostHeap { self.quick_is(f.index, 0); self.made.set(f.index, f.key); self.keep(f.index, kept); + self.note_cast_serial(f.index, cast_serial); #[cfg(feature = "diagnostics")] if f.late.is_some() && was != 0 { same_bytes(was, f.key); @@ -3349,6 +3437,7 @@ impl HostHeap { /// made: a null view of the kind it held. Under its lock ([`Made`]). fn unmake(&self, index: u32) { self.quick_is(index, 0); + self.note_cast_serial(index, None); let Some(key) = self.made.get(index) else { return; }; @@ -3715,7 +3804,7 @@ impl HostHeap { /// Makes slot `index` (a dynamic one) from `view`; a null view if the /// host cannot. pub(crate) fn make_at(&self, index: u32, view: &View) { - let kept = make_twinned(view, self.at(index), self.twin(index)); + let kept = make_twinned_info(view, self.at(index), self.twin(index)).0; let bias = take_twin_bias(); if kept.is_none() { null_for(view, self.at(index)); @@ -3746,8 +3835,45 @@ impl HostHeap { flush_listed(); views.recording = recording; views.made.clear(); + views.cast_serials.clear(); } let twins = self.twins.get(index as usize).is_some(); + let stale_at = if views.cast_serials.is_empty() { + None + } else { + views.cast_serials.get(&words).and_then(|&was| { + let m = views.made.get(&words)?; + (view_cast_serial(&m.view) != Some(was)).then(|| (m.at, m.view.clone())) + }) + }; + if let Some((at, view)) = stale_at { + // (Copies still noted under `batch_descriptors()` read `views.slot(at)` before it is overwritten.) + flush_listed(); + let (s0, s1) = (views.slot(at), views.slot(at + 1)); + let (kept, cast_serial) = make_twinned_info(&view, s0, Some(s1)); + let Some(kept) = kept else { + null_for(&view, s0); + if let Some(existing) = views.made.get_mut(&words) { + existing.kept = None; + existing.twin = false; + existing.listed.ready = (0, 0, false); + } + views.cast_serials.insert(words, u64::MAX); + return None; + }; + if let Some(existing) = views.made.get_mut(&words) { + existing.kept = kept; + existing.listed.ready = (0, 0, false); + match cast_serial { + Some(cs) => { + views.cast_serials.insert(words, cs); + } + None => { + views.cast_serials.remove(&words); + } + } + } + } if !views.made.contains_key(&words) { let view = super::view_at(words[1], words[2])?; let at = 2 * views.made.len() as u32; @@ -3756,10 +3882,13 @@ impl HostHeap { return None; } let twin = twinned(&view); - let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1))); + let (kept, cast_serial) = make_twinned_info(&view, views.slot(at), Some(views.slot(at + 1))); // (The twin's bias goes with the record's copies.) let stride_word = with_twin_bias(view_stride_word(&view), take_twin_bias()); let kept = kept?; + if let Some(cs) = cast_serial { + views.cast_serials.insert(words, cs); + } let listed = Listed { kind: crate::draw::view_kind(&view), texture: is_texture_view(&view), @@ -4479,10 +4608,10 @@ impl HostHeap { } self.quick_is(index, 0); self.made.set(index, if later { 0 } else { key }); - let kept = if later { - None + let (kept, cast_serial) = if later { + (None, None) } else { - make_twinned(&view, self.at(index), self.twin(index)) + make_twinned_info(&view, self.at(index), self.twin(index)) }; let bias = take_twin_bias(); if kept.is_none() && !self.sampler { @@ -4492,18 +4621,58 @@ impl HostHeap { self.put(index); } self.twin_made(index, kept.is_some() && twinned(&view)); - if kept.is_some() && bias != 0 { + let is_made = kept.is_some(); + if is_made && bias != 0 { // (`note_buffer` wrote the word without it.) self.write_stride(index, with_twin_bias(view_stride_word(&view), bias)); } self.keep(index, kept.flatten()); - self.quick_is(index, if later { 0 } else { key }); + self.note_cast_serial(index, cast_serial.filter(|&cs| is_made || cs != 0)); + self.quick_is(index, if later || cast_serial.is_some() { 0 } else { key }); drop(held); self.unmake_stale(index, stale); + } else if !self.sampler + && let Some(now_serial) = view_cast_serial(&view) + && self.cast_serial_of(index) != Some(now_serial) + { + let (kept, cast_serial) = make_twinned_info(&view, self.at(index), self.twin(index)); + if kept.is_none() { + null_for(&view, self.at(index)); + } + let is_made = kept.is_some(); + self.put(index); + self.twin_made(index, is_made && twinned(&view)); + self.keep(index, kept.flatten()); + self.note_cast_serial( + index, + if is_made { + cast_serial.or(Some(now_serial)) + } else { + cast_serial.filter(|&cs| cs != 0) + }, + ); + self.quick_is(index, 0); } Some(view) } + fn note_cast_serial(&self, index: u32, serial: Option) { + let mut map = self.cast_serials.lock().unwrap_or_else(|e| e.into_inner()); + match serial { + Some(serial) => { + map.insert(index, serial); + } + None if !map.is_empty() => { + map.remove(&index); + } + None => {} + } + } + + fn cast_serial_of(&self, index: u32) -> Option { + self.cast_serials.lock().unwrap_or_else(|e| e.into_inner()).get(&index).copied() + } + /// Whether slot `index` was made from no record: what [`HostHeap::mirror`] /// would find before it did nothing for one that holds no view. pub(crate) fn shows_none(&self, index: u32) -> bool { @@ -5295,7 +5464,12 @@ fn buffer_uav( /// family takes the texture's format. /// shortcut: such a view (sRGB of UNORM, say) reads without its /// conversion; cast with castable formats if colors come out wrong. -fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { +fn fits( + texture: &ID3D12Resource, + castable_r9g9b9e5: bool, + mut format: Option<&mut DXGI_FORMAT>, + unordered: bool, +) -> bool { use crate::resource::{DEPTH_FORMATS, family}; // SAFETY: a live resource. let d = unsafe { texture.GetDesc() }; @@ -5331,6 +5505,9 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere if view == 0 { return !typeless; } + if castable_r9g9b9e5 && !unordered && view == DXGI_FORMAT_R9G9B9E5_SHAREDEXP.0 as u32 { + return true; + } // A view of a target whose format the host refuses, in the title's // format: in the stand-in the host copy has. if view != own && crate::resource::target_format(view) == own { @@ -5351,6 +5528,84 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere true } +/// An explicit `R9G9B9E5_SHAREDEXP` shader resource view description for a +/// castable `R32_UINT` / `R32_SINT` texture `texture`, preserving any mip/layer +/// window in `desc` and spelling out the whole texture when `desc` is `None` or +/// `DXGI_FORMAT_UNKNOWN`. +fn r9g9b9e5_srv_desc( + texture: &ID3D12Resource, + desc: Option<[u32; 10]>, +) -> Option { + if let Some(words) = &desc { + let mut d = srv_desc(words); + if d.Format.0 == 0 { + d.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + } + return Some(d); + } + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }; + let mips = u32::from(own.MipLevels); + let layers = u32::from(own.DepthOrArraySize); + let (dimension, view) = match (own.Dimension, layers > 1) { + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, false) => ( + D3D12_SRV_DIMENSION_TEXTURE1D, + D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture1D: D3D12_TEX1D_SRV { MostDetailedMip: 0, MipLevels: mips, ResourceMinLODClamp: 0.0 }, + }, + ), + (D3D12_RESOURCE_DIMENSION_TEXTURE1D, true) => ( + D3D12_SRV_DIMENSION_TEXTURE1DARRAY, + D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture1DArray: D3D12_TEX1D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: mips, + FirstArraySlice: 0, + ArraySize: layers, + ResourceMinLODClamp: 0.0, + }, + }, + ), + (D3D12_RESOURCE_DIMENSION_TEXTURE2D, false) => ( + D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: mips, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ), + (D3D12_RESOURCE_DIMENSION_TEXTURE2D, true) => ( + D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: mips, + FirstArraySlice: 0, + ArraySize: layers, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ), + (D3D12_RESOURCE_DIMENSION_TEXTURE3D, _) => ( + D3D12_SRV_DIMENSION_TEXTURE3D, + D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture3D: D3D12_TEX3D_SRV { MostDetailedMip: 0, MipLevels: mips, ResourceMinLODClamp: 0.0 }, + }, + ), + _ => return None, + }; + Some(D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + ViewDimension: dimension, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: view, + }) +} + /// The title's unordered access view of a depth texture, as a view of the /// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip /// and slices, in the colour format of the twin's family for a depth or @@ -5482,40 +5737,43 @@ fn constant_twinned( true } -/// Makes the host descriptor for `view` at `at`: the host resource it -/// views, or `None` if it cannot. +#[cfg(test)] fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { - make_twinned(view, at, None) + make_twinned_info(view, at, None).0 } -/// [`make`]; `twin`: where the raw twin of a buffer view goes -/// ([`raw_twins`]; a constant buffer's is the same view again, other views -/// have none). -fn make_twinned( +/// Makes `view` at `at` (and `twin` when needed), plus the cast-source serial +/// (`Some(serial)` or `Some(0)`) when `view` is a placed `R9G9B9E5` texture view. +fn make_twinned_info( view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE, twin: Option, -) -> Option { +) -> (Option, Option) { // (What a twin made here begins before its view by: [`take_twin_bias`].) let _ = take_twin_bias(); - let host = host()?; + let Some(host) = host() else { return (None, None) }; let device = &host.device; match view { &View::Constant(address, size) => { - let shadow = crate::shadow::find(address, u64::from(size))?; + let Some(shadow) = crate::shadow::find(address, u64::from(size)) else { + return (None, None); + }; let gpu = shadow.gpu(address); if crate::port_cbv::on() { // Renderer port 5: shaders read constant buffers as raw bytes // through the twin; a constant buffer view there would be read // raw, with no end on AMD. - return constant_twinned(&shadow.buffer, gpu, size, at, twin).then(|| Some(shadow.buffer.clone())); + return ( + constant_twinned(&shadow.buffer, gpu, size, at, twin).then(|| Some(shadow.buffer.clone())), + None, + ); } if gpu % 256 != 0 { once!( address = format_args!("{address:#x}"), "constant buffer not 256-byte aligned on the host" ); - return None; + return (None, None); } let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { BufferLocation: gpu, @@ -5528,10 +5786,28 @@ fn make_twinned( device.CreateConstantBufferView(Some(&desc), twin); } } - Some(Some(shadow.buffer.clone())) + (Some(Some(shadow.buffer.clone())), None) } View::Shader(resource, desc) => { let resource = *resource as crate::object::This; + if let Some((_held, copy)) = crate::resource::cast_alias_of(resource) { + let texture = ©.texture; + let mut srv = r9g9b9e5_srv_desc(texture, *desc); + if !fits(texture, true, srv.as_mut().map(|d| &mut d.Format), false) { + return (None, Some(copy.serial)); + } + // SAFETY: a live castable texture and a slot of our heap. + unsafe { + device.CreateShaderResourceView( + texture, + srv.as_ref().map(std::ptr::from_ref), + at, + ) + }; + note_volume_view(texture, srv.as_ref()); + return (Some(Some(texture.clone())), Some(copy.serial)); + } + let cast_candidate = crate::resource::is_r9g9b9e5_placed(resource).then_some(0); if let Some(copy) = crate::resource::host_copy(resource) { let texture = ©.texture; // The title's views of textures with a stencil plane, as it @@ -5559,8 +5835,8 @@ fn make_twinned( } } let mut desc = desc.as_ref().map(srv_desc); - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { - return None; + if !fits(texture, false, desc.as_mut().map(|d| &mut d.Format), false) { + return (None, cast_candidate); } // Levels on demand (`crate::tiles`): a texture made level by // level is shown from the first level that is the title's @@ -5604,13 +5880,13 @@ fn make_twinned( ) }; note_volume_view(texture, desc.as_ref()); - Some(Some(texture.clone())) + (Some(Some(texture.clone())), cast_candidate) } else if let (Some((data, len)), Some(desc)) = (crate::resource::buffer_bytes(resource), desc) { - buffer_srv(data as u64, len, srv_desc(desc), at, twin) + (buffer_srv(data as u64, len, srv_desc(desc), at, twin), None) } else { - None + (None, cast_candidate) } } View::Unordered(resource, _counter, desc) => { @@ -5618,9 +5894,9 @@ fn make_twinned( let Some(texture) = crate::resource::host_resource(resource) else { return match (crate::resource::buffer_bytes(resource), desc) { (Some((data, len)), Some(desc)) => { - buffer_uav(data as u64, len, uav_desc(desc), at, twin) + (buffer_uav(data as u64, len, uav_desc(desc), at, twin), None) } - _ => None, + _ => (None, None), }; }; // The first such views of depth textures are logged as the @@ -5654,8 +5930,8 @@ fn make_twinned( } None => texture, }; - if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { - return None; + if !fits(texture, false, desc.as_mut().map(|d| &mut d.Format), true) { + return (None, None); } // SAFETY: a live texture and a slot of our heap. unsafe { @@ -5666,7 +5942,7 @@ fn make_twinned( at, ) }; - Some(Some(texture.clone())) + (Some(Some(texture.clone())), None) } View::Sampler(words) => { // SAFETY: 13 words in the host's layout. @@ -5677,17 +5953,17 @@ fn make_twinned( }; // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; - Some(None) + (Some(None), None) } View::ConsoleSampler(words) => { let desc = crate::sampler::console(words, crate::sampler::aniso_point_mip(device)); // SAFETY: a slot of our sampler heap. unsafe { device.CreateSampler(&desc, at) }; - Some(None) + (Some(None), None) } View::Placed(unordered, resource, desc) => { if let Some(view) = placed_texture(view) { - return make(&view, at); + return make_twinned_info(&view, at, twin); } const BUFFER: u32 = 1; if resource[0] != BUFFER { @@ -5713,7 +5989,7 @@ fn make_twinned( ); } } - return None; + return (None, None); } // The resource description's width, after the alignment. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; @@ -5722,13 +5998,14 @@ fn make_twinned( // An empty title buffer: nothing to view, and no host copy to // look for (#70: such views were in flight at device removals). if len == 0 { - return None; + return (None, None); } - if *unordered { + let made = if *unordered { buffer_uav(address, len, uav_desc(words), at, twin) } else { buffer_srv(address, len, srv_desc(words), at, twin) - } + }; + (made, None) } } } @@ -7919,6 +8196,7 @@ struct ListViews { step: usize, start: usize, made: std::collections::HashMap<[u32; 3], ListView, std::hash::BuildHasherDefault>, + cast_serials: std::collections::HashMap<[u32; 3], u64, std::hash::BuildHasherDefault>, } impl ListViews { @@ -7938,7 +8216,14 @@ impl ListViews { .ok()?; let step = host.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; let start = heap.GetCPUDescriptorHandleForHeapStart().ptr; - Some(ListViews { recording: 0, heap, step, start, made: Default::default() }) + Some(ListViews { + recording: 0, + heap, + step, + start, + made: Default::default(), + cast_serials: Default::default(), + }) } } @@ -7955,6 +8240,12 @@ thread_local! { const { std::cell::RefCell::new(Vec::new()) }; } +#[cfg(test)] +thread_local! { + /// A test's choice for [`batch_descriptors`], for its thread only. + pub(crate) static TEST_BATCH_DESCRIPTORS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Whether the descriptor copies of the views a list made before go into a table's dynamic slots in one /// `CopyDescriptors` call for the table instead of one `CopyDescriptorsSimple` call a slot /// (`LEONIDA_BATCH_DESCRIPTORS=1`, or by turns with `LEONIDA_AB`; off by default). After PL-VIP/sureVI @@ -7965,6 +8256,10 @@ thread_local! { /// threads have room. The copies are done right after the table's loop (`draw.rs`), and before a thread's /// views of a recording are made anew. pub(crate) fn batch_descriptors() -> bool { + #[cfg(test)] + if let Some(on) = TEST_BATCH_DESCRIPTORS.get() { + return on; + } const SWITCH: &str = "LEONIDA_BATCH_DESCRIPTORS"; #[cfg(feature = "diagnostics")] if let Some(on) = crate::ab::pick(SWITCH) { diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 6f146d7961..dacccfd751 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -2950,6 +2950,7 @@ impl State { // The title may release the pipeline before it submits the list. list.bind_pipeline(&p.name, &p.pso, &p.root); } + let _written_cast_sources = self.begin_written_cast_sources(p, compute); for stage in &p.stages { let t = stage.translated(); STORES.set(t.stores); @@ -3513,29 +3514,35 @@ impl State { let placed = crate::descriptor::host::placed_texture(&view); if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) { let resource = resource as This; - let texture = crate::resource::host_resource(resource); - let title_fills = texture.is_some_and(crate::texture::title_written); - let first = match (&placed, &view) { - (Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc), - _ => 0, - }; - if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) { - sync.keep.push(copy); - } - if title_fills - && !crate::texture::ahead::there(resource) - && (sync.is_some() || !crate::texture::unchanged(resource, first)) - { - let was_staged = crate::texture::is_staged(resource); - let _ = crate::residency::take_staging_deferred(); - readable(list, sampled.kind, &view); - let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused(); - if !was_staged { - crate::texture::unstage(resource); + if let Some((_, copy)) = crate::resource::cast_alias_of(resource) { + if let Some(sync) = sync.as_deref_mut() { + sync.keep.push(copy); } - if failed { - host.restore_pending_list_flip(item); - continue; + } else { + let texture = crate::resource::host_resource(resource); + let title_fills = texture.is_some_and(crate::texture::title_written); + let first = match (&placed, &view) { + (Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc), + _ => 0, + }; + if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) { + sync.keep.push(copy); + } + if title_fills + && !crate::texture::ahead::there(resource) + && (sync.is_some() || !crate::texture::unchanged(resource, first)) + { + let was_staged = crate::texture::is_staged(resource); + let _ = crate::residency::take_staging_deferred(); + readable(list, sampled.kind, &view); + let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused(); + if !was_staged { + crate::texture::unstage(resource); + } + if failed { + host.restore_pending_list_flip(item); + continue; + } } } } @@ -4280,6 +4287,15 @@ impl State { continue; } }; + if crate::resource::cast_alias_of(resource).is_some() { + if (shows_other || late || (sync_bake && upload_key.is_some())) + && let Some(handle) = heap.handle(index) + { + let _ = host.mirror(index, handle, true); + } + host.texture_slot_done(index, write, None); + continue; + } let texture = crate::resource::host_resource(resource); if crate::residency::upload_refused() { served = false; @@ -5177,6 +5193,9 @@ impl State { let mut h = RecordHash::default(); h.add(words); h.add([tested as u32, (tested >> 32) as u32, u32::from(compute)]); + if let Some(cs) = crate::descriptor::host::view_cast_serial(&view) { + h.add([0xca57_99e5, cs as u32, (cs >> 32) as u32]); + } h.0 }); let known = key @@ -5318,6 +5337,61 @@ impl State { } // (A view of unordered access a storing stage has that is not gone through here was // declared nowhere: `views_untold`.) + let check_cast_conflict = WRITTEN_CAST_LEN.get() != 0; + let cast_conflict = |handle: u64| -> bool { + if !check_cast_conflict { + return false; + } + let Some(view) = crate::descriptor::view(handle) else { + return false; + }; + let placed = crate::descriptor::host::placed_texture(&view); + let Some(&View::Shader(r, _)) = placed.as_ref().or(Some(&view)) else { + return false; + }; + crate::resource::is_r9g9b9e5_placed(r as This) + && crate::resource::alias_of(r as This) + .is_some_and(|held| draw_writes_texture(held.get())) + }; + if check_cast_conflict { + for &(g, e) in &plan.direct { + let group = &plan.groups[g]; + if !selected_slot(&fresh, group.slot) { + let u = &group.entries[e]; + if u.kind == ResourceType::Srv + && let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(group.slot)) + && let Some(handle) = self.checked_view_handle(table, u64::from(u.table_offset_dwords) * 4) + && cast_conflict(handle) + { + fresh[usize::from(group.slot / 64)] |= 1u64 << (group.slot % 64); + } + } + } + for group in &plan.groups { + if !selected_slot(&fresh, group.slot) + && !group.indexed.is_empty() + && let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(group.slot)) + && let Some(heap) = self.valid_view_table(table) + { + for index in &group.indexed { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + let k = index.byte_offset.wrapping_add(constant << index.shift) / 32; + if let Some(handle) = table.checked_add(u64::from(k) * 32) + && heap.index(handle).is_some() + && cast_conflict(handle) + { + fresh[usize::from(group.slot / 64)] |= 1u64 << (group.slot % 64); + break; + } + } + } + } + } let storing = STORES.get(); for &(g, e) in &plan.direct { let group = &plan.groups[g]; @@ -5400,6 +5474,19 @@ impl State { if half.contains(&(slot, k * 8)) { h.add([u32::MAX, slot.into(), k]); } + if check_cast_conflict && cast_conflict(at) { + h.add([u32::MAX - 1, slot.into(), k]); + } + } + let mut cast_views = Vec::new(); + crate::descriptor::host::table_r9g9b9e5_views(table, n, &mut cast_views); + for (k, view) in cast_views { + if !(check_cast_conflict && cast_conflict(table + u64::from(k) * 32)) + && let Some(cs) = crate::descriptor::host::view_cast_serial(&view) + { + h.add([u32::MAX - 2, k, cs as u32]); + h.add([u32::MAX - 3, slot.into(), (cs >> 32) as u32]); + } } (if content { std::ptr::from_ref(heap) as u64 | 1 } else { table }, n, h.0) }; @@ -5518,10 +5605,13 @@ impl State { // used-resource list names (descriptor arrays). for k in 0..n { let index = first + k; + let handle_k = table + u64::from(k) * 32; + let conflict_k = cast_conflict(handle_k); // A view this list has made before: its descriptor copied, // and nothing more if nothing changed in the list since. if list_views - && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) + && !conflict_k + && let Some(words) = crate::descriptor::record_at(handle_k) && let Some(mut listed) = host.make_listed(recording, words, index) { let kind = group @@ -5622,8 +5712,8 @@ impl State { && crate::descriptor::host::is_texture_view(&view) { host.texture_slot_tabled(title + k, kind.is_some()); - if kind.is_some() { - host.mirror_after(list, title + k, table + u64::from(k) * 32); + if kind.is_some() && !conflict_k { + host.mirror_after(list, title + k, handle_k); } } } @@ -7178,11 +7268,133 @@ impl RecordHash { } } +thread_local! { + static WRITTEN_CAST_LEN: std::cell::Cell = const { std::cell::Cell::new(0) }; + static WRITTEN_CAST_SOURCES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +struct WrittenCastGuard(usize); + +impl Drop for WrittenCastGuard { + fn drop(&mut self) { + let prev = self.0; + WRITTEN_CAST_SOURCES.with(|s| s.borrow_mut().truncate(prev)); + WRITTEN_CAST_LEN.set(prev); + } +} + +/// Whether the draw or dispatch being bound on this thread writes `source` +/// (as a render target or unordered-access texture): an aliased `R9G9B9E5` +/// shader view of `source` in the same draw or dispatch falls back to its own +/// host copy so whole-resource barriers keep both uses in legal states. +pub(crate) fn draw_writes_texture(source: This) -> bool { + WRITTEN_CAST_LEN.get() != 0 + && WRITTEN_CAST_SOURCES.with(|s| s.borrow().contains(&(source as usize))) +} + +impl State { + fn valid_view_table(&self, table: u64) -> Option<&'static crate::descriptor::Heap> { + let heap = self.heap_of(table)?; + (!heap.samplers() && (table - heap.start).is_multiple_of(32)).then_some(heap) + } + + fn checked_view_handle(&self, table: u64, byte_offset: u64) -> Option { + if !byte_offset.is_multiple_of(32) { + return None; + } + let heap = self.valid_view_table(table)?; + table.checked_add(byte_offset).filter(|&h| heap.index(h).is_some()) + } + + fn begin_written_cast_sources(&self, p: &HostPipeline, compute: bool) -> WrittenCastGuard { + let prev = WRITTEN_CAST_LEN.get(); + if !crate::texture::alias_cast() { + return WrittenCastGuard(prev); + } + let push = |r: usize| { + if r != 0 && crate::resource::is_castable_alias_source(r as This) { + WRITTEN_CAST_SOURCES.with(|s| { + let mut v = s.borrow_mut(); + if !v[prev..].contains(&r) { + v.push(r); + WRITTEN_CAST_LEN.set(v.len()); + } + }); + } + }; + if !compute { + for &t in &self.targets { + push(t); + } + } + for stage in &p.stages { + let plan = &stage.translated().tables; + for group in &plan.groups { + if !group.has_uav { + continue; + } + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(group.slot)) else { + continue; + }; + let Some(heap) = self.valid_view_table(table) else { + continue; + }; + for u in &group.entries { + if u.kind == ResourceType::Uav + && u.table_offset_dwords.is_multiple_of(8) + && let Some(handle) = table.checked_add(u64::from(u.table_offset_dwords) * 4) + && heap.index(handle).is_some() + && let Some(View::Unordered(r, _, _)) = crate::descriptor::view(handle) + { + push(r); + } + } + for index in &group.indexed { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + let k = index.byte_offset.wrapping_add(constant << index.shift) / 32; + if let Some(handle) = table.checked_add(u64::from(k) * 32) + && heap.index(handle).is_some() + && let Some(View::Unordered(r, _, _)) = crate::descriptor::view(handle) + { + push(r); + } + } + } + } + WrittenCastGuard(prev) + } +} + +#[cfg(test)] +pub(crate) fn test_state_for_table(heap: This, table: u64) -> State { + let mut state = State::default(); + state.heaps[0] = heap as usize; + state.compute = vec![Root::Table(table), Root::Constants(vec![u32::MAX])]; + state +} + +#[cfg(test)] +pub(crate) fn with_test_written_cast_source(source: This, run: impl FnOnce() -> R) -> R { + let prev = WRITTEN_CAST_LEN.get(); + let _guard = WrittenCastGuard(prev); + WRITTEN_CAST_SOURCES.with(|s| { + let mut v = s.borrow_mut(); + v.push(source as usize); + WRITTEN_CAST_LEN.set(v.len()); + }); + run() +} + /// Brings what `view` shows up to date in `list` for a read (or a write) as /// `kind`. True if it shows an aliased texture /// (`crate::resource::alias_of`): its copy follows what the list does to /// its source, which no epoch of the list says ([`list_alias_exact`]). -fn readable(list: &HostList, kind: ResourceType, view: &View) -> bool { +pub(crate) fn readable(list: &HostList, kind: ResourceType, view: &View) -> bool { const UNORDERED_ACCESS: u32 = 0x8; let placed = crate::descriptor::host::placed_texture(view); let view = placed.as_ref().unwrap_or(view); @@ -7209,6 +7421,20 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) -> bool { } match (view, kind) { (View::Shader(resource, _), ResourceType::Srv) => { + if let Some((held_source, _)) = crate::resource::cast_alias_of(*resource as This) { + let source = held_source.get(); + #[cfg(feature = "diagnostics")] + crate::texture::alias_cast_counted(); + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == source as usize { + TESTED_DEPTH.set((tested, true)); + DEPTH_READ | SHADER_RESOURCE + } else { + SHADER_RESOURCE + }; + crate::list::ensure_state(list, source, state); + return true; + } // A view the title placed, in another format, in the memory of // a texture the host writes: that texture's texels, copied on // the host (title memory does not have them). diff --git a/d3d12/crates/leonida-gpu/src/pool.rs b/d3d12/crates/leonida-gpu/src/pool.rs index bb1535a0f8..a2ea6bb7f8 100644 --- a/d3d12/crates/leonida-gpu/src/pool.rs +++ b/d3d12/crates/leonida-gpu/src/pool.rs @@ -564,30 +564,61 @@ fn give_back_with(texture: &ID3D12Resource, piece: Piece) { } } +#[cfg(test)] +thread_local! { + /// Forces [`on`] for a test on this thread even if `LEONIDA_TEXTURE_POOL=0`. + pub(crate) static TEST_POOL_FORCE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// A texture of `desc` (no target, depth or unordered access) in a block; /// `None`: not pooled, or the host refused. /// /// # Safety /// `desc` is a valid description. +#[cfg(test)] pub(crate) unsafe fn texture( device: &ID3D12Device, desc: *const D3D12_RESOURCE_DESC, state: D3D12_RESOURCE_STATES, ) -> Option { - if !on() { + // SAFETY: forwarded from caller. + unsafe { texture_with_cast(device, desc, state).map(|(t, _)| t) } +} + +/// [`texture`], also returning whether `CreatePlacedResource2` made the texture +/// castable to `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` (in `D3D12_BARRIER_LAYOUT_COMMON`). +/// +/// # Safety +/// `desc` is a valid description. +pub(crate) unsafe fn texture_with_cast( + device: &ID3D12Device, + desc: *const D3D12_RESOURCE_DESC, + state: D3D12_RESOURCE_STATES, +) -> Option<(ID3D12Resource, bool)> { + #[cfg(test)] + let forced = TEST_POOL_FORCE.get(); + #[cfg(not(test))] + let forced = false; + if !forced && !on() { return None; } // Small textures lie at multiples of 4 KiB where the host allows it // (the top mip is 64 KiB at most): 64 KiB each otherwise. // SAFETY: the caller's description. let mut d = unsafe { *desc }; - d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); - // SAFETY: plain queries. - let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; - if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment { - d.Alignment = 0; - info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; - } + let try_cast = crate::texture::want_r9g9b9e5_cast(&d) && crate::texture::castable_r9g9b9e5(device); + let info = if try_cast { + crate::texture::r9g9b9e5_placed_allocation_info(device, &mut d) + } else { + d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + // SAFETY: plain queries. + let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; + if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment { + d.Alignment = 0; + info = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; + } + info + }; if info.SizeInBytes == u64::MAX { return None; } @@ -617,12 +648,29 @@ pub(crate) unsafe fn texture( } heap })?; - let mut made: Option = None; - // SAFETY: the piece is no one else's; the heap lives while a piece of - // it is taken. - let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) }; - match (result, made) { - (Ok(()), Some(made)) => { + let allow_fallback = if try_cast { + // SAFETY: plain query on `d` so fallback `CreatePlacedResource` only runs if `piece` fits it too. + let plain = unsafe { device.GetResourceAllocationInfo(0, &[d]) }; + plain.SizeInBytes != u64::MAX + && piece.start.is_multiple_of(plain.Alignment.max(1)) + && plain.SizeInBytes <= piece.len + } else { + true + }; + // SAFETY: the piece is no one else's; the heap lives while a piece of it is taken. + let result = unsafe { + crate::texture::create_placed_r9g9b9e5_or_legacy( + device, + &heap, + piece.start, + &d, + state, + None, + allow_fallback, + ) + }; + match result { + Ok((made, castable)) => { HELD.fetch_add(piece.len, Ordering::Relaxed); give_back_with(&made, piece); made_now(&made); @@ -645,9 +693,9 @@ pub(crate) unsafe fn texture( ) }); } - Some(made) + Some((made, castable)) } - _ => { + Err(_) => { lock(&TEXTURES).give(piece, now()); None } diff --git a/d3d12/crates/leonida-gpu/src/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index 5158aa09a9..3c988251ab 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs @@ -1275,6 +1275,10 @@ pub(crate) struct HostTexture { /// The texture's flags (asked once: the runtime takes 100 ns to say, and /// every texture of every draw is asked about). flags: u32, + /// Made via `CreateCommittedResource3` or `CreatePlacedResource2` with + /// `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` in `pCastableFormats`, so placed + /// `R9G9B9E5` views can read it in place. + pub(crate) castable_r9g9b9e5: bool, } /// What a host copy was filled with last: the first level of it and the @@ -1620,6 +1624,58 @@ pub(crate) fn aliased(this: This) -> bool { alias_source(this, |_| Some(())).is_some() } +/// Whether `this` is a shader-written `R32_UINT` or `R32_SINT` title texture +/// that placed `R9G9B9E5` views may alias in place. +#[cfg(windows)] +pub(crate) fn is_castable_alias_source(this: This) -> bool { + if this.is_null() { + return false; + } + let r = resource(this); + r.desc.dimension != BUFFER && !fills(&r.desc) && matches!(pc_format(r.desc.format), 42 | 43) +} + +/// Whether `this` is a placed `R9G9B9E5_SHAREDEXP` texture resource ([`texture_at`]). +#[cfg(windows)] +pub(crate) fn is_r9g9b9e5_placed(this: This) -> bool { + const R9G9B9E5: u32 = 67; + if this.is_null() { + return false; + } + let r = resource(this); + r.desc.dimension != BUFFER + && r.host.placed.load(std::sync::atomic::Ordering::Relaxed) + && pc_format(r.desc.format) == R9G9B9E5 +} + +/// For `this`, a placed `R9G9B9E5_SHAREDEXP` view's texture: the pinned source +/// resource and its castable host texture when `LEONIDA_ALIAS_CAST` is active, +/// the source's host texture supports `R9G9B9E5` format casting, and the draw +/// or dispatch being bound does not also write that source texture. +#[cfg(windows)] +pub(crate) fn cast_alias_of(this: This) -> Option<(Held, std::sync::Arc)> { + if !crate::texture::alias_cast() || !is_r9g9b9e5_placed(this) { + return None; + } + let held = alias_of(this)?; + if crate::draw::draw_writes_texture(held.get()) { + return None; + } + let (copy, _) = hosted(held.get(), true)?; + copy.castable_r9g9b9e5.then_some((held, copy)) +} + +/// For `this`, if it is a placed `R9G9B9E5_SHAREDEXP` texture: the serial of +/// the castable source host texture it reads in place now, or `0` when it uses +/// its own host copy; `None` for every other resource. +#[cfg(windows)] +pub(crate) fn cast_alias_serial(this: This) -> Option { + if !is_r9g9b9e5_placed(this) { + return None; + } + Some(cast_alias_of(this).map_or(0, |(_, copy)| copy.serial)) +} + /// [`alias_of`]: `found` is called with the texture, under the lock of the /// table it was found in (it is alive there, and may have no reference /// left). @@ -1820,7 +1876,13 @@ fn hosted(this: This, make: bool) -> Option { && (!crate::texture::committed(r.data().cast_const(), bytes as usize) || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); - let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true).ok() } else { None }; + let reserved = if partly { + host_texture_as(&r.desc, r.host.state, clear, true) + .ok() + .map(|made| made.0) + } else { + None + }; let cut = reserved .as_ref() .zip(crate::host::host()) @@ -1843,12 +1905,12 @@ fn hosted(this: This, make: bool) -> Option { base = base_level(&r.desc, first); } } - let texture = match texture { - Some(texture) => Ok(texture), + let made_texture = match texture { + Some(texture) => Ok((texture, false, None)), None => host_texture(&r.desc.from_level(base), r.host.state, clear), }; - let texture = match texture { - Ok(texture) => texture, + let (texture, castable_r9g9b9e5, initial_state) = match made_texture { + Ok(made) => made, Err(NoTexture::Refused) => { r.host.refused.store(true, Relaxed); return None; @@ -1879,11 +1941,13 @@ fn hosted(this: This, make: bool) -> Option { "depth texture with unordered access" ); } - let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); + let state = initial_state + .unwrap_or_else(|| crate::host::legal_state(&texture, crate::host::texture_state(r.host.state))); let mut host = match tiled { Some(tiled) => HostTexture::new_tiled(texture, state, tiled), None => HostTexture::new(texture, state), }; + host.castable_r9g9b9e5 = castable_r9g9b9e5; host.base = base; host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed); if base > 0 { @@ -2739,6 +2803,7 @@ impl HostTexture { holds: Default::default(), ahead: crate::texture::ahead::fresh(), flags, + castable_r9g9b9e5: false, } } @@ -2764,6 +2829,7 @@ impl HostTexture { holds: Default::default(), ahead: crate::texture::ahead::fresh(), flags, + castable_r9g9b9e5: false, } } } @@ -2882,7 +2948,7 @@ fn host_texture( desc: &ResourceDesc, state: u32, clear: *const c_void, -) -> Result { +) -> Result<(windows::Win32::Graphics::Direct3D12::ID3D12Resource, bool, Option), NoTexture> { host_texture_as(desc, state, clear, false) } @@ -2894,7 +2960,7 @@ fn host_texture_as( state: u32, clear: *const c_void, reserved: bool, -) -> Result { +) -> Result<(windows::Win32::Graphics::Direct3D12::ID3D12Resource, bool, Option), NoTexture> { use windows::Win32::Graphics::Direct3D12::*; const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access if desc.dimension == BUFFER { @@ -2948,6 +3014,13 @@ fn host_texture_as( Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let initial = crate::host::legal_for(d.flags, crate::host::texture_state(state)); + #[cfg(test)] + let pool_uav = crate::texture::TEST_POOL_CAST_TARGETS.get() + && d.flags & (TARGET | DEPTH) == 0 + && matches!(d.format, 42 | 43); + #[cfg(not(test))] + let pool_uav = false; // A texture the title fills, whose every subresource is uploaded before // anything reads it: cut from a block (what the piece held before shows // in no texel). Not one asked for as reserved: cut from a block, it was @@ -2955,25 +3028,27 @@ fn host_texture_as( // (`crate::tiles`; found by aki-gta6/aki-runtime ad214cd, KeethSmith: 1,596 // of 1,596 refused there). if !reserved - && fills(desc) + && (fills(desc) || pool_uav) && d.sample_count <= 1 && clear_value.is_none() && texture_layout(desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()) // SAFETY: the description has the host layout, as below. - && let Some(t) = unsafe { - crate::pool::texture( + && let Some((t, castable)) = unsafe { + crate::pool::texture_with_cast( &host.device, (&raw const d).cast(), - D3D12_RESOURCE_STATES(crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32), + D3D12_RESOURCE_STATES(initial as i32), ) } { crate::host::name(&t, || { format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags) }); - return Ok(t); + return Ok((t, castable, castable.then_some(0))); } let mut texture: Option = None; + let mut castable_r9g9b9e5 = false; + let mut initial_override = None; let made = if reserved { // The card's own layout of 64 KiB tiles, which a reserved texture // must have. @@ -2982,28 +3057,33 @@ fn host_texture_as( unsafe { host.device.CreateReservedResource( (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), + D3D12_RESOURCE_STATES(initial as i32), None, &mut texture, ) } } else { - // SAFETY: the description has the host layout (checked size, same - // fields); the out pointer is ours. + // SAFETY: `d` has `D3D12_RESOURCE_DESC`'s layout; `clear_value` has + // `D3D12_CLEAR_VALUE`'s layout. unsafe { - host.device.CreateCommittedResource( + let base_desc = (&raw const d).cast::().read_unaligned(); + let clear_ptr = clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()); + match crate::texture::create_committed_r9g9b9e5_or_legacy( + &host.device, &heap, crate::host::not_resident(), - (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), - // The same layout: format, then color or depth and stencil. - clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), - &mut texture, - ) + &base_desc, + D3D12_RESOURCE_STATES(initial as i32), + clear_ptr, + ) { + Ok((made, castable)) => { + castable_r9g9b9e5 = castable; + initial_override = castable.then_some(0); + texture = Some(made); + Ok(()) + } + Err(e) => Err(e), + } } }; // Out of room may come back each second for many textures: its first @@ -3043,7 +3123,7 @@ fn host_texture_as( crate::host::name(&texture, || { format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) }); - Ok(texture) + Ok((texture, castable_r9g9b9e5, initial_override)) } /// The host copy of title texture `this` if it is made and was made @@ -3197,9 +3277,12 @@ fn hand_out_resource( textures().insert(at); crate::texback::replaced(resource.data() as usize); if !fills(&desc) { + let at_addr = resource.data() as u64; let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); TARGETS_CHANGED.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - targets.insert(resource.data() as u64, at); + targets.insert(at_addr, at); + drop(targets); + crate::descriptor::host::levels_changed(at_addr); } if !lazy() { let _ = hosted(at as This, true); @@ -3228,6 +3311,8 @@ impl Drop for Resource { if targets.get(&at) == Some(&(std::ptr::from_ref::(self) as usize)) { TARGETS_CHANGED.fetch_add(1, std::sync::atomic::Ordering::SeqCst); targets.remove(&at); + drop(targets); + crate::descriptor::host::levels_changed(at); } } } diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index fffb3d221b..8ad760157d 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -292,6 +292,266 @@ fn alias_direct() -> bool { thread_local! { /// A test's choice for [`alias_direct`], for its thread only. pub(crate) static TEST_ALIAS_DIRECT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// A test's choice for [`alias_cast`], for its thread only. + pub(crate) static TEST_ALIAS_CAST: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// Routes non-RT/non-DS UAV `R32_UINT`/`R32_SINT` host textures on this thread through + /// `pool::texture_with_cast` (`CreatePlacedResource2`) for placed-casting GPU tests. + pub(crate) static TEST_POOL_CAST_TARGETS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Reads of aliased views on this thread that recorded a fallback copy. + pub(crate) static TEST_ALIAS_COPIES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The castable format list passed to `CreateCommittedResource3` and `CreatePlacedResource2` +/// for `R32_UINT` / `R32_SINT` textures read through placed `R9G9B9E5_SHAREDEXP` views. +pub(crate) const R9G9B9E5_CASTABLE: [windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; 1] = [ + windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R9G9B9E5_SHAREDEXP, +]; + +/// Whether an `R9G9B9E5` view placed in a shader-written `R32_UINT` or `R32_SINT` texture reads +/// that host texture in place through a castable-format view (`CreateCommittedResource3` or +/// `CreatePlacedResource2`), with no copy on the card and no host texture of its own +/// (`LEONIDA_ALIAS_CAST=0`: copied as before; `LEONIDA_AB` can name it). +pub(crate) fn alias_cast() -> bool { + #[cfg(test)] + if let Some(on) = TEST_ALIAS_CAST.get() { + return on; + } + crate::toggled!("LEONIDA_ALIAS_CAST") +} + +/// Whether `R32_UINT` and `R32_SINT` host textures ask for `R9G9B9E5_SHAREDEXP` among their +/// castable formats when made: whenever [`alias_cast`] may be on (including while `LEONIDA_AB` +/// switches `LEONIDA_ALIAS_CAST` in turns). +pub(crate) fn alias_cast_create() -> bool { + #[cfg(test)] + if let Some(on) = TEST_ALIAS_CAST.get() { + return on; + } + #[cfg(feature = "diagnostics")] + if crate::ab::bit("LEONIDA_ALIAS_CAST").is_some() { + return true; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_ALIAS_CAST").is_none_or(|v| v != "0")) +} + +fn query_relaxed_format_casting(device: &ID3D12Device) -> bool { + use windows::core::Interface; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); + let has_device10 = device.cast::().is_ok(); + // SAFETY: writes `options` of the given size. + let ok = has_device10 + && unsafe { + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS12, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + ok && options.EnhancedBarriersSupported.as_bool() && options.RelaxedFormatCastingSupported.as_bool() +} + +/// Whether `device` supports `ID3D12Device10` relaxed format casting (`EnhancedBarriersSupported` +/// and `RelaxedFormatCastingSupported`); cached for the primary adapter and logged once. +pub(crate) fn relaxed_format_casting(device: &ID3D12Device) -> bool { + static PRIMARY: std::sync::OnceLock<(i32, u32, bool)> = std::sync::OnceLock::new(); + // SAFETY: plain LUID query on a live device. + let luid = unsafe { device.GetAdapterLuid() }; + let &(hi, lo, supported) = PRIMARY.get_or_init(|| { + let supported = query_relaxed_format_casting(device); + tracing::info!(supported, "relaxed format casting"); + (luid.HighPart, luid.LowPart, supported) + }); + if (luid.HighPart, luid.LowPart) == (hi, lo) { + supported + } else { + query_relaxed_format_casting(device) + } +} + +/// Whether `device` should create compatible `R32_UINT` / `R32_SINT` textures with +/// `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` in `pCastableFormats`. +pub(crate) fn castable_r9g9b9e5(device: &ID3D12Device) -> bool { + alias_cast_create() && relaxed_format_casting(device) +} + +/// Whether `desc` describes a single-sample, shader-readable `R32_UINT` or `R32_SINT` +/// 1D/2D/3D/array texture eligible for `R9G9B9E5_SHAREDEXP` relaxed format casting. +pub(crate) fn want_r9g9b9e5_cast(desc: &D3D12_RESOURCE_DESC) -> bool { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R32_UINT}; + matches!( + desc.Dimension, + D3D12_RESOURCE_DIMENSION_TEXTURE1D + | D3D12_RESOURCE_DIMENSION_TEXTURE2D + | D3D12_RESOURCE_DIMENSION_TEXTURE3D + ) && desc.SampleDesc.Count <= 1 + && !desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) + && !desc.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + && desc.Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE + && matches!(desc.Format, DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R32_SINT) +} + +/// Widens a legacy `D3D12_RESOURCE_DESC` to `D3D12_RESOURCE_DESC1` with an empty mip region. +pub(crate) fn desc1_of(desc: &D3D12_RESOURCE_DESC) -> D3D12_RESOURCE_DESC1 { + D3D12_RESOURCE_DESC1 { + Dimension: desc.Dimension, + Alignment: desc.Alignment, + Width: desc.Width, + Height: desc.Height, + DepthOrArraySize: desc.DepthOrArraySize, + MipLevels: desc.MipLevels, + Format: desc.Format, + SampleDesc: desc.SampleDesc, + Layout: desc.Layout, + Flags: desc.Flags, + SamplerFeedbackMipRegion: Default::default(), + } +} + +/// Placement size and alignment for `desc` when placed with [`R9G9B9E5_CASTABLE`], trying +/// 4 KiB small-resource alignment first via `ID3D12Device12::GetResourceAllocationInfo3` +/// and falling back to default 64 KiB alignment. +pub(crate) fn r9g9b9e5_placed_allocation_info( + device: &ID3D12Device, + desc: &mut D3D12_RESOURCE_DESC, +) -> D3D12_RESOURCE_ALLOCATION_INFO { + use windows::core::Interface; + if let Ok(device12) = device.cast::() { + let count = R9G9B9E5_CASTABLE.len() as u32; + let fmt_ptr = R9G9B9E5_CASTABLE.as_ptr(); + desc.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT); + let d1_small = desc1_of(desc); + // SAFETY: `d1_small`, `count`, and `fmt_ptr` outlive the synchronous query. + let info = unsafe { + device12.GetResourceAllocationInfo3(0, 1, &d1_small, Some(&count), Some(&fmt_ptr), None) + }; + if info.SizeInBytes != u64::MAX && info.Alignment == desc.Alignment { + return info; + } + desc.Alignment = 0; + let d1_default = desc1_of(desc); + // SAFETY: as above. + unsafe { device12.GetResourceAllocationInfo3(0, 1, &d1_default, Some(&count), Some(&fmt_ptr), None) } + } else { + desc.Alignment = 0; + // SAFETY: plain query on a single valid `D3D12_RESOURCE_DESC`. + unsafe { device.GetResourceAllocationInfo(0, &[*desc]) } + } +} + +/// Creates a committed texture with `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` in `pCastableFormats` +/// and `D3D12_BARRIER_LAYOUT_COMMON` (so legacy `ResourceBarrier` transitions continue to +/// work everywhere) when [`want_r9g9b9e5_cast`] and [`castable_r9g9b9e5`] hold, falling back +/// to `CreateCommittedResource` with `initial_state` otherwise. +/// +/// # Safety +/// `heap`, `desc`, and any `clear` pointer must be valid for the call. +pub(crate) unsafe fn create_committed_r9g9b9e5_or_legacy( + device: &ID3D12Device, + heap: &D3D12_HEAP_PROPERTIES, + heap_flags: D3D12_HEAP_FLAGS, + desc: &D3D12_RESOURCE_DESC, + initial_state: D3D12_RESOURCE_STATES, + clear: Option<*const D3D12_CLEAR_VALUE>, +) -> windows::core::Result<(ID3D12Resource, bool)> { + use windows::Win32::Foundation::E_OUTOFMEMORY; + use windows::core::Interface; + if want_r9g9b9e5_cast(desc) + && castable_r9g9b9e5(device) + && let Ok(device10) = device.cast::() + { + let desc1 = desc1_of(desc); + let mut made: Option = None; + // SAFETY: valid heap/resource descriptions and castable format slice; `made` is ours. + let hr = unsafe { + device10.CreateCommittedResource3( + heap, + heap_flags, + &desc1, + D3D12_BARRIER_LAYOUT_COMMON, + clear, + None::<&ID3D12ProtectedResourceSession>, + Some(&R9G9B9E5_CASTABLE), + &mut made, + ) + }; + match (hr, made) { + (Ok(()), Some(made)) => return Ok((made, true)), + (Ok(()), None) => return Err(windows::core::Error::empty()), + (Err(e), _) if e.code() == E_OUTOFMEMORY => return Err(e), + (Err(e), _) => { + once!(error = %e, ?desc, "CreateCommittedResource3 refused R9G9B9E5 castable list; falling back to CreateCommittedResource"); + } + } + } + let mut made: Option = None; + // SAFETY: forwarded from caller; `made` is ours. + unsafe { device.CreateCommittedResource(heap, heap_flags, desc, initial_state, clear, &mut made)? }; + made.map(|m| (m, false)).ok_or_else(windows::core::Error::empty) +} + +/// Creates a placed texture in `heap` at `offset` with `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` in +/// `pCastableFormats` and `D3D12_BARRIER_LAYOUT_COMMON` when [`want_r9g9b9e5_cast`] and +/// [`castable_r9g9b9e5`] hold, falling back to `CreatePlacedResource` with `initial_state` +/// when `allow_fallback` holds (or when casting is off / unsupported). +/// +/// # Safety +/// `heap` must be a live heap with an unaliased range at `offset` fitting `desc`. +pub(crate) unsafe fn create_placed_r9g9b9e5_or_legacy( + device: &ID3D12Device, + heap: &ID3D12Heap, + offset: u64, + desc: &D3D12_RESOURCE_DESC, + initial_state: D3D12_RESOURCE_STATES, + clear: Option<*const D3D12_CLEAR_VALUE>, + allow_fallback: bool, +) -> windows::core::Result<(ID3D12Resource, bool)> { + use windows::Win32::Foundation::E_OUTOFMEMORY; + use windows::core::Interface; + if want_r9g9b9e5_cast(desc) + && castable_r9g9b9e5(device) + && let Ok(device10) = device.cast::() + { + let desc1 = desc1_of(desc); + let mut made: Option = None; + // SAFETY: caller guarantees `heap` + `offset` fit the castable allocation info; `made` is ours. + let hr = unsafe { + device10.CreatePlacedResource2( + heap, + offset, + &desc1, + D3D12_BARRIER_LAYOUT_COMMON, + clear, + Some(&R9G9B9E5_CASTABLE), + &mut made, + ) + }; + match (hr, made) { + (Ok(()), Some(made)) => return Ok((made, true)), + (Ok(()), None) => return Err(windows::core::Error::empty()), + (Err(e), _) if !allow_fallback || e.code() == E_OUTOFMEMORY => return Err(e), + (Err(e), _) => { + once!(error = %e, ?desc, offset, "CreatePlacedResource2 refused R9G9B9E5 castable list; falling back to CreatePlacedResource"); + } + } + } + let mut made: Option = None; + // SAFETY: caller guarantees `heap` + `offset` fit `desc`; `made` is ours. + unsafe { device.CreatePlacedResource(heap, offset, desc, initial_state, clear, &mut made)? }; + made.map(|m| (m, false)).ok_or_else(windows::core::Error::empty) +} + +/// Since the last frame-rate line: reads of aliased views served in place through a castable +/// view on their source texture ([`alias_cast`]). +#[cfg(feature = "diagnostics")] +static ALIAS_CAST_READS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Notes one read of an aliased view served in place without a copy ([`alias_cast`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn alias_cast_counted() { + ALIAS_CAST_READS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } /// Since the last frame-rate line, for [`alias_line`]: reads of aliased views that asked for @@ -378,12 +638,16 @@ fn alias_counted(placed: This, from: &ID3D12Resource, through: &Through, new_sou #[cfg(feature = "diagnostics")] pub(crate) fn alias_line(frames: f64) { use std::sync::atomic::Ordering::Relaxed; + let cast = ALIAS_CAST_READS.swap(0, Relaxed) as f64 / frames; let c: [f64; 7] = std::array::from_fn(|i| ALIAS_COUNTS[i].swap(0, Relaxed) as f64 / frames); if c[0] == 0.0 { + if cast > 0.0 { + tracing::info!("aliased views per frame: {cast:.1} read in place as castable views, 0.0 copied"); + } return; } tracing::info!( - "aliased views per frame: {:.1} reads asked for their copy and {:.1} needed none (their list had it); copies at a list's first read: \ + "aliased views per frame: {cast:.1} read in place, {:.1} asked for their copy and {:.1} needed none (their list had it); copies at a list's first read: \ {:.1} with the source as the list found it, {:.1} with it last read by the list, {:.1} last written; copies again in a list: {:.1} \ with the source last read, {:.1} last written", c[0], c[1], c[2], c[3], c[4], c[5], c[6] @@ -576,6 +840,8 @@ pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { if !new_source && before.is_none() { return true; } + #[cfg(test)] + TEST_ALIAS_COPIES.set(TEST_ALIAS_COPIES.get() + 1); card_writes(list, placed, to, None); crate::list::ensure_state(list, placed, COPY_DEST); let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { @@ -3526,6 +3792,1876 @@ mod allocation_costs { } } +#[cfg(all(test, windows))] +mod alias_cast_tests { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Direct3D12::*; + use windows::core::s; + + use super::{TEST_ALIAS_CAST, TEST_ALIAS_COPIES, TEST_ALIAS_DIRECT}; + use crate::descriptor::View; + use crate::descriptor::host::HostHeap; + use crate::object::{This, guid}; + use leonida_shader::native::{ResourceType, RootType, UsedResource}; + use leonida_shader::resource::RootIndexedView; + + struct CastFlagGuard(Option, Option); + + impl CastFlagGuard { + fn set(cast: Option, direct: Option) -> Self { + let prev = (TEST_ALIAS_CAST.get(), TEST_ALIAS_DIRECT.get()); + TEST_ALIAS_CAST.set(cast); + TEST_ALIAS_DIRECT.set(direct); + Self(prev.0, prev.1) + } + } + + impl Drop for CastFlagGuard { + fn drop(&mut self) { + TEST_ALIAS_CAST.set(self.0); + TEST_ALIAS_DIRECT.set(self.1); + } + } + + fn alloc_title_pages(bytes: usize) -> u64 { + let layout = std::alloc::Layout::from_size_align(bytes.max(65536), 65536).unwrap(); + // SAFETY: non-zero aligned allocation kept alive for the test's title VA. + unsafe { std::alloc::alloc_zeroed(layout) as u64 } + } + + fn resource_iid() -> [u8; 16] { + guid(0x696442be, 0xa72e, 0x4059, [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad]) + } + + fn tex_words(dim: u32, w: u32, h: u32, depth_or_layers: u16, mips: u16, fmt: u32, flags: u32) -> [u32; 14] { + [ + dim, + 0, + 0, + 0, + w, + 0, + h, + u32::from(depth_or_layers) | (u32::from(mips) << 16), + fmt, + 1, + 0, + 0x105, + flags, + 0, + ] + } + + #[repr(C, align(8))] + struct AlignedWords([u32; 14]); + + fn make_source_at(address: u64, words: &[u32; 14]) -> This { + let aligned = AlignedWords(*words); + let iid = resource_iid(); + let mut out: This = std::ptr::null(); + let hr = crate::resource::create_at_address( + std::ptr::null(), + address, + aligned.0.as_ptr().cast(), + 0, + std::ptr::null(), + &iid, + &mut out, + ); + assert_eq!(hr, 0, "create_at_address failed: {hr:#x}"); + out + } + + #[derive(Clone, Copy)] + enum RootSlot { + SrvTable, + UavTable, + SrvUavTable, + Uav(u32), + Const(u32, u32), + } + + fn serialize_root( + device: &ID3D12Device, + slots: &[RootSlot], + point_sampler: bool, + ) -> ID3D12RootSignature { + let range = |kind, base, offset| D3D12_DESCRIPTOR_RANGE { + RangeType: kind, + NumDescriptors: 1, + BaseShaderRegister: base, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: offset, + }; + let r_srv = [range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0)]; + let r_uav = [range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 0)]; + let r_srv_uav = [ + range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 0), + range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 0, 1), + ]; + let table = |ranges: &[D3D12_DESCRIPTOR_RANGE]| D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params: Vec = slots + .iter() + .map(|&slot| match slot { + RootSlot::SrvTable => table(&r_srv), + RootSlot::UavTable => table(&r_uav), + RootSlot::SrvUavTable => table(&r_srv_uav), + RootSlot::Uav(reg) => D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + RootSlot::Const(reg, count) => D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: reg, + RegisterSpace: 0, + Num32BitValues: count, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + }) + .collect(); + let sampler = D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + ..Default::default() + }; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: u32::from(point_sampler), + pStaticSamplers: if point_sampler { &sampler } else { std::ptr::null() }, + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let (mut blob, mut err): (Option, Option) = (None, None); + // SAFETY: `params`, descriptor-range slices, and `sampler` live through serialization; + // `blob` owns the serialized root-signature bytes while passed to `CreateRootSignature`. + unsafe { + if let Err(e) = D3D12SerializeRootSignature( + &desc, + D3D_ROOT_SIGNATURE_VERSION_1, + &mut blob, + Some(&mut err), + ) { + let msg = err.map_or_else(String::new, |b| { + String::from_utf8_lossy(std::slice::from_raw_parts( + b.GetBufferPointer().cast::(), + b.GetBufferSize(), + )) + .into_owned() + }); + panic!("D3D12SerializeRootSignature failed ({e}): {msg}"); + } + let blob = blob.unwrap(); + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes).unwrap() + } + } + + fn compile_cs( + hlsl: &str, + slots: &[RootSlot], + point_sampler: bool, + ) -> (ID3D12RootSignature, ID3D12PipelineState) { + let host = crate::host::host().unwrap(); + let (mut code, mut errors): (Option, Option) = (None, None); + // SAFETY: valid HLSL slice and entry/target strings. + let compiled = unsafe { + D3DCompile( + hlsl.as_ptr().cast(), + hlsl.len(), + s!("alias_cast_test"), + None, + None, + s!("main"), + s!("cs_5_0"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + let msg = errors.map_or_else(String::new, |b| unsafe { + std::str::from_utf8_unchecked(std::slice::from_raw_parts( + b.GetBufferPointer().cast::(), + b.GetBufferSize(), + )) + .to_owned() + }); + panic!("D3DCompile failed ({e}): {msg}"); + } + let code = code.unwrap(); + let root = serialize_root(&host.device, slots, point_sampler); + // SAFETY: explicit `root` and live `code` bytecode outlive PSO creation. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let pso: ID3D12PipelineState = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + .unwrap(); + (root, pso) + } + } + + /// Packs exact integer mantissas `(r, g, b)` (`0..512`) with `E = 24` (`2^(24-24) = 1.0`), + /// so `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` decodes to exact `[r as f32, g as f32, b as f32]`. + fn pack_rgb9e5_unit(r: u32, g: u32, b: u32) -> u32 { + (24u32 << 27) | (r & 0x1ff) | ((g & 0x1ff) << 9) | ((b & 0x1ff) << 18) + } + + fn gpu_slot(heap: &HostHeap, slot: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: live shader-visible descriptor heap. + unsafe { + let host = crate::host::host().unwrap(); + let step = host + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let start = heap.heap.GetGPUDescriptorHandleForHeapStart(); + D3D12_GPU_DESCRIPTOR_HANDLE { ptr: start.ptr + u64::from(slot) * u64::from(step) } + } + } + + /// Placed `R9G9B9E5_SHAREDEXP` views over shader-written `R32_UINT` and `R32_SINT` textures + /// (2D, 4-mip 2D probe atlas, 6-layer cube sky cache, 3D volume, and `DXGI_FORMAT_UNKNOWN` + /// default SRVs) read the live GPU-written texels in place with zero `alias` copies and zero + /// host-texture allocations on the placed resource, matching the copy path bit-for-bit. + #[test] + fn castable_r9g9b9e5_views_sample_written_r32_uint_and_sint_without_copying() { + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + eprintln!("host lacks RelaxedFormatCastingSupported; skipping castable GPU test"); + return; + } + let heap = HostHeap::new(false, 64).unwrap(); + let (out_buf, out_ptr) = host.shared_buffer(4096).unwrap(); + // SAFETY: live buffer. + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + + // 1. 2D R32_UINT & R32_SINT + DXGI_FORMAT_UNKNOWN (0) view format: compare cast=true vs cast=false. + let write_2d_u = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let write_2d_s = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = asint(packed_val); }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_2d = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + cbuffer C : register(b0) { uint mip_level; };\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + float3 v = t.Load(int3(1, 1, mip_level));\n\ + o.Store3(mip_level * 12, asuint(v));\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0), RootSlot::Const(0, 1)], + false, + ); + + for (src_fmt, srv_fmt, writer) in [ + (42u32, 67u32, &write_2d_u), + (43u32, 67u32, &write_2d_s), + (42u32, 0u32, &write_2d_u), + ] { + let mut results = [[0.0f32; 3]; 2]; + for (mode_idx, cast_on) in [(0usize, false), (1usize, true)] { + let _guard = CastFlagGuard::set(Some(cast_on), Some(true)); + let addr = alloc_title_pages(256 << 10); + let source = make_source_at(addr, &tex_words(3, 16, 16, 1, 1, src_fmt, 4)); + let placed_res_words = tex_words(3, 16, 16, 1, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[srv_fmt, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav_view = View::Unordered(source as usize, 0, Some([src_fmt, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + let srv_view = View::Placed(false, placed_res_words, placed_desc); + let placed_obj = match crate::descriptor::host::placed_texture(&srv_view).unwrap() { + View::Shader(r, _) => r as This, + _ => unreachable!(), + }; + + let base_slot = heap.dynamic(2).unwrap(); + heap.make_at(base_slot, &uav_view); + heap.make_at(base_slot + 1, &srv_view); + + let copies_before = TEST_ALIAS_COPIES.get(); + let packed = pack_rgb9e5_unit(37 + src_fmt, 19, 105); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav_view); + // SAFETY: open command list and live descriptors/pipelines. + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&writer.0); + list.list.SetPipelineState(&writer.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(4, 4, 1); + } + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv_view)); + let mip0 = 0u32; + unsafe { + list.list.SetComputeRootSignature(&read_2d.0); + list.list.SetPipelineState(&read_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.SetComputeRoot32BitConstants(2, 1, (&raw const mip0).cast(), 0); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + let copies_delta = TEST_ALIAS_COPIES.get() - copies_before; + if cast_on { + assert_eq!(copies_delta, 0, "castable R9G9B9E5 view must record 0 alias copies"); + assert!( + crate::resource::made_copy(placed_obj).is_none(), + "placed resource must not allocate its own HostTexture when cast-aliased" + ); + } else { + assert_eq!(copies_delta, 1, "fallback copy path must record 1 alias copy"); + } + // SAFETY: completed GPU write into mapped shared buffer. + results[mode_idx] = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + heap.release(base_slot, 2); + crate::object::release(source); + } + let want = [(37 + src_fmt) as f32, 19.0, 105.0]; + assert_eq!(results[1], want, "cast path exact RGB9E5 decode for fmt={src_fmt} srv={srv_fmt}"); + assert_eq!(results[1], results[0], "cast path must match copy path bit-for-bit"); + } + + // 2. 4-level mip-chain probe atlas (64x64, 4 mips): distinct RGB9E5 light per mip. + { + let _guard = CastFlagGuard::set(Some(true), Some(true)); + let addr = alloc_title_pages(512 << 10); + let source = make_source_at(addr, &tex_words(3, 64, 64, 1, 4, 42, 4)); + let placed_res_words = tex_words(3, 64, 64, 1, 4, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 4, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let srv_view = View::Placed(false, placed_res_words, placed_desc); + let base_slot = heap.dynamic(5).unwrap(); + for mip in 0..4u32 { + let uav = View::Unordered(source as usize, 0, Some([42, 4, mip, 0, 0, 0, 0, 0, 0, 0])); + heap.make_at(base_slot + mip, &uav); + } + heap.make_at(base_slot + 4, &srv_view); + + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + let uav0 = View::Unordered(source as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + crate::draw::readable(&list, ResourceType::Uav, &uav0); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_2d_u.0); + list.list.SetPipelineState(&write_2d_u.1); + for mip in 0..4u32 { + let packed = pack_rgb9e5_unit(10 + mip * 20, 3 + mip * 7, 100 + mip); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot + mip)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(16 >> mip, 16 >> mip, 1); + } + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv_view)); + list.list.SetComputeRootSignature(&read_2d.0); + list.list.SetPipelineState(&read_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot + 4)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + for mip in 0..4u32 { + list.list.SetComputeRoot32BitConstants(2, 1, (&raw const mip).cast(), 0); + list.list.Dispatch(1, 1, 1); + } + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0); + for mip in 0..4u32 { + let got = unsafe { out_ptr.add(mip as usize * 12).cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [(10 + mip * 20) as f32, (3 + mip * 7) as f32, (100 + mip) as f32], "mip {mip}"); + } + heap.release(base_slot, 5); + crate::object::release(source); + } + + // 3. 6-layer Cube (`TEXTURECUBE` = 6) & 3D Volume (`TEXTURE3D` = 8). + { + let _guard = CastFlagGuard::set(Some(true), Some(true)); + let write_arr = compile_cs( + "RWTexture2DArray u : register(u0);\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + uint face = id.z;\n\ + u[id] = (24u << 27) | (face * 10u + 1u) | ((face * 5u + 2u) << 9) | ((face + 3u) << 18);\n\ + }", + &[RootSlot::UavTable], + false, + ); + let read_cube = compile_cs( + "TextureCube t : register(t0);\n\ + SamplerState s : register(s0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + float3 dirs[6] = { float3(1,0,0), float3(-1,0,0), float3(0,1,0), float3(0,-1,0), float3(0,0,1), float3(0,0,-1) };\n\ + [unroll] for (uint f = 0; f < 6; ++f) { o.Store3(f * 12, asuint(t.SampleLevel(s, dirs[f], 0))); }\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + true, + ); + let addr = alloc_title_pages(512 << 10); + let source = make_source_at(addr, &tex_words(3, 16, 16, 6, 1, 42, 4)); + let placed_res_words = tex_words(3, 16, 16, 6, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + // TEXTURECUBE = 9: MostDetailedMip=0, MipLevels=1 + placed_desc[..10].copy_from_slice(&[67, D3D12_SRV_DIMENSION_TEXTURECUBE.0 as u32, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav = View::Unordered(source as usize, 0, Some([42, 5, 0, 0, 6, 0, 0, 0, 0, 0])); + let srv = View::Placed(false, placed_res_words, placed_desc); + let base_slot = heap.dynamic(2).unwrap(); + heap.make_at(base_slot, &uav); + heap.make_at(base_slot + 1, &srv); + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_arr.0); + list.list.SetPipelineState(&write_arr.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot)); + list.list.Dispatch(4, 4, 6); + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv)); + list.list.SetComputeRootSignature(&read_cube.0); + list.list.SetPipelineState(&read_cube.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base_slot + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0); + for face in 0..6u32 { + let got = unsafe { out_ptr.add(face as usize * 12).cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [(face * 10 + 1) as f32, (face * 5 + 2) as f32, (face + 3) as f32], "cube face {face}"); + } + heap.release(base_slot, 2); + crate::object::release(source); + + // 3D Volume (`Dimension = 4`, `SRV_DIMENSION_TEXTURE3D = 8`, `UAV_DIMENSION_TEXTURE3D = 8`) + let write_3d = compile_cs( + "RWTexture3D u : register(u0);\n\ + [numthreads(4, 4, 4)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + u[id] = (24u << 27) | (id.x + 10u) | ((id.y + 20u) << 9) | ((id.z + 30u) << 18);\n\ + }", + &[RootSlot::UavTable], + false, + ); + let read_3d = compile_cs( + "Texture3D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + o.Store3(0, asuint(t.Load(int4(3, 5, 7, 0))));\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + false, + ); + let addr3d = alloc_title_pages(512 << 10); + let source3d = make_source_at(addr3d, &tex_words(4, 8, 8, 8, 1, 42, 4)); + let placed_3d_words = tex_words(4, 8, 8, 8, 1, 67, 0); + let mut placed_3d_desc = [0u32; 16]; + placed_3d_desc[..10].copy_from_slice(&[67, 8, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_3d_desc[10] = addr3d as u32; + placed_3d_desc[11] = (addr3d >> 32) as u32; + let uav3d = View::Unordered(source3d as usize, 0, Some([42, 8, 0, 0, 8, 0, 0, 0, 0, 0])); + let srv3d = View::Placed(false, placed_3d_words, placed_3d_desc); + let base3d = heap.dynamic(2).unwrap(); + heap.make_at(base3d, &uav3d); + heap.make_at(base3d + 1, &srv3d); + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav3d); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_3d.0); + list.list.SetPipelineState(&write_3d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base3d)); + list.list.Dispatch(2, 2, 2); + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv3d)); + list.list.SetComputeRootSignature(&read_3d.0); + list.list.SetPipelineState(&read_3d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, base3d + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0); + let got3d = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got3d, [13.0, 25.0, 37.0]); + heap.release(base3d, 2); + crate::object::release(source3d); + } + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// Toggling `LEONIDA_ALIAS_CAST` (`true -> false -> true`, as `LEONIDA_AB` does) and replacing + /// the `R32_UINT` source texture at the same title virtual address without rewriting the title + /// descriptor slot both refresh `HostHeap::mirror` and `HostHeap::make_listed` descriptors. + #[test] + fn cast_alias_switches_live_and_tracks_replaced_source_at_same_address() { + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + return; + } + let heap = HostHeap::new(false, 8).unwrap(); + let (out_buf, out_ptr) = host.shared_buffer(256).unwrap(); + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + let write_cs = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_cs = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(0, asuint(t.Load(int3(0, 0, 0)))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + false, + ); + + let addr = alloc_title_pages(256 << 10); + let mut source = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + let placed_res_words = tex_words(3, 8, 8, 1, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let srv_view = View::Placed(false, placed_res_words, placed_desc); + + let mut slot_words = [0u32; 8]; + crate::descriptor::create_placed_srv( + std::ptr::null(), + &placed_res_words, + &placed_desc, + slot_words.as_mut_ptr() as u64, + ); + let handle = slot_words.as_ptr() as u64; + let rec = [slot_words[0], slot_words[1], slot_words[2]]; + let dyn_slots = heap.dynamic(2).unwrap(); + + let check_phase = |cast_on: bool, src: This, r_val: u32, expect_copies: u64| { + let _guard = CastFlagGuard::set(Some(cast_on), Some(true)); + let uav_view = View::Unordered(src as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + heap.make_at(dyn_slots, &uav_view); + assert!(heap.mirror(0, handle, true).is_some()); + assert!(heap.make_listed(0x7777, rec, dyn_slots + 1).is_some()); + + for srv_slot in [0u32, dyn_slots + 1] { + let before = TEST_ALIAS_COPIES.get(); + let packed = pack_rgb9e5_unit(r_val + srv_slot, 12, 34); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav_view); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_cs.0); + list.list.SetPipelineState(&write_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, dyn_slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(2, 2, 1); + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv_view)); + list.list.SetComputeRootSignature(&read_cs.0); + list.list.SetPipelineState(&read_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, srv_slot)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - before, expect_copies); + let got = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [(r_val + srv_slot) as f32, 12.0, 34.0]); + } + }; + + check_phase(true, source, 40, 0); + check_phase(false, source, 60, 1); + check_phase(true, source, 80, 0); + + // Replace `source` at the exact same virtual address without touching `slot_words`. + crate::object::release(source); + source = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + check_phase(true, source, 110, 0); + + // Multiple view heaps each track their own `last_cast_on` across `texture_views_remade`. + let heap2 = HostHeap::new(false, 16).unwrap(); + { + let _guard = CastFlagGuard::set(Some(true), Some(true)); + assert!(heap2.mirror(0, handle, true).is_some()); + let _ = heap.texture_views_remade(); + let _ = heap2.texture_views_remade(); + } + { + let _guard = CastFlagGuard::set(Some(false), Some(true)); + assert_eq!(heap.texture_views_remade(), 1); + assert_eq!(heap2.texture_views_remade(), 1); + } + + heap.release(dyn_slots, 2); + crate::object::release(source); + } + + /// When a single dispatch writes `source` (mip 1 UAV) and reads its placed `R9G9B9E5` view + /// (mip 0 SRV) simultaneously, `WRITTEN_CAST_SOURCES` forces the safe copy fallback so + /// `source` stays in `UNORDERED_ACCESS` and `placed` in `SHADER_RESOURCE`; the next read-only + /// pass resumes zero-copy casting and reads the mip 1 result directly from `source`. + #[test] + fn same_dispatch_source_uav_and_aliased_srv_falls_back_to_copy_without_state_conflict() { + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + return; + } + let _guard = CastFlagGuard::set(Some(true), Some(true)); + let heap = HostHeap::new(false, 16).unwrap(); + let (out_buf, out_ptr) = host.shared_buffer(256).unwrap(); + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + + let seed_cs = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let downsample_cs = compile_cs( + "Texture2D src : register(t0);\n\ + RWTexture2D dst : register(u0);\n\ + [numthreads(2, 2, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + float3 c = src.Load(int3(id.xy * 2, 0)) * 2.0;\n\ + uint r = (uint)round(c.r);\n\ + uint g = (uint)round(c.g);\n\ + uint b = (uint)round(c.b);\n\ + dst[id.xy] = (24u << 27) | r | (g << 9) | (b << 18);\n\ + }", + &[RootSlot::SrvUavTable], + false, + ); + let read_mip1_cs = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(0, asuint(t.Load(int3(0, 0, 1)))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + false, + ); + + let addr = alloc_title_pages(256 << 10); + let source = make_source_at(addr, &tex_words(3, 16, 16, 1, 2, 42, 4)); + let placed_res_words = tex_words(3, 16, 16, 1, 2, 67, 0); + let mut mip0_desc = [0u32; 16]; + mip0_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + mip0_desc[10] = addr as u32; + mip0_desc[11] = (addr >> 32) as u32; + let mut all_desc = mip0_desc; + all_desc[5] = 2; + + let uav_mip0 = View::Unordered(source as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + let uav_mip1 = View::Unordered(source as usize, 0, Some([42, 4, 1, 0, 0, 0, 0, 0, 0, 0])); + let srv_mip0 = View::Placed(false, placed_res_words, mip0_desc); + let srv_all = View::Placed(false, placed_res_words, all_desc); + let placed_obj = match crate::descriptor::host::placed_texture(&srv_mip0).unwrap() { + View::Shader(r, _) => r as This, + _ => unreachable!(), + }; + + let slots = heap.dynamic(4).unwrap(); + heap.make_at(slots, &uav_mip0); + + let list = host.new_list().unwrap(); + let packed = pack_rgb9e5_unit(15, 25, 35); + crate::draw::readable(&list, ResourceType::Uav, &uav_mip0); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&seed_cs.0); + list.list.SetPipelineState(&seed_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(4, 4, 1); + } + + // Simultaneous read (mip 0 SRV) + write (mip 1 UAV) on `source` in one dispatch. + let before_conflict = TEST_ALIAS_COPIES.get(); + crate::draw::with_test_written_cast_source(source, || { + assert!(crate::resource::cast_alias_of(placed_obj).is_none()); + heap.make_at(slots + 1, &srv_mip0); + heap.make_at(slots + 2, &uav_mip1); + crate::draw::readable(&list, ResourceType::Uav, &uav_mip1); + crate::draw::readable(&list, ResourceType::Srv, &srv_mip0); + }); + assert_eq!(TEST_ALIAS_COPIES.get() - before_conflict, 1); + unsafe { + list.list.SetComputeRootSignature(&downsample_cs.0); + list.list.SetPipelineState(&downsample_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 1)); + list.list.Dispatch(4, 4, 1); + } + + // Subsequent read-only pass resumes zero-copy casting and sees mip 1 = 2x mip 0. + assert!(crate::resource::cast_alias_of(placed_obj).is_some()); + heap.make_at(slots + 3, &srv_all); + let before_readonly = TEST_ALIAS_COPIES.get(); + crate::draw::readable(&list, ResourceType::Srv, &srv_all); + assert_eq!(TEST_ALIAS_COPIES.get() - before_readonly, 0); + unsafe { + list.list.SetComputeRootSignature(&read_mip1_cs.0); + list.list.SetPipelineState(&read_mip1_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 3)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + let got = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [30.0, 50.0, 70.0]); + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + heap.release(slots, 4); + crate::object::release(source); + } + + /// `State::tables` (`fresh_tables` CBV-snapshotted tables) hashes the active `cast_serial` + /// so mid-list console VA replacement (`source_1 -> source_2` at the same address without + /// rewriting descriptor memory) and mid-list `LEONIDA_AB` / `TEST_ALIAS_CAST` flips + /// (`true -> false -> true`) allocate/select the matching dynamic table and transition the + /// active resource cleanly, and `HostHeap::make_listed` returns `None` (overwriting its + /// cached slot with a null view) instead of copying a stale descriptor if a stale rebuild + /// fails. + #[test] + fn state_tables_fresh_cache_tracks_mid_list_va_reuse_and_live_cast_flip() { + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + return; + } + let _guard = CastFlagGuard::set(Some(true), Some(true)); + + let heap_iid = guid(0x8efb471d, 0x616c, 0x4f49, [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51]); + let heap_desc_words: [u32; 8] = [0, 16, 1, 0, 0, 0, 0, 0]; + let mut title_heap: This = std::ptr::null(); + assert_eq!( + crate::descriptor::create_heap( + std::ptr::null(), + heap_desc_words.as_ptr().cast(), + &heap_iid, + &mut title_heap, + ), + 0 + ); + let heap_ref = crate::descriptor::heap(title_heap); + let host_heap = heap_ref.host().unwrap(); + let table_base = heap_ref.start; + + let cbv_mem = alloc_title_pages(65536); + let cbv_desc = [cbv_mem as u32, (cbv_mem >> 32) as u32, 256u32, 0u32]; + crate::descriptor::create_cbv(std::ptr::null(), &cbv_desc, table_base); + + let addr = alloc_title_pages(256 << 10); + let source_1 = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + let placed_res_words = tex_words(3, 8, 8, 1, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + crate::descriptor::create_placed_srv( + std::ptr::null(), + &placed_res_words, + &placed_desc, + table_base + 32, + ); + + let plan = crate::draw::TablePlan::new( + &[ + UsedResource { + kind: ResourceType::Cbv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }, + ], + &[], + ); + let mut state = crate::draw::test_state_for_table(title_heap, table_base); + + let (out_buf, out_ptr) = host.shared_buffer(256).unwrap(); + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + let write_cs = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_cs = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + cbuffer C : register(b0) { uint byte_off; };\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(byte_off, asuint(t.Load(int3(0, 0, 0)))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0), RootSlot::Const(0, 1)], + false, + ); + + let uav_slots = host_heap.dynamic(2).unwrap(); + let uav_1 = View::Unordered(source_1 as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + host_heap.make_at(uav_slots, &uav_1); + + let list = host.new_list().unwrap(); + unsafe { + list.list.SetDescriptorHeaps(&[Some(host_heap.heap.clone())]); + } + + let record_write = |uav_view: &View, uav_slot: u32, r: u32, g: u32, b: u32| { + let packed = pack_rgb9e5_unit(r, g, b); + crate::draw::readable(&list, ResourceType::Uav, uav_view); + unsafe { + list.list.SetComputeRootSignature(&write_cs.0); + list.list.SetPipelineState(&write_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(host_heap, uav_slot)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(2, 2, 1); + } + }; + let record_read = |srv_slot: u32, byte_off: u32| unsafe { + list.list.SetComputeRootSignature(&read_cs.0); + list.list.SetPipelineState(&read_cs.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(host_heap, srv_slot)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.SetComputeRoot32BitConstants(2, 1, (&raw const byte_off).cast(), 0); + list.list.Dispatch(1, 1, 1); + }; + + // 1. Cold `fresh_tables` build + immediate `fresh_tables` cache hit on `source_1`. + record_write(&uav_1, uav_slots, 45, 11, 22); + let copies_0 = TEST_ALIAS_COPIES.get(); + let off_a = state.tables(&list, &plan, &[], true).to_vec()[0].1; + let off_a_hit = state.tables(&list, &plan, &[], true).to_vec()[0].1; + assert_eq!(off_a_hit, off_a, "unchanged source must hit fresh_tables"); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_0, 0); + record_read(off_a / 32 + 1, 0); + + // 2. Mid-list VA replacement at the exact same address without touching `table_base + 32`. + crate::object::release(source_1); + let source_2 = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + let uav_2 = View::Unordered(source_2 as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + host_heap.make_at(uav_slots + 1, &uav_2); + record_write(&uav_2, uav_slots + 1, 75, 22, 88); + let copies_1 = TEST_ALIAS_COPIES.get(); + let off_b = state.tables(&list, &plan, &[], true).to_vec()[0].1; + assert_ne!(off_b, off_a, "mid-list VA reuse must not reuse source_1's cached table"); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_1, 0); + record_read(off_b / 32 + 1, 16); + + // 3. Mid-list live flip `true -> false` in the same HostList. + record_write(&uav_2, uav_slots + 1, 95, 33, 66); + let off_c = { + let _flip_off = CastFlagGuard::set(Some(false), Some(true)); + let copies_2 = TEST_ALIAS_COPIES.get(); + let off = state.tables(&list, &plan, &[], true).to_vec()[0].1; + assert_ne!(off, off_b, "flipping alias_cast off must allocate a separate copy-mode table"); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_2, 1); + off + }; + record_read(off_c / 32 + 1, 32); + + // 4. Mid-list live flip `false -> true` back to `source_2`'s cached zero-copy table. + record_write(&uav_2, uav_slots + 1, 125, 44, 19); + let copies_3 = TEST_ALIAS_COPIES.get(); + let off_d = state.tables(&list, &plan, &[], true).to_vec()[0].1; + assert_eq!(off_d, off_b, "flipping alias_cast back on hits source_2's cast table and re-transitions it"); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_3, 0); + record_read(off_d / 32 + 1, 48); + + list.close(); + host.execute(&[&list]); + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + + let expected = [ + [45.0f32, 11.0, 22.0], + [75.0, 22.0, 88.0], + [95.0, 33.0, 66.0], + [125.0, 44.0, 19.0], + ]; + for (i, want) in expected.iter().enumerate() { + let got = unsafe { out_ptr.add(i * 16).cast::<[f32; 3]>().read_volatile() }; + assert_eq!(&got, want, "dispatch step {i}"); + } + + // 5. `make_listed` stale rebuild failure (`kept == None`) returns `None` instead of copying stale `s0`, + // and retries cleanly in the same recording once `alias_cast` turns back on. + let mut mismatch_desc = [0u32; 16]; + mismatch_desc[..10].copy_from_slice(&[42, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + mismatch_desc[10] = addr as u32; + mismatch_desc[11] = (addr >> 32) as u32; + let mut mismatch_slot = [0u32; 8]; + crate::descriptor::create_placed_srv( + std::ptr::null(), + &placed_res_words, + &mismatch_desc, + mismatch_slot.as_mut_ptr() as u64, + ); + let mismatch_rec = [mismatch_slot[0], mismatch_slot[1], mismatch_slot[2]]; + let check_slot = host_heap.dynamic(1).unwrap(); + assert!(host_heap.make_listed(0x8888, mismatch_rec, check_slot).is_some()); + { + let _flip_off = CastFlagGuard::set(Some(false), Some(true)); + assert!( + host_heap.make_listed(0x8888, mismatch_rec, check_slot).is_none(), + "failed stale rebuild must return None instead of copying stale source descriptor" + ); + } + assert!( + host_heap.make_listed(0x8888, mismatch_rec, check_slot).is_some(), + "subsequent call in same recording must retry and succeed once cast is valid again" + ); + + // 6. Sentinel `0xFFFF_FFFF` root constant in `group.indexed` + out-of-bounds `plan.direct` + // offset with active `WRITTEN_CAST_SOURCES` must be bounds-guarded without OOB reads. + let oob_plan = crate::draw::TablePlan::new( + &[ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }, + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0x1000_0000, + lower_bound: 1, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }, + ], + &[RootIndexedView { + table_slot: 0, + constant_slot: 1, + constant_dword: 0, + byte_offset: 0, + shift: 5, + }], + ); + let oob_list = host.new_list().unwrap(); + crate::draw::with_test_written_cast_source(source_2, || { + let _ = state.tables(&oob_list, &oob_plan, &[], true); + }); + oob_list.close(); + + host_heap.release(check_slot, 1); + host_heap.release(uav_slots, 2); + drop(state); + crate::object::release(source_2); + crate::object::release(title_heap); + } + + /// Reproduces the `d3d12/docs/findings.md` waterside aliased-view frame workload (`59` views, + /// `86` reads = `~390 MiB/frame`: 11x `2560x1440`, 8x `1280x720`, 1x `2048x2048`, cubes, + /// 4-level probe atlases, and 3D volumes, with 32 interleaved `R32_UINT` shader writes) and + /// compares D3D12 GPU timestamp time, CPU recording time, and extra VRAM across: + /// 1. `cast=0, direct=0` (buffer-staged copies), + /// 2. `cast=0, direct=1` (direct texture copies, launcher baseline), + /// 3. `cast=1` (zero-copy `CreateCommittedResource3` castable `R9G9B9E5` views). + /// + /// Run with: + /// `cargo test --release -p leonida-gpu waterside_alias_cast_vs_copy_gpu_benchmark -- --ignored --nocapture` + #[test] + #[ignore = "a measurement, not a check"] + fn waterside_alias_cast_vs_copy_gpu_benchmark() { + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + println!("host lacks RelaxedFormatCastingSupported"); + return; + } + let freq = unsafe { host.queue().GetTimestampFrequency() }.unwrap_or(1_000_000_000); + let mut qheap: Option = None; + unsafe { + host.device.CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut qheap, + ) + } + .unwrap(); + let qheap = qheap.unwrap(); + let qbuf = host.read_back_buffer(16).unwrap(); + + let write_cs = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint v; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = v; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_cs = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(0, asuint(t.Load(int3(0, 0, 0)))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + false, + ); + let write_cube_cs = compile_cs( + "RWTexture2DArray u : register(u0);\n\ + cbuffer C : register(b0) { uint v; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id] = v; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_cube_cs = compile_cs( + "TextureCube t : register(t0);\n\ + SamplerState s : register(s0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(0, asuint(t.SampleLevel(s, float3(1, 0, 0), 0))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + true, + ); + + // 59 views matching findings.md:764-775 (~390 MiB across 86 reads/frame): + // (dim, width, height, layers, mips, reads_per_frame, writes_per_frame) + let mut specs: Vec<(u32, u32, u32, u16, u16, u32, u32)> = Vec::with_capacity(59); + for i in 0..11 { + // 11x 2560x1440 (14.0625 MiB each): 2 read twice, 9 read once => 13 reads = 182.8 MiB + let reads = if i < 2 { 2 } else { 1 }; + let writes = if i < 4 { 1 } else { 0 }; + specs.push((3, 2560, 1440, 1, 1, reads, writes)); + } + // 1x 2048x2048 (16.0 MiB): 4 reads/frame => 64.0 MiB + specs.push((3, 2048, 2048, 1, 1, 4, 1)); + for i in 0..8 { + // 8x 1280x720 (3.5156 MiB each): 2 reads each => 16 reads = 56.25 MiB + specs.push((3, 1280, 720, 1, 1, 2, u32::from(i < 5))); + } + for _ in 0..6 { + // 6x 1024x1024 4-mip probe atlases (5.33 MiB each): 2 reads each => 12 reads = 64.0 MiB + specs.push((3, 1024, 1024, 1, 4, 2, 1)); + } + for _ in 0..8 { + // 8x 256x256x6 sky cubes (1.5 MiB each): 1 read each => 8 reads = 12.0 MiB + specs.push((3, 256, 256, 6, 1, 1, 1)); + } + for i in 0..25 { + // Remaining 25 smaller probe/LUT/volume 2D textures (512x256 = 0.5 MiB): 33 reads = 16.5 MiB + let reads = if i < 8 { 2 } else { 1 }; + specs.push((3, 512, 256, 1, 1, reads, u32::from(i < 8))); + } + assert_eq!(specs.len(), 59); + let total_reads: u32 = specs.iter().map(|s| s.5).sum(); + assert_eq!(total_reads, 86); + + let (sink_buf, _) = host.shared_buffer(256).unwrap(); + let sink_gpu = unsafe { sink_buf.GetGPUVirtualAddress() }; + + // Allocate console-VA backing and the 59 shader-written R32_UINT source textures once, + // then run CAST=1 first (before any duplicate placed textures or Through buffers exist) + // followed by CAST=0 DIRECT=1 and CAST=0 DIRECT=0 to measure extra duplicate VRAM cleanly. + let mut sources = Vec::with_capacity(59); + { + let _guard = CastFlagGuard::set(Some(true), Some(true)); + for (idx, &(dim, w, h, layers, mips, reads, writes)) in specs.iter().enumerate() { + let est_bytes = (w as usize) + .saturating_mul(h as usize) + .saturating_mul(usize::from(layers)) + .saturating_mul(8) + .max(65536); + let addr = alloc_title_pages(est_bytes); + let src = make_source_at(addr, &tex_words(dim, w, h, layers, mips, 42, 4)); + if crate::resource::host_resource(src).is_none() { + let vmem = host.video_memory(); + let rem = unsafe { host.device.GetDeviceRemovedReason() }; + panic!( + "host_resource(src) returned None at idx={idx} ({dim}, {w}x{h}, layers={layers}, mips={mips}), vmem={vmem:?}, removed={rem:?}, not_made_for_now={}", + crate::resource::NOT_MADE_FOR_NOW.load(Relaxed) + ); + } + sources.push((addr, src, dim, w, h, layers, mips, reads, writes)); + } + } + let base_tex_vram = crate::resource::HOST_TEXTURES[1].load(Relaxed); + let base_through_vram: u64 = super::THROUGH + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |m| { + m.values() + .filter(|t| t.buffer.get().is_some_and(Option::is_some)) + .map(|t| t.bytes) + .sum() + }); + + for (label, cast_on, direct_on) in [ + ("castable-zero-copy (CAST=1)", true, true), + ("copy-direct-texture (CAST=0, DIRECT=1)", false, true), + ("copy-through-buffer (CAST=0, DIRECT=0)", false, false), + ] { + let _guard = CastFlagGuard::set(Some(cast_on), Some(direct_on)); + let heap = HostHeap::new(false, 256).unwrap(); + let slots = heap.dynamic(118).unwrap(); + let mut entries = Vec::with_capacity(59); + + for (idx, &(addr, src, dim, w, h, layers, mips, reads, writes)) in sources.iter().enumerate() { + let placed_words = tex_words(dim, w, h, layers, mips, 67, 0); + let srv_dim = if layers == 6 { + D3D12_SRV_DIMENSION_TEXTURECUBE.0 as u32 + } else { + 4u32 + }; + let uav_dim = if layers > 1 { 5u32 } else { 4u32 }; + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, srv_dim, 5768, 0, 0, u32::from(mips), 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav = View::Unordered( + src as usize, + 0, + Some([42, uav_dim, 0, 0, u32::from(layers), 0, 0, 0, 0, 0]), + ); + let srv = View::Placed(false, placed_words, placed_desc); + let uav_slot = slots + (idx as u32) * 2; + let srv_slot = uav_slot + 1; + heap.make_at(uav_slot, &uav); + heap.make_at(srv_slot, &srv); + entries.push((uav, srv, uav_slot, srv_slot, layers, reads, writes)); + } + + // Warm up 5 frames (also allocates any lazy placed textures / Through buffers in copy modes). + const WARMUP: usize = 5; + const FRAMES: usize = 30; + let mut gpu_ms_samples = Vec::with_capacity(FRAMES); + let mut cpu_us_samples = Vec::with_capacity(FRAMES); + let mut copies_per_frame = 0u64; + + for frame in 0..(WARMUP + FRAMES) { + let copies_start = TEST_ALIAS_COPIES.get(); + let cpu_t0 = std::time::Instant::now(); + let list = host.new_list().unwrap_or_else(|e| { + crate::host::fail(format_args!("new_list failed at {label} frame={frame}: {e}")) + }); + unsafe { + list.list.EndQuery(&qheap, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + } + let val = pack_rgb9e5_unit(10 + (frame as u32 % 50), 20, 30); + for (uav, srv, uav_slot, srv_slot, layers, reads, writes) in &entries { + for r in 0..*reads { + if r > 0 || *writes > 0 { + crate::draw::readable(&list, ResourceType::Uav, uav); + unsafe { + if *layers == 6 { + list.list.SetComputeRootSignature(&write_cube_cs.0); + list.list.SetPipelineState(&write_cube_cs.1); + } else { + list.list.SetComputeRootSignature(&write_cs.0); + list.list.SetPipelineState(&write_cs.1); + } + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, *uav_slot)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const val).cast(), 0); + list.list.Dispatch(1, 1, 1); + } + } + crate::draw::readable(&list, ResourceType::Srv, srv); + unsafe { + if *layers == 6 { + list.list.SetComputeRootSignature(&read_cube_cs.0); + list.list.SetPipelineState(&read_cube_cs.1); + } else { + list.list.SetComputeRootSignature(&read_cs.0); + list.list.SetPipelineState(&read_cs.1); + } + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, *srv_slot)); + list.list.SetComputeRootUnorderedAccessView(1, sink_gpu); + list.list.Dispatch(1, 1, 1); + } + } + } + unsafe { + list.list.EndQuery(&qheap, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.list.ResolveQueryData(&qheap, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &qbuf, 0); + } + list.close(); + let cpu_us = cpu_t0.elapsed().as_secs_f64() * 1e6; + host.execute(&[&list]); + copies_per_frame = TEST_ALIAS_COPIES.get() - copies_start; + if frame >= WARMUP { + let mut mapped = std::ptr::null_mut(); + let ticks = unsafe { + qbuf.Map(0, None, Some(&mut mapped)).unwrap(); + let pair = mapped.cast::<[u64; 2]>().read_unaligned(); + qbuf.Unmap(0, None); + pair[1].saturating_sub(pair[0]) + }; + gpu_ms_samples.push(ticks as f64 * 1000.0 / freq as f64); + cpu_us_samples.push(cpu_us); + } + } + + let dup_tex_mib = + crate::resource::HOST_TEXTURES[1].load(Relaxed).saturating_sub(base_tex_vram) as f64 / (1024.0 * 1024.0); + let through_after: u64 = super::THROUGH + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |m| { + m.values() + .filter(|t| t.buffer.get().is_some_and(Option::is_some)) + .map(|t| t.bytes) + .sum() + }); + let stage_buf_mib = through_after.saturating_sub(base_through_vram) as f64 / (1024.0 * 1024.0); + gpu_ms_samples.sort_by(f64::total_cmp); + cpu_us_samples.sort_by(f64::total_cmp); + let gpu_mean = gpu_ms_samples.iter().sum::() / FRAMES as f64; + let gpu_med = gpu_ms_samples[FRAMES / 2]; + let cpu_med = cpu_us_samples[FRAMES / 2]; + println!( + "{label}: gpu_mean={gpu_mean:.3} ms, gpu_median={gpu_med:.3} ms, cpu_record_median={cpu_med:.1} us, copies/frame={copies_per_frame}, dup_tex_vram={dup_tex_mib:.1} MiB, stage_buf_vram={stage_buf_mib:.1} MiB, extra_vram={:.1} MiB", + dup_tex_mib + stage_buf_mib + ); + + heap.release(slots, 118); + } + + for (_, src, ..) in sources { + crate::object::release(src); + } + } + + /// Both committed (`CreateCommittedResource3`) and placed (`CreatePlacedResource2`, via + /// `pool::texture_with_cast` and direct `ID3D12Heap` placement) `R32_UINT` 2D, 2D-array, and + /// 3D textures start in `D3D12_BARRIER_LAYOUT_COMMON` (`state == 0`), write texels through + /// UAVs after legacy `ResourceBarrier` transitions, transition with legacy `ensure_state` to + /// `SHADER_RESOURCE`, and sample directly via `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` SRVs with zero + /// `alias` copies. + #[test] + fn committed_and_placed_r32_uint_textures_cast_to_r9g9b9e5_under_legacy_barriers() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R32_UINT, DXGI_SAMPLE_DESC, + }; + + struct PoolCastGuard(bool, bool); + impl PoolCastGuard { + fn new(pool_targets: bool) -> Self { + let prev = ( + super::TEST_POOL_CAST_TARGETS.get(), + crate::pool::TEST_POOL_FORCE.get(), + ); + super::TEST_POOL_CAST_TARGETS.set(pool_targets); + crate::pool::TEST_POOL_FORCE.set(pool_targets); + Self(prev.0, prev.1) + } + } + impl Drop for PoolCastGuard { + fn drop(&mut self) { + super::TEST_POOL_CAST_TARGETS.set(self.0); + crate::pool::TEST_POOL_FORCE.set(self.1); + } + } + + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + eprintln!("host lacks RelaxedFormatCastingSupported; skipping committed+placed cast test"); + return; + } + let _cast_guard = CastFlagGuard::set(Some(true), Some(true)); + let heap = HostHeap::new(false, 32).unwrap(); + let (out_buf, out_ptr) = host.shared_buffer(1024).unwrap(); + // SAFETY: live buffer. + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + + let write_2d = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_2d = compile_cs( + "Texture2D t : register(t0);\n\ + SamplerState s : register(s0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + o.Store3(0, asuint(t.SampleLevel(s, float2(0.5, 0.5), 0.0)));\n\ + o.Store3(12, asuint(t.SampleLevel(s, float2(0.5, 0.5), 1.0)));\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + true, + ); + let write_arr = compile_cs( + "RWTexture2DArray u : register(u0);\n\ + cbuffer C : register(b0) { uint bias; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + uint s = id.z;\n\ + u[id] = (24u << 27) | (bias + s * 11u) | ((bias + s * 7u + 3u) << 9) | ((bias + s * 5u + 9u) << 18);\n\ + }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_arr = compile_cs( + "Texture2DArray t : register(t0);\n\ + SamplerState s : register(s0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + [unroll] for (uint k = 0; k < 3; ++k) {\n\ + o.Store3(k * 12, asuint(t.SampleLevel(s, float3(0.5, 0.5, k), 0.0)));\n\ + }\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + true, + ); + let write_3d = compile_cs( + "RWTexture3D u : register(u0);\n\ + cbuffer C : register(b0) { uint bias; };\n\ + [numthreads(4, 4, 4)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + u[id] = (24u << 27) | (bias + id.x) | ((bias + id.y + 10u) << 9) | ((bias + id.z + 20u) << 18);\n\ + }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_3d = compile_cs( + "Texture3D t : register(t0);\n\ + SamplerState s : register(s0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + o.Store3(0, asuint(t.SampleLevel(s, float3(2.5 / 8.0, 3.5 / 8.0, 1.5 / 4.0), 0.0)));\n\ + }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + true, + ); + + // Exercise both runtime paths: `CreateCommittedResource3` (`placed_pool == false`) and + // `CreatePlacedResource2` via `pool::texture_with_cast` (`placed_pool == true`). + for (mode_idx, placed_pool) in [(0u32, false), (1u32, true)] { + let _pool_guard = PoolCastGuard::new(placed_pool); + let bias = 20 + mode_idx * 40; + + // 1. 2D 2-mip R32_UINT texture + { + let addr = alloc_title_pages(256 << 10); + let source = make_source_at(addr, &tex_words(3, 16, 16, 1, 2, 42, 4)); + let copy = crate::resource::host_copy(source).expect("source host copy"); + assert!(copy.castable_r9g9b9e5, "R32_UINT 2D must be castable (placed={placed_pool})"); + assert_eq!(copy.state.load(Relaxed), 0, "castable texture must start in legacy COMMON (0)"); + assert_eq!(crate::pool::fresh(©.texture), placed_pool, "pool placement mismatch"); + + let placed_words = tex_words(3, 16, 16, 1, 2, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 2, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav0 = View::Unordered(source as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + let uav1 = View::Unordered(source as usize, 0, Some([42, 4, 1, 0, 0, 0, 0, 0, 0, 0])); + let srv = View::Placed(false, placed_words, placed_desc); + let placed_obj = match crate::descriptor::host::placed_texture(&srv).unwrap() { + View::Shader(r, _) => r as This, + _ => unreachable!(), + }; + + let slots = heap.dynamic(3).unwrap(); + heap.make_at(slots, &uav0); + heap.make_at(slots + 1, &uav1); + heap.make_at(slots + 2, &srv); + + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav0); + let p0 = pack_rgb9e5_unit(bias + 1, bias + 2, bias + 3); + let p1 = pack_rgb9e5_unit(bias + 11, bias + 12, bias + 13); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_2d.0); + list.list.SetPipelineState(&write_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const p0).cast(), 0); + list.list.Dispatch(4, 4, 1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 1)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const p1).cast(), 0); + list.list.Dispatch(2, 2, 1); + + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv)); + list.list.SetComputeRootSignature(&read_2d.0); + list.list.SetPipelineState(&read_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 2)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0, "0 alias copies (placed={placed_pool})"); + assert!(crate::resource::made_copy(placed_obj).is_none()); + let m0 = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + let m1 = unsafe { out_ptr.add(12).cast::<[f32; 3]>().read_volatile() }; + assert_eq!(m0, [(bias + 1) as f32, (bias + 2) as f32, (bias + 3) as f32]); + assert_eq!(m1, [(bias + 11) as f32, (bias + 12) as f32, (bias + 13) as f32]); + heap.release(slots, 3); + crate::object::release(source); + } + + // 2. 2D Array (3 slices) R32_UINT texture + { + let addr = alloc_title_pages(256 << 10); + let source = make_source_at(addr, &tex_words(3, 16, 16, 3, 1, 42, 4)); + let copy = crate::resource::host_copy(source).expect("array source host copy"); + assert!(copy.castable_r9g9b9e5); + assert_eq!(crate::pool::fresh(©.texture), placed_pool); + + let placed_words = tex_words(3, 16, 16, 3, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + // TEXTURE2DARRAY = 5: MostDetailedMip=0, MipLevels=1, FirstArraySlice=0, ArraySize=3 + placed_desc[..10].copy_from_slice(&[67, 5, 5768, 0, 0, 1, 0, 3, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav = View::Unordered(source as usize, 0, Some([42, 5, 0, 0, 3, 0, 0, 0, 0, 0])); + let srv = View::Placed(false, placed_words, placed_desc); + + let slots = heap.dynamic(2).unwrap(); + heap.make_at(slots, &uav); + heap.make_at(slots + 1, &srv); + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_arr.0); + list.list.SetPipelineState(&write_arr.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const bias).cast(), 0); + list.list.Dispatch(4, 4, 3); + + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv)); + list.list.SetComputeRootSignature(&read_arr.0); + list.list.SetPipelineState(&read_arr.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0); + for k in 0..3u32 { + let got = unsafe { out_ptr.add(k as usize * 12).cast::<[f32; 3]>().read_volatile() }; + assert_eq!( + got, + [(bias + k * 11) as f32, (bias + k * 7 + 3) as f32, (bias + k * 5 + 9) as f32], + "placed={placed_pool} slice {k}" + ); + } + heap.release(slots, 2); + crate::object::release(source); + } + + // 3. 3D Volume (`8x8x4`) R32_UINT texture + { + let addr = alloc_title_pages(256 << 10); + let source = make_source_at(addr, &tex_words(4, 8, 8, 4, 1, 42, 4)); + let copy = crate::resource::host_copy(source).expect("3d source host copy"); + assert!(copy.castable_r9g9b9e5); + assert_eq!(crate::pool::fresh(©.texture), placed_pool); + + let placed_words = tex_words(4, 8, 8, 4, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 8, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let uav = View::Unordered(source as usize, 0, Some([42, 8, 0, 0, 4, 0, 0, 0, 0, 0])); + let srv = View::Placed(false, placed_words, placed_desc); + + let slots = heap.dynamic(2).unwrap(); + heap.make_at(slots, &uav); + heap.make_at(slots + 1, &srv); + let copies_before = TEST_ALIAS_COPIES.get(); + let list = host.new_list().unwrap(); + crate::draw::readable(&list, ResourceType::Uav, &uav); + unsafe { + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_3d.0); + list.list.SetPipelineState(&write_3d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const bias).cast(), 0); + list.list.Dispatch(2, 2, 1); + + assert!(crate::draw::readable(&list, ResourceType::Srv, &srv)); + list.list.SetComputeRootSignature(&read_3d.0); + list.list.SetPipelineState(&read_3d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + assert_eq!(TEST_ALIAS_COPIES.get() - copies_before, 0); + let got = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [(bias + 2) as f32, (bias + 3 + 10) as f32, (bias + 1 + 20) as f32]); + heap.release(slots, 2); + crate::object::release(source); + } + } + + // Direct `create_placed_r9g9b9e5_or_legacy` at a non-zero `ID3D12Heap` offset: UAV write -> + // legacy `ResourceBarrier` -> `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` SRV sample. + { + let mut desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let info = super::r9g9b9e5_placed_allocation_info(&host.device, &mut desc); + let offset = info.Alignment.max(65536); + let mut raw_heap: Option = None; + unsafe { + host.device + .CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: offset + info.SizeInBytes.max(65536), + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }, + &mut raw_heap, + ) + .unwrap(); + } + let raw_heap = raw_heap.unwrap(); + let (tex, castable) = unsafe { + super::create_placed_r9g9b9e5_or_legacy( + &host.device, + &raw_heap, + offset, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + true, + ) + .unwrap() + }; + assert!(castable); + let slots = heap.dynamic(2).unwrap(); + let step = unsafe { + host.device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } as usize; + let cpu0 = unsafe { heap.heap.GetCPUDescriptorHandleForHeapStart() }; + unsafe { + host.device.CreateUnorderedAccessView( + &tex, + None::<&ID3D12Resource>, + Some(&D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, + }, + }), + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu0.ptr + slots as usize * step }, + ); + host.device.CreateShaderResourceView( + &tex, + Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }), + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu0.ptr + (slots as usize + 1) * step }, + ); + } + let list = host.new_list().unwrap(); + let packed = pack_rgb9e5_unit(311, 212, 113); + unsafe { + list.list.ResourceBarrier(&[crate::host::transition( + &tex, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + list.list.SetComputeRootSignature(&write_2d.0); + list.list.SetPipelineState(&write_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots)); + list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed).cast(), 0); + list.list.Dispatch(2, 2, 1); + list.list.ResourceBarrier(&[crate::host::transition( + &tex, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )]); + list.list.SetComputeRootSignature(&read_2d.0); + list.list.SetPipelineState(&read_2d.1); + list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slots + 1)); + list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + list.list.Dispatch(1, 1, 1); + } + list.close(); + host.execute(&[&list]); + let got = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, [311.0, 212.0, 113.0]); + heap.release(slots, 2); + } + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// Under `batch_descriptors()` (`LEONIDA_BATCH_DESCRIPTORS=1`), calling `HostHeap::make_listed` + /// for a stale `R9G9B9E5` descriptor `words` flushes any queued `LISTED_COPIES` referencing the + /// previous `views.slot(at)` before overwriting it (preserving earlier slots' views while + /// updating subsequent slots to the replacement texture or null on failure). + #[test] + fn make_listed_stale_rebuild_flushes_batched_copies_before_overwrite() { + struct BatchGuard(Option); + impl BatchGuard { + fn set(on: bool) -> Self { + let prev = crate::descriptor::host::TEST_BATCH_DESCRIPTORS.get(); + crate::descriptor::host::TEST_BATCH_DESCRIPTORS.set(Some(on)); + Self(prev) + } + } + impl Drop for BatchGuard { + fn drop(&mut self) { + crate::descriptor::host::TEST_BATCH_DESCRIPTORS.set(self.0); + } + } + + let Some(host) = crate::host::host() else { + return; + }; + if !super::relaxed_format_casting(&host.device) { + return; + } + let _cast_guard = CastFlagGuard::set(Some(true), Some(true)); + let _batch_guard = BatchGuard::set(true); + + let heap = HostHeap::new(false, 16).unwrap(); + let (out_buf, out_ptr) = host.shared_buffer(256).unwrap(); + // SAFETY: live buffer. + let out_gpu = unsafe { out_buf.GetGPUVirtualAddress() }; + + let write_cs = compile_cs( + "RWTexture2D u : register(u0);\n\ + cbuffer C : register(b0) { uint packed_val; };\n\ + [numthreads(4, 4, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { u[id.xy] = packed_val; }", + &[RootSlot::UavTable, RootSlot::Const(0, 1)], + false, + ); + let read_cs = compile_cs( + "Texture2D t : register(t0);\n\ + RWByteAddressBuffer o : register(u0);\n\ + [numthreads(1, 1, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) { o.Store3(0, asuint(t.Load(int3(0, 0, 0)))); }", + &[RootSlot::SrvTable, RootSlot::Uav(0)], + false, + ); + + let addr = alloc_title_pages(256 << 10); + let source1 = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + let placed_res_words = tex_words(3, 8, 8, 1, 1, 67, 0); + let mut placed_desc = [0u32; 16]; + placed_desc[..10].copy_from_slice(&[67, 4, 5768, 0, 0, 1, 0, 0, 0, 0]); + placed_desc[10] = addr as u32; + placed_desc[11] = (addr >> 32) as u32; + let mut slot_words = [0u32; 8]; + crate::descriptor::create_placed_srv( + std::ptr::null(), + &placed_res_words, + &placed_desc, + slot_words.as_mut_ptr() as u64, + ); + let rec = [slot_words[0], slot_words[1], slot_words[2]]; + + let uav1 = View::Unordered(source1 as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + let dyn_slots = heap.dynamic(4).unwrap(); + heap.make_at(dyn_slots, &uav1); + + // Seed `source1` before building the same-recording descriptor batch. + let seed_list = host.new_list().unwrap(); + crate::draw::readable(&seed_list, ResourceType::Uav, &uav1); + let packed1 = pack_rgb9e5_unit(45, 55, 65); + unsafe { + seed_list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + seed_list.list.SetComputeRootSignature(&write_cs.0); + seed_list.list.SetPipelineState(&write_cs.1); + seed_list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, dyn_slots)); + seed_list.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed1).cast(), 0); + seed_list.list.Dispatch(2, 2, 1); + seed_list.list.ResourceBarrier(&[crate::host::transition( + crate::resource::host_resource(source1).unwrap(), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )]); + } + seed_list.close(); + host.execute(&[&seed_list]); + + let rec_id = 0x9999u64; + // `k1` queues a deferred copy from `views.slot(at)` holding `source1`. + assert!(heap.make_listed(rec_id, rec, dyn_slots + 1).is_some()); + + // Mid-table VA reuse replaces `source1` with `source2` before `flush_listed()`. + let source2 = make_source_at(addr, &tex_words(3, 8, 8, 1, 1, 42, 4)); + let uav2 = View::Unordered(source2 as usize, 0, Some([42, 4, 0, 0, 0, 0, 0, 0, 0, 0])); + heap.make_at(dyn_slots + 2, &uav2); + let seed2 = host.new_list().unwrap(); + crate::draw::readable(&seed2, ResourceType::Uav, &uav2); + let packed2 = pack_rgb9e5_unit(145, 155, 165); + unsafe { + seed2.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + seed2.list.SetComputeRootSignature(&write_cs.0); + seed2.list.SetPipelineState(&write_cs.1); + seed2.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, dyn_slots + 2)); + seed2.list.SetComputeRoot32BitConstants(1, 1, (&raw const packed2).cast(), 0); + seed2.list.Dispatch(2, 2, 1); + seed2.list.ResourceBarrier(&[crate::host::transition( + crate::resource::host_resource(source2).unwrap(), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )]); + } + seed2.close(); + host.execute(&[&seed2]); + + // `k2` triggers `stale_at`: must flush `k1`'s queued copy BEFORE overwriting `views.slot(at)`. + assert!(heap.make_listed(rec_id, rec, dyn_slots + 3).is_some()); + crate::descriptor::host::flush_listed(); + + for (slot, want) in [ + (dyn_slots + 1, [45.0f32, 55.0, 65.0]), + (dyn_slots + 3, [145.0f32, 155.0, 165.0]), + ] { + let read_list = host.new_list().unwrap(); + unsafe { + read_list.list.SetDescriptorHeaps(&[Some(heap.heap.clone())]); + read_list.list.SetComputeRootSignature(&read_cs.0); + read_list.list.SetPipelineState(&read_cs.1); + read_list.list.SetComputeRootDescriptorTable(0, gpu_slot(&heap, slot)); + read_list.list.SetComputeRootUnorderedAccessView(1, out_gpu); + read_list.list.Dispatch(1, 1, 1); + } + read_list.close(); + host.execute(&[&read_list]); + let got = unsafe { out_ptr.cast::<[f32; 3]>().read_volatile() }; + assert_eq!(got, want, "slot {slot} lost its pre-overwrite batched descriptor"); + } + + heap.release(dyn_slots, 4); + crate::object::release(source1); + crate::object::release(source2); + } +} + #[cfg(test)] mod backoff_tests { use super::turn_skipped;