From 36a0a6c1e3d2ef192f10c50c070003af5307cf03 Mon Sep 17 00:00:00 2001 From: Yaekai <21324379+Yaekai@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:29:14 +0100 Subject: [PATCH 01/13] GPU: composite multiple PresentX planes (fixes Series S black UI/menus) --- crates/victory-gpu/src/host.rs | 388 +++++++++++++++++++++++++++++--- crates/victory-gpu/src/queue.rs | 51 +++-- 2 files changed, 390 insertions(+), 49 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 17852d82ea0..36d2c82b5e0 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -9,14 +9,17 @@ use std::sync::{Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; -use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::{ + D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ID3DBlob, +}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows::Win32::Graphics::Dxgi::*; use windows::Win32::System::LibraryLoader::GetModuleHandleW; use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; use windows::Win32::UI::WindowsAndMessaging::*; -use windows::core::{Interface, PCWSTR, w}; +use windows::core::{Interface, PCSTR, PCWSTR, s, w}; /// Resource states without the console's own bits (compression hints from /// bit 25 up), which the host rejects. @@ -2747,6 +2750,161 @@ fn swap_format(format: DXGI_FORMAT) -> Option { } const BUFFERS: u32 = 2; +const MAX_PLANES: u32 = 8; + +/// Built-in fullscreen-triangle compositor for multi-plane `PresentX` calls +/// (e.g. Series S presenting a 1080p scene plane with a 4K UI overlay plane). +struct Compositor { + format: DXGI_FORMAT, + root: ID3D12RootSignature, + opaque: ID3D12PipelineState, + overlay: ID3D12PipelineState, + rtv_heap: ID3D12DescriptorHeap, + srv_heap: ID3D12DescriptorHeap, + srv_stride: u32, +} + +impl Compositor { + fn new(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result { + const SOURCE: &str = r#" + #define RS "DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL), \ + StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, \ + addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, \ + visibility=SHADER_VISIBILITY_PIXEL)" + Texture2D tex : register(t0); + SamplerState smp : register(s0); + [RootSignature(RS)] + void vs(uint id : SV_VertexID, out float4 pos : SV_Position, out float2 uv : TEXCOORD) { + uv = float2((id << 1) & 2, id & 2); + pos = float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); + } + [RootSignature(RS)] + float4 ps(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { + return tex.Sample(smp, uv); + } + "#; + let compile = |entry: PCSTR, target: PCSTR| -> windows::core::Result { + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: static source and entry/target strings; out pointers ours. + let res = unsafe { + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("present_composite"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = res { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("present compositor: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + code.ok_or_else(windows::core::Error::empty) + }; + let vs = compile(s!("vs"), s!("vs_5_1"))?; + let ps = compile(s!("ps"), s!("ps_5_1"))?; + // SAFETY: compiled shader blobs live through PSO creation. + unsafe { + let vs_bytes = + std::slice::from_raw_parts(vs.GetBufferPointer().cast::(), vs.GetBufferSize()); + let ps_bytes = + std::slice::from_raw_parts(ps.GetBufferPointer().cast::(), ps.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, vs_bytes)?; + let make_pso = |blend: bool| -> windows::core::Result { + let mut rt_blend = D3D12_RENDER_TARGET_BLEND_DESC { + RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, + ..Default::default() + }; + if blend { + rt_blend.BlendEnable = true.into(); + rt_blend.SrcBlend = D3D12_BLEND_ONE; + rt_blend.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + rt_blend.BlendOp = D3D12_BLEND_OP_ADD; + rt_blend.SrcBlendAlpha = D3D12_BLEND_ONE; + rt_blend.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + rt_blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + } + let mut blend_desc = D3D12_BLEND_DESC::default(); + blend_desc.RenderTarget[0] = rt_blend; + let mut rtv_formats = [DXGI_FORMAT_UNKNOWN; 8]; + rtv_formats[0] = format; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(root.clone())), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs_bytes.as_ptr().cast(), + BytecodeLength: vs_bytes.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps_bytes.as_ptr().cast(), + BytecodeLength: ps_bytes.len(), + }, + BlendState: blend_desc, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: false.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: rtv_formats, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pso = device.CreateGraphicsPipelineState(&desc); + let _ = std::mem::ManuallyDrop::into_inner(desc.pRootSignature); + pso + }; + let opaque = make_pso(false)?; + let overlay = make_pso(true)?; + let rtv_heap: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + })?; + let srv_heap: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: MAX_PLANES, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + let srv_stride = + device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + Ok(Compositor { + format, + root, + opaque, + overlay, + rtv_heap, + srv_heap, + srv_stride, + }) + } + } +} #[derive(Default)] struct Presentation { @@ -2784,6 +2942,7 @@ struct Presenter { copy: HostList, hwnd: HWND, meter: Meter, + compositor: Option, } /// The frame rate, shown in the window's caption every second and logged @@ -2958,17 +3117,26 @@ impl Meter { } 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. - pub(crate) fn present(&self, texture: &ID3D12Resource, state: 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"); + /// Shows one or more `planes` (each a live host texture and its current + /// host state, kept in that state), compositing planes 1.. on top of + /// plane 0 when multiple planes are presented, as frame `frame` (saved if + /// captures are on). `None` if nothing was shown; else, in diagnostics + /// builds, whether the frame was black. + pub(crate) fn present(&self, planes: &[(&ID3D12Resource, u32)], frame: u64) -> Option { + let &(primary, _) = planes.first()?; + // SAFETY: live resources. + let primary_desc = unsafe { primary.GetDesc() }; + let Some(format) = swap_format(primary_desc.Format) else { + tracing::warn!(format = primary_desc.Format.0, "cannot present this format"); return None; }; - let (width, height) = (desc.Width as u32, desc.Height); + let (mut width, mut height) = (primary_desc.Width as u32, primary_desc.Height); + for &(tex, _) in &planes[1..] { + // SAFETY: live resource. + let d = unsafe { tex.GetDesc() }; + width = width.max(d.Width as u32); + height = height.max(d.Height); + } let mut presentation = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); let Presentation { presenter, retry } = &mut *presentation; if presenter.is_none() { @@ -3004,8 +3172,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 textures. unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::(index) else { @@ -3013,31 +3180,182 @@ impl Host { }; p.copy.reset(); let list = &p.copy.list; - list.ResourceBarrier(&[ - transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition( + let (capture, probe) = if planes.len() == 1 { + let (texture, state) = planes[0]; + let state = D3D12_RESOURCE_STATES(state as i32); + let mut before = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + before.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); + } + before.push(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)) - .flatten(); - #[cfg(feature = "diagnostics")] - let probe = crate::capture::probe(&self.device, list, texture); - #[cfg(not(feature = "diagnostics"))] - let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( + )); + list.ResourceBarrier(&before); + list.CopyResource(&back, texture); + #[cfg(feature = "diagnostics")] + let capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + #[cfg(feature = "diagnostics")] + let probe = crate::capture::probe(&self.device, list, texture); + #[cfg(not(feature = "diagnostics"))] + let (capture, probe) = { + let _ = frame; + (None::<()>, None::<()>) + }; + let mut after = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + after.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state)); + } + after.push(transition( &back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT, - ), - ]); + )); + list.ResourceBarrier(&after); + (capture, probe) + } else { + if p.compositor.as_ref().is_none_or(|c| c.format != format) { + match Compositor::new(&self.device, format) { + Ok(c) => p.compositor = Some(c), + Err(e) => { + tracing::warn!(error = %e, "no present compositor"); + return None; + } + } + } + let comp = p.compositor.as_ref()?; + let rtv = comp.rtv_heap.GetCPUDescriptorHandleForHeapStart(); + self.device.CreateRenderTargetView( + &back, + Some(&D3D12_RENDER_TARGET_VIEW_DESC { + Format: format, + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_RENDER_TARGET_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_RTV { + MipSlice: 0, + PlaneSlice: 0, + }, + }, + }), + rtv, + ); + let srv_cpu_base = comp.srv_heap.GetCPUDescriptorHandleForHeapStart(); + let srv_gpu_base = comp.srv_heap.GetGPUDescriptorHandleForHeapStart(); + let count = planes.len().min(MAX_PLANES as usize); + let mut before = Vec::with_capacity(count + 1); + for (i, &(tex, state)) in planes[..count].iter().enumerate() { + let d = tex.GetDesc(); + let srv_fmt = swap_format(d.Format).unwrap_or(d.Format); + let handle = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: srv_cpu_base.ptr + i * comp.srv_stride as usize, + }; + self.device.CreateShaderResourceView( + tex, + Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: srv_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }), + handle, + ); + let state = D3D12_RESOURCE_STATES(state as i32); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + before.push(transition( + tex, + state, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )); + } + } + before.push(transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_RENDER_TARGET, + )); + list.ResourceBarrier(&before); + list.SetDescriptorHeaps(&[Some(comp.srv_heap.clone())]); + list.SetGraphicsRootSignature(&comp.root); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + for i in 0..count { + list.SetPipelineState(if i == 0 { &comp.opaque } else { &comp.overlay }); + list.SetGraphicsRootDescriptorTable( + 0, + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: srv_gpu_base.ptr + (i as u64) * u64::from(comp.srv_stride), + }, + ); + list.DrawInstanced(3, 1, 0, 0); + } + #[cfg(feature = "diagnostics")] + let (capture, probe) = { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, &back)) + .flatten(); + let probe = crate::capture::probe(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_PRESENT, + )]); + (capture, probe) + }; + #[cfg(not(feature = "diagnostics"))] + let (capture, probe) = { + let _ = frame; + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PRESENT, + )]); + (None::<()>, None::<()>) + }; + let mut after = Vec::with_capacity(count); + for &(tex, state) in &planes[..count] { + let state = D3D12_RESOURCE_STATES(state as i32); + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + after.push(transition( + tex, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + state, + )); + } + } + if !after.is_empty() { + list.ResourceBarrier(&after); + } + (capture, probe) + }; p.copy.close(); self.execute(&[&p.copy]); #[cfg(feature = "diagnostics")] @@ -3049,7 +3367,10 @@ impl Host { #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); #[cfg(not(feature = "diagnostics"))] - Some(false) + { + let _ = (capture, probe); + Some(false) + } } } @@ -3095,6 +3416,7 @@ impl Host { copy, hwnd, meter: Meter::new(), + compositor: None, }) } } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 3da261b7be9..de228f24de2 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -344,13 +344,17 @@ fn account_frame(frame: u64) { } } -/// The start of a present plane: frame token, then the plane's resources. +/// One plane of a `PresentX` call (`D3D12XBOX_PRESENT_PLANE_PARAMETERS`, +/// 0x48 bytes): frame token, resource array, view rects, color space, +/// extended descriptors, and plane flags. #[repr(C)] pub(crate) struct Plane { token: u64, count: u32, resources: *const This, + _rest: [u64; 6], } +const _: () = assert!(std::mem::size_of::() == 0x48); /// Submission tagged with the frame it belongs to `(count, lists, frame /// token, flags)`; frames are paced elsewhere, so it runs as a plain one. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { @@ -532,24 +536,39 @@ extern "system" fn present( } #[cfg(windows)] if planes > 0 - // SAFETY: the title passes `planes` plane descriptions. - && let Some(plane) = unsafe { plane_parameters.as_ref() } - && plane.count > 0 - && !plane.resources.is_null() - // SAFETY: the plane lists `count` resources. - && let resource = unsafe { *plane.resources } - && let Some(texture) = crate::resource::host_resource(resource) + && !plane_parameters.is_null() && let Some(host) = crate::host::host() { const COPY_SOURCE: u32 = 0x800; - let state = crate::resource::host_transition(resource, COPY_SOURCE) - .map_or(COPY_SOURCE, |(_, before)| before); - let shown = host.present(&texture, state, frame); - crate::resource::host_transition(resource, state); - #[cfg(feature = "diagnostics")] - blinks(frame, resource, state, shown); - #[cfg(not(feature = "diagnostics"))] - let _ = shown; + // SAFETY: the title passes `planes` plane descriptions. + let slice = unsafe { std::slice::from_raw_parts(plane_parameters, planes.min(8) as usize) }; + let mut resources = Vec::with_capacity(slice.len()); + for plane in slice { + if plane.count == 0 || plane.resources.is_null() { + continue; + } + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + if let Some(texture) = crate::resource::host_resource(resource) { + let state = crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + resources.push((resource, texture, state)); + } + } + if !resources.is_empty() { + let sources: Vec<(&_, u32)> = resources + .iter() + .map(|(_, tex, state)| (tex, *state)) + .collect(); + let shown = host.present(&sources, frame); + for &(resource, _, state) in &resources { + crate::resource::host_transition(resource, state); + } + #[cfg(feature = "diagnostics")] + blinks(frame, resources[0].0, resources[0].2, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = shown; + } } #[cfg(not(windows))] let _ = (planes, plane_parameters); From d3cf45c17e90880cd9123b5f588b3f2408cc197a Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 05:13:51 -0500 Subject: [PATCH 02/13] Serialize the PresentX compositor root signature explicitly --- crates/victory-gpu/src/host.rs | 51 +++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 36d2c82b5e0..5e30a018810 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2767,18 +2767,12 @@ struct Compositor { impl Compositor { fn new(device: &ID3D12Device, format: DXGI_FORMAT) -> windows::core::Result { const SOURCE: &str = r#" - #define RS "DescriptorTable(SRV(t0), visibility=SHADER_VISIBILITY_PIXEL), \ - StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, \ - addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP, \ - visibility=SHADER_VISIBILITY_PIXEL)" Texture2D tex : register(t0); SamplerState smp : register(s0); - [RootSignature(RS)] void vs(uint id : SV_VertexID, out float4 pos : SV_Position, out float2 uv : TEXCOORD) { uv = float2((id << 1) & 2, id & 2); pos = float4(uv * float2(2, -2) + float2(-1, 1), 0, 1); } - [RootSignature(RS)] float4 ps(float4 pos : SV_Position, float2 uv : TEXCOORD) : SV_Target { return tex.Sample(smp, uv); } @@ -2825,7 +2819,50 @@ impl Compositor { std::slice::from_raw_parts(vs.GetBufferPointer().cast::(), vs.GetBufferSize()); let ps_bytes = std::slice::from_raw_parts(ps.GetBufferPointer().cast::(), ps.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, vs_bytes)?; + // Wine's D3DCompile does not embed a root signature in the shader blobs. + let range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + OffsetInDescriptorsFromTableStart: D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + ..Default::default() + }; + let parameter = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: 1, + pDescriptorRanges: &range, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + }; + let sampler = D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MaxAnisotropy: 16, + ComparisonFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + BorderColor: D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + MaxLOD: f32::MAX, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + ..Default::default() + }; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: 1, + pParameters: ¶meter, + NumStaticSamplers: 1, + pStaticSamplers: &sampler, + ..Default::default() + }; + let mut signature = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut signature, None)?; + let signature = signature.ok_or_else(windows::core::Error::empty)?; + let signature = std::slice::from_raw_parts( + signature.GetBufferPointer().cast::(), + signature.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, signature)?; let make_pso = |blend: bool| -> windows::core::Result { let mut rt_blend = D3D12_RENDER_TARGET_BLEND_DESC { RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, From 1a547a2704c74e59a9f848fdff0642dcf33b70e2 Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 05:23:38 -0500 Subject: [PATCH 03/13] Exercise PresentX pipeline creation with the installed shader compiler --- crates/victory-gpu/src/host.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5e30a018810..0f4fe232325 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -633,6 +633,17 @@ pub(crate) mod tests { list.close(); } + #[test] + fn present_compositor_builds_both_pipeline_states() { + let Some(host) = host() else { + eprintln!("skipping compositor initialization: no D3D12 device"); + return; + }; + Compositor::new(&host.device, DXGI_FORMAT_R8G8B8A8_UNORM) + .expect("create compositor root signature and both pipeline states"); + eprintln!("PresentX compositor initialized"); + } + #[test] fn warp_adapter_accepts_only_software() { // This probes DXGI without creating a D3D12 device or running a title. From fcbc4e29ecafa28627310e3571b11d9853a1bad1 Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 05:50:00 -0500 Subject: [PATCH 04/13] Initialize the PresentX compositor before opening the copy list --- crates/victory-gpu/src/host.rs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 0f4fe232325..35484563800 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3220,6 +3220,21 @@ impl Host { } } } + // Leave the copy list closed if compositor initialization fails. + let compositor = if planes.len() > 1 { + if p.compositor.as_ref().is_none_or(|c| c.format != format) { + match Compositor::new(&self.device, format) { + Ok(c) => p.compositor = Some(c), + Err(e) => { + tracing::warn!(error = %e, "no present compositor"); + return None; + } + } + } + Some(p.compositor.as_ref()?) + } else { + None + }; // SAFETY: our swap chain, list and live source textures. unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); @@ -3265,16 +3280,7 @@ impl Host { list.ResourceBarrier(&after); (capture, probe) } else { - if p.compositor.as_ref().is_none_or(|c| c.format != format) { - match Compositor::new(&self.device, format) { - Ok(c) => p.compositor = Some(c), - Err(e) => { - tracing::warn!(error = %e, "no present compositor"); - return None; - } - } - } - let comp = p.compositor.as_ref()?; + let comp = compositor.expect("compositor was created for multiple planes"); let rtv = comp.rtv_heap.GetCPUDescriptorHandleForHeapStart(); self.device.CreateRenderTargetView( &back, From 09ae8a0145f019c522b39d65349d8fbb1809cb3e Mon Sep 17 00:00:00 2001 From: swarm Date: Tue, 24 Nov 2026 05:59:53 -0500 Subject: [PATCH 05/13] Test PresentX recovery after compositor initialization fails --- crates/victory-gpu/src/host.rs | 86 +++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 35484563800..c5b959c89e5 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3171,6 +3171,15 @@ impl Host { /// captures are on). `None` if nothing was shown; else, in diagnostics /// builds, whether the frame was black. pub(crate) fn present(&self, planes: &[(&ID3D12Resource, u32)], frame: u64) -> Option { + self.present_with_compositor(planes, frame, Compositor::new) + } + + fn present_with_compositor( + &self, + planes: &[(&ID3D12Resource, u32)], + frame: u64, + create_compositor: impl FnOnce(&ID3D12Device, DXGI_FORMAT) -> windows::core::Result, + ) -> Option { let &(primary, _) = planes.first()?; // SAFETY: live resources. let primary_desc = unsafe { primary.GetDesc() }; @@ -3223,7 +3232,7 @@ impl Host { // Leave the copy list closed if compositor initialization fails. let compositor = if planes.len() > 1 { if p.compositor.as_ref().is_none_or(|c| c.format != format) { - match Compositor::new(&self.device, format) { + match create_compositor(&self.device, format) { Ok(c) => p.compositor = Some(c), Err(e) => { tracing::warn!(error = %e, "no present compositor"); @@ -3956,3 +3965,78 @@ mod withholding { } } } + +#[cfg(all(test, feature = "diagnostics"))] +mod present_plane_tests { + use super::*; + + #[test] + fn compositor_failure_preserves_single_plane_presentation() { + let Some(host) = host() else { + eprintln!("skipping PresentX recovery: no D3D12 device"); + return; + }; + let list = host.new_list().unwrap(); + let make_plane = |width, height, color: &[f32; 4]| { + let mut texture = None; + // SAFETY: live device, valid render target description, and an open list. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: width, + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut texture, + ) + .unwrap(); + let texture = texture.unwrap(); + list.list + .ClearRenderTargetView(host.rtv(&texture, None), color, None); + texture + } + }; + let scene = make_plane(32, 32, &[1.0, 0.0, 0.0, 1.0]); + let overlay = make_plane(32, 32, &[0.0, 0.0, 128.0 / 255.0, 128.0 / 255.0]); + list.close(); + host.execute(&[&list]); + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + assert!( + host.present(&[(&scene, state)], 1).is_some(), + "single-plane control" + ); + let mut attempted = false; + assert!( + host.present_with_compositor(&[(&scene, state), (&overlay, state)], 2, |_, _| { + attempted = true; + Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )) + }) + .is_none(), + "injected compositor failure" + ); + assert!(attempted); + assert!( + host.present(&[(&scene, state)], 3).is_some(), + "single-plane presentation after compositor initialization failed" + ); + } +} From aa56caad3f33efd1b5c5f30d507261473aac3b3c Mon Sep 17 00:00:00 2001 From: Blitz Studios <271002048+jamesn-xt@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:49 +0000 Subject: [PATCH 06/13] GPU tests: verify composited pixels after present initialization recovers --- crates/victory-gpu/src/host.rs | 54 ++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index c5b959c89e5..1a64bcca7d3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -4038,5 +4038,59 @@ mod present_plane_tests { host.present(&[(&scene, state)], 3).is_some(), "single-plane presentation after compositor initialization failed" ); + assert!( + host.present(&[(&scene, state), (&overlay, state)], 4) + .is_some(), + "compositor initialization can be retried after failure" + ); + let back = { + let presenter = host.presenter.lock().unwrap_or_else(|e| e.into_inner()); + let presenter = presenter.as_ref().unwrap(); + // SAFETY: the swap chain owns BUFFERS live back buffers. Present advanced + // its index, so the preceding buffer holds the frame just composed. + unsafe { + let index = + (presenter.swap_chain.GetCurrentBackBufferIndex() + BUFFERS - 1) % BUFFERS; + presenter + .swap_chain + .GetBuffer::(index) + .unwrap() + } + }; + let copy = host.new_list().unwrap(); + // SAFETY: the preceding presentation completed, the back buffer is live, + // and this list is open. Restore PRESENT after reading its contents. + let (buffer, footprint) = unsafe { + copy.list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let readback = crate::capture::read_back(&host.device, ©.list, &back).unwrap(); + copy.list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_PRESENT, + )]); + readback + }; + copy.close(); + host.execute(&[©]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: execute waited for the copy; the footprint contains at least + // one RGBA pixel. Copy that pixel before unmapping the readback buffer. + let pixel = unsafe { + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + let pixel = mapped + .cast::() + .add(footprint.Offset as usize) + .cast::<[u8; 4]>() + .read(); + buffer.Unmap(0, None); + pixel + }; + // Premultiplied half-blue over opaque red: neither an ignored overlay + // (red) nor a replaced scene (blue) may pass this check. + assert_eq!(pixel, [127, 0, 128, 255]); } } From 5156eaaac96db4afb7488b3bfc177970c2b10eaf Mon Sep 17 00:00:00 2001 From: Blitz Studios <271002048+jamesn-xt@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:11:05 +0000 Subject: [PATCH 07/13] GPU tests: inspect composed pixels before flip-discard Present --- crates/victory-gpu/src/host.rs | 110 ++++++++++++++++----------------- 1 file changed, 52 insertions(+), 58 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1a64bcca7d3..6249ab5ffed 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3171,7 +3171,13 @@ impl Host { /// captures are on). `None` if nothing was shown; else, in diagnostics /// builds, whether the frame was black. pub(crate) fn present(&self, planes: &[(&ID3D12Resource, u32)], frame: u64) -> Option { - self.present_with_compositor(planes, frame, Compositor::new) + self.present_with_compositor( + planes, + frame, + Compositor::new, + #[cfg(all(test, feature = "diagnostics"))] + |_, _| {}, + ) } fn present_with_compositor( @@ -3179,6 +3185,10 @@ impl Host { planes: &[(&ID3D12Resource, u32)], frame: u64, create_compositor: impl FnOnce(&ID3D12Device, DXGI_FORMAT) -> windows::core::Result, + #[cfg(all(test, feature = "diagnostics"))] inspect: impl FnOnce( + &ID3D12Resource, + &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + ), ) -> Option { let &(primary, _) = planes.first()?; // SAFETY: live resources. @@ -3267,7 +3277,7 @@ impl Host { list.ResourceBarrier(&before); list.CopyResource(&back, texture); #[cfg(feature = "diagnostics")] - let capture = crate::capture::wanted(frame) + let capture = (cfg!(test) || crate::capture::wanted(frame)) .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] @@ -3382,7 +3392,7 @@ impl Host { D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); - let capture = crate::capture::wanted(frame) + let capture = (cfg!(test) || crate::capture::wanted(frame)) .then(|| crate::capture::read_back(&self.device, list, &back)) .flatten(); let probe = crate::capture::probe(&self.device, list, &back); @@ -3423,6 +3433,10 @@ impl Host { self.execute(&[&p.copy]); #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { + // Tests inspect the completed copy before flip-discard Present + // can invalidate the back buffer, with the presenter still locked. + #[cfg(test)] + inspect(&buffer, &footprint); crate::capture::save_read_back(frame, &buffer, &footprint); } let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); @@ -4024,12 +4038,17 @@ mod present_plane_tests { ); let mut attempted = false; assert!( - host.present_with_compositor(&[(&scene, state), (&overlay, state)], 2, |_, _| { - attempted = true; - Err(windows::core::Error::from_hresult( - windows::Win32::Foundation::E_FAIL, - )) - }) + host.present_with_compositor( + &[(&scene, state), (&overlay, state)], + 2, + |_, _| { + attempted = true; + Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )) + }, + |_, _| {}, + ) .is_none(), "injected compositor failure" ); @@ -4038,59 +4057,34 @@ mod present_plane_tests { host.present(&[(&scene, state)], 3).is_some(), "single-plane presentation after compositor initialization failed" ); + let mut pixel = None; assert!( - host.present(&[(&scene, state), (&overlay, state)], 4) - .is_some(), + host.present_with_compositor( + &[(&scene, state), (&overlay, state)], + 4, + Compositor::new, + |buffer, footprint| { + let mut mapped = std::ptr::null_mut(); + // SAFETY: execute waited for the pre-Present copy. Read one + // RGBA pixel from its footprint, before unmapping the buffer. + unsafe { + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + pixel = Some( + mapped + .cast::() + .add(footprint.Offset as usize) + .cast::<[u8; 4]>() + .read(), + ); + buffer.Unmap(0, None); + } + }, + ) + .is_some(), "compositor initialization can be retried after failure" ); - let back = { - let presenter = host.presenter.lock().unwrap_or_else(|e| e.into_inner()); - let presenter = presenter.as_ref().unwrap(); - // SAFETY: the swap chain owns BUFFERS live back buffers. Present advanced - // its index, so the preceding buffer holds the frame just composed. - unsafe { - let index = - (presenter.swap_chain.GetCurrentBackBufferIndex() + BUFFERS - 1) % BUFFERS; - presenter - .swap_chain - .GetBuffer::(index) - .unwrap() - } - }; - let copy = host.new_list().unwrap(); - // SAFETY: the preceding presentation completed, the back buffer is live, - // and this list is open. Restore PRESENT after reading its contents. - let (buffer, footprint) = unsafe { - copy.list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_COPY_SOURCE, - )]); - let readback = crate::capture::read_back(&host.device, ©.list, &back).unwrap(); - copy.list.ResourceBarrier(&[transition( - &back, - D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_PRESENT, - )]); - readback - }; - copy.close(); - host.execute(&[©]); - let mut mapped = std::ptr::null_mut(); - // SAFETY: execute waited for the copy; the footprint contains at least - // one RGBA pixel. Copy that pixel before unmapping the readback buffer. - let pixel = unsafe { - buffer.Map(0, None, Some(&mut mapped)).unwrap(); - let pixel = mapped - .cast::() - .add(footprint.Offset as usize) - .cast::<[u8; 4]>() - .read(); - buffer.Unmap(0, None); - pixel - }; // Premultiplied half-blue over opaque red: neither an ignored overlay // (red) nor a replaced scene (blue) may pass this check. - assert_eq!(pixel, [127, 0, 128, 255]); + assert_eq!(pixel, Some([127, 0, 128, 255])); } } From a1819aca74fc98d6ba8a9cb3e6e6c7861f9c47f0 Mon Sep 17 00:00:00 2001 From: Yaekai <21324379+Yaekai@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:27:27 +0100 Subject: [PATCH 08/13] Update queue.rs --- crates/victory-gpu/src/queue.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index de228f24de2..13d67e37275 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -344,9 +344,9 @@ fn account_frame(frame: u64) { } } -/// One plane of a `PresentX` call (`D3D12XBOX_PRESENT_PLANE_PARAMETERS`, -/// 0x48 bytes): frame token, resource array, view rects, color space, -/// extended descriptors, and plane flags. +/// One plane of a `PresentX` call (0x48-byte stride): frame token, +/// resource count, and pointer to the plane's resources. + #[repr(C)] pub(crate) struct Plane { token: u64, From 5d4e72679f37dc9fe5074e8026eadc60b0583b98 Mon Sep 17 00:00:00 2001 From: Yaekai <21324379+Yaekai@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:32:50 +0100 Subject: [PATCH 09/13] Update queue.rs --- crates/victory-gpu/src/queue.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 13d67e37275..31c9b8008f1 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -346,7 +346,6 @@ fn account_frame(frame: u64) { /// One plane of a `PresentX` call (0x48-byte stride): frame token, /// resource count, and pointer to the plane's resources. - #[repr(C)] pub(crate) struct Plane { token: u64, From afcbaf428a8db3a9e6d14e1e761ced647bdeab3c Mon Sep 17 00:00:00 2001 From: Calvix2k Date: Wed, 25 Nov 2026 11:21:55 +0100 Subject: [PATCH 10/13] GPU: a failed compositor still presents the first plane When the multi-plane compositor cannot be created, the frame was dropped (`return None`). Show plane 0 through the single-plane copy path instead, and keep retrying the compositor on the next present. The test now asserts that the failing frame is presented, not skipped. --- crates/victory-gpu/src/host.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6249ab5ffed..7d1fca28953 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3245,12 +3245,17 @@ impl Host { match create_compositor(&self.device, format) { Ok(c) => p.compositor = Some(c), Err(e) => { - tracing::warn!(error = %e, "no present compositor"); - return None; + // The frame is still shown: its first plane alone, as + // a single-plane present would. + tracing::warn!( + error = %e, + "no present compositor; presenting the first plane" + ); + p.compositor = None; } } } - Some(p.compositor.as_ref()?) + p.compositor.as_ref() } else { None }; @@ -3262,7 +3267,8 @@ impl Host { }; p.copy.reset(); let list = &p.copy.list; - let (capture, probe) = if planes.len() == 1 { + // One plane, or no compositor to combine several: copy the first. + let (capture, probe) = if planes.len() == 1 || compositor.is_none() { let (texture, state) = planes[0]; let state = D3D12_RESOURCE_STATES(state as i32); let mut before = Vec::with_capacity(2); @@ -3299,7 +3305,7 @@ impl Host { list.ResourceBarrier(&after); (capture, probe) } else { - let comp = compositor.expect("compositor was created for multiple planes"); + let comp = compositor?; let rtv = comp.rtv_heap.GetCPUDescriptorHandleForHeapStart(); self.device.CreateRenderTargetView( &back, @@ -4037,6 +4043,8 @@ mod present_plane_tests { "single-plane control" ); let mut attempted = false; + // A failing compositor still presents the frame: its first plane, as + // a single-plane present does, instead of dropping it. assert!( host.present_with_compositor( &[(&scene, state), (&overlay, state)], @@ -4049,8 +4057,8 @@ mod present_plane_tests { }, |_, _| {}, ) - .is_none(), - "injected compositor failure" + .is_some(), + "the frame is presented after a compositor failure" ); assert!(attempted); assert!( From 0258df3e9db70f3ba8d6ab018d113919141e85b0 Mon Sep 17 00:00:00 2001 From: andrewpozdnakov7-jpg Date: Wed, 25 Nov 2026 04:47:23 +0200 Subject: [PATCH 11/13] GPU: present the primary plane when compositor setup fails (cherry picked from commit 5a1b9ad5ae79f1e7b0bb6e29ea89af928d43e6bf) --- crates/victory-gpu/src/host.rs | 165 +++++++++++++++++++-------------- 1 file changed, 96 insertions(+), 69 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 7d1fca28953..e2f0b9193b9 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2966,6 +2966,10 @@ struct SwapChainRetry { } impl SwapChainRetry { + fn ready(&self, now: Instant) -> bool { + self.next_attempt.is_none_or(|next| now >= next) + } + /// A desktop can become presentable again. Keep retrying while limiting /// the DXGI calls and warnings during the outage. fn attempt( @@ -2973,7 +2977,7 @@ impl SwapChainRetry { now: Instant, operation: impl FnOnce() -> Result, ) -> Option> { - if self.next_attempt.is_some_and(|next| now < next) { + if !self.ready(now) { return None; } let result = operation(); @@ -3197,6 +3201,30 @@ impl Host { tracing::warn!(format = primary_desc.Format.0, "cannot present this format"); return None; }; + let mut presentation = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); + let Presentation { presenter, retry } = &mut *presentation; + if presenter.is_none() && !retry.ready(Instant::now()) { + return None; + } + let cached_format = presenter + .as_ref() + .and_then(|p| p.compositor.as_ref()) + .map(|c| c.format); + let mut new_compositor = None; + let planes = if planes.len() > 1 && cached_format != Some(format) { + match create_compositor(&self.device, format) { + Ok(c) => { + new_compositor = Some(c); + planes + } + Err(e) => { + tracing::warn!(error = %e, "presenting the primary plane after compositor initialization failed"); + &planes[..1] + } + } + } else { + planes + }; let (mut width, mut height) = (primary_desc.Width as u32, primary_desc.Height); for &(tex, _) in &planes[1..] { // SAFETY: live resource. @@ -3204,8 +3232,6 @@ impl Host { width = width.max(d.Width as u32); height = height.max(d.Height); } - let mut presentation = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); - let Presentation { presenter, retry } = &mut *presentation; if presenter.is_none() { *presenter = match retry .attempt(Instant::now(), || self.presenter(width, height, format))? @@ -3218,6 +3244,9 @@ impl Host { }; } let p = presenter.as_mut()?; + if let Some(c) = new_compositor { + p.compositor = Some(c); + } if (p.width, p.height, p.format) != (width, height, format) { let resized = retry.attempt(Instant::now(), || { // SAFETY: no back buffer is held; every submission was waited for. @@ -3239,26 +3268,6 @@ impl Host { } } } - // Leave the copy list closed if compositor initialization fails. - let compositor = if planes.len() > 1 { - if p.compositor.as_ref().is_none_or(|c| c.format != format) { - match create_compositor(&self.device, format) { - Ok(c) => p.compositor = Some(c), - Err(e) => { - // The frame is still shown: its first plane alone, as - // a single-plane present would. - tracing::warn!( - error = %e, - "no present compositor; presenting the first plane" - ); - p.compositor = None; - } - } - } - p.compositor.as_ref() - } else { - None - }; // SAFETY: our swap chain, list and live source textures. unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); @@ -3267,8 +3276,7 @@ impl Host { }; p.copy.reset(); let list = &p.copy.list; - // One plane, or no compositor to combine several: copy the first. - let (capture, probe) = if planes.len() == 1 || compositor.is_none() { + let (capture, probe) = if planes.len() == 1 { let (texture, state) = planes[0]; let state = D3D12_RESOURCE_STATES(state as i32); let mut before = Vec::with_capacity(2); @@ -3282,8 +3290,24 @@ impl Host { )); list.ResourceBarrier(&before); list.CopyResource(&back, texture); - #[cfg(feature = "diagnostics")] - let capture = (cfg!(test) || crate::capture::wanted(frame)) + #[cfg(all(test, feature = "diagnostics"))] + let capture = { + // Inspect what reached the swap chain, before Present. + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let readback = crate::capture::read_back(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + readback + }; + #[cfg(all(not(test), feature = "diagnostics"))] + let capture = crate::capture::wanted(frame) .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] @@ -3305,7 +3329,7 @@ impl Host { list.ResourceBarrier(&after); (capture, probe) } else { - let comp = compositor?; + let comp = p.compositor.as_ref().expect("compositor was prepared for multiple planes"); let rtv = comp.rtv_heap.GetCPUDescriptorHandleForHeapStart(); self.device.CreateRenderTargetView( &back, @@ -3991,7 +4015,7 @@ mod present_plane_tests { use super::*; #[test] - fn compositor_failure_preserves_single_plane_presentation() { + fn compositor_failure_presents_primary_in_the_same_frame() { let Some(host) = host() else { eprintln!("skipping PresentX recovery: no D3D12 device"); return; @@ -4034,7 +4058,7 @@ mod present_plane_tests { } }; let scene = make_plane(32, 32, &[1.0, 0.0, 0.0, 1.0]); - let overlay = make_plane(32, 32, &[0.0, 0.0, 128.0 / 255.0, 128.0 / 255.0]); + let overlay = make_plane(64, 64, &[0.0, 0.0, 128.0 / 255.0, 128.0 / 255.0]); list.close(); host.execute(&[&list]); let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; @@ -4042,57 +4066,60 @@ mod present_plane_tests { host.present(&[(&scene, state)], 1).is_some(), "single-plane control" ); + let first_pixel = + |buffer: &ID3D12Resource, footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + let mut mapped = std::ptr::null_mut(); + // SAFETY: the present copy has completed. The footprint names + // a live RGBA pixel inside the readback buffer. + let rgba = unsafe { + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + let rgba = mapped + .cast::() + .add(footprint.Offset as usize) + .cast::<[u8; 4]>() + .read(); + buffer.Unmap(0, None); + rgba + }; + (footprint.Footprint.Width, footprint.Footprint.Height, rgba) + }; + let mut attempted = false; - // A failing compositor still presents the frame: its first plane, as - // a single-plane present does, instead of dropping it. - assert!( - host.present_with_compositor( - &[(&scene, state), (&overlay, state)], - 2, - |_, _| { - attempted = true; - Err(windows::core::Error::from_hresult( - windows::Win32::Foundation::E_FAIL, - )) - }, - |_, _| {}, - ) - .is_some(), - "the frame is presented after a compositor failure" + let mut fallback = None; + let shown = host.present_with_compositor( + &[(&scene, state), (&overlay, state)], + 2, + |_, _| { + attempted = true; + Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )) + }, + |buffer, footprint| fallback = Some(first_pixel(buffer, footprint)), ); assert!(attempted); assert!( - host.present(&[(&scene, state)], 3).is_some(), - "single-plane presentation after compositor initialization failed" + shown.is_some(), + "the primary plane must still be shown in this frame" ); - let mut pixel = None; + assert_eq!(fallback, Some((32, 32, [255, 0, 0, 255]))); + let presentation = host.presenter.lock().unwrap_or_else(|e| e.into_inner()); + let swap_chain = presentation.presenter.as_ref().unwrap(); + assert_eq!((swap_chain.width, swap_chain.height), (32, 32)); + drop(presentation); + + let mut composite = None; assert!( host.present_with_compositor( &[(&scene, state), (&overlay, state)], - 4, + 3, Compositor::new, - |buffer, footprint| { - let mut mapped = std::ptr::null_mut(); - // SAFETY: execute waited for the pre-Present copy. Read one - // RGBA pixel from its footprint, before unmapping the buffer. - unsafe { - buffer.Map(0, None, Some(&mut mapped)).unwrap(); - pixel = Some( - mapped - .cast::() - .add(footprint.Offset as usize) - .cast::<[u8; 4]>() - .read(), - ); - buffer.Unmap(0, None); - } - }, + |buffer, footprint| composite = Some(first_pixel(buffer, footprint)), ) .is_some(), "compositor initialization can be retried after failure" ); - // Premultiplied half-blue over opaque red: neither an ignored overlay - // (red) nor a replaced scene (blue) may pass this check. - assert_eq!(pixel, Some([127, 0, 128, 255])); + // Premultiplied half-blue over opaque red. + assert_eq!(composite, Some((64, 64, [127, 0, 128, 255]))); } } From 181bec0524a5efa6e855d6ad06fc473fb6a98cc1 Mon Sep 17 00:00:00 2001 From: andrewpozdnakov7-jpg Date: Wed, 25 Nov 2026 04:55:12 +0200 Subject: [PATCH 12/13] GPU: restore each presented host texture state once (cherry picked from commit 660568e673b20f333bc9c8c2d37267190b3b1093) --- crates/victory-gpu/src/host.rs | 23 ++++--- crates/victory-gpu/src/queue.rs | 109 ++++++++++++++++++++++++++++---- 2 files changed, 108 insertions(+), 24 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index e2f0b9193b9..8a8eec746ed 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -3349,6 +3349,7 @@ impl Host { let srv_gpu_base = comp.srv_heap.GetGPUDescriptorHandleForHeapStart(); let count = planes.len().min(MAX_PLANES as usize); let mut before = Vec::with_capacity(count + 1); + let mut after = Vec::with_capacity(count); for (i, &(tex, state)) in planes[..count].iter().enumerate() { let d = tex.GetDesc(); let srv_fmt = swap_format(d.Format).unwrap_or(d.Format); @@ -3373,12 +3374,21 @@ impl Host { handle, ); let state = D3D12_RESOURCE_STATES(state as i32); - if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { + if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + && planes[..i] + .iter() + .all(|(earlier, _)| earlier.as_raw() != tex.as_raw()) + { before.push(transition( tex, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, )); + after.push(transition( + tex, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + state, + )); } } before.push(transition( @@ -3443,17 +3453,6 @@ impl Host { )]); (None::<()>, None::<()>) }; - let mut after = Vec::with_capacity(count); - for &(tex, state) in &planes[..count] { - let state = D3D12_RESOURCE_STATES(state as i32); - if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - after.push(transition( - tex, - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, - state, - )); - } - } if !after.is_empty() { list.ResourceBarrier(&after); } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 31c9b8008f1..db27086944c 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -479,10 +479,7 @@ pub(crate) fn presented() -> u64 { FRAMES.load(Ordering::Relaxed) } -/// Shows the first plane's first resource in our window. -/// -/// shortcut: one plane, no scaling or placement, the source expected in -/// the common state. +/// Shows the first resource of each presented plane in our window. extern "system" fn present( _: This, planes: u32, @@ -538,10 +535,14 @@ extern "system" fn present( && !plane_parameters.is_null() && let Some(host) = crate::host::host() { + use windows::Win32::Graphics::Direct3D12::ID3D12Resource; + use windows::core::Interface; + const COPY_SOURCE: u32 = 0x800; - // SAFETY: the title passes `planes` plane descriptions. + // SAFETY: the title passes the plane descriptions. let slice = unsafe { std::slice::from_raw_parts(plane_parameters, planes.min(8) as usize) }; - let mut resources = Vec::with_capacity(slice.len()); + let mut resources: Vec<(This, &ID3D12Resource, u32, bool)> = + Vec::with_capacity(slice.len()); for plane in slice { if plane.count == 0 || plane.resources.is_null() { continue; @@ -549,19 +550,28 @@ extern "system" fn present( // SAFETY: the plane lists `count` resources. let resource = unsafe { *plane.resources }; if let Some(texture) = crate::resource::host_resource(resource) { - let state = crate::resource::host_transition(resource, COPY_SOURCE) - .map_or(COPY_SOURCE, |(_, before)| before); - resources.push((resource, texture, state)); + // Distinct title resources may refer to one host texture. + // Keep its original state for every plane and restore it once. + let prior = resources.iter().find_map(|(_, earlier, state, _)| { + (earlier.as_raw() == texture.as_raw()).then_some(*state) + }); + let state = prior.unwrap_or_else(|| { + crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before) + }); + resources.push((resource, texture, state, prior.is_none())); } } if !resources.is_empty() { let sources: Vec<(&_, u32)> = resources .iter() - .map(|(_, tex, state)| (tex, *state)) + .map(|(_, tex, state, _)| (tex, *state)) .collect(); let shown = host.present(&sources, frame); - for &(resource, _, state) in &resources { - crate::resource::host_transition(resource, state); + for &(resource, _, state, first) in &resources { + if first { + crate::resource::host_transition(resource, state); + } } #[cfg(feature = "diagnostics")] blinks(frame, resources[0].0, resources[0].2, shown); @@ -747,6 +757,81 @@ mod tests { use super::*; use crate::object::slot; + /// Distinct title resources can name the same host texture. Presenting + /// both planes must preserve that texture's original rendering state. + #[cfg(windows)] + #[test] + fn aliased_present_planes_preserve_the_host_texture_state() { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET; + + let Some(host) = crate::host::host() else { + return; + }; + const TARGET: u32 = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let address = crate::watch::tests::pool(1); + let null = std::ptr::null(); + let iid = crate::object::guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ); + #[repr(align(8))] + struct TextureWords([u32; 14]); + let desc = TextureWords([3, 0, 0, 0, 32, 0, 32, 1 | 1 << 16, 87, 1, 0, 1, 1, 0]); + let resources = std::array::from_fn::<_, 2, _>(|_| { + let mut resource = null; + assert_eq!( + crate::resource::create_at_address( + null, + address as u64, + desc.0.as_ptr().cast(), + 0, + null.cast(), + &iid, + &mut resource, + ), + S_OK + ); + resource + }); + assert_ne!(resources[0], resources[1]); + let primary = crate::resource::host_copy(resources[0]).unwrap(); + let alias = crate::resource::host_copy(resources[1]).unwrap(); + assert!(std::sync::Arc::ptr_eq(&primary, &alias)); + let list = host.new_list().unwrap(); + crate::list::ensure_state(&list, resources[0], TARGET); + // SAFETY: the texture is a live render target, on an open list. + unsafe { + list.list.ClearRenderTargetView( + host.rtv(&primary.texture, None), + &[0.25, 0.5, 0.75, 1.0], + None, + ); + } + list.close(); + host.execute(&[&list]); + assert_eq!(primary.state.load(Ordering::Relaxed), TARGET); + + let planes = resources.each_ref().map(|resource| Plane { + token: 0, + count: 1, + resources: std::ptr::from_ref(resource), + _rest: [0; 6], + }); + assert_eq!(present(null, 2, planes.as_ptr(), null.cast()), S_OK); + let restored = primary.state.load(Ordering::Relaxed); + let release = |resource| slot:: u32>(resource, 0x10)(resource); + for resource in resources { + assert_eq!(release(resource), 0); + } + drop((list, primary, alias)); + crate::watch::tests::free(address); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + assert_eq!(restored, TARGET, "the two planes share one rendering state"); + } + /// Where a queue's signal is: newer layouts have it two slots later. /// Another test may switch layouts while this one runs, so the queue's /// own table decides. From fdc5ff5c9ee17cde0095f83675615c65dd11999d Mon Sep 17 00:00:00 2001 From: Calvix2k Date: Wed, 25 Nov 2026 17:37:11 +0100 Subject: [PATCH 13/13] GPU: keep the composed plane list's host textures owned The ported fix in the previous commit was written against a `host_resource` that lent its host texture; on `main` it returns a clone, so the composed list cannot hold `&ID3D12Resource` across the `host.present` call. Hold the clones and lend them to `present`; the per-texture state bookkeeping is unchanged. --- crates/victory-gpu/src/queue.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index db27086944c..217c4cef41d 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -541,7 +541,7 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; // SAFETY: the title passes the plane descriptions. let slice = unsafe { std::slice::from_raw_parts(plane_parameters, planes.min(8) as usize) }; - let mut resources: Vec<(This, &ID3D12Resource, u32, bool)> = + let mut resources: Vec<(This, ID3D12Resource, u32, bool)> = Vec::with_capacity(slice.len()); for plane in slice { if plane.count == 0 || plane.resources.is_null() {