From 005a4427d2926f29d96ea28bf6747dc70321806c 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] 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 | 451 +++++++++++++++++++++++++++++- crates/xcl/src/host.rs | 7 +- 3 files changed, 468 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 01e3e1015..edab94804 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2239,6 +2239,16 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, 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) }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): @@ -2319,6 +2329,20 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } } +/// 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 6d3fc8e21..450298a09 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -183,6 +183,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 @@ -233,6 +237,10 @@ struct Target { used_extra: Vec<(usize, usize)>, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: 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 @@ -684,7 +692,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() { @@ -780,21 +788,26 @@ 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) + /// 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, 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) -> Option<(Vec, Vec<(usize, usize)>)> { + unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, 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 { @@ -819,6 +832,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) { @@ -1003,6 +1020,9 @@ unsafe fn place_on_pages( dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); 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) { @@ -1010,10 +1030,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, skip_mips, skip }); true - } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); + } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total, &skip) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, skip_mips, skip }); true } else { false @@ -1028,6 +1048,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); + } Some(hr) } @@ -1066,7 +1089,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 { @@ -1077,7 +1100,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) { @@ -1090,6 +1113,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) { + forget_skipped_mips(resource); let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); for pages in g.values_mut().flatten() { @@ -1188,6 +1212,197 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla }; } +// --------------------------------------------------------------------------------------- +// 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 @@ -1298,7 +1513,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(); } @@ -1307,7 +1522,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) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, &[]) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; t.used.extend(used); t.used_extra.extend(used_extra); @@ -1327,6 +1542,12 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec::new() } +/// 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())) @@ -2146,4 +2367,210 @@ mod tests { assert!(new_calls < old_calls); } } + + /// 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 444333d89..bd3fdc020 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -71,9 +71,10 @@ 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; 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)", + "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)", mb(private as u64), mb(local), mb(non_local), @@ -82,7 +83,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) ); last = now; }