From 000235bdeebddd7c68fd744aa77e703f7e4a48e4 Mon Sep 17 00:00:00 2001 From: NWProgramming00 <75951308+NWProgramming00@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:19:54 +0100 Subject: [PATCH 1/3] D3D12.X: sampled textures go without their top mips while video memory fills up When the device's local video memory passes 75 % of its budget, a new sampled title texture gets no pool tiles for its largest mips (the largest side kept: 2048 from 75 %, 1024 from 85 %, 512 from 92 %). Those tiles stay unmapped and every view of the texture is clamped to the first mip that has memory (ResourceMinLODClamp, which counts from the resource's first mip). With lazy levels (XCL_TEXTURE_LEVEL_PAGES=1) those levels never get pages. XCL_TEXTURE_BUDGET=0 turns it off; XCL_TEXTURE_MAX caps every new texture. Part of #1773. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 24 ++ crates/xcl/src/hle/d3d12x/vram.rs | 457 +++++++++++++++++++++++++++++- crates/xcl/src/host.rs | 7 +- 3 files changed, 472 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6fcaf053c6..c5a602ade4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3258,6 +3258,16 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { copy = Some(v); } + // a texture without video memory for its top mips (`vram::top_mip_tiles`): its views sample + // from the first mip it has + let skipped = if res.is_null() { 0 } else { super::vram::skipped_mips(res as usize) }; + if skipped > 0 { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + let mut v = copy.unwrap_or_else(|| default_texture2d_srv(&r.GetDesc())); + super::vram::clamp_skipped_mips(&mut v, skipped); + copy = Some(v); + } + } let desc = copy.as_ref().map_or(desc, |c| c as *const _); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; let _tracked_write_lock = super::vram::lock_tracked_srv_write(); @@ -3374,6 +3384,20 @@ unsafe fn dev_create_srv_inner(this: *mut c_void, res: *mut c_void, desc: *const } } +/// The view D3D12 makes of a 2D texture `rd` when it is given no description: all its mips and +/// slices, in its own format. +fn default_texture2d_srv(rd: &D3D12_RESOURCE_DESC) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: rd.Format, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; + if rd.DepthOrArraySize > 1 { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: u32::MAX, ArraySize: u32::from(rd.DepthOrArraySize), ..Default::default() }; + } else { + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: u32::MAX, ..Default::default() }; + } + v +} + /// A TEXTURECUBE view as the TEXTURECUBEARRAY of its one cube (None: any other view). fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option { if v.ViewDimension != D3D12_SRV_DIMENSION_TEXTURECUBE { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 38c7f70c7a..a47c4990db 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1008,6 +1008,10 @@ const COOL: std::time::Duration = std::time::Duration::from_secs(2); /// A pool tile: (pool heap, tile in it). type Tile = (u32, u32); +/// A tile of a resource that gets no video memory (a top mip left out, `top_mips_to_skip`): +/// left unmapped, so it reads as zero and takes writes nowhere (tiled resources tier 2). +const NO_TILE: Tile = (u32::MAX, 0); + struct Page { tile: Tile, /// targets using the page @@ -1061,6 +1065,10 @@ struct Target { /// virtual, resident, and SRV-sampled texel accounting for sampled placed textures (`None` for GPU-owned targets) texels: Option, recycle: Option, + /// top mips left without video memory (`top_mip_tiles`): their levels never get pages + skip_mips: u32, + /// their tiles (empty: none), kept for `remap_if_unmapped` + skip: Vec, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -1899,7 +1907,7 @@ impl Pages { return; } self.scratch_heaps.clear(); - self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.extend(tiles.iter().map(|t| t.0).filter(|&h| h != NO_TILE.0)); self.scratch_heaps.sort_unstable(); self.scratch_heaps.dedup(); for i in 0..self.scratch_heaps.len() { @@ -2087,24 +2095,29 @@ impl Pages { } } - /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { - self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false) + /// Acquire/share the `total` tiles for `res` at `va` and map them on the `Pages` queue – all + /// but those `skip` marks, which stay unmapped. + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, skip: &[bool]) -> Option<(Vec, Vec<(usize, usize)>)> { + self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false, skip) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. #[allow(clippy::too_many_arguments)] unsafe fn bind_range( &mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, - console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, evictable: bool, + console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, evictable: bool, skip: &[bool], ) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); + let skipped = |i: usize| skip.get(i).copied().unwrap_or(false); let mut missing = 0usize; let mut preferred: Option = None; for i in range.clone() { + if skipped(i) { + continue; + } let existing = if i < own { self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) } else { @@ -2129,6 +2142,10 @@ impl Pages { let mut used = Vec::with_capacity(own.min(range.len())); let mut used_extra = Vec::new(); for i in range { + if skipped(i) { + tiles.push(NO_TILE); + continue; + } let tile = if i < own { let a = first + i * PAGE; let t = match self.pages.get_mut(&a) { @@ -2367,6 +2384,9 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + // sampled textures only: what the GPU renders to keeps all of its memory + let (skip_mips, skip) = if require_aligned { (0, Vec::new()) } else { top_mip_tiles(dev, res, &tiled, total) }; + let skip_tiles = skip.iter().filter(|&&s| s).count(); let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2375,11 +2395,11 @@ unsafe fn place_on_pages( LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels, recycle: recycle_key, skip_mips, skip }); true - } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total, &skip) { record_texel_insert(&texels); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels, recycle: recycle_key, skip_mips, skip }); true } else { false @@ -2394,6 +2414,9 @@ unsafe fn place_on_pages( return None; } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + if skip_mips > 0 { + note_skipped_mips(raw as usize, skip_mips, skip_tiles); + } let (first, own) = owned_pages(va, console_bytes, total as usize).unwrap_or((va, 0)); let kind = if gpu_owned(desc.Flags.0 as u32) { super::placements::Kind::Target } else { super::placements::Kind::Sampled }; // (the older targets it supersedes leave the shared pages once the work before is done) @@ -2473,7 +2496,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { let key = res.as_raw() as usize; let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { + let Some((va, console_bytes, total, mapped, skip)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.skip.clone())) else { return false; }; if mapped { @@ -2504,7 +2527,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.mapped = true; return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total, &skip) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { @@ -2523,6 +2546,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { /// A resource released: its pages are no longer its. fn forget_pages(resource: usize, held: bool) -> Option { + forget_skipped_mips(resource); let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); for (&dev_key, slot) in g.iter_mut() { @@ -2722,6 +2746,197 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla drop((pruned, observed)); } +// --------------------------------------------------------------------------------------- +// Sampled textures without their top mips while video memory fills up +// +// A title streams more textures than a PC card's video memory holds once the console's copy +// of its memory is in video memory too (#1773): past the card's budget the driver pages, or +// removes the device. So when the device's local video memory is filling up, a new sampled +// texture gets no video memory for its largest mips: their tiles stay unmapped (they read as +// zero), and every view of the texture is clamped to the first mip that has memory +// (`clamp_skipped_mips`), so sampling never reaches them. The texture keeps its shape, its +// mip numbering and the title's uploads; it is only less sharp up close. +// +// `XCL_TEXTURE_BUDGET=0` turns it off; `XCL_TEXTURE_MAX=` caps the largest side of +// every new sampled texture at that whatever the fill (tests, measurements). +// --------------------------------------------------------------------------------------- + +/// The largest side a new sampled texture keeps when the device's local video memory is +/// `fill` (usage / budget) full; None: all of it. +fn cap_for_fill(fill: f64) -> Option { + if fill < 0.75 { + None + } else if fill < 0.85 { + Some(2048) + } else if fill < 0.92 { + Some(1024) + } else { + Some(512) + } +} + +/// How many top mips of a texture whose largest side is `largest` to leave out for none of its +/// sides to pass `cap`, keeping at least one mip that has tiles of its own (`standard_mips`: +/// the mips before the packed tail). +fn mips_to_skip(largest: u64, standard_mips: u32, cap: u64) -> u32 { + let mut skip = 0; + while largest >> skip > cap && skip + 1 < standard_mips { + skip += 1; + } + skip +} + +/// The cap that applies now (None: textures keep all their mips). +unsafe fn texture_cap(dev: &ID3D12Device) -> Option { + static SET: std::sync::OnceLock<(bool, Option)> = std::sync::OnceLock::new(); + let (on, max) = *SET.get_or_init(|| { + let on = std::env::var("XCL_TEXTURE_BUDGET").map_or(true, |v| v.trim() != "0"); + let max = std::env::var("XCL_TEXTURE_MAX").ok().and_then(|v| v.trim().parse::().ok()).filter(|&m| m > 0); + (on, max) + }); + if !on { + return None; + } + if max.is_some() { + return max; + } + cap_for_fill(local_fill(dev)?) +} + +/// The device's local video memory in use / its budget, asked at most every 100 ms. +unsafe fn local_fill(dev: &ID3D12Device) -> Option { + use windows::Win32::Graphics::Dxgi::*; + struct Cached { + luid: (u32, i32), + adapter: IDXGIAdapter3, + at: std::time::Instant, + fill: f64, + } + // DXGI adapters are free-threaded + unsafe impl Send for Cached {} + static CACHE: Mutex> = Mutex::new(None); + let luid = dev.GetAdapterLuid(); + let luid = (luid.LowPart, luid.HighPart); + let mut g = CACHE.lock().unwrap(); + if g.as_ref().is_none_or(|c| c.luid != luid) { + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter3 = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + *g = Some(Cached { luid, adapter, at: std::time::Instant::now() - std::time::Duration::from_secs(1), fill: 0.0 }); + } + let c = g.as_mut()?; + if c.at.elapsed() >= std::time::Duration::from_millis(100) { + let mut info = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + c.adapter.QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut info).ok()?; + c.fill = info.CurrentUsage as f64 / info.Budget.max(1) as f64; + c.at = std::time::Instant::now(); + } + Some(c.fill) +} + +/// For a new sampled texture `res` (`desc`, `total` tiles): how many top mips get no video +/// memory now, and which of its tiles those are (empty: none). +unsafe fn top_mip_tiles(dev: &ID3D12Device, res: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC, total: u32) -> (u32, Vec) { + if desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.MipLevels < 2 || desc.SampleDesc.Count > 1 { + return (0, Vec::new()); + } + let Some(cap) = texture_cap(dev) else { return (0, Vec::new()) }; + let (standard, tilings) = mip_tilings(dev, res, desc); + let skip = mips_to_skip(desc.Width.max(u64::from(desc.Height)), standard, cap); + if skip == 0 { + return (0, Vec::new()); + } + (skip, top_mip_mask(desc, &tilings, total, skip)) +} + +/// The mips of `res` with tiles of their own (before the packed tail), and every +/// subresource's tiling. +unsafe fn mip_tilings(dev: &ID3D12Device, res: &ID3D12Resource, desc: &D3D12_RESOURCE_DESC) -> (u32, Vec) { + let mips = u32::from(desc.MipLevels); + let mut count = mips * u32::from(desc.DepthOrArraySize.max(1)); + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); count as usize]; + dev.GetResourceTiling(res, None, Some(&mut packed), None, Some(&mut count), 0, tilings.as_mut_ptr()); + (u32::from(packed.NumStandardMips).min(mips), tilings) +} + +/// The tiles of the `skip` top mips of every slice, of `total`. +fn top_mip_mask(desc: &D3D12_RESOURCE_DESC, tilings: &[D3D12_SUBRESOURCE_TILING], total: u32, skip: u32) -> Vec { + let mips = u32::from(desc.MipLevels); + let slices = u32::from(desc.DepthOrArraySize.max(1)); + let mut mask = vec![false; total as usize]; + for slice in 0..slices { + for mip in 0..skip { + let Some(t) = tilings.get((slice * mips + mip) as usize) else { continue }; + if t.StartTileIndexInOverallResource == u32::MAX { + continue; + } + let n = u32::from(t.WidthInTiles) * u32::from(t.HeightInTiles) * u32::from(t.DepthInTiles); + for i in t.StartTileIndexInOverallResource..t.StartTileIndexInOverallResource.saturating_add(n) { + if let Some(m) = mask.get_mut(i as usize) { + *m = true; + } + } + } + } + mask +} + +/// resource → (top mips it has no video memory for, tiles of them) +static SKIPPED_MIPS: Mutex>> = Mutex::new(None); +/// whether any texture has (the views' fast path) +static ANY_SKIPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn note_skipped_mips(resource: usize, mips: u32, tiles: usize) { + let first = { + let mut g = SKIPPED_MIPS.lock().unwrap(); + let m = g.get_or_insert_with(std::collections::HashMap::new); + m.insert(resource, (mips, tiles)); + !ANY_SKIPPED.swap(true, std::sync::atomic::Ordering::AcqRel) + }; + if first { + crate::xlog_info!("D3D12.X: video memory is filling up: new sampled textures go without their largest mips (XCL_TEXTURE_BUDGET=0 keeps them)"); + } +} + +fn forget_skipped_mips(resource: usize) { + if ANY_SKIPPED.load(std::sync::atomic::Ordering::Acquire) { + if let Some(m) = SKIPPED_MIPS.lock().unwrap().as_mut() { + m.remove(&resource); + } + } +} + +/// How many top mips `resource` has no video memory for (0: all of them). +pub(super) fn skipped_mips(resource: usize) -> u32 { + if !ANY_SKIPPED.load(std::sync::atomic::Ordering::Acquire) { + return 0; + } + SKIPPED_MIPS.lock().unwrap().as_ref().and_then(|m| m.get(&resource).map(|e| e.0)).unwrap_or(0) +} + +/// (textures alive now without their top mips, bytes of tiles they go without) – `XCL_ACTIVITY`. +pub fn skipped_textures() -> (u64, u64) { + SKIPPED_MIPS.lock().unwrap().as_ref().map_or((0, 0), |m| (m.len() as u64, m.values().map(|e| (e.1 * PAGE) as u64).sum())) +} + +/// A texture view of a resource without its `mips` top mips: sampling clamped to the first mip +/// it has (`ResourceMinLODClamp` counts from the resource's first mip, not the view's). +pub(super) fn clamp_skipped_mips(v: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, mips: u32) { + let lod = mips as f32; + // SAFETY: the union member the view dimension names + unsafe { + let a = &mut v.Anonymous; + let clamp = match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => &mut a.Texture2D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => &mut a.Texture2DArray.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBE => &mut a.TextureCube.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => &mut a.TextureCubeArray.ResourceMinLODClamp, + _ => return, + }; + *clamp = clamp.max(lod); + } +} + /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind @@ -3005,7 +3220,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> wanted.sort_unstable(); wanted.dedup(); let todo: Vec<(usize, u32, u32, u32, std::ops::Range)> = - wanted.into_iter().filter(|&k| !lv.groups[k].3).map(|k| (k, lv.groups[k].0, lv.groups[k].1, lv.groups[k].2, lv.levels_of(k))).collect(); + groups_to_map(lv, wanted, t.skip_mips).into_iter().map(|k| (k, lv.groups[k].0, lv.groups[k].1, lv.groups[k].2, lv.levels_of(k))).collect(); if todo.is_empty() { return Vec::new(); } @@ -3014,7 +3229,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false, &[]) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; @@ -3117,6 +3332,12 @@ pub(super) fn note_srv(resource: usize, desc: Option<&D3D12_SHADER_RESOURCE_VIEW } } +/// Of the level groups `wanted`, those to give pages now: not mapped yet, and not of the +/// `skip_mips` top mips left without video memory (`top_mip_tiles`), which never get pages. +fn groups_to_map(lv: &Levels, wanted: Vec, skip_mips: u32) -> Vec { + wanted.into_iter().filter(|&k| !lv.groups[k].3 && lv.levels_of(k).start >= skip_mips).collect() +} + /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). pub(super) fn has_lazy_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) @@ -4130,6 +4351,8 @@ mod tests { levels: Some(levels), texels: None, recycle: None, + skip_mips: 0, + skip: Vec::new(), }; assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); @@ -5456,7 +5679,7 @@ mod tests { assert!(total >= 1); let key = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); - let (used1, extra1) = pages.bind(&dev, borrowed, 0x2000_0000, Some(total as u64 * PAGE as u64), total).expect("initial bind"); + let (used1, extra1) = pages.bind(&dev, borrowed, 0x2000_0000, Some(total as u64 * PAGE as u64), total, &[]).expect("initial bind"); let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); pages.queue.Wait(&gate, 1).unwrap(); pages.unmap(borrowed, total); @@ -5484,7 +5707,7 @@ mod tests { assert_eq!(reused_total, total); let reused_ptr = reused_raw as *mut c_void; let reused = ID3D12Resource::from_raw_borrowed(&reused_ptr).unwrap(); - let (used2, extra2) = pages.bind(&dev, reused, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total).expect("rebind after recycle"); + let (used2, extra2) = pages.bind(&dev, reused, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total, &[]).expect("rebind after recycle"); pages.unmap(reused, reused_total); pages.release_tiles(used2, extra2, std::time::Instant::now(), false); // Wait for unmap on the tile-mapping queue before dropping the resource and heaps. @@ -5616,4 +5839,210 @@ mod tests { late_release::drain_known(true); } } + + /// A texture with lazy levels (`XCL_TEXTURE_LEVEL_PAGES=1`) whose top mips were left out: + /// those levels never get pages, the others do once, and the packed tail with them. + #[test] + fn lazy_levels_never_map_the_top_mips_left_out() { + // 4 levels with tiles of their own (16, 4, 1, 1 tiles), then a packed tail of 1 tile + let mut lv = Levels::new(&[(0, 16), (16, 4), (20, 1), (21, 1)], Some((22, 1)), 23, 8).unwrap(); + let all: Vec = (0..lv.groups.len()).collect(); + assert_eq!(groups_to_map(&lv, all.clone(), 0), vec![0, 1, 2, 3, 4]); + assert_eq!(groups_to_map(&lv, all.clone(), 2), vec![2, 3, 4], "levels 0 and 1 left out"); + lv.groups[2].3 = true; + assert_eq!(groups_to_map(&lv, all.clone(), 2), vec![3, 4], "a group with pages is not mapped again"); + assert_eq!(groups_to_map(&lv, vec![0, 1], 2), Vec::::new(), "an upload of the left-out levels maps nothing"); + } + + #[test] + fn the_cap_follows_how_full_video_memory_is() { + assert_eq!(cap_for_fill(0.0), None); + assert_eq!(cap_for_fill(0.749), None); + assert_eq!(cap_for_fill(0.75), Some(2048)); + assert_eq!(cap_for_fill(0.85), Some(1024)); + assert_eq!(cap_for_fill(0.92), Some(512)); + assert_eq!(cap_for_fill(1.3), Some(512)); + } + + #[test] + fn top_mips_go_until_the_largest_side_fits_and_one_tiled_mip_stays() { + assert_eq!(mips_to_skip(4096, 13, 2048), 1); + assert_eq!(mips_to_skip(4096, 13, 1024), 2); + assert_eq!(mips_to_skip(4096, 13, 4096), 0); + assert_eq!(mips_to_skip(2048, 13, 2048), 0); + assert_eq!(mips_to_skip(4096, 13, 512), 3); + // never into the packed tail: the last mip with tiles of its own stays + assert_eq!(mips_to_skip(4096, 2, 256), 1); + assert_eq!(mips_to_skip(4096, 1, 256), 0); + } + + /// A reserved texture bound without its top mip on the pages, the way a sampled texture is + /// when video memory fills up: the top mip takes no page, sampling through a clamped view + /// reads the first mip that has memory, and the clamp counts from the resource's first mip, + /// not the view's (a view from mip 1 clamped to 2 reads mip 2, not mip 3). + #[test] + fn gpu_a_texture_without_its_top_mip_samples_the_first_it_has() { + use std::mem::{transmute_copy, ManuallyDrop}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let skip = crate::gpu::recomp::runner::skip_test; + let dev = unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return skip("no DXGI") }; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((a, d)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else { return skip("no GPU") }; + let Ok(dev) = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0) else { return skip("no GPU") }; + println!("adapter: {}", crate::gpu::adapter::name(&d)); + dev + }; + if !tier2(&dev) || crate::gpu::recomp::dxc::location().is_err() { + return skip("no tiled resources tier 2 or no DXC"); + } + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_POINT)" +RWByteAddressBuffer outb : register(u0); +SamplerState pt : register(s0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + for (uint i = 0; i < 3; i++) { + Texture2D t = ResourceDescriptorHeap[i]; + outb.Store(4 * i, uint(t.SampleLevel(pt, float2(0.5, 0.5), 0.0).r * 255.0 + 0.5)); + } +} +"#; + const MIPS: u16 = 4; + let shade = |mip: u32| 0x11 * (mip + 1); // mip 0 → 0x11 … mip 3 → 0x44 + unsafe { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + DepthOrArraySize: 1, + MipLevels: MIPS, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let mut tex: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut tex).unwrap(); + let tex = tex.unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(&tex, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let (standard, tilings) = mip_tilings(&dev, &tex, &desc); + assert!(standard >= 3, "512x512 RGBA8 has its first mips tiled ({standard})"); + let mask = top_mip_mask(&desc, &tilings, total, 1); + let mip0 = u32::from(tilings[0].WidthInTiles) * u32::from(tilings[0].HeightInTiles); + assert_eq!(mask.iter().filter(|&&m| m).count() as u32, mip0, "exactly mip 0's tiles"); + assert!(mask.iter().take(mip0 as usize).all(|&m| m)); + + let mut pages = Pages::new(&dev).unwrap(); + let (used, extra) = pages.bind(&dev, &tex, 0x10_0000_0000, None, total, &mask).unwrap(); + assert_eq!((used.len() + extra.len()) as u32, total - mip0, "mip 0 takes no page"); + + // the title's upload of every mip: mip 0's goes nowhere + let mut layouts = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); MIPS as usize]; + let mut rows = vec![0u32; MIPS as usize]; + let mut row_bytes = vec![0u64; MIPS as usize]; + let mut upload_bytes = 0u64; + dev.GetCopyableFootprints(&desc, 0, u32::from(MIPS), 0, Some(layouts.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut upload_bytes)); + let buffer = |size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool| { + let d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, state, None, &mut r).unwrap(); + r.unwrap() + }; + let upload = buffer(upload_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + for (m, l) in layouts.iter().enumerate() { + for r in 0..rows[m] as usize { + let at = (p as *mut u8).add(l.Offset as usize + r * l.Footprint.RowPitch as usize) as *mut u32; + for x in 0..l.Footprint.Width as usize { + at.add(x).write_unaligned(0xFF00_0000 | shade(m as u32)); + } + } + } + upload.Unmap(0, None); + + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .unwrap(); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 3, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let view = |first: u32, skipped: u32| { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: desc.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: first, MipLevels: u32::MAX, ..Default::default() } }, + }; + if skipped > 0 { + clamp_skipped_mips(&mut v, skipped); + } + v + }; + // 0: the whole texture, its top mip left out; 1: a view from mip 1 of a texture + // without two; 2: the whole texture unclamped (mip 0 has no memory: zero) + for (i, v) in [view(0, 1), view(1, 2), view(0, 0)].iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh.GetCPUDescriptorHandleForHeapStart().ptr + i * inc }; + dev.CreateShaderResourceView(&tex, Some(v), at); + } + let out = buffer(256, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buffer(256, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + queue.Wait(&pages.fence, pages.value).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + for (m, l) in layouts.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&tex), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: m as u32 } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&upload), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *l } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + let barrier = |r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: before, StateAfter: after }), + }, + }; + list.ResourceBarrier(&[barrier(&tex, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[barrier(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 0, &out, 0, 256); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let got = std::slice::from_raw_parts(q as *const u32, 3).to_vec(); + rb.Unmap(0, None); + assert_eq!(got, vec![shade(1), shade(2), 0], "clamped to mip 1; clamped from the resource's mip 0 (mip 2, not 3); mip 0 unmapped reads zero"); + } + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f76e9a7a8d..ecbb9f2f04 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -180,6 +180,7 @@ pub fn host_main(boot_path: &Path) -> i32 { let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); + let (thin, thin_bytes) = crate::hle::d3d12x::vram::skipped_textures(); let mb = |b: u64| b >> 20; // (at the end: tools read the line's beginning; the guard script reads the budget) let mut budget_text = if budget != 0 { format!("; video memory budget {} MB", mb(budget)) } else { String::new() }; @@ -191,7 +192,7 @@ pub fn host_main(boot_path: &Path) -> i32 { warn_low_commit(commit, commit_limit, private, local); } crate::xlog_info!( - "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped){budget_text}", + "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped); top mips left out of {} textures ({} MB){budget_text}", mb(private), mb(local), mb(non_local), @@ -200,7 +201,9 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(arenas as u64), mb(arenas_made as u64), mb(pools as u64), - mb(pools_mapped as u64) + mb(pools_mapped as u64), + thin, + mb(thin_bytes) ); crate::xlog_info!("{}", owner.line()); let pso = crate::hle::d3d12x::pso_async::retention_stats(); From 6ceff578964a9e59e3142126503935f8f94ee700 Mon Sep 17 00:00:00 2001 From: NWProgramming00 <75951308+NWProgramming00@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:35:19 +0100 Subject: [PATCH 2/3] D3D12.X: the activity line counts left-out top-mip memory once per page Textures placed at one title address share their pages, so summing the left-out tiles of each texture counted the same 64 KiB page several times, and counted pages another texture there still has. Each texture now keeps the pages its left-out tiles would have had (keyed as Pages::bind keys them); skipped_textures counts the distinct ones no texture holds now. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/vram.rs | 53 ++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index a47c4990db..5ee3899e0f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2386,7 +2386,7 @@ unsafe fn place_on_pages( let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); // sampled textures only: what the GPU renders to keeps all of its memory let (skip_mips, skip) = if require_aligned { (0, Vec::new()) } else { top_mip_tiles(dev, res, &tiled, total) }; - let skip_tiles = skip.iter().filter(|&&s| s).count(); + let skip_pages = if skip_mips > 0 { skipped_pages(va, console_bytes, total, &skip) } else { Vec::new() }; let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2415,7 +2415,7 @@ unsafe fn place_on_pages( } PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); if skip_mips > 0 { - note_skipped_mips(raw as usize, skip_mips, skip_tiles); + note_skipped_mips(raw as usize, skip_mips, skip_pages); } let (first, own) = owned_pages(va, console_bytes, total as usize).unwrap_or((va, 0)); let kind = if gpu_owned(desc.Flags.0 as u32) { super::placements::Kind::Target } else { super::placements::Kind::Sampled }; @@ -2881,16 +2881,27 @@ fn top_mip_mask(desc: &D3D12_RESOURCE_DESC, tilings: &[D3D12_SUBRESOURCE_TILING] mask } -/// resource → (top mips it has no video memory for, tiles of them) -static SKIPPED_MIPS: Mutex>> = Mutex::new(None); +/// A page a left-out tile would have had: (title page address, `usize::MAX`) for one of the +/// texture's own pages, (its address, tile index) for an extra tile – as `Pages::bind` keys them. +type SkippedPage = (usize, usize); + +/// resource → (top mips it has no video memory for, the pages of their tiles) +type SkippedMips = std::collections::HashMap)>; +static SKIPPED_MIPS: Mutex> = Mutex::new(None); /// whether any texture has (the views' fast path) static ANY_SKIPPED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -fn note_skipped_mips(resource: usize, mips: u32, tiles: usize) { +/// The pages of the tiles `skip` marks of a texture at `va` (`console_bytes`, `total` tiles). +fn skipped_pages(va: usize, console_bytes: Option, total: u32, skip: &[bool]) -> Vec { + let Some((first, own)) = owned_pages(va, console_bytes, total as usize) else { return Vec::new() }; + skip.iter().enumerate().filter(|&(_, &s)| s).map(|(i, _)| if i < own { (first + i * PAGE, usize::MAX) } else { (va, i) }).collect() +} + +fn note_skipped_mips(resource: usize, mips: u32, pages: Vec) { let first = { let mut g = SKIPPED_MIPS.lock().unwrap(); let m = g.get_or_insert_with(std::collections::HashMap::new); - m.insert(resource, (mips, tiles)); + m.insert(resource, (mips, pages)); !ANY_SKIPPED.swap(true, std::sync::atomic::Ordering::AcqRel) }; if first { @@ -2914,9 +2925,19 @@ pub(super) fn skipped_mips(resource: usize) -> u32 { SKIPPED_MIPS.lock().unwrap().as_ref().and_then(|m| m.get(&resource).map(|e| e.0)).unwrap_or(0) } -/// (textures alive now without their top mips, bytes of tiles they go without) – `XCL_ACTIVITY`. +/// (textures alive now without their top mips, bytes of the pages they left out that no texture +/// has now) – `XCL_ACTIVITY`. A page textures at one address share counts once, and not at all +/// while another texture there has it. pub fn skipped_textures() -> (u64, u64) { - SKIPPED_MIPS.lock().unwrap().as_ref().map_or((0, 0), |m| (m.len() as u64, m.values().map(|e| (e.1 * PAGE) as u64).sum())) + let (textures, wanted) = { + let g = SKIPPED_MIPS.lock().unwrap(); + let Some(m) = g.as_ref() else { return (0, 0) }; + let wanted: HashSet = m.values().flat_map(|e| e.1.iter().copied()).collect(); + (m.len() as u64, wanted) + }; + let g = PAGES.lock().unwrap(); + let held = |&(a, i): &SkippedPage| g.values().flatten().any(|p| if i == usize::MAX { p.pages.contains_key(&a) } else { p.extra_pages.contains_key(&(a, i)) }); + (textures, (wanted.iter().filter(|k| !held(k)).count() * PAGE) as u64) } /// A texture view of a resource without its `mips` top mips: sampling clamped to the first mip @@ -5854,6 +5875,22 @@ mod tests { assert_eq!(groups_to_map(&lv, vec![0, 1], 2), Vec::::new(), "an upload of the left-out levels maps nothing"); } + /// The pages of left-out tiles are keyed as `Pages::bind` keys them, so two textures at one + /// address name the same pages (and `skipped_textures` counts them once). + #[test] + fn left_out_tiles_name_the_pages_bind_would_give_them() { + let (va, total) = (0x10_0000_0000usize, 6u32); + let skip = [true, true, false, false, false, false]; + let a = skipped_pages(va, None, total, &skip); + assert_eq!(a, vec![(va, usize::MAX), (va + PAGE, usize::MAX)]); + assert_eq!(skipped_pages(va, None, total, &skip), a, "a second texture there: the same pages"); + // a texture covering 2 pages of its own (from the next 64 KiB boundary): the rest are extra tiles + let at = va + 0x1000; + let b = skipped_pages(at, Some((2 * PAGE) as u64), total, &[false, true, true, false, false, false]); + assert_eq!(b, vec![(va + 2 * PAGE, usize::MAX), (at, 2)]); + assert!(skipped_pages(va, None, total, &[false; 6]).is_empty()); + } + #[test] fn the_cap_follows_how_full_video_memory_is() { assert_eq!(cap_for_fill(0.0), None); From acad90b01b24a0ece58dc641f776bf820bd4adbe Mon Sep 17 00:00:00 2001 From: NWProgramming00 <75951308+NWProgramming00@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:08:11 +0100 Subject: [PATCH 3/3] D3D12.X: a GPU test compares the filtered picture of a texture without its top mip 64x64 samples with trilinear and 16x anisotropic filtering, level of detail -3 to +3, anisotropy 1 to 16 and turned footprints, from two copies of one texture whose mip 0 holds a colour no other mip has: one with mip 0 left out and its view clamped, one with every mip in memory and the same clamp. The pictures are the same to the bit and neither has the colour; without the clamp the samples do reach mip 0. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/vram.rs | 221 ++++++++++++++++++++++++++++++ 1 file changed, 221 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5ee3899e0f..a1bb85218f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -6082,4 +6082,225 @@ void main() { assert_eq!(got, vec![shade(1), shade(2), 0], "clamped to mip 1; clamped from the resource's mip 0 (mip 2, not 3); mip 0 unmapped reads zero"); } } + + /// The picture a texture without its top mip gives, filtered: 64x64 samples with trilinear and + /// 16x anisotropic filtering, over level of detail -3 to +3 and anisotropy 1 to 16 (gradients + /// given), from two copies of one 256x256 texture with nine mips. In both, mip 0 holds a + /// poison colour (red) that no other mip has. One copy has mip 0 left out (no pages) and its + /// view clamped; the other has every mip in memory and the same clamp. The two pictures are + /// the same to the bit, and neither has any red: the left-out mip adds nothing to any pixel + /// (not even a filter tap reading zeros), so the texture looks the way the clamp alone makes + /// it look. Without the clamp the same samples do show red (the picture reaches mip 0). + #[test] + fn gpu_a_texture_without_its_top_mip_filters_like_the_clamp_alone() { + use std::mem::{transmute_copy, ManuallyDrop}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let skip = crate::gpu::recomp::runner::skip_test; + let dev = unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return skip("no DXGI") }; + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let Some((a, d)) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next() else { return skip("no GPU") }; + let Ok(dev) = crate::gpu::agility::create_device(&a, D3D_FEATURE_LEVEL_12_0) else { return skip("no GPU") }; + println!("adapter: {}", crate::gpu::adapter::name(&d)); + dev + }; + if !tier2(&dev) || crate::gpu::recomp::dxc::location().is_err() { + return skip("no tiled resources tier 2 or no DXC"); + } + // views 0..3 (left out + clamp, all in memory + clamp, all in memory unclamped) x samplers + // (trilinear, anisotropic 16x): six pictures of N x N, RGBA8 packed + const N: u32 = 64; + let src = r#" +#define RS "RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED), UAV(u0), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR), StaticSampler(s1, filter=FILTER_ANISOTROPIC, maxAnisotropy=16)" +RWByteAddressBuffer outb : register(u0); +SamplerState tri : register(s0); +SamplerState aniso : register(s1); +uint pack(float4 c) { + uint4 b = uint4(saturate(c) * 255.0 + 0.5); + return b.r | (b.g << 8) | (b.b << 16) | (b.a << 24); +} +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void main(uint3 id : SV_DispatchThreadID) { + const uint N = 64; + float2 uv = (float2(id.xy) + 0.5) / N; + // level of detail -3 .. +3 down the picture, anisotropy 1 .. 16 across it + float scale = exp2(lerp(-3.0, 3.0, id.y / float(N - 1))) / 256.0; + float ratio = exp2(4.0 * id.x / float(N - 1)); + // every other column turned 45 degrees: the footprint is not only along the axes + float2 major = (id.x & 1) ? float2(0.7071, 0.7071) : float2(1.0, 0.0); + float2 minor = float2(-major.y, major.x); + float2 ddx = major * scale * ratio; + float2 ddy = minor * scale; + for (uint v = 0; v < 3; v++) { + Texture2D t = ResourceDescriptorHeap[v]; + uint at = ((v * 2) * N * N + id.y * N + id.x) * 4; + outb.Store(at, pack(t.SampleGrad(tri, uv, ddx, ddy))); + outb.Store(at + N * N * 4, pack(t.SampleGrad(aniso, uv, ddx, ddy))); + } +} +"#; + const MIPS: u16 = 9; + const PICTURES: usize = 6; + let bytes = (PICTURES as u32 * N * N * 4) as u64; + // mip 0: red (the poison); mips 1..8: no red, a checker of 4x4 texels in green and blue + // that differs from mip to mip, so filtering between mips changes the picture + let texel = |mip: u32, x: u32, y: u32| -> u32 { + if mip == 0 { + return 0xFF00_00FF; + } + let odd = ((x / 4) + (y / 4)) & 1; + let g = if odd == 1 { 255 - 24 * mip } else { 24 * mip }; + let b = if odd == 1 { 40 } else { 200 }; + 0xFF00_0000 | (b << 16) | (g << 8) + }; + unsafe { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: MIPS, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let reserved = || { + let mut t: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut t).unwrap(); + t.unwrap() + }; + let (left_out, whole) = (reserved(), reserved()); + let mut total = 0u32; + dev.GetResourceTiling(&left_out, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let (standard, tilings) = mip_tilings(&dev, &left_out, &desc); + assert!(standard >= 1, "256x256 RGBA8 has mip 0 tiled ({standard})"); + let mask = top_mip_mask(&desc, &tilings, total, 1); + let mip0 = u32::from(tilings[0].WidthInTiles) * u32::from(tilings[0].HeightInTiles); + assert_eq!(mask.iter().filter(|&&m| m).count() as u32, mip0, "exactly mip 0's tiles left out"); + + let mut pages = Pages::new(&dev).unwrap(); + let (used, extra) = pages.bind(&dev, &left_out, 0x10_0000_0000, None, total, &mask).unwrap(); + assert_eq!((used.len() + extra.len()) as u32, total - mip0, "mip 0 takes no page"); + pages.bind(&dev, &whole, 0x20_0000_0000, None, total, &vec![false; total as usize]).unwrap(); + + let mut layouts = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); MIPS as usize]; + let mut rows = vec![0u32; MIPS as usize]; + let mut row_bytes = vec![0u64; MIPS as usize]; + let mut upload_bytes = 0u64; + dev.GetCopyableFootprints(&desc, 0, u32::from(MIPS), 0, Some(layouts.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut upload_bytes)); + let buffer = |size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES, uav: bool| { + let d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, state, None, &mut r).unwrap(); + r.unwrap() + }; + let upload = buffer(upload_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + for (m, l) in layouts.iter().enumerate() { + for y in 0..rows[m] { + let at = (p as *mut u8).add(l.Offset as usize + y as usize * l.Footprint.RowPitch as usize) as *mut u32; + for x in 0..l.Footprint.Width { + at.add(x as usize).write_unaligned(texel(m as u32, x, y)); + } + } + } + upload.Unmap(0, None); + + let dxil = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as _, BytecodeLength: dxil.len() }, + ..Default::default() + }) + .unwrap(); + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 3, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let view = |skipped: u32| { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: desc.Format, + 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: u32::MAX, ..Default::default() } }, + }; + if skipped > 0 { + clamp_skipped_mips(&mut v, skipped); + } + v + }; + for (i, (t, v)) in [(&left_out, view(1)), (&whole, view(1)), (&whole, view(0))].into_iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh.GetCPUDescriptorHandleForHeapStart().ptr + i * inc }; + dev.CreateShaderResourceView(t, Some(&v), at); + } + let out = buffer(bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true); + let rb = buffer(bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + queue.Wait(&pages.fence, pages.value).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).unwrap(); + for t in [&left_out, &whole] { + for (m, l) in layouts.iter().enumerate() { + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(t), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: m as u32 } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&upload), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *l } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + } + let barrier = |r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: before, StateAfter: after }), + }, + }; + let to_read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + list.ResourceBarrier(&[barrier(&left_out, D3D12_RESOURCE_STATE_COPY_DEST, to_read), barrier(&whole, D3D12_RESOURCE_STATE_COPY_DEST, to_read)]); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, out.GetGPUVirtualAddress()); + list.Dispatch(N / 8, N / 8, 1); + list.ResourceBarrier(&[barrier(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&rb, 0, &out, 0, bytes); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 20_000).map_err(|e| format!("{e}")).unwrap(); + let mut q = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut q)).unwrap(); + let all = std::slice::from_raw_parts(q as *const u32, PICTURES * (N * N) as usize).to_vec(); + rb.Unmap(0, None); + + let n = (N * N) as usize; + let picture = |v: usize, sampler: usize| &all[(v * 2 + sampler) * n..(v * 2 + sampler + 1) * n]; + let red = |px: &[u32]| px.iter().filter(|&&c| c & 0xFF != 0).count(); + for (sampler, name) in [(0, "trilinear"), (1, "anisotropic 16x")] { + let (cut, clamped, unclamped) = (picture(0, sampler), picture(1, sampler), picture(2, sampler)); + let differ = cut.iter().zip(clamped).filter(|(a, b)| a != b).count(); + println!("{name}: {differ} of {n} pixels differ; red in: left out {}, clamp alone {}, unclamped {}", red(cut), red(clamped), red(unclamped)); + assert!(red(unclamped) > 0, "{name}: the samples reach mip 0 without the clamp (else this test shows nothing)"); + assert!(cut.iter().any(|&c| c & 0x00FF_FF00 != 0), "{name}: the texture without mip 0 is not black"); + assert_eq!(red(clamped), 0, "{name}: the clamp alone keeps mip 0 out of every pixel"); + assert_eq!(differ, 0, "{name}: without mip 0 in memory the picture is the clamp's, to the bit"); + } + } + } }