diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs new file mode 100644 index 0000000..dfcf50b --- /dev/null +++ b/crates/victory-gpu/src/compose.rs @@ -0,0 +1,325 @@ +//! Two presented planes as one image: the console's display puts the second +//! (the interface) over the first (the scene), each scaled to the screen. +//! Grand Theft Auto VI presents so on Series S. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{PCSTR, s}; + +use crate::host::Host; + +const SOURCE: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" +Texture2D scene : register(t0); +Texture2D over : register(t1); +SamplerState smooth_ : register(s0); +struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] +V vs(uint id : SV_VertexID) { + V v; + v.uv = float2((id << 1) & 2, id & 2); + v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1); + return v; +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + float4 s = scene.SampleLevel(smooth_, v.uv, 0); + float4 o = over.SampleLevel(smooth_, v.uv, 0); + return float4(saturate(o.rgb + s.rgb * (1 - saturate(o.a))), 1); +} +"#; + +pub(crate) struct Composer { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + views: Vec, + step: u32, +} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Composer {} +// SAFETY: as above. +unsafe impl Sync for Composer {} + +fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result { + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out pointer is + // ours. + unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("compose"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + None, + )?; + } + code.ok_or_else(windows::core::Error::empty) +} + +impl Composer { + pub(crate) fn new(host: &Host, format: DXGI_FORMAT) -> windows::core::Result { + let (vs, ps) = ( + compile(s!("vs"), s!("vs_5_1"))?, + compile(s!("ps"), s!("ps_5_1"))?, + ); + // SAFETY: the blobs' own bytes, alive through the calls. + unsafe { + let bytes = |b: &ID3DBlob| { + std::slice::from_raw_parts(b.GetBufferPointer().cast::(), b.GetBufferSize()) + }; + let device = &host.device; + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; + let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.GetBufferPointer(), + BytecodeLength: b.GetBufferSize(), + }; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs), + PS: code(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.RTVFormats[0] = format; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let pso = device.CreateGraphicsPipelineState(&desc)?; + Ok(Composer { + root, + pso, + views: Vec::new(), + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + }) + } + } + + /// Each presenter command-list slot owns its own pair of SRVs. The swap + /// chain may have several outstanding presents; the slot is selected by + /// the completion fence, and its descriptors are only overwritten on reuse. + pub(crate) fn record( + &mut self, + host: &Host, + slot: usize, + list: &ID3D12GraphicsCommandList, + planes: [(&ID3D12Resource, DXGI_FORMAT); 2], + back: &ID3D12Resource, + (width, height): (u32, u32), + ) -> windows::core::Result<()> { + while self.views.len() <= slot { + let heap = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })? + }; + self.views.push(heap); + } + let views = &self.views[slot]; + // SAFETY: an open list; the views are made in slots no frame in flight + // reads; live textures. + unsafe { + let (cpu, gpu) = ( + views.GetCPUDescriptorHandleForHeapStart(), + views.GetGPUDescriptorHandleForHeapStart(), + ); + for (i, plane) in planes.iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + (i * self.step as usize), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: plane.1, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + host.device + .CreateShaderResourceView(Some(plane.0), Some(&desc), at); + } + let rtv = host.rtv(Some(back), None); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetGraphicsRootSignature(&self.root); + list.SetPipelineState(&self.pso); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: width as f32, + Height: height as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.DrawInstanced(3, 1, 0, 0); + } + Ok(()) + } +} + +/// Select a legal float-sampled view of a display plane, preserving a typed +/// resource's format. Typeless resources use the corresponding display type. +pub(crate) fn view(d: &D3D12_RESOURCE_DESC) -> Option { + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || d.DepthOrArraySize != 1 + || d.SampleDesc.Count != 1 + || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + { + return None; + } + match d.Format.0 { + 9 => Some(DXGI_FORMAT_R16G16B16A16_FLOAT), + 23 => Some(DXGI_FORMAT_R10G10B10A2_UNORM), + 27 => Some(DXGI_FORMAT_R8G8B8A8_UNORM), + 90 => Some(DXGI_FORMAT_B8G8R8A8_UNORM), + 10 | 11 | 13 | 24 | 26 | 28 | 29 | 31 | 67 | 87 | 91 => Some(d.Format), + _ => None, + } +} + +#[cfg(all(test, feature = "diagnostics"))] +mod tests { + use super::*; + + #[test] + fn composes_scaled_premultiplied_plane_on_gpu() { + let Some(host) = crate::host::host() else { + eprintln!("skipping display-plane readback: no D3D12 device"); + return; + }; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut compositor = Composer::new(host, format).unwrap(); + let list = host.new_list().unwrap(); + let texture = |width: u64| -> ID3D12Resource { + let mut resource = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut resource, + ) + .unwrap() + }; + resource.unwrap() + }; + // A half-red base at one resolution. The overlay at output resolution + // contains transparent, half-opaque green and fully opaque blue pixels. + let base = texture(1); + let overlay = texture(3); + let output = texture(3); + let target = D3D12_RESOURCE_STATE_RENDER_TARGET; + let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + let cmds = &list.list; + unsafe { + cmds.ClearRenderTargetView(host.rtv(Some(&base), None), &[0.5, 0.0, 0.0, 1.0], None); + let overlay_rtv = host.rtv(Some(&overlay), None); + let colors = [ + [0.0, 0.0, 0.0, 0.0], + [0.0, 0.5, 0.0, 0.5], + [0.0, 0.0, 1.0, 1.0], + ]; + for (i, color) in colors.iter().enumerate() { + let rect = windows::Win32::Foundation::RECT { + left: i as i32, + right: i as i32 + 1, + top: 0, + bottom: 1, + }; + cmds.ClearRenderTargetView(overlay_rtv, color, Some(&[rect])); + } + cmds.ResourceBarrier(&[ + crate::host::transition(&base, target, read), + crate::host::transition(&overlay, target, read), + ]); + compositor + .record( + host, + 0, + cmds, + [(&base, format), (&overlay, format)], + &output, + (3, 1), + ) + .unwrap(); + cmds.ResourceBarrier(&[crate::host::transition( + &output, + target, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let (buffer, footprint) = + crate::capture::read_back(&host.device, cmds, &output).unwrap(); + list.close(); + host.execute(&[&list]); + host.device.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + let start = mapped.cast::().add(footprint.Offset as usize); + let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap(); + buffer.Unmap(0, None); + for (actual, expected) in pixels + .iter() + .zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255]) + { + assert!( + actual.abs_diff(expected) <= 1, + "unexpected composite {pixels:?}" + ); + } + eprintln!("D3D12 display-plane readback RGBA: {pixels:?}"); + } + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index f04fe53..1b8c561 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -24,6 +24,94 @@ use crate::host::HostList; use crate::object::This; use crate::pipeline::host::HostPipeline; +/// Shader interface metadata shared by every pipeline variant and draw. +pub(crate) struct TablePlan { + groups: Vec, + // Direct entries can interleave slots. Preserve their declaration order + // when recording resource reads, writes, and transitions. + direct: Vec<(usize, usize)>, +} + +struct TableGroup { + slot: u8, + has_cbv: bool, + has_uav: bool, + max_dword: u32, + entries: Vec, + indexed: Vec, + // Descriptor number -> first declaration, matching the bind-time search. + by_descriptor: Vec<(u32, usize)>, +} + +impl TablePlan { + pub(crate) fn new(used: &[UsedResource], indexed: &[RootIndexedView]) -> Self { + let mut slots: Vec<_> = used + .iter() + .filter(|u| u.root == RootType::Table) + .map(|u| u.slot) + .collect(); + slots.sort_unstable(); + slots.dedup(); + let mut groups: Vec<_> = slots + .iter() + .map(|&slot| TableGroup { + slot, + has_cbv: false, + has_uav: false, + max_dword: 0, + entries: Vec::new(), + by_descriptor: Vec::new(), + indexed: indexed.iter().filter(|v| v.table_slot == slot).copied().collect(), + }) + .collect(); + let mut direct = Vec::new(); + for &u in used.iter().filter(|u| u.root == RootType::Table) { + let i = slots + .binary_search(&u.slot) + .expect("table slot collected from these declarations"); + let group = &mut groups[i]; + group.has_cbv |= u.kind == ResourceType::Cbv; + group.has_uav |= u.kind == ResourceType::Uav; + group.max_dword = group.max_dword.max(u.table_offset_dwords); + direct.push((i, group.entries.len())); + group + .by_descriptor + .push((u.table_offset_dwords / 8, group.entries.len())); + group.entries.push(u); + } + for group in &mut groups { + group.by_descriptor.sort_unstable(); + group.by_descriptor.dedup_by_key(|item| item.0); + } + Self { groups, direct } + } +} + +impl TableGroup { + fn entry(&self, descriptor: u32) -> Option<&UsedResource> { + let i = self + .by_descriptor + .binary_search_by_key(&descriptor, |item| item.0) + .ok()?; + Some(&self.entries[self.by_descriptor[i].1]) + } + + fn needs_snapshot(&self, heap: &crate::descriptor::Heap, host_count: u32, table: u64) -> bool { + let index_at = |dword: u32| { + table + .checked_add(u64::from(dword) * 4) + .and_then(|end| heap.index(end)) + }; + match index_at(self.max_dword) { + Some(i) => i >= host_count, + None => self + .entries + .iter() + .any(|u| index_at(u.table_offset_dwords).is_some_and(|i| i >= host_count)), + } + } +} + /// A root argument as the title set it. #[derive(Debug, Clone, Default)] enum Root { @@ -334,6 +422,7 @@ pub(crate) struct State { /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], + host_heaps_set: bool, /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault>, @@ -1143,6 +1232,7 @@ impl State { self.host_pipeline = 0; self.host_roots = [0; 2]; self.host_heaps = [0; 2]; + self.host_heaps_set = false; if self.topology_set { self.set_topology(list, self.topology); } @@ -1443,19 +1533,44 @@ impl State { self.heaps[0] = heap; } // Heaps first: a root signature with directly indexed heaps must be - // set after them. - if self.host_heaps != self.heaps { - let heaps: Vec> = self - .heaps - .iter() - .filter(|&&h| h != 0) - .filter_map(|&h| crate::descriptor::heap(h as This).host()) - .map(|h| Some(h.heap.clone())) - .collect(); - heaps.iter().flatten().for_each(|h| list.keep(h)); - // SAFETY: an open list and shader-visible heaps. - unsafe { l.SetDescriptorHeaps(&heaps) }; + // set after them, with both a view heap and a sampler heap bound. + if !self.host_heaps_set || self.host_heaps != self.heaps { + let mut view_heap: Option = None; + let mut sampler_heap: Option = None; + for &h in &self.heaps { + if h == 0 { + continue; + } + let title_heap = crate::descriptor::heap(h as This); + if let Some(host_heap) = title_heap.host() { + if title_heap.samplers() { + sampler_heap = Some(host_heap.heap.clone()); + } else { + view_heap = Some(host_heap.heap.clone()); + } + } + } + if view_heap.is_none() { + view_heap = crate::host::host().and_then(|h| h.fallback_view_heap().cloned()); + } + if sampler_heap.is_none() { + sampler_heap = crate::host::host().and_then(|h| h.fallback_sampler_heap().cloned()); + } + let mut heaps: Vec> = Vec::with_capacity(2); + if let Some(h) = view_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if let Some(h) = sampler_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if !heaps.is_empty() { + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + } self.host_heaps = self.heaps; + self.host_heaps_set = true; self.host_roots = [0; 2]; } // The depth target a draw only tests, for the views of it that the @@ -1493,7 +1608,7 @@ impl State { if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) { crate::picked::runs_in(list); } - let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + let made = self.tables(list, &t.tables, compute); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { once!("a draw whose descriptor table found no free slots is dropped"); @@ -3148,55 +3263,41 @@ impl State { pub(crate) fn tables( &mut self, list: &HostList, - used: &[UsedResource], - indexed: &[RootIndexedView], + plan: &TablePlan, compute: bool, ) -> Few<(u8, u32), 16> { - let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Few = Few::default(); - for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) { - if !fresh.contains(&u.slot) { - fresh.push(u.slot); + let mut fresh = [0u64; 4]; + let selected_slot = |mask: &[u64; 4], slot: u8| mask[usize::from(slot / 64)] & (1u64 << (slot % 64)) != 0; + for group in &plan.groups { + let slot = group.slot; + let needs_snapshot = group.has_cbv + || match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => self.heap_of(table).is_some_and(|heap| { + heap.host() + .is_some_and(|host| group.needs_snapshot(heap, host.count(), table)) + }), + _ => false, + }; + if needs_snapshot { + fresh[usize::from(slot / 64)] |= 1u64 << (slot % 64); } } - // Tables reaching past a host heap smaller than the title's (the - // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the - // title's slots there have no host slot of their own. - for u in used.iter().filter(tables) { - if fresh.contains(&u.slot) { - continue; - } - let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { - continue; - }; - let end = table + u64::from(u.table_offset_dwords) * 4; - let Some(heap) = self.heap_of(table) else { - continue; - }; - let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { - continue; - }; - if index >= host.count() { - fresh.push(u.slot); - } - } - fresh.sort_unstable(); - for u in used.iter().filter(tables) { - if !fresh.contains(&u.slot) { - self.table_entry(list, u, compute); + for &(g, e) in &plan.direct { + let group = &plan.groups[g]; + if !selected_slot(&fresh, group.slot) { + self.table_entry(list, &group.entries[e], compute); } } let mut made = Few::default(); - for &slot in fresh.iter() { + for group in &plan.groups { + let slot = group.slot; + if !selected_slot(&fresh, slot) { + continue; + } let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; - // (Their places among `used`.) - let mut places: Few = Few::default(); - for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) { - places.push(i as u16); - } - let entries = || places.iter().map(|&i| &used[usize::from(i)]); + let entries = &group.entries; let Some(heap) = self.heap_of(table) else { continue; }; @@ -3206,9 +3307,9 @@ impl State { let Some(host) = heap.host() else { continue; }; - let mut selected: Vec = indexed + let mut selected: Vec = group + .indexed .iter() - .filter(|index| index.table_slot == slot) .map(|index| { let constant = self.user_value( compute, @@ -3222,12 +3323,7 @@ impl State { .collect(); selected.sort_unstable(); selected.dedup(); - let n = entries() - .map(|u| u.table_offset_dwords / 8) - .chain(selected.last().copied()) - .max() - .unwrap_or(0) - + 1; + let n = (group.max_dword / 8).max(selected.last().copied().unwrap_or(0)) + 1; let last = table.checked_add(u64::from(n - 1) * 32); if n > crate::descriptor::host::DYNAMIC || last.and_then(|handle| heap.index(handle)).is_none() @@ -3246,12 +3342,12 @@ impl State { (table, n, h.0) }; // Who reads of it, and as what, as far as [`readable`] goes by it. - let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0); + let reader = (std::ptr::from_ref(plan) as usize, plan.direct.len(), STORES.get(), TESTED_DEPTH.get().0); if let Some(known) = self.fresh_tables.get_mut(&key) { let first = known.first; // This reader had it brought up to date, and nothing in the // list changed since: nothing to do again. - let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav); + let once = ready_once() && selected.is_empty() && !group.has_uav; if once && known.epoch == list.epoch() && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) @@ -3264,14 +3360,14 @@ impl State { } let depth_before = TESTED_DEPTH.get(); TESTED_DEPTH.set((depth_before.0, false)); - for u in entries().filter(|u| u.kind != ResourceType::Cbv) { + for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { readable(list, u.kind, &view); } } for k in selected { - if entries().any(|u| u.table_offset_dwords / 8 == k) { + if group.entry(k).is_some() { continue; } let handle = table + u64::from(k) * 32; @@ -3314,7 +3410,7 @@ impl State { // which may lie over slots shaders pick by index, only the ones // the shader names.) if let Some(title) = title_first { - for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) { + for k in (0..n).filter(|&k| n <= 64 || group.entry(k).is_some()) { host.slot_tabled(title + k); } } @@ -3334,8 +3430,8 @@ impl State { && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) && let Some(mut listed) = host.make_listed(recording, words, index) { - let kind = entries() - .find(|u| u.table_offset_dwords / 8 == k) + let kind = group + .entry(k) .map(|u| u.kind) .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); let was = (listed.ready, listed.tabled); @@ -3370,7 +3466,7 @@ impl State { } continue; } - let used = entries().find(|u| u.table_offset_dwords / 8 == k); + let used = group.entry(k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { @@ -4044,7 +4140,7 @@ fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_ /// A few things, up to `N` of them without memory of the heap: what a draw's /// tables are gone through with, some six lists a stage. -struct Few { +pub(crate) struct Few { few: [T; N], len: usize, /// All of them, if they are more. diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 10a9e93..3ca3d41 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -115,7 +115,32 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if fence.value.load(Ordering::Acquire) >= value { return S_OK; } - tracing::warn!(value, "blocking fence wait not implemented"); + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250); + loop { + let current = fence.value.load(Ordering::Acquire); + if current >= value { + return S_OK; + } + let now = std::time::Instant::now(); + if now >= deadline { + break; + } + let ms = (deadline - now).as_millis().min(10) as u32; + // SAFETY: wait on the atomic u64 until woken by WakeByAddressAll or timeout. + unsafe { + windows_sys::Win32::System::Threading::WaitOnAddress( + (&raw const fence.value).cast(), + (&raw const current).cast(), + size_of::(), + ms.max(1), + ); + } + crate::queue::release_held(false); + } + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait timed out"); return E_NOTIMPL; } // shortcut: a null event means "block until reached"; nothing can @@ -140,6 +165,12 @@ pub(crate) fn set(this: This, value: u64) { } !reached }); + drop(waiters); + #[cfg(windows)] + // SAFETY: wake any guest thread polling/blocking via WaitOnAddress on the fence's GPU VA. + unsafe { + windows_sys::Win32::System::Threading::WakeByAddressAll((&raw const fence.value).cast()); + } } pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { let _called = crate::timeline::span("a fence set"); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1ae56ee..abf6bc9 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -57,6 +57,10 @@ pub(crate) struct Host { /// The adapter the device is on, for its memory budget /// ([`Host::video_memory`]); `None` if the system does not name it. adapter: Option, + /// 1-descriptor shader-visible fallback heaps bound when a command list + /// omits a view or sampler heap while using directly-indexed root signatures. + fallback_view: OnceLock>, + fallback_sampler: OnceLock>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -368,7 +372,11 @@ pub(crate) fn keep_freed() -> bool { /// when free physical RAM is low. Never returns less than 2,000 ms. /// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { - ram_idle_for(avail_phys, keep_freed()) + let effective = match (avail_phys, crate::residency::headroom()) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + ram_idle_for(effective, keep_freed()) } fn ram_idle_for(avail_phys: Option, keep: bool) -> u64 { @@ -432,6 +440,10 @@ fn sweep() { } #[cfg(feature = "diagnostics")] crate::book::check(); + crate::residency::refresh(); + if crate::residency::pressured() { + trim_spare_chunks(); + } crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -484,7 +496,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not. fn bury_lag() -> u64 { static LAG: OnceLock = OnceLock::new(); - *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64)) + *LAG.get_or_init(|| { + let default = if crate::residency::limited_host_ram() { 16 } else { 64 }; + std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(default) + }) } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The @@ -967,6 +982,8 @@ fn create() -> windows::core::Result { next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), adapter, + fallback_view: OnceLock::new(), + fallback_sampler: OnceLock::new(), }) } } @@ -1915,7 +1932,12 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); for (chunk, size) in chunks { let back = if scratch_pool() { - spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST }) + let limit = if keep_freed() && !crate::residency::limited_host_ram() { + SPARE_KEPT + } else { + SPARE_MOST + }; + spare.give(chunk, size, limit) } else { Some(chunk) }; @@ -1936,6 +1958,25 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { drop(freed); } +/// Drops spare scratch chunks kept idle when host memory is pressured. +fn trim_spare_chunks() { + let freed: Vec<(Chunk, u64)> = { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.kept.is_empty() { + return; + } + spare.bytes = 0; + std::mem::take(&mut spare.kept) + }; + let count = freed.len() as u64; + let bytes: u64 = freed.iter().map(|(_, s)| *s).sum(); + ALIVE[1].fetch_sub(count, Ordering::Relaxed); + ALIVE[2].fetch_sub(bytes, Ordering::Relaxed); + ALIVE[3].fetch_sub(count, Ordering::Relaxed); + ALIVE[4].fetch_sub(bytes, Ordering::Relaxed); + drop(freed); +} + /// What the host keeps for copies in the card's own memory /// ([`crate::shadow::cards`]): three lists of ours and the compare. struct CardWork { @@ -4258,6 +4299,7 @@ impl Host { // pass: a wait between each copy and its pass had the // card do them one after the other. let mut sent = Vec::new(); + let mut transitioned = Vec::new(); if let Some(own) = &own { own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow))); } @@ -4276,11 +4318,15 @@ impl Host { #[cfg(feature = "diagnostics")] traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied()); if own.is_none() && before.is_some() && !ranges.is_empty() { - sent.push(transition( - &shadow.buffer, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )); + let raw = shadow.buffer.as_raw(); + if !transitioned.contains(&raw) { + transitioned.push(raw); + sent.push(transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )); + } } } if !sent.is_empty() { @@ -6042,6 +6088,71 @@ impl Host { handle } } + + /// 1-descriptor shader-visible CBV/SRV/UAV fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_view_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_view + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible heap + null SRV initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV::default(), + }, + }; + self.device.CreateShaderResourceView( + None, + Some(&desc), + heap.GetCPUDescriptorHandleForHeapStart(), + ); + Some(heap) + } + }) + .as_ref() + } + + /// 1-descriptor shader-visible Sampler fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_sampler_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_sampler + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible sampler heap initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + ..Default::default() + }; + self.device + .CreateSampler(&desc, heap.GetCPUDescriptorHandleForHeapStart()); + Some(heap) + } + }) + .as_ref() + } } impl HostList { @@ -8480,6 +8591,7 @@ struct Presenter { ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, + composer: Option, #[cfg(feature = "diagnostics")] panel: panel::Panel, } @@ -8803,12 +8915,40 @@ impl Host { /// Shows `texture`, which is in `state` (a host state) and stays in it, /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. + #[allow(dead_code)] pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { + self.present_planes(texture, state, None, frame) + } + + /// Shows `texture`, optionally alpha-compositing a second `overlay` plane + /// over it (Series S two-plane presentation), and returns them to their states. + pub(crate) fn present_planes( + &self, + texture: &ID3D12Resource, + state: u32, + overlay: Option<(&ID3D12Resource, u32)>, + frame: u64, + ) -> Option { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; - let Some(format) = swap_format(desc.Format) else { - tracing::warn!(format = desc.Format.0, "cannot present this format"); - return None; + let planes = overlay.and_then(|(over, over_state)| { + // SAFETY: a live overlay resource. + let over_desc = unsafe { over.GetDesc() }; + Some(( + over, + D3D12_RESOURCE_STATES(over_state as i32), + crate::compose::view(&desc)?, + crate::compose::view(&over_desc)?, + )) + }); + let format = if planes.is_some() { + DXGI_FORMAT_R8G8B8A8_UNORM + } else { + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + format }; let (width, height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); @@ -8832,6 +8972,9 @@ impl Host { }; match resized { Ok(()) => { + if p.format != format { + p.composer = None; + } (p.width, p.height, p.format) = (width, height, format); tracing::info!( width, @@ -8849,7 +8992,7 @@ impl Host { } } let state = D3D12_RESOURCE_STATES(state as i32); - // SAFETY: our swap chain, list and a live source texture. + // SAFETY: our swap chain, list and live source texture(s). unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::(index) else { @@ -8878,36 +9021,119 @@ impl Host { None => &p.copy, }; copy.reset(); + copy.keep(texture); let list = ©.list; - list.ResourceBarrier(&[ - transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition( - &back, - D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_COPY_DEST, - ), - ]); - list.CopyResource(&back, texture); + let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { + copy.keep(over); + if p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => tracing::warn!(error = %e, "two-plane composer not made; showing base plane only"), + } + } + if let Some(composer) = p.composer.as_mut() { + let mut pre = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + } + pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + list.ResourceBarrier(&pre); + let compose_slot = slot.map_or(0, |i| i + 1); + let _ = composer.record( + self, + compose_slot, + list, + [(texture, base_fmt), (over, over_fmt)], + &back, + (width, height), + ); + let mut post = Vec::with_capacity(3); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state)); + } + if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_DEST, + )); + list.ResourceBarrier(&post); + true + } else { + false + } + } else { + false + }; + if !composed { + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + ), + ]); + list.CopyResource(&back, texture); + } #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) - .then(|| crate::capture::read_back(&self.device, list, texture)) + .then(|| { + if composed { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let res = crate::capture::read_back(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + res + } else { + crate::capture::read_back(&self.device, list, texture) + } + }) .flatten(); #[cfg(feature = "diagnostics")] - let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + let probe = if slot.is_some() || composed { + None + } else { + crate::capture::probe(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] - let watched = crate::popwatch::take(&self.device, list, texture); + let watched = if composed { + None + } else { + crate::popwatch::take(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] p.panel.draw(self, copy, &back, (width, height), format); #[cfg(not(feature = "diagnostics"))] let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( + if composed { + list.ResourceBarrier(&[transition( &back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT, - ), - ]); + )]); + } else { + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + } copy.close(); let flown = match slot { Some(i) => { @@ -8989,6 +9215,7 @@ impl Host { ahead: Vec::new(), hwnd, meter: Meter::new(), + composer: None, #[cfg(feature = "diagnostics")] panel: panel::Panel::new(), }) diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 908dbec..2843d0c 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -19,6 +19,8 @@ mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; +#[cfg(windows)] +mod compose; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; @@ -58,6 +60,8 @@ pub mod query; pub mod queue; #[cfg(all(windows, feature = "diagnostics"))] pub mod replay; +#[cfg(windows)] +mod residency; pub mod resource; pub mod root; #[cfg(windows)] diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index e8a9f29..aedc396 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -130,6 +130,7 @@ pub(crate) struct Translated { /// A compute program's threads in a group. pub(crate) threads: Option<[u32; 3]>, pub(crate) used: Vec, + pub(crate) tables: crate::draw::TablePlan, /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. pub(crate) stores: bool, @@ -222,10 +223,12 @@ fn translate(container: &[u8]) -> Result { }) .map(|p| p.used) .unwrap_or_default(); + let tables = crate::draw::TablePlan::new(&used, &host.root_indexed_views); Ok(Translated { host, threads, used, + tables, stores, stores_by_address, picks: Default::default(), diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index ede3bb3..17b0a36 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -801,6 +801,8 @@ impl Written { } else { at.cast::().write_unaligned(value); } + #[cfg(windows)] + windows_sys::Win32::System::Threading::WakeByAddressAll(at.cast()); } } } @@ -927,29 +929,33 @@ extern "system" fn present( #[cfg(windows)] if behind::on() && !this.is_null() { const COPY_SOURCE: u32 = 0x800; - let texture = if planes > 0 + let take_plane = |index: usize| -> Option<(usize, std::sync::Arc, u32)> { + if planes as usize <= index || plane_parameters.is_null() { + return None; + } // SAFETY: the title passes `planes` plane descriptions. - && let Some(plane) = unsafe { plane_parameters.as_ref() } - && plane.count > 0 - && !plane.resources.is_null() - { + let plane = unsafe { plane_parameters.add(index).as_ref()? }; + if plane.count == 0 || plane.resources.is_null() { + return None; + } // SAFETY: the plane lists `count` resources. let resource = unsafe { *plane.resources }; - // The state the lists recorded so far leave it in (the next - // frame's, recorded before this is shown, go on from there). crate::resource::host_copy(resource).map(|copy| { let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); crate::resource::host_transition(resource, state); - // (Lists not translated yet leave it in no state yet: the - // one it is in when its turn in the line comes.) let state = if crate::list::thin::wanted() { u32::MAX } else { state }; (resource as usize, copy, state) }) - } else { - None }; + let texture = take_plane(0); + let overlay = take_plane(1).filter(|o| texture.as_ref().is_none_or(|t| t.0 != o.0)); let resource = texture.as_ref().map_or(0, |t| t.0); - behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource }); + behind::present( + this, + texture.map(|(_, copy, state)| (copy, state)), + overlay.map(|(_, copy, state)| (copy, state)), + Shown { frame, resource }, + ); called.end(); #[cfg(feature = "diagnostics")] frame_ends(); @@ -969,8 +975,36 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - show(texture, state, Shown { frame, resource: resource as usize }); + let overlay = if planes > 1 + // SAFETY: `planes > 1`, so index 1 is within `plane_parameters`. + && let Some(over_plane) = unsafe { plane_parameters.add(1).as_ref() } + && over_plane.count > 0 + && !over_plane.resources.is_null() + { + // SAFETY: `over_plane.count > 0`, so `*over_plane.resources` is valid. + let over_res = unsafe { *over_plane.resources }; + if over_res != resource { + crate::resource::host_resource(over_res).map(|over_tex| { + let over_state = crate::resource::host_transition(over_res, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + (over_res, over_tex, over_state) + }) + } else { + None + } + } else { + None + }; + show_planes( + texture, + state, + overlay.as_ref().map(|(_, tex, st)| (*tex, *st)), + Shown { frame, resource: resource as usize }, + ); crate::resource::host_transition(resource, state); + if let Some((over_res, _, over_state)) = overlay { + crate::resource::host_transition(over_res, over_state); + } let _ = host; } #[cfg(not(windows))] @@ -1001,13 +1035,18 @@ struct Shown { resource: usize, } -/// Shows `texture`, in host state `state`, in our window. +/// Shows `texture` (with optional `overlay` plane blended over it) in our window. #[cfg(windows)] -fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) { +fn show_planes( + texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + overlay: Option<(&windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)>, + what: Shown, +) { let Some(host) = crate::host::host() else { return; }; - let shown = host.present(texture, state, what.frame); + let shown = host.present_planes(texture, state, overlay, what.frame); #[cfg(feature = "diagnostics")] blinks(what.frame, what.resource as This, state, shown); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index b5624eb..813155c 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -391,8 +391,12 @@ enum Job { Joined(usize, Vec, Vec, Vec, Vec<(usize, u64)>), /// A signal of the queue's. Signal(usize, u64), - /// A frame is shown: the texture and the state its lists leave it in. - Present(Option<(std::sync::Arc, u32)>, super::Shown), + /// A frame is shown: the base texture (and optional overlay plane) and the states their lists leave them in. + Present( + Option<(std::sync::Arc, u32)>, + Option<(std::sync::Arc, u32)>, + super::Shown, + ), } // SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it @@ -569,12 +573,16 @@ impl Work for Job { crate::fence::set(fence as This, value); } } - Job::Present(texture, shown) => { + Job::Present(texture, overlay, shown) => { if let Some((texture, state)) = texture { // (Where its lists were not translated when the title // presented: the state they left it in.) let state = if state == u32::MAX { texture.state.load(Relaxed) } else { state }; - super::show(&texture.texture, state, shown); + let over = overlay.as_ref().map(|(ov, ov_state)| { + let st = if *ov_state == u32::MAX { ov.state.load(Relaxed) } else { *ov_state }; + (&ov.texture, st) + }); + super::show_planes(&texture.texture, state, over, shown); } QUEUED.fetch_sub(1, Relaxed); } @@ -811,10 +819,15 @@ pub(super) fn wait(this: This, fence: This, value: u64) { /// A present on queue `this` of `texture`, in the state the lists recorded so /// far leave it in. -pub(super) fn present(this: This, texture: Option<(std::sync::Arc, u32)>, shown: super::Shown) { +pub(super) fn present( + this: This, + texture: Option<(std::sync::Arc, u32)>, + overlay: Option<(std::sync::Arc, u32)>, + shown: super::Shown, +) { QUEUED.fetch_add(1, Relaxed); STATS[PRESENTS].fetch_add(1, Relaxed); - LANE.push(this as usize, [Job::Present(texture, shown)]); + LANE.push(this as usize, [Job::Present(texture, overlay, shown)]); let began = Instant::now(); let _waiting = crate::timeline::span("a present waits for the one before it to be sent"); LANE.wait_presents(frames_most()); diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs new file mode 100644 index 0000000..9968941 --- /dev/null +++ b/crates/victory-gpu/src/residency.rs @@ -0,0 +1,93 @@ +//! Host-memory admission for speculative texture work and reusable upload storage. +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + +const GIB: u64 = 1 << 30; +static PRESSURED: AtomicBool = AtomicBool::new(false); +static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); + +fn memory_status() -> Option { + // SAFETY: the API initializes the fields of a correctly sized structure. + let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + status.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status) +} + +pub(crate) fn limited_host_ram() -> bool { + static LIMITED: OnceLock = OnceLock::new(); + *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB)) +} + +fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { + if was { + physical < 6 * GIB || commit < 8 * GIB + } else { + physical <= 4 * GIB || commit <= 6 * GIB + } +} + +/// Called by the once-per-second submission sweep. A failed sample keeps the last good state. +pub(crate) fn refresh() { + let Some(status) = memory_status() else { return }; + let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile); + HEADROOM.store(physical.min(commit), Ordering::Relaxed); + let was = pressured(); + let pressure = next_pressure(was, physical, commit); + if pressure != was { + PRESSURED.store(pressure, Ordering::Relaxed); + if pressure { + tracing::warn!( + pid = std::process::id(), + frame = crate::frame::current(), + physical_free_mib = physical >> 20, + available_commit_mib = commit >> 20, + buffer_mirror_span_mib = crate::shadow::live_span_bytes() >> 20, + texture_staging_mib = crate::texture::live_staging_bytes() >> 20, + spare_scratch_mib = crate::host::ALIVE[4].load(Ordering::Relaxed) >> 20, + game_filled_gpu_texture_mib = crate::resource::KINDS[1].load(Ordering::Relaxed) >> 20, + "host memory pressure: limiting texture prefetch and idle upload storage" + ); + } else { + tracing::info!(physical_free_mib = physical >> 20, available_commit_mib = commit >> 20, "host memory pressure cleared"); + } + } +} + +pub(crate) fn headroom() -> Option { + let bytes = HEADROOM.load(Ordering::Relaxed); + (bytes != u64::MAX).then_some(bytes) +} + +pub(crate) fn pressured() -> bool { + PRESSURED.load(Ordering::Relaxed) +} + +/// A soft per-frame admission limit. A single texture can cross it. The +/// queue retains unserved slots so they can be retried on later frames. +pub(crate) fn prefetch_limit(bytes: u64, pressure: bool) -> u64 { + if pressure { bytes.min(16 << 20) } else { bytes } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn either_constraint_enters_pressure_and_both_must_recover() { + assert!(next_pressure(false, 12 * GIB, 6 * GIB)); + assert!(next_pressure(false, 4 * GIB, 16 * GIB)); + assert!(next_pressure(true, 5 * GIB, 9 * GIB)); + assert!(next_pressure(true, 7 * GIB, 7 * GIB)); + assert!(!next_pressure(true, 6 * GIB, 8 * GIB)); + assert!(!next_pressure(false, 5 * GIB, 7 * GIB)); + } + + #[test] + fn prefetch_respects_existing_budgets_and_resumes_after_recovery() { + assert_eq!(prefetch_limit(0, true), 0); + assert_eq!(prefetch_limit(8 << 20, true), 8 << 20); + assert_eq!(prefetch_limit(512 << 20, true), 16 << 20); + assert_eq!(prefetch_limit(192 << 20, false), 192 << 20); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 43d1b76..14dc160 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -314,6 +314,12 @@ static CARDED: Mutex>> = Mutex::new(Vec::new()); /// bytes; the waits for the card the fetches added and their microseconds. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +pub(crate) fn live_span_bytes() -> u64 { + CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) +} + /// [`CARD_STATS`], taken; then the copies in the card's memory, their /// bytes and their "before" twins' bytes. pub(crate) fn card_stats() -> [u64; 10] { diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 1fbc585..e0cdf0c 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -467,6 +467,10 @@ fn with_title(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> /// bytes. static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +pub(crate) fn live_staging_bytes() -> u64 { + STAGED[1].load(std::sync::atomic::Ordering::Relaxed) +} + impl Drop for Staging { fn drop(&mut self) { use std::sync::atomic::Ordering::Relaxed; diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index a44d599..14911cd 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -227,11 +227,20 @@ extern "system" fn create_queue( ) } -/// The title asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. Give PC worker threads +/// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't +/// starve the remaining cores. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { - tracing::info!(size, "dstorage: staging buffer size"); + static FLOOR_MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let floor = *FLOOR_MB.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_STAGING_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(256) + }) << 20; + tracing::info!(size, floor, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { - scheduler.lock().staging = u64::from(size); + scheduler.lock().staging = u64::from(size).max(floor); } S_OK } diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index d0b0bf9..d8e7056 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1197,7 +1197,6 @@ mod host { // pad's buttons, by the stand-in pad's table: with a real pad // connected the stand-in is not there, and a title that listens // to the pad (the title's start screen) saw nothing. - #[cfg(feature = "diagnostics")] if slot == 0 { for vk in scripted() { if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { @@ -1209,10 +1208,7 @@ mod host { } fn keys(&mut self) -> Vec { - #[cfg(feature = "diagnostics")] let mut down = scripted(); - #[cfg(not(feature = "diagnostics"))] - let mut down = Vec::new(); if focused() { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). @@ -1250,7 +1246,6 @@ mod host { /// time), with or without focus. A key is a /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, /// `Left`, `Right` (the stand-in pad's table maps them to buttons). - #[cfg(feature = "diagnostics")] fn scripted() -> Vec { static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| { let list = std::env::var("VICTORY_KEYS").unwrap_or_default();