From c9067a7d3f7a640423a90cd7d3fcbfa678e25f56 Mon Sep 17 00:00:00 2001 From: theme613 <66501763+theme613@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:19:56 +0800 Subject: [PATCH] gpu: add 6GB VRAM mip dropping, 16GB RAM pool caps/OOM recovery, and clear_air +inf clamp --- crates/victory-gpu/src/ambient.rs | 7 + crates/victory-gpu/src/descriptor/host.rs | 34 +++-- crates/victory-gpu/src/host.rs | 67 ++++++++-- crates/victory-gpu/src/host/menu.rs | 1 + crates/victory-gpu/src/host/send.rs | 36 +++++- crates/victory-gpu/src/list.rs | 118 ++++++++++++++--- crates/victory-gpu/src/resource.rs | 148 ++++++++++++++++++++-- crates/victory-gpu/src/shadow.rs | 6 + 8 files changed, 366 insertions(+), 51 deletions(-) diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index e7153c1..cc9b651 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -327,8 +327,15 @@ void clear_air(uint3 at : SV_DispatchThreadID) { float far = float(at.z) / float(d); float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far); float3 c = scattered[at]; + uint3 bits = asuint(c); + bool3 bad = (bits & 0x7f800000u) == 0x7f800000u; + bool fixed_any = any(bad); + if (fixed_any) { + c = bad ? (bits == 0x7f800000u ? 64512.0 : 0.0) : c; + } float has = dot(c, LUMA); if (has > cap) scattered[at] = c * (cap / has); + else if (fixed_any) scattered[at] = c; } #endif diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d331dd4..4e67c29 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -5159,20 +5159,30 @@ fn make_twinned( } /// The view `desc` of a texture, of a host copy of its levels from `base` -/// on (`crate::resource::held_only`). What it shows of larger ones, if any, -/// is left out. +/// on (`crate::resource::held_only` / `VICTORY_TEXTURE_DROP_MIPS`). What it +/// shows of larger ones, if any, is left out. fn from_base(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, base: u32) { - if desc.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D { - return; + let shift = |first: &mut u32, levels: &mut u32, clamp: &mut f32| { + let lost = base.saturating_sub(*first); + *first = first.saturating_sub(base); + if *levels != u32::MAX { + *levels = levels.saturating_sub(lost).max(1); + } + *clamp = (*clamp - base as f32).max(0.0); + }; + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: the member its dimension says. + let t = unsafe { &mut desc.Anonymous.Texture2D }; + shift(&mut t.MostDetailedMip, &mut t.MipLevels, &mut t.ResourceMinLODClamp); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: the member its dimension says. + let t = unsafe { &mut desc.Anonymous.Texture2DArray }; + shift(&mut t.MostDetailedMip, &mut t.MipLevels, &mut t.ResourceMinLODClamp); + } + _ => {} } - // SAFETY: the member its dimension says. - let t = unsafe { &mut desc.Anonymous.Texture2D }; - let lost = base.saturating_sub(t.MostDetailedMip); - t.MostDetailedMip = t.MostDetailedMip.saturating_sub(base); - if t.MipLevels != u32::MAX { - t.MipLevels = t.MipLevels.saturating_sub(lost).max(1); - } - t.ResourceMinLODClamp = (t.ResourceMinLODClamp - base as f32).max(0.0); } /// Writes of a slot with another view of the placed texture it showed, diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6671067..9fe714b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -456,6 +456,11 @@ fn sweep() { if crate::residency::pressured() { trim_spare_chunks(); } + if crate::residency::critical_commit() { + send::trim_spare(); + crate::shadow::trim_snapshot_pool(); + crate::list::trim_idle(); + } crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -4547,9 +4552,9 @@ impl Host { /// An allocator and a closed list for a prelude. fn make_prelude(&self) -> Option { - // SAFETY: plain object creation. - let made: windows::core::Result = unsafe { - (|| { + let create = || -> windows::core::Result { + // SAFETY: plain object creation. + unsafe { let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; let list: ID3D12GraphicsCommandList = @@ -4557,8 +4562,18 @@ impl Host { .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; list.Close()?; Ok((allocator, list)) - })() + } }; + let mut made = create(); + if let Err(ref e) = made + && e.code() == windows::Win32::Foundation::E_OUTOFMEMORY + { + crate::residency::allocation_error(e); + send::trim_spare(); + crate::shadow::trim_snapshot_pool(); + crate::list::trim_idle(); + made = create(); + } LISTS[1].fetch_add(1, Ordering::Relaxed); match made { Ok(prelude) => { @@ -4566,6 +4581,7 @@ impl Host { Some(prelude) } Err(e) => { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, "no host list for a prelude"); None } @@ -7450,9 +7466,7 @@ impl HostList { // skornuta/victory-memory-stack 57fb136, GPL-3.0.) let fresh = allocator_refresh(allocator, made, &ALLOCATOR_TRIMS[1]); let (allocator, list) = (&*allocator, &*list); - // SAFETY: the prelude is not executing (every submission is waited - // for); the textures are live. A fresh allocator is new and empty. - let recorded = unsafe { + let record = || unsafe { (if fresh { Ok(()) } else { allocator.Reset() }).and_then(|()| { list.Reset(allocator, None)?; if !aliasing.is_empty() { @@ -7473,7 +7487,18 @@ impl HostList { list.Close() }) }; + let mut recorded = record(); + if let Err(ref e) = recorded + && e.code() == windows::Win32::Foundation::E_OUTOFMEMORY + { + crate::residency::allocation_error(e); + send::trim_spare(); + crate::shadow::trim_snapshot_pool(); + crate::list::trim_idle(); + recorded = record(); + } if let Err(e) = recorded { + crate::residency::allocation_error(&e); fail(format_args!("a host state prelude did not record ({e})")); } list.cast().ok() @@ -7697,8 +7722,13 @@ impl HostList { /// /// shortcut: one buffer per copy; pool them once uploads are frequent. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { - // With [`card_steps`] the card may be the one that fills it. - let (buffer, data) = if card_steps::stage() > 1 { host.shared_buffer(size)? } else { host.upload_buffer(size)? }; + // With [`card_steps`] the card may be the one that fills it; skip the + // copy-queue `mapped()` fence stall since direct-queue submission runs later. + let (buffer, data) = if card_steps::stage() > 1 { + host.shared_buffer_for_list(size)? + } else { + host.upload_buffer(size)? + }; name(&buffer, || format!("list upload {size:#x}")); self.deferred().hold_upload(buffer.clone(), size); Some((buffer, data)) @@ -10851,6 +10881,21 @@ impl Host { /// [`Host::shared_buffer`], made now. pub(crate) fn shared_buffer_now(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + self.shared_buffer_impl(size, true) + } + + /// [`Host::shared_buffer`] for a command list upload without blocking on the + /// copy-queue `mapped()` fence wait. + pub(crate) fn shared_buffer_for_list(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + if size == crate::ahead::SIZE + && let Some(made) = crate::ahead::shared() + { + return Some(made); + } + self.shared_buffer_impl(size, false) + } + + fn shared_buffer_impl(&self, size: u64, wait_mapped: bool) -> Option<(ID3D12Resource, *mut u8)> { MADE[2].fetch_add(1, Ordering::Relaxed); MADE[3].fetch_add(size, Ordering::Relaxed); let heap = D3D12_HEAP_PROPERTIES { @@ -10889,7 +10934,9 @@ impl Host { .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; resident(&self.device, b)?; - mapped(&self.device)?; + if wait_mapped { + mapped(&self.device)?; + } b.Map(0, None, Some(&mut data)) }) }; diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs index 906674e..47ad32d 100644 --- a/crates/victory-gpu/src/host/menu.rs +++ b/crates/victory-gpu/src/host/menu.rs @@ -173,6 +173,7 @@ const ITEMS: &[Item] = &[ // On unless "0": a file saved by an earlier version holds an empty value (its OFF) or "1", // and both start it on, so nobody keeps it off from before by accident (2026-11-27). Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: &[("", "ON"), ("0", "OFF")], live: false }, + Item { var: "VICTORY_TEXTURE_DROP_MIPS", label: "TEXTURE SCALE (VRAM)", values: &[("", "FULL"), ("1", "HALF (6GB GPU)"), ("2", "QUARTER (4GB GPU)")], live: false }, Item { var: "VICTORY_LEAVE_OUT", label: "HEAT HAZE AND DECAL DEFRAG", values: &[("02384a60fda6f2d0,731a39171b568298", "LEFT OUT"), ("", "RUN (SLOWER, SMEARS)")], live: false }, Item { var: "VICTORY_EARLY_DEPTH", label: "EARLY DEPTH TEST", values: ON_UNSET, live: false }, Item { var: "VICTORY_WC_NO_BACK", label: "SKIP BIG COPY-BACKS", values: ON_UNSET, live: false }, diff --git a/crates/victory-gpu/src/host/send.rs b/crates/victory-gpu/src/host/send.rs index 68e9967..2e523a8 100644 --- a/crates/victory-gpu/src/host/send.rs +++ b/crates/victory-gpu/src/host/send.rs @@ -119,8 +119,14 @@ unsafe impl Send for Memory {} static SPARE: Mutex> = Mutex::new(Vec::new()); /// At most this much is kept (of the card's memory, with [`on_card`]). +/// On hosts with <= 32 GiB RAM, cap the idle upload pool at 256 MiB (instead +/// of 768 MiB) so streaming bursts have more commit headroom. fn kept() -> u64 { - if on_card() { 256 << 20 } else { 768 << 20 } + if on_card() || crate::residency::limited_host_ram() { + 256 << 20 + } else { + 768 << 20 + } } /// Whether the memory lies in the card's memory, written by the CPU through @@ -164,9 +170,35 @@ pub(super) fn give_back(memory: Memory) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); spare.push(memory); spare.sort_by_key(|m| std::cmp::Reverse(m.size)); + let mut freed = Vec::new(); while spare.iter().map(|m| m.size).sum::() > kept() { - spare.remove(0); + freed.push(spare.remove(0)); } + drop(spare); + drop(freed); +} + +/// Drops excess idle submission upload buffers during critical host commit +/// pressure, keeping up to two small buffers (<= 32 MiB). +pub(super) fn trim_spare() { + let freed: Vec = { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.is_empty() { + return; + } + spare.sort_by_key(|m| m.size); + let mut kept_bytes = 0u64; + let mut keep = 0usize; + for m in spare.iter().take(2) { + if kept_bytes + m.size > 32 << 20 { + break; + } + kept_bytes += m.size; + keep += 1; + } + spare.split_off(keep) + }; + drop(freed); } /// Since the last frame-rate line: bytes copied, runs copied, words stored, diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index d2baec2..32435ad 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -300,14 +300,18 @@ unsafe impl Send for Idle {} #[cfg(windows)] static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); -/// The most host lists kept idle (128 were too few: flights land several at -/// a time, so lists were thrown away and others made in the same frame, with -/// their preludes and buffers, 12 % of the submitting thread in the opening, -/// profile cpu-1), and the most upload memory they may keep -/// between them (a list keeps scratch chunks over a reset only while lists -/// do not share them, `VICTORY_SCRATCH_POOL=0`). +/// The most host lists kept idle, and the most upload memory they may keep +/// between them. On hosts with <= 32 GiB RAM, cap at 96 idle lists / 64 MiB +/// instead of 512 / 256 MiB so command-allocator pools cannot push a 16 GB +/// host into `E_OUTOFMEMORY` during long open-world sessions. #[cfg(windows)] -const IDLE_MOST: (usize, u64) = (512, 256 << 20); +fn idle_most() -> (usize, u64) { + if crate::residency::limited_host_ram() { + (96, 64 << 20) + } else { + (512, 256 << 20) + } +} // Idle-list trim: memory stack by skornuta (skornuta/victory-memory-stack 57fb136, GPL-3.0), // patch 13 (and the idle trim of its base). @@ -382,7 +386,8 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { if !ran.contains(&i) { continue; } - if IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + let (max_lists, max_bytes) = idle_most(); + if IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= max_lists { // Its submission has run: its prelude serves another list. host.give_prelude(); continue; @@ -392,7 +397,7 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { host.reset(); let bytes = host.scratch_kept(); let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); - if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { + if idle.0.len() < max_lists && idle.1 + bytes <= max_bytes { let now = crate::host::now_ms(); idle.0.push(Idle(host, bytes, now)); idle.1 += bytes; @@ -412,6 +417,24 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { } } +/// Drops excess idle command lists/allocators during critical host commit +/// pressure, keeping a small working set (64 lists). +#[cfg(windows)] +pub(crate) fn trim_idle() { + const PRESSURED_KEEP: usize = 64; + let freed: Vec = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() <= PRESSURED_KEEP { + return; + } + let dropped = idle.0.split_off(PRESSURED_KEEP); + let dropped_bytes: u64 = dropped.iter().map(|Idle(_, b, _)| *b).sum(); + idle.1 = idle.1.saturating_sub(dropped_bytes); + dropped + }; + drop(freed); +} + /// A wait for a memory value recorded into list `this`, with waits cut /// into lists (`crate::queue::cuts`). On the console the queue runs the /// list up to the wait, stands there until the value is in memory, and @@ -1007,7 +1030,14 @@ extern "system" fn copy_buffer_region( /// other is not ([`crate::resource::target_format`]): their texels differ /// in size, so the host cannot copy between them (logged once). #[cfg(windows)] -fn unlike(dst: This, src: This) -> bool { +fn unlike(dst: This, src: This, mapped: bool) -> bool { + if !mapped && (crate::resource::dropped(src) > 0 || crate::resource::dropped(dst) > 0) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(?dst, ?src, "copy with a texture whose host copy leaves out levels skipped") + }); + return true; + } let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src); if unlike { static ONCE: std::sync::Once = std::sync::Once::new(); @@ -1033,7 +1063,8 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { crate::resource::host_resource(dst), crate::resource::host_resource(src), ) { - if unlike(dst, src) { + let levelwise = crate::resource::dropped(dst) != crate::resource::dropped(src); + if unlike(dst, src, true) { return; } // Two title textures over the same memory have one host @@ -1075,8 +1106,12 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { ensure_state(list, src, COPY_SOURCE); #[cfg(feature = "diagnostics")] list.note_op(|| format!("copy resource {src:?} to {dst:?}")); - // SAFETY: an open list and live textures. - unsafe { list.list.CopyResource(to, from) }; + if levelwise { + copy_levels(list, dst, to, src, from); + } else { + // SAFETY: an open list and live textures. + unsafe { list.list.CopyResource(to, from) }; + } } else if let (Some((to, a)), Some((from, b))) = ( crate::resource::buffer_bytes(dst), crate::resource::buffer_bytes(src), @@ -1088,6 +1123,41 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { let _ = (this, dst, src); } +/// A whole-texture copy between host copies that leave out different +/// numbers of levels (`crate::resource::drop_levels`): each title level both +/// host copies have, at its own index in each. +#[cfg(windows)] +fn copy_levels( + list: &crate::host::HostList, + dst: This, + to: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + src: This, + from: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_TEXTURE_COPY_LOCATION, D3D12_TEXTURE_COPY_LOCATION_0, + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, ID3D12Resource, + }; + let location = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index }, + }; + let count = crate::resource::title_subresources(dst).min(crate::resource::title_subresources(src)); + for index in 0..count { + let (Some(d), Some(s)) = ( + crate::resource::host_subresource(dst, index), + crate::resource::host_subresource(src, index), + ) else { + continue; + }; + // SAFETY: an open list and live textures; both subresources exist + // and have the title level's size. + unsafe { list.list.CopyTextureRegion(&location(to, d), 0, 0, 0, &location(from, s), None) }; + } +} + extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) { copy_resource(this, dst, src); } @@ -1161,9 +1231,16 @@ extern "system" fn copy_texture_region( } return; }; - if unlike(dst.resource, src.resource) { + if unlike(dst.resource, src.resource, true) { return; } + let mut dst = dst; + if dst.kind != FOOTPRINT && crate::resource::dropped(dst.resource) > 0 { + match crate::resource::host_subresource(dst.resource, dst.footprint.offset as u32) { + Some(index) => dst.footprint.offset = u64::from(index), + None => return, + } + } let mut from = src; // Both sides are the same subresource of one host texture (set below). let mut same = false; @@ -1207,10 +1284,15 @@ extern "system" fn copy_texture_region( // title textures over one memory): not a copy the host allows. // The states and the copy are left out below; the rest is // noted as before. + if crate::resource::dropped(src.resource) > 0 { + match crate::resource::host_subresource(src.resource, src.footprint.offset as u32) { + Some(index) => from.footprint.offset = u64::from(index), + None => return, + } + } same = texture.as_raw() == to.as_raw() - && src.kind != FOOTPRINT && dst.kind != FOOTPRINT - && src.footprint.offset as u32 == dst.footprint.offset as u32; + && from.footprint.offset == dst.footprint.offset; list.twin_use(src.resource, false, false); if crate::texture::title_written(texture) { crate::texture::upload(list, src.resource, texture); @@ -1342,6 +1424,7 @@ fn read_back( // The title's buffer holds every row at its own pitch. let bytes = pitch * (rows - 1) + row; let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let index = crate::resource::readback_subresource(src.resource, src.footprint.offset as u32)?; let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; // As a texture source of any copy: what shaders wrote to a depth twin @@ -1353,6 +1436,7 @@ fn read_back( ensure_state(list, src.resource, COPY_SOURCE); let mut from = src; from.resource = texture.as_raw().cast_const().cast(); + from.footprint.offset = u64::from(index); let mut to = dst; to.resource = buffer.as_raw().cast_const().cast(); to.footprint = footprint; @@ -1412,7 +1496,7 @@ extern "system" fn resolve( use windows::core::Interface; const RESOLVE_DEST: u32 = 0x1000; const RESOLVE_SOURCE: u32 = 0x2000; - if unlike(dst, src) { + if unlike(dst, src, false) { return; } // Depth textures shaders also write: what they wrote, first. diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 597ede5..5638f35 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1351,12 +1351,128 @@ pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) - if layout.bytes_from(first) < layout.size { first } else { 0 } } +/// Configured `VICTORY_TEXTURE_DROP_MIPS` count (0..=4; 0 leaves out none). +#[cfg(windows)] +pub(crate) fn drop_mips_configured() -> u32 { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_DROP_MIPS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + .min(4) + }) +} + +/// How many of its largest levels the host copy of a texture described by +/// `desc` leaves out (`VICTORY_TEXTURE_DROP_MIPS=N`, at most 4; 0, the +/// default, leaves out none). Each level left out divides the texture's +/// bytes by about four, keeping 6 GB / 4 GB GPUs within VRAM budget with +/// frame generation active. Only 2D single-slice textures the title fills +/// ([`fills`]), at least 512 texels on their shorter side, whose sides +/// halve cleanly into whole 4-texel blocks. +/// +/// `VICTORY_TEXTURE_KEEP_SIDE=`: no texture is taken below that +/// many texels on its longer side ([`levels_above`]). +#[cfg(windows)] +pub(crate) fn drop_levels(desc: &ResourceDesc) -> u32 { + const TEXTURE_2D: u32 = 3; + let n = drop_mips_configured(); + if n == 0 + || !fills(desc) + || desc.dimension != TEXTURE_2D + || desc.depth_or_array_size != 1 + || desc.sample_count > 1 + || desc.mip_levels < 5 + { + return 0; + } + static KEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + let keep = *KEEP.get_or_init(|| { + std::env::var("VICTORY_TEXTURE_KEEP_SIDE") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + }); + let (w, h) = (desc.width, u64::from(desc.height)); + let n = levels_above(n.min(u32::from(desc.mip_levels).saturating_sub(1)), w.max(h), keep); + let whole = |side: u64| side % (4 << n) == 0; + if n == 0 || w.min(h) < 512 || !whole(w) || !whole(h) { + return 0; + } + n +} + +/// Of `n` levels, how many a texture `longer` texels long can give up and +/// stay at least `keep` texels long (`keep` 0: all `n`). +fn levels_above(n: u32, longer: u64, keep: u64) -> u32 { + match keep { + 0 => n, + keep => n.min((longer / keep).checked_ilog2().unwrap_or(0)), + } +} + +#[cfg(test)] +#[test] +fn a_kept_side_bounds_the_levels_dropped() { + assert_eq!(levels_above(2, 4096, 0), 2); + assert_eq!(levels_above(2, 4096, 1024), 2); + assert_eq!(levels_above(2, 2048, 1024), 1); + assert_eq!(levels_above(2, 1024, 1024), 0); + assert_eq!(levels_above(2, 512, 1024), 0); + assert_eq!(levels_above(4, 8192, 1024), 3); + assert_eq!(levels_above(1, 3000, 1024), 1); +} + +/// Base mip level omitted by the host copy of `this` (0 for buffers and null). +#[cfg(windows)] +pub(crate) fn dropped(this: This) -> u32 { + if this.is_null() { + return 0; + } + made_copy(this).map_or_else(|| drop_levels(&resource(this).desc), |copy| copy.base) +} + +/// The host copy's subresource for subresource `index` of title texture +/// `this`, whose host copy leaves out [`dropped`] levels: `None` for a +/// level it leaves out. +#[cfg(windows)] +pub(crate) fn host_subresource(this: This, index: u32) -> Option { + let drop = dropped(this); + let mips = u32::from(resource(this).desc.mip_levels).max(1); + let (mip, slice) = (index % mips, index / mips); + (mip >= drop).then(|| mip - drop + slice * (mips - drop)) +} + +/// Subresources in the first plane of title texture `this`, as the title +/// numbers them (levels times slices). +#[cfg(windows)] +pub(crate) fn title_subresources(this: This) -> u32 { + let desc = &resource(this).desc; + u32::from(desc.mip_levels).max(1) * u32::from(desc.depth_or_array_size).max(1) +} + +/// Maps a readback before creating a host texture. Ordinary textures keep +/// their native subresource numbering. Shrunken textures support plane zero. +#[cfg(windows)] +pub(crate) fn readback_subresource(this: This, index: u32) -> Result { + if dropped(this) == 0 { + return Ok(index); + } + let desc = &resource(this).desc; + if index >= u32::from(desc.mip_levels) * u32::from(desc.depth_or_array_size) { + return Err("a read back outside the first plane of the host texture"); + } + host_subresource(this, index).ok_or("a mip level omitted from the host texture") +} + /// The level a host copy begins at for views that start at `first`: one the /// host can have as a texture's level 0 ([`read_from`]; block-compressed -/// formats in whole blocks). +/// formats in whole blocks), never below [`drop_levels`]. #[cfg(windows)] fn base_level(desc: &ResourceDesc, first: u32) -> u32 { const TEXTURE_2D: u32 = 3; + let first = first.max(drop_levels(desc)); if first == 0 || !fills(desc) || desc.dimension != TEXTURE_2D @@ -1387,7 +1503,8 @@ fn base_level(desc: &ResourceDesc, first: u32) -> u32 { /// [`placed_bytes`]. Remembered: asked for every slot that is looked at. #[cfg(windows)] pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option { - if first == 0 || !held_only() { + let drop_on = drop_mips_configured() > 0; + if !drop_on && (first == 0 || !held_only()) { return placed_bytes(desc); } type Known = std::collections::HashMap<([u32; 14], u32), Option>; @@ -1399,11 +1516,16 @@ pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option { let whole = placed_bytes(desc)?; // SAFETY: 56 bytes in the description's layout. let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + let floor = drop_levels(&d); + let effective = if held_only() { first.max(floor) } else { floor }; + if effective == 0 { + return Some(whole); + } let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else { return Some(whole); }; let layout = &t.planes[0].layout; - Some(layout.bytes_from(read_from(layout, first)).min(whole)) + Some(layout.bytes_from(read_from(layout, effective)).min(whole)) }) }) } @@ -1752,14 +1874,20 @@ fn hosted(this: This, make: bool) -> Option { texture = reserved; } } - // The levels views show ([`held_only`]), those of the slots shaders - // pick by index among them. + // The levels views show ([`held_only`]) and any configured mip floor + // (`VICTORY_TEXTURE_DROP_MIPS`), for non-aliased, non-tiled textures. let mut base = 0; - if shape_fits && r.host.placed.load(Relaxed) && held_only() && !is_aliased(this) { - let wanted = r.host.wanted.load(Relaxed); - let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX); - let first = wanted.min(viewed); - if first != u32::MAX { + if shape_fits && !is_aliased(this) && tiled.is_none() { + let mut first = drop_levels(&r.desc); + if r.host.placed.load(Relaxed) && held_only() { + let wanted = r.host.wanted.load(Relaxed); + let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX); + let held = wanted.min(viewed); + if held != u32::MAX { + first = first.max(held); + } + } + if first > 0 { base = base_level(&r.desc, first); } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 2ac83e4..749f612 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1319,6 +1319,12 @@ mod relay_tests { /// Snapshot memory kept for reuse (already touched, so no page faults). static POOL: Mutex>> = Mutex::new(Vec::new()); +/// Drops pooled CPU snapshot buffers during critical host commit pressure. +pub(crate) fn trim_snapshot_pool() { + let gone = std::mem::take(&mut *POOL.lock().unwrap_or_else(|e| e.into_inner())); + drop(gone); +} + /// An empty buffer with room for `n` bytes, from the pool if it has one /// of about that size: a small copy's snapshot took the 174 MB buffer kept /// for the big heap's, which then got another, until eight of them were