diff --git a/CMakeLists.txt b/CMakeLists.txt index ad93d3a12f..8f7b97a2cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1951,6 +1951,28 @@ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_sharedexp_target_${adapter} COMMAND offscreen_check ${adapter} --startup-sharedexp-target) set_tests_properties(startup_sharedexp_target_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) endforeach() +# Presented planes (src/startup_stubs/present_planes.h): the plane record layout and the composite order +# on synthetic records. The control reads 0x40-byte records and composites plane 0 alone, and must FAIL. +add_executable(startup_present_planes tests/startup_present_planes_check.cpp) +target_include_directories(startup_present_planes PRIVATE src) +target_compile_features(startup_present_planes PRIVATE cxx_std_17) +add_test(NAME startup_present_planes COMMAND startup_present_planes) +add_test(NAME startup_present_planes_control COMMAND startup_present_planes --control) +set_tests_properties(startup_present_planes_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The window's plane composite (src/startup_stubs/plane_compositor.h) read back on WARP: a single-plane +# baseline, stacked planes with transparent, partly transparent and opaque overlays, and skipped repeats +# and empty records. The control then removes the overlays and passes only on "control ok:", printed when +# the baseline matched, every fence completed and the overlay-free picture differs from the stacked +# expectation in exactly the overlay cells. Any FAIL line (setup, fence, device removal, pixels) fails it. +add_executable(startup_present_composite_warp tests/startup_present_composite_warp.cpp) +target_include_directories(startup_present_composite_warp PRIVATE src) +target_compile_features(startup_present_composite_warp PRIVATE cxx_std_17) +target_link_libraries(startup_present_composite_warp PRIVATE d3d12 dxgi d3dcompiler) +add_test(NAME startup_present_composite_warp COMMAND startup_present_composite_warp) +add_test(NAME startup_present_composite_overlay_removed_control_warp COMMAND startup_present_composite_warp --control) +set_tests_properties(startup_present_composite_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) +set_tests_properties(startup_present_composite_overlay_removed_control_warp PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 + PASS_REGULAR_EXPRESSION "control ok: baseline matched" FAIL_REGULAR_EXPRESSION "FAIL: ") # Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) target_include_directories(startup_sampler_comparison_check PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e38af186e6..2ba7c59bfc 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -271,6 +271,67 @@ presenter, its owned window and a dialog stay visible. Where the host lets the t it also checks that the foreground moves to the output window. A run under Wine did; the fixture prints which case applied. +### Presented planes + +A console present (CommandQueue slot 32) carries a plane count and an array of plane records +(`src/startup_stubs/present_planes.h`). Measured from the first presents: one record is 0x48 bytes, +with +0x00 a frame token, +0x08 the resource count and +0x10 a pointer to the resource array. On the +Series S profile a title presented two planes: plane 0 at 1920x1080 stayed black and plane 1 at +3840x2160 held the picture, with alpha 255 wherever it drew. Showing plane 0 alone gave a black +window. Why plane 0 stays black is not known. + +By default the output window still shows plane 0 alone, as before the planes were decoded. The +experimental `X2W_PRESENT_COMPOSITE=1` makes it composite the planes instead +(`src/startup_stubs/plane_compositor.h`, shared by the window presenter and its fixture). It stays +opt-in until a matched comparison on the same executable, with this change alone, shows what it does +to a real present. The contract under the switch: + +- Order: plane 0 first, each later plane over it, in plane order (`composite_steps`). At most four + planes are read. +- The lowest drawn plane is opaque: its colour replaces the window and its alpha is ignored. +- Each later plane is blended by its own alpha, not premultiplied: + `rgb = src.rgb * src.a + dst.rgb * (1 - src.a)`, `a = src.a + dst.a * (1 - src.a)` (D3D12 + `SRC_ALPHA` / `INV_SRC_ALPHA`, alpha `ONE` / `INV_SRC_ALPHA`). Alpha 0 leaves what is below, + alpha 255 replaces it, and the window alpha stays 255. +- Left out: a plane whose record or resource array is unreadable or empty, a surface that is not a + known resource or that the presenter cannot draw (`present_view_format.h`), and a repeat of a + surface already drawn. If plane 0 is left out, the next drawn plane is the opaque base. +- Each plane is scaled to the whole window with a linear, clamped sampler. The planes' source and + destination rectangles in the record (after +0x10) are not decoded; a plane that covers only part + of the screen on the console is stretched here. +- The baseline capture is unchanged with or without the switch: the frame capture, the presented + signature, `X2W_D3D12_DUMP_SURFACE` and the `x2w-render presented` readback all read plane 0's + first resource, as before. Under the switch the highest plane above plane 0 with a known resource + is also sampled on the same frames, before compositing, and logged as a raw plane: + + ```text + x2w-render raw plane (not composited): surface x format , sample , mean level /255, mean alpha /255 + ``` + + Neither line is the composited window picture. + +The first presents and every 300th log each plane: + +```text +x2w-present frame plane /: x format flags=0x +``` + +`ctest --preset dev --no-tests=error -R '^startup_present_planes(_control)?$'` checks the record layout +and the composite order on synthetic records; the control reads 0x40-byte records and composites +plane 0 alone, and must print `FAIL:`. +`ctest --preset dev --no-tests=error -R '^startup_present_composite_(warp|overlay_removed_control_warp)$'` +draws source-built planes through the same records, `composite_steps` and compositor (directly, without +the switch) into a 64x32 RGBA8 target on WARP and reads every texel back: a single plane is shown as is (including a cell with alpha 0); a black +plane 0 under a plane with alpha 0, 128, 5 and 255 cells and a third plane with opaque and +half-transparent cells gives 0, 128, 5 and 255 levels and the plane-order result 128,0,127 for half +red over blue (within 1 for blended cells, exact otherwise); a repeated surface and an empty record +are left out. The control runs the same cases, then removes the overlays and composites the black +plane 0 alone. It passes only on `control ok: baseline matched, ...`, printed when the baseline and +stacked cases matched, every fence completed without device removal, and the overlay-free picture is +black and differs from the stacked expectation in exactly the six cells the overlays draw. Any `FAIL:` +line fails it, including queue, compositor, target or plane setup, a fence that does not complete and +device removal. Both exit 77 without a WARP adapter. + ## Null Texture2D descriptors When the adapter lacks typed UAV support for B5G5R5A1_UNORM or render-target support for @@ -1354,6 +1415,8 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | | `X2W_D3D12_DUMP_SURFACE=` | writes the last presented surface | +| `X2W_PRESENT_COMPOSITE=1` | experimental, in render mode: the output window composites every presented plane, bottom to top, instead of showing plane 0 alone, and the highest plane above plane 0 is sampled as `x2w-render raw plane (not composited)`. Off by default; the baseline capture and `x2w-render presented` read plane 0 either way. See [Presented planes](#presented-planes) | +| `X2W_PRESENT_PLANE=` | diagnostic, in render mode: the output window shows plane `n` of each present alone (plane 0 when `n` is past the count), with or without `X2W_PRESENT_COMPOSITE`. See [Presented planes](#presented-planes) | | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 58bec8cf4b..40ff3f6a5f 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -2,25 +2,25 @@ // Included inside d3d12_xs_device.cpp's anonymous namespace, before queue_present. // // A flip-model swap chain on the title window, created on the queue the title presents with; each -// present draws the presented surface into the back buffer with a full-window triangle (the surface -// is usually larger than the window) and flips. Diagnostics go to the window title, because GDI -// drawing does not mix with a flip-model swap chain. +// present draws its planes into the back buffer, bottom to top, with the plane compositor +// (plane_compositor.h: one full-window triangle a plane; a surface is usually larger than the +// window), and flips. Plane 0 alone by default; every plane with X2W_PRESENT_COMPOSITE=1. Diagnostics go to the window title, because GDI drawing does not mix with a +// flip-model swap chain. struct WindowPresenter { IDXGISwapChain3* chain = nullptr; ID3D12DescriptorHeap* targets = nullptr; - ID3D12DescriptorHeap* textures = nullptr; ID3D12Resource* buffers[2] = {}; ID3D12CommandAllocator* allocator = nullptr; ID3D12GraphicsCommandList* list = nullptr; - ID3D12RootSignature* root = nullptr; - ID3D12PipelineState* pipeline = nullptr; + x2w_startup::PlaneCompositor compositor; // shaders, pipelines and plane views ID3D12Fence* fence = nullptr; HANDLE reached = nullptr; UINT64 fence_value = 0; UINT width = 0, height = 0; bool failed = false; }; +constexpr UINT window_planes = 4; WindowPresenter window_presenter; LONG window_presents; @@ -97,7 +97,7 @@ HWND output_window() return output_handle; } -bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) +bool create_window_presenter(ID3D12CommandQueue* queue, HWND window, UINT plane_capacity) { WindowPresenter& p = window_presenter; ID3D12Device* device = device_of(the_device); @@ -124,9 +124,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (chain1) chain1->Release(); if (factory) factory->Release(); const D3D12_DESCRIPTOR_HEAP_DESC target_heap{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC texture_heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&target_heap, IID_PPV_ARGS(&p.targets)); - if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&texture_heap, IID_PPV_ARGS(&p.textures)); const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); for (UINT i = 0; SUCCEEDED(hr) && i < 2; ++i) { hr = p.chain->GetBuffer(i, IID_PPV_ARGS(&p.buffers[i])); @@ -138,100 +136,52 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) if (SUCCEEDED(hr)) hr = p.list->Close(); if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&p.fence)); p.reached = CreateEventW(nullptr, FALSE, FALSE, nullptr); - static const char source[] = - "Texture2D surface : register(t0); SamplerState smooth : register(s0);\n" - "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" - "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" - "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n"; - ID3DBlob* vs = nullptr; - ID3DBlob* ps = nullptr; - ID3DBlob* blob = nullptr; - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); - if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); - if (SUCCEEDED(hr)) { - const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_ROOT_PARAMETER parameter{}; - parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - parameter.DescriptorTable = {1, &range}; - parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - D3D12_STATIC_SAMPLER_DESC sampler{}; - sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; - sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; - sampler.MaxLOD = D3D12_FLOAT32_MAX; - sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; - const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); - if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&p.root)); - } - if (SUCCEEDED(hr)) { - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = p.root; - desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; - desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - desc.SampleMask = ~0u; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.SampleDesc.Count = 1; - hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&p.pipeline)); - } - if (vs) vs->Release(); - if (ps) ps->Release(); - if (blob) blob->Release(); + if (SUCCEEDED(hr)) hr = p.compositor.create(device, DXGI_FORMAT_R8G8B8A8_UNORM, plane_capacity); log("x2w-present window swap chain %ux%u -> 0x%08lx", p.width, p.height, static_cast(hr)); check_device("window presenter", 0); return SUCCEEDED(hr); } -// Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. -bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) +// Whether the window presenter can draw `surface` (present_view_format.h); logs the first refusals. +bool presentable_surface(ID3D12Resource* surface) +{ + if (!surface) return false; + const D3D12_RESOURCE_DESC desc = surface->GetDesc(); + if (x2w_startup::present_surface_supported(desc)) return true; + static LONG refused; + if (first_calls(refused, 4)) + log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", + desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); + return false; +} + +// Composites the steps of a present (present_planes.h composite_steps) into the window and flips. +// plane_surfaces[step.plane] is that plane's surface (resting in COMMON and presentable), or null to +// leave it out. Returns false if not shown. +bool present_to_window(ID3D12CommandQueue* queue, const x2w_startup::PlaneStep* steps, unsigned count, + ID3D12Resource* const* plane_surfaces, UINT plane_capacity) { X2W_ZONE("window present (blit + fence wait)"); WindowPresenter& p = window_presenter; - if (p.failed || !queue || !surface) return false; - const D3D12_RESOURCE_DESC desc = surface->GetDesc(); - if (!x2w_startup::present_surface_supported(desc)) { - static LONG refused; - if (first_calls(refused, 4)) - log("x2w-present surface dim=%d samples=%u flags=0x%x format=%d not supported (present_view_format.h)", - desc.Dimension, desc.SampleDesc.Count, desc.Flags, desc.Format); - return false; - } + if (p.failed || !queue || !steps || !count || !plane_surfaces) return false; HWND window = output_window(); if (!window) return false; - if (!p.chain && !create_window_presenter(queue, window)) { + if (!p.chain && !create_window_presenter(queue, window, plane_capacity)) { p.failed = true; return false; } ID3D12Device* device = device_of(the_device); - const DXGI_FORMAT view_format = x2w_startup::present_view_format(desc.Format); - D3D12_SHADER_RESOURCE_VIEW_DESC view{}; - view.Format = view_format; - view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - view.Texture2D.MipLevels = 1; - device->CreateShaderResourceView(surface, &view, p.textures->GetCPUDescriptorHandleForHeapStart()); const UINT index = p.chain->GetCurrentBackBufferIndex(); const D3D12_CPU_DESCRIPTOR_HANDLE target{p.targets->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{index} * device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV)}; - if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.pipeline))) return false; - transition(p.list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + if (FAILED(p.allocator->Reset()) || FAILED(p.list->Reset(p.allocator, p.compositor.initial_pipeline()))) return false; transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET); - const D3D12_VIEWPORT viewport{0, 0, static_cast(p.width), static_cast(p.height), 0, 1}; - const D3D12_RECT scissor{0, 0, static_cast(p.width), static_cast(p.height)}; - p.list->SetGraphicsRootSignature(p.root); - p.list->SetDescriptorHeaps(1, &p.textures); - p.list->SetGraphicsRootDescriptorTable(0, p.textures->GetGPUDescriptorHandleForHeapStart()); - p.list->RSSetViewports(1, &viewport); - p.list->RSSetScissorRects(1, &scissor); - p.list->OMSetRenderTargets(1, &target, FALSE, nullptr); - p.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - p.list->DrawInstanced(3, 1, 0, 0); + const UINT drawn = p.compositor.record(device, p.list, target, p.width, p.height, steps, count, plane_surfaces); transition(p.list, p.buffers[index], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); - transition(p.list, surface, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!drawn) { + p.list->Close(); + return false; + } if (FAILED(p.list->Close())) { p.failed = true; return false; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 50a37c5aa6..f7c0ace6db 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -55,6 +55,8 @@ #include "startup_stubs/slice_footprints.h" #include "startup_stubs/present_signature_sampler.h" +#include "startup_stubs/present_planes.h" +#include "startup_stubs/plane_compositor.h" #include #include "command_list_slot_names.h" @@ -1808,8 +1810,22 @@ SRWLOCK shown_lock = SRWLOCK_INIT; char shown_note[160] = "no frame read back yet"; void write_file(const wchar_t* path, const void* data, std::size_t bytes); -void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) -{ +// raw_plane < 0: the baseline capture of the presented surface (plane 0), reduced for the window and +// logged as `x2w-render presented`. raw_plane >= 0 (X2W_PRESENT_COMPOSITE=1 only): a sample of that +// plane's own surface, before compositing, logged as `x2w-render raw plane `; it leaves the window +// copy, the note and the dump alone. Neither is the composited window picture. +void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface, int raw_plane = -1) +{ + const bool raw = raw_plane >= 0; + char failure[160] = ""; + const auto report_failure = [&] { + if (!raw) { + std::snprintf(shown_note, sizeof(shown_note), "%s", failure); + return; + } + static LONG raw_failures; + if (first_calls(raw_failures, 4)) log("x2w-render raw plane %d (not composited): %s", raw_plane, failure); + }; static ID3D12CommandAllocator* allocator; static ID3D12GraphicsCommandList* list; static ID3D12Fence* fence; @@ -1825,7 +1841,8 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM || desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; const bool bgra = desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; if ((!rgba && !bgra) || total == 0 || total == ~0ull) { - std::snprintf(shown_note, sizeof(shown_note), "presented surface format %d not shown yet", desc.Format); + std::snprintf(failure, sizeof(failure), "presented surface format %d not shown yet", desc.Format); + report_failure(); return; } HRESULT hr = S_OK; @@ -1855,7 +1872,8 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) if (SUCCEEDED(hr)) hr = allocator->Reset(); if (SUCCEEDED(hr)) hr = list->Reset(allocator, nullptr); if (FAILED(hr)) { - std::snprintf(shown_note, sizeof(shown_note), "readback setup failed 0x%08lx", static_cast(hr)); + std::snprintf(failure, sizeof(failure), "readback setup failed 0x%08lx", static_cast(hr)); + report_failure(); return; } transition(list, surface, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1873,32 +1891,36 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) queue->Signal(fence, ++fence_value); fence->SetEventOnCompletion(fence_value, event); if (WaitForSingleObject(event, 3000) != WAIT_OBJECT_0) { - std::snprintf(shown_note, sizeof(shown_note), "readback timed out"); + std::snprintf(failure, sizeof(failure), "readback timed out"); + report_failure(); return; } void* mapped = nullptr; const D3D12_RANGE range{0, static_cast(total)}; if (FAILED(readback->Map(0, &range, &mapped))) return; - AcquireSRWLockExclusive(&shown_lock); - shown_pixels.resize(shown_width * shown_height); - std::uint64_t sum = 0; + if (!raw) { + AcquireSRWLockExclusive(&shown_lock); + shown_pixels.resize(shown_width * shown_height); + } + std::uint64_t sum = 0, alpha_sum = 0; for (int y = 0; y < shown_height; ++y) { const auto* row = static_cast(mapped) + footprint.Offset + static_cast(y) * desc.Height / shown_height * footprint.Footprint.RowPitch; for (int x = 0; x < shown_width; ++x) { const unsigned char* texel = row + static_cast(x) * desc.Width / shown_width * 4; const unsigned r = rgba ? texel[0] : texel[2], g = texel[1], b = rgba ? texel[2] : texel[0]; - shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; + if (!raw) shown_pixels[y * shown_width + x] = (r << 16) | (g << 8) | b; sum += r + g + b; + alpha_sum += texel[3]; } } - ReleaseSRWLockExclusive(&shown_lock); + if (!raw) ReleaseSRWLockExclusive(&shown_lock); // X2W_D3D12_DUMP_SURFACE=: every 40th read-back is also written at full resolution as a // 32-bit BMP (overwritten each time), for looking at detail the reduced overlay copy loses. { static wchar_t dump_path[MAX_PATH]; static const bool dump = GetEnvironmentVariableW(L"X2W_D3D12_DUMP_SURFACE", dump_path, MAX_PATH) != 0; - if (dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { + if (!raw && dump && (shown_frames % 4) == 3 && desc.Width <= 8192 && desc.Height <= 8192) { const UINT width = static_cast(desc.Width), height = desc.Height; std::vector file(54 + std::size_t{width} * height * 4); const std::uint32_t header[] = {static_cast(file.size()), 0, 54, 40, width, static_cast(-static_cast(height)), @@ -1921,6 +1943,15 @@ void read_back_presented(ID3D12CommandQueue* queue, ID3D12Resource* surface) } const D3D12_RANGE none{0, 0}; readback->Unmap(0, &none); + if (raw) { + static LONG raw_frames; + const LONG count = InterlockedIncrement(&raw_frames); + if ((count > 0 && count <= 3) || count % 40 == 0) + log("x2w-render raw plane %d (not composited): surface %llux%u format %d, sample %ld, mean level %.2f/255, mean alpha %.2f/255", + raw_plane, desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height), + alpha_sum / (1.0 * shown_width * shown_height)); + return; + } const LONG count = InterlockedIncrement(&shown_frames); std::snprintf(shown_note, sizeof(shown_note), "surface %llux%u format %d, readback %ld, mean level %.2f/255", desc.Width, desc.Height, desc.Format, count, sum / (3.0 * shown_width * shown_height)); @@ -5953,6 +5984,74 @@ void report_budget(ID3D12CommandQueue* queue) log("x2w-budget local=%s nonlocal=%s%s unmeasured=%llu", local, nonlocal, text, counts.unmeasured); } +// X2W_PRESENT_COMPOSITE=1 (experimental, docs/startup-runtime.md#presented-planes): the output +// window composites every presented plane. Unset, the window shows plane 0 alone, as before. +bool present_composite_enabled() +{ + static const bool on = x2w_local::env_on("X2W_PRESENT_COMPOSITE"); + return on; +} + +// The planes the output window draws for a present, resolved to real resources it can draw. +// X2W_PRESENT_PLANE= (diagnostic) keeps plane n alone (plane 0 when n is past the count). Otherwise +// plane 0 alone is kept, unless X2W_PRESENT_COMPOSITE=1 keeps every plane for the composite +// (present_planes.h). The baseline capture and readback do not use this: they read plane 0 as before. +struct PresentedPlanes { + ID3D12Resource* drawable[window_planes] = {}; // per plane, null when left out + x2w_startup::PlaneStep steps[window_planes]; + unsigned count = 0; // composite steps + unsigned top_plane = 0; // the highest kept plane with a known resource + ID3D12Resource* top = nullptr; // its surface +}; +PresentedPlanes presented_planes(UINT planes, const void* plane_parameters) +{ + static const long wanted = [] { + char value[16]{}; + return GetEnvironmentVariableA("X2W_PRESENT_PLANE", value, sizeof(value)) ? std::atol(value) : -1L; + }(); + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + PresentedPlanes out; + std::uint64_t shown[window_planes] = {}; + const unsigned total = planes < window_planes ? planes : window_planes; + const unsigned only = wanted >= 0 ? (static_cast(wanted) < planes ? static_cast(wanted) : 0u) + : present_composite_enabled() ? ~0u + : 0u; + for (unsigned i = 0; i < total; ++i) { + if (only != ~0u && i != only) continue; + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) continue; + auto* const real = static_cast(surface->own().real); + out.top_plane = i; + out.top = real; + if (!presentable_surface(real)) continue; + out.drawable[i] = real; + shown[i] = resource; + } + out.count = x2w_startup::composite_steps(shown, total, out.steps, window_planes); + return out; +} + +// The first presents and every 300th: each plane's first resource and its shape. +void log_present_planes(LONG frame, UINT planes, const void* plane_parameters) +{ + if (frame > 2 && frame % 300 != 0) return; + static LONG lines; + if (!first_calls(lines, 24)) return; + const auto readable = [](const void* address, std::size_t bytes) { return x2w_local::readable(address, bytes); }; + for (unsigned i = 0; i < planes && i < 4; ++i) { + const std::uint64_t resource = x2w_startup::present_plane_resource(plane_parameters, planes, i, readable); + Wrapper* const surface = resource ? as_wrapper(reinterpret_cast(resource)) : nullptr; + if (!surface || surface->own().kind != resource_kind || !surface->own().real) { + log("x2w-present frame %ld plane %u/%u: resource %p is not a known resource", frame, i, planes, reinterpret_cast(resource)); + continue; + } + const D3D12_RESOURCE_DESC desc = static_cast(surface->own().real)->GetDesc(); + log("x2w-present frame %ld plane %u/%u: %llux%u format %d flags=0x%x", frame, i, planes, + static_cast(desc.Width), desc.Height, desc.Format, static_cast(desc.Flags)); + } +} + // Queue slot 32 (Xbox order): (plane count, plane parameters*, present parameters*) -> HRESULT, the // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) @@ -5988,7 +6087,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa } } bool shown_in_window = false; + log_present_planes(frame, planes, plane_parameters); + // X2W_PRESENT_COMPOSITE=1: the highest plane above plane 0, sampled raw below. + ID3D12Resource* raw_surface = nullptr; + unsigned raw_plane = 0; { + // The baseline: plane 0's first resource, captured, sampled and read back as before the planes + // were decoded, with or without X2W_PRESENT_COMPOSITE. Wrapper* surface = nullptr; const auto* words = static_cast(plane_parameters); if (planes && words && x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) @@ -5996,9 +6101,18 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa capture::present(frame, surface); if (surface && surface->own().kind == resource_kind) red_producers().present(static_cast(surface->own().real)); - // Render mode: the presented surface goes to the title's window through a swap chain. - if (render_mode() && surface && surface->own().kind == resource_kind && surface->own().real) - shown_in_window = present_to_window(static_cast(self->own().real), static_cast(surface->own().real)); + // Render mode: the presented planes go to the output window through a swap chain: plane 0 alone + // by default, every plane with X2W_PRESENT_COMPOSITE=1. The compositor draws the steps in order. + if (render_mode()) { + const PresentedPlanes presented = presented_planes(planes, plane_parameters); + if (presented.count) + shown_in_window = present_to_window(static_cast(self->own().real), presented.steps, presented.count, + presented.drawable, present_composite_enabled() ? window_planes : 1); + if (present_composite_enabled() && presented.top && presented.top_plane > 0) { + raw_surface = presented.top; + raw_plane = presented.top_plane; + } + } InterlockedExchange(&last_frame_shown, shown_in_window ? 1 : 0); if (render_mode()) present_signature(self, surface, frame); } @@ -6021,6 +6135,8 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa std::snprintf(shown_note, sizeof(shown_note), "presented object %p is not a known resource", *reinterpret_cast(words[2])); } + // The raw plane sample is that plane's own surface, not the composited window picture. + if (raw_surface) read_back_presented(static_cast(self->own().real), raw_surface, static_cast(raw_plane)); } if (shown_in_window) { if (frame % 30 == 0) { diff --git a/src/startup_stubs/plane_compositor.h b/src/startup_stubs/plane_compositor.h new file mode 100644 index 0000000000..b41cd58957 --- /dev/null +++ b/src/startup_stubs/plane_compositor.h @@ -0,0 +1,186 @@ +// Experimental (docs/startup-runtime.md#presented-planes): the draw that composites the planes of a +// console present into one render target. The output window (d3d12_present.inl) records it into its +// back buffer; tests/startup_present_composite_warp.cpp records it into a texture it reads back. +// +// Contract: the steps come from composite_steps (present_planes.h), bottom to top. The first step +// drawn replaces the target with its plane's colour and ignores that plane's alpha (nothing is below +// it); each later step with `blended` set is drawn over the result with +// colour = src.rgb * src.a + dst.rgb * (1 - src.a), alpha = src.a + dst.a * (1 - src.a) +// (SRC_ALPHA / INV_SRC_ALPHA, ONE / INV_SRC_ALPHA), so after an opaque base the target alpha stays 1. +// A step without `blended` (or whose plane has no surface) after the first is drawn opaque or left +// out. Each plane is one full-target triangle sampled with a linear, clamped sampler: a plane the +// size of the target is copied texel for texel; a larger or smaller plane is scaled to fit. +// Plane surfaces must rest in COMMON and pass present_surface_supported (present_view_format.h); they +// are left in COMMON. The target must be in RENDER_TARGET. +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include + +#include "startup_stubs/present_planes.h" +#include "startup_stubs/present_view_format.h" + +namespace x2w_startup { + +class PlaneCompositor { +public: + // Create the opaque pipeline and a heap for up to `max_planes` views. More than one plane also needs a blend pipeline. + HRESULT create(ID3D12Device* device, DXGI_FORMAT target_format, UINT max_planes) + { + release(); + max_planes_ = max_planes ? max_planes : 1; + static const char source[] = + "Texture2D surface : register(t0); SamplerState smooth : register(s0);\n" + "struct V { float4 position : SV_Position; float2 uv : TEXCOORD0; };\n" + "V vs(uint id : SV_VertexID) { V o; o.uv = float2((id << 1) & 2, id & 2); o.position = float4(o.uv * float2(2, -2) + float2(-1, 1), 0, 1); return o; }\n" + "float4 ps(V i) : SV_Target0 { return float4(surface.Sample(smooth, i.uv).rgb, 1); }\n" + "float4 ps_over(V i) : SV_Target0 { return surface.Sample(smooth, i.uv); }\n"; + ID3DBlob* vs = nullptr; + ID3DBlob* ps = nullptr; + ID3DBlob* ps_over = nullptr; + ID3DBlob* blob = nullptr; + const D3D12_DESCRIPTOR_HEAP_DESC heap{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, max_planes_, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + HRESULT hr = device->CreateDescriptorHeap(&heap, IID_PPV_ARGS(&textures_)); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs, nullptr); + if (SUCCEEDED(hr)) hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps, nullptr); + if (SUCCEEDED(hr) && max_planes_ > 1) + hr = D3DCompile(source, sizeof(source) - 1, "present", nullptr, nullptr, "ps_over", "ps_5_0", 0, 0, &ps_over, nullptr); + if (SUCCEEDED(hr)) { + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); + if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root_)); + } + if (SUCCEEDED(hr)) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root_; + desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + desc.SampleMask = ~0u; + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + desc.NumRenderTargets = 1; + desc.RTVFormats[0] = target_format; + desc.SampleDesc.Count = 1; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&opaque_)); + if (SUCCEEDED(hr) && ps_over) { + desc.PS = {ps_over->GetBufferPointer(), ps_over->GetBufferSize()}; + D3D12_RENDER_TARGET_BLEND_DESC& blend = desc.BlendState.RenderTarget[0]; + blend.BlendEnable = TRUE; + blend.SrcBlend = D3D12_BLEND_SRC_ALPHA; + blend.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOp = D3D12_BLEND_OP_ADD; + blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + hr = device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&blend_)); + } + } + if (vs) vs->Release(); + if (ps) ps->Release(); + if (ps_over) ps_over->Release(); + if (blob) blob->Release(); + if (FAILED(hr)) release(); + return hr; + } + + // The pipeline a list can be reset with before record(). + ID3D12PipelineState* initial_pipeline() const { return opaque_; } + UINT max_planes() const { return max_planes_; } + + // Records the composite into `list` (open) over `target` (width x height, in RENDER_TARGET). + // steps[0..count) as from composite_steps; plane_surfaces[step.plane] is that plane's surface, + // or null to leave the step out. Returns the number of planes drawn (0: nothing recorded). + UINT record(ID3D12Device* device, ID3D12GraphicsCommandList* list, D3D12_CPU_DESCRIPTOR_HANDLE target, UINT width, + UINT height, const PlaneStep* steps, unsigned count, ID3D12Resource* const* plane_surfaces) + { + if (!opaque_ || !list || !steps || !plane_surfaces) return 0; + ID3D12Resource* drawn[16] = {}; + bool blended[16] = {}; + UINT planes = 0; + const UINT limit = max_planes_ < 16 ? max_planes_ : 16; + for (unsigned i = 0; i < count && planes < limit; ++i) { + ID3D12Resource* const surface = plane_surfaces[steps[i].plane]; + if (!surface) continue; + blended[planes] = planes != 0 && steps[i].blended; // the first plane drawn is the opaque base + drawn[planes++] = surface; + } + if (!planes) return 0; + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < planes; ++i) { + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = present_view_format(drawn[i]->GetDesc().Format); + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.Texture2D.MipLevels = 1; + device->CreateShaderResourceView(drawn[i], &view, + D3D12_CPU_DESCRIPTOR_HANDLE{textures_->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{i} * step}); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; + list->SetGraphicsRootSignature(root_); + list->SetDescriptorHeaps(1, &textures_); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &target, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + for (UINT i = 0; i < planes; ++i) { + list->SetPipelineState(blended[i] ? blend_ : opaque_); + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{textures_->GetGPUDescriptorHandleForHeapStart().ptr + UINT64{i} * step}); + list->DrawInstanced(3, 1, 0, 0); + } + for (UINT i = 0; i < planes; ++i) transition(list, drawn[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + return planes; + } + + void release() + { + if (blend_) blend_->Release(); + if (opaque_) opaque_->Release(); + if (root_) root_->Release(); + if (textures_) textures_->Release(); + blend_ = opaque_ = nullptr; + root_ = nullptr; + textures_ = nullptr; + } + +private: + static void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = resource; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + barrier.Transition.StateBefore = from; + barrier.Transition.StateAfter = to; + list->ResourceBarrier(1, &barrier); + } + + ID3D12DescriptorHeap* textures_ = nullptr; + ID3D12RootSignature* root_ = nullptr; + ID3D12PipelineState* opaque_ = nullptr; // the bottom plane, alpha ignored + ID3D12PipelineState* blend_ = nullptr; // later planes, over it by their alpha + UINT max_planes_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/present_planes.h b/src/startup_stubs/present_planes.h new file mode 100644 index 0000000000..0c71c7ac1d --- /dev/null +++ b/src/startup_stubs/present_planes.h @@ -0,0 +1,61 @@ +// Experimental (docs/startup-runtime.md): the planes of a console present (CommandQueue slot 32). +// +// The present takes a plane count and an array of plane records. Measured from the first presents +// of a console executable: one record is 0x48 bytes, with +0x00 a frame token, +0x08 the resource +// count and +0x10 a pointer to the array of resources; the second plane's token sits at +0x48 when +// two planes are presented. The fields after +0x10 (source and destination rectangles, flags) are +// not decoded here. Pure: the caller passes a readability check, so a control can run it on +// synthetic records. +#pragma once + +#include +#include +#include + +namespace x2w_startup { +inline constexpr std::size_t present_plane_stride = 0x48; + +// The first resource of plane `index`, or 0 when the plane, its record or its resource array is +// not readable or has no resource. readable(address, bytes) answers whether memory can be read. +template +std::uint64_t present_plane_resource(const void* planes, unsigned count, unsigned index, Readable&& readable, + std::size_t stride = present_plane_stride) +{ + if (!planes || index >= count) return 0; + const auto* record = static_cast(planes) + std::size_t{index} * stride; + if (!readable(record, 0x18)) return 0; + std::uint64_t resources = 0, resource_count = 0, first = 0; + std::memcpy(&resource_count, record + 0x08, 8); + std::memcpy(&resources, record + 0x10, 8); + if (resource_count == 0 || !resources || !readable(reinterpret_cast(resources), 8)) return 0; + std::memcpy(&first, reinterpret_cast(resources), 8); + return first; +} + +// One draw of the window composite: plane `plane`, either replacing what is below (the bottom +// layer) or blended over it by the plane's own alpha. +struct PlaneStep { + unsigned plane = 0; + bool blended = false; +}; + +// The window composite of a present, bottom to top, the way planes stack on the console: plane 0 +// first, each later plane over it. `resources[i]` is plane i's surface, 0 when it cannot be shown; +// those planes and repeats of a surface already drawn are left out. The lowest drawn plane is +// opaque (nothing is below it), every later one blended. Returns the number of steps written. +// Measured on a two-plane present: plane 0 was black and plane 1, with alpha 255 wherever the +// picture was, held it; showing plane 0 alone gave a black window. +inline unsigned composite_steps(const std::uint64_t* resources, unsigned count, PlaneStep* steps, unsigned max_steps) +{ + unsigned written = 0; + for (unsigned i = 0; resources && i < count && written < max_steps; ++i) { + if (!resources[i]) continue; + bool repeat = false; + for (unsigned j = 0; j < written; ++j) repeat = repeat || resources[steps[j].plane] == resources[i]; + if (repeat) continue; + steps[written] = PlaneStep{i, written != 0}; + ++written; + } + return written; +} +} // namespace x2w_startup diff --git a/tests/startup_present_composite_warp.cpp b/tests/startup_present_composite_warp.cpp new file mode 100644 index 0000000000..e7e054724b --- /dev/null +++ b/tests/startup_present_composite_warp.cpp @@ -0,0 +1,481 @@ +// Pixel readback of the presented-plane composite on WARP (docs/startup-runtime.md#presented-planes). +// Source-built planes go through the code the output window uses: synthetic 0x48-byte plane records +// read by present_plane_resource, the order from composite_steps (present_planes.h), and the draws of +// PlaneCompositor (plane_compositor.h) into a 64 x 32 RGBA8 target that is read back. +// +// Contract checked: the bottom plane is drawn opaque, its alpha ignored; each later plane is blended +// over the result in plane order, colour = src * a + dst * (1 - a); the target alpha stays 255; +// repeats of a surface and planes whose record has no readable resource are left out. +// +// Cases: +// baseline one plane of four colours, one cell with alpha 0, shown as is. +// stacked black opaque plane 0; plane 1 with a fully transparent cell, a half-transparent cell, +// a nearly transparent cell (alpha 5) and an opaque cell; plane 2 with an opaque cell, a +// cell blended over plane 1's opaque cell (order) and transparent elsewhere. +// skipped plane 0 black, plane 1 as above, plane 2 the same surface as plane 1, plane 3 a record +// with no resource: the same picture as plane 0 and 1 alone. +// --control runs the same cases and then removes the overlay: stacked composited from the black +// plane 0 alone. It prints "control ok:" and exits 0 only when the baseline and stacked cases matched, +// every fence completed without device removal, and the overlay-free result is black and differs from +// the stacked expectation in exactly the six cells the overlays draw. A setup failure, a missing +// fence, device removal or any other difference prints FAIL and exits 1. +// usage: startup_present_composite_warp [--control] (exit 77 when no WARP adapter is available) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include "startup_stubs/plane_compositor.h" +#include "startup_stubs/present_planes.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; +void fail(const char* format, const char* a, unsigned b, unsigned c, const unsigned char* got, const unsigned char* want) +{ + ++failures; + std::printf(format, a, b, c, got[0], got[1], got[2], got[3], want[0], want[1], want[2], want[3]); +} + +constexpr UINT width = 64, height = 32; +constexpr UINT columns = 4, rows = 2; // cells of 16 x 16 texels +constexpr UINT cell_w = width / columns, cell_h = height / rows; + +struct Rgba { + unsigned char r, g, b, a; +}; +// A plane picture: one colour per cell, row-major. +using Cells = Rgba[rows][columns]; + +struct Gpu { + ID3D12Device* device = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + + // Executes the list and waits for its fence. A list that does not close or execute, a fence that + // does not reach the value in time, or one that reports device removal (UINT64_MAX) is a failure. + bool run() + { + const HRESULT closed = list->Close(); + if (FAILED(closed)) { + ++failures; + std::printf("FAIL: command list close 0x%08lx\n", static_cast(closed)); + return false; + } + ID3D12CommandList* lists[] = {list}; + queue->ExecuteCommandLists(1, lists); + const HRESULT signalled = queue->Signal(fence, ++value); + if (SUCCEEDED(signalled) && fence->GetCompletedValue() < value && SUCCEEDED(fence->SetEventOnCompletion(value, event))) + WaitForSingleObject(event, 10000); + const UINT64 completed = fence->GetCompletedValue(); + if (FAILED(signalled) || completed == UINT64_MAX || completed < value) { + ++failures; + std::printf("FAIL: fence %llu not completed (completed %llu, signal 0x%08lx)\n", static_cast(value), + static_cast(completed), static_cast(signalled)); + return false; + } + ++fences; + allocator->Reset(); + list->Reset(allocator, nullptr); + return true; + } + unsigned fences = 0; // fences that completed +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = resource; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = from; + b.Transition.StateAfter = to; + list->ResourceBarrier(1, &b); +} + +D3D12_RESOURCE_DESC texture_desc(D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +ID3D12Resource* buffer(Gpu& gpu, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* out = nullptr; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&out)); + return out; +} + +// A plane surface holding `cells`, left in COMMON as the compositor expects. +ID3D12Resource* plane(Gpu& gpu, const Cells& cells) +{ + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_NONE); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + ID3D12Resource* texture = nullptr; + if (FAILED(gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&texture)))) + return nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + ID3D12Resource* upload = buffer(gpu, D3D12_HEAP_TYPE_UPLOAD, total, D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + upload->Map(0, nullptr, &mapped); + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) { + const Rgba& c = cells[y / cell_h][x / cell_w]; + unsigned char* t = static_cast(mapped) + footprint.Offset + std::size_t{y} * footprint.Footprint.RowPitch + x * 4; + t[0] = c.r, t[1] = c.g, t[2] = c.b, t[3] = c.a; + } + upload->Unmap(0, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = texture; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = upload; + from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + from.PlacedFootprint = footprint; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + barrier(gpu.list, texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + const bool ran = gpu.run(); + upload->Release(); + if (!ran) { + texture->Release(); + return nullptr; + } + return texture; +} + +// Plane records as a console present passes them: 0x48 bytes each, +0x08 the resource count and +// +0x10 a pointer to the resource array. A null surface gives a record with no resource. +struct Records { + alignas(8) unsigned char bytes[4 * x2w_startup::present_plane_stride] = {}; + std::uint64_t arrays[4][1] = {}; + explicit Records(ID3D12Resource* const* surfaces, unsigned count) + { + for (unsigned i = 0; i < count; ++i) { + unsigned char* record = bytes + i * x2w_startup::present_plane_stride; + const std::uint64_t token = 7, resources = surfaces[i] ? 1 : 0; + arrays[i][0] = reinterpret_cast(surfaces[i]); + const std::uint64_t pointer = reinterpret_cast(arrays[i]); + std::memcpy(record + 0x00, &token, 8); + std::memcpy(record + 0x08, &resources, 8); + std::memcpy(record + 0x10, &pointer, 8); + } + } +}; + +struct Target { + ID3D12Resource* texture = nullptr; + ID3D12DescriptorHeap* heap = nullptr; + ID3D12Resource* readback = nullptr; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; +}; + +// Runs the window's composite path on `count` plane records and reads the target back. +// Returns width * height RGBA texels, or nothing when the composite drew no plane. +std::vector composite(Gpu& gpu, x2w_startup::PlaneCompositor& compositor, Target& target, ID3D12Resource* const* surfaces, + unsigned count, unsigned* steps_out) +{ + Records records(surfaces, count); + const auto readable = [&](const void* address, std::size_t bytes) { + const auto* a = static_cast(address); + const auto* lo = reinterpret_cast(&records); + return a >= lo && a + bytes <= lo + sizeof(records); + }; + // As queue_present: plane i's first resource, 0 when the record has none. + std::uint64_t resources[4] = {}; + ID3D12Resource* plane_surfaces[4] = {}; + for (unsigned i = 0; i < count; ++i) { + resources[i] = x2w_startup::present_plane_resource(records.bytes, count, i, readable); + plane_surfaces[i] = reinterpret_cast(resources[i]); + } + x2w_startup::PlaneStep steps[4]; + const unsigned n = x2w_startup::composite_steps(resources, count, steps, 4); + *steps_out = n; + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + const float clear[4] = {0.25f, 0.5f, 0.75f, 0.0f}; // nothing of this may survive the opaque base + gpu.list->ClearRenderTargetView(target.heap->GetCPUDescriptorHandleForHeapStart(), clear, 0, nullptr); + const UINT drawn = compositor.record(gpu.device, gpu.list, target.heap->GetCPUDescriptorHandleForHeapStart(), width, height, steps, n, + plane_surfaces); + barrier(gpu.list, target.texture, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = target.readback; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint = target.footprint; + from.pResource = target.texture; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + std::vector pixels; + if (!gpu.run() || !drawn) return pixels; + pixels.resize(std::size_t{width} * height * 4); + void* mapped = nullptr; + const D3D12_RANGE range{0, static_cast(target.footprint.Footprint.RowPitch) * height}; + target.readback->Map(0, &range, &mapped); + for (UINT y = 0; y < height; ++y) + std::memcpy(&pixels[std::size_t{y} * width * 4], + static_cast(mapped) + target.footprint.Offset + std::size_t{y} * target.footprint.Footprint.RowPitch, + std::size_t{width} * 4); + const D3D12_RANGE none{0, 0}; + target.readback->Unmap(0, &none); + return pixels; +} + +// Whether every texel of a cell is within `tolerance` of `want` (alpha 255); the first texel off it +// goes to `got`. +bool cell_matches(const std::vector& pixels, UINT row, UINT column, const Rgba& want, int tolerance, unsigned char* got) +{ + const unsigned char w[4] = {want.r, want.g, want.b, 255}; + for (UINT y = row * cell_h; y < (row + 1) * cell_h; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance) { + std::memcpy(got, g, 4); + return false; + } + } + return true; +} + +// Every texel of every cell must be within `tolerance` of the expected colour (alpha 255). +void expect(const char* name, const std::vector& pixels, const Rgba (&want)[rows][columns], const int (&tolerance)[rows][columns]) +{ + if (pixels.empty()) { + ++failures; + std::printf("FAIL: %s: nothing composited\n", name); + return; + } + for (UINT row = 0; row < rows; ++row) + for (UINT column = 0; column < columns; ++column) { + const unsigned char w[4] = {want[row][column].r, want[row][column].g, want[row][column].b, 255}; + bool reported = false; + for (UINT y = row * cell_h; y < (row + 1) * cell_h && !reported; ++y) + for (UINT x = column * cell_w; x < (column + 1) * cell_w && !reported; ++x) { + const unsigned char* g = &pixels[(std::size_t{y} * width + x) * 4]; + for (int k = 0; k < 4 && !reported; ++k) + if (std::abs(int{g[k]} - int{w[k]}) > tolerance[row][column]) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", name, row, column, g, w); + reported = true; + } + } + if (!reported) + std::printf("%s cell row %u column %u: %u,%u,%u,255 (+/-%d)\n", name, row, column, w[0], w[1], w[2], tolerance[row][column]); + } +} + +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + IDXGIFactory4* factory = nullptr; + IDXGIAdapter* warp = nullptr; + Gpu gpu; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp))) || + FAILED(D3D12CreateDevice(warp, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&gpu.device)))) { + std::printf("SKIP: no WARP device\n"); + return 77; + } + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(gpu.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&gpu.queue))) || + FAILED(gpu.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&gpu.allocator))) || + FAILED(gpu.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, gpu.allocator, nullptr, IID_PPV_ARGS(&gpu.list))) || + FAILED(gpu.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gpu.fence)))) { + std::printf("FAIL: WARP queue setup\n"); + return 1; + } + x2w_startup::PlaneCompositor compositor; + const HRESULT created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 1); + if (FAILED(created)) { + std::printf("FAIL: compositor setup 0x%08lx\n", static_cast(created)); + return 1; + } + + Target target; + { + const D3D12_RESOURCE_DESC desc = texture_desc(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + gpu.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, nullptr, + IID_PPV_ARGS(&target.texture)); + const D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + gpu.device->CreateDescriptorHeap(&rtv, IID_PPV_ARGS(&target.heap)); + gpu.device->CreateRenderTargetView(target.texture, nullptr, target.heap->GetCPUDescriptorHandleForHeapStart()); + UINT64 total = 0; + gpu.device->GetCopyableFootprints(&desc, 0, 1, 0, &target.footprint, nullptr, nullptr, &total); + target.readback = buffer(gpu, D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST); + } + if (!target.texture || !target.heap || !target.readback) { + std::printf("FAIL: target setup\n"); + return 1; + } + + // Plane pictures. The baseline plane's last cell has alpha 0 to show that the bottom plane's + // alpha is ignored. + const Cells baseline = {{{200, 40, 10, 255}, {10, 200, 40, 255}, {40, 10, 200, 128}, {250, 250, 250, 255}}, + {{0, 0, 0, 255}, {128, 64, 32, 255}, {1, 2, 3, 255}, {90, 180, 60, 0}}}; + const Cells black = {{{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}, + {{0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + // Plane 1: row 0 transparent (alpha 0), half (128), nearly transparent (5), opaque; row 1 opaque + // blue under plane 2's blended cell, opaque blue under plane 2's opaque cell, transparent twice. + const Cells overlay = {{{255, 0, 0, 0}, {0, 255, 0, 128}, {255, 255, 255, 5}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {255, 255, 255, 0}, {255, 255, 255, 0}}}; + // Plane 2: row 0 transparent; row 1 half red over blue (order), opaque yellow over blue, opaque + // cyan over black, transparent. + const Cells top = {{{255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}, {255, 255, 0, 0}}, + {{255, 0, 0, 128}, {255, 255, 0, 255}, {0, 255, 255, 255}, {255, 0, 255, 0}}}; + ID3D12Resource* const p_baseline = plane(gpu, baseline); + ID3D12Resource* const p_black = plane(gpu, black); + ID3D12Resource* const p_overlay = plane(gpu, overlay); + ID3D12Resource* const p_top = plane(gpu, top); + if (!p_baseline || !p_black || !p_overlay || !p_top) { + std::printf("FAIL: plane setup\n"); + return 1; + } + + const int exact[rows][columns] = {{0, 0, 0, 0}, {0, 0, 0, 0}}; + unsigned steps = 0; + + // Baseline: one plane, shown as is, alpha forced to 255. + { + ID3D12Resource* const planes[] = {p_baseline}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + Rgba want[rows][columns]; + for (UINT r = 0; r < rows; ++r) + for (UINT c = 0; c < columns; ++c) want[r][c] = baseline[r][c]; + if (steps != 1) { + ++failures; + std::printf("FAIL: baseline: %u steps, want 1\n", steps); + } + expect("baseline", pixels, want, exact); + } + + const HRESULT composite_created = compositor.create(gpu.device, DXGI_FORMAT_R8G8B8A8_UNORM, 4); + if (FAILED(composite_created)) { + std::printf("FAIL: multi-plane compositor setup 0x%08lx\n", static_cast(composite_created)); + return 1; + } + + // Stacked: black, overlay, top. + // Expected (UNORM8, src * a/255 + dst * (1 - a/255)): 128/255 of 255 is 128; 5/255 of 255 is 5; + // half red over blue is 128,0,127. + const Rgba stacked_want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{128, 0, 127, 255}, {255, 255, 0, 255}, {0, 255, 255, 255}, {0, 0, 0, 255}}}; + const int blended[rows][columns] = {{0, 1, 1, 0}, {1, 0, 0, 0}}; + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_top}; + const auto pixels = composite(gpu, compositor, target, planes, 3, &steps); + if (steps != 3) { + ++failures; + std::printf("FAIL: stacked: %u steps, want 3\n", steps); + } + expect("stacked", pixels, stacked_want, blended); + } + + // Skipped: plane 2 repeats plane 1's surface and plane 3 has no resource. Drawing the repeat + // would blend the half-green cell twice (0,191,0) and the nearly transparent one twice (10). + { + ID3D12Resource* const planes[] = {p_black, p_overlay, p_overlay, nullptr}; + const auto pixels = composite(gpu, compositor, target, planes, 4, &steps); + if (steps != 2) { + ++failures; + std::printf("FAIL: skipped: %u steps, want 2 (plane 0 and plane 1)\n", steps); + } + const Rgba want[rows][columns] = {{{0, 0, 0, 255}, {0, 128, 0, 255}, {5, 5, 5, 255}, {0, 0, 255, 255}}, + {{0, 0, 255, 255}, {0, 0, 255, 255}, {0, 0, 0, 255}, {0, 0, 0, 255}}}; + const int tolerance[rows][columns] = {{0, 1, 1, 0}, {0, 0, 0, 0}}; + expect("skipped", pixels, want, tolerance); + } + + // Control: the overlays removed, stacked is composited from the black plane 0 alone. That must be + // black everywhere, and must differ from the stacked expectation in exactly the cells the overlays + // draw: every cell except row 0 column 0 (plane 1 transparent) and row 1 column 3 (both transparent). + unsigned control_differences = 0; + if (control && !failures) { + const bool overlay_drawn[rows][columns] = {{false, true, true, true}, {true, true, true, false}}; + const Rgba black_want = {0, 0, 0, 255}; + ID3D12Resource* const planes[] = {p_black}; + const auto pixels = composite(gpu, compositor, target, planes, 1, &steps); + if (steps != 1) { + ++failures; + std::printf("FAIL: control: overlay removed: %u steps, want 1\n", steps); + } + if (pixels.empty()) { + ++failures; + std::printf("FAIL: control: overlay removed: nothing composited\n"); + } + for (UINT row = 0; row < rows && !pixels.empty(); ++row) + for (UINT column = 0; column < columns; ++column) { + unsigned char got[4] = {}; + const unsigned char black[4] = {0, 0, 0, 255}; + if (!cell_matches(pixels, row, column, black_want, 0, got)) { + fail("FAIL: %s cell row %u column %u: got %u,%u,%u,%u want %u,%u,%u,%u\n", "control: overlay removed", row, column, got, + black); + continue; + } + const bool differs = !cell_matches(pixels, row, column, stacked_want[row][column], blended[row][column], got); + if (differs) ++control_differences; + if (differs != overlay_drawn[row][column]) { + ++failures; + std::printf("FAIL: control: overlay removed: cell row %u column %u %s the stacked expectation, want it to %s\n", row, + column, differs ? "differs from" : "matches", overlay_drawn[row][column] ? "differ" : "match"); + } else { + std::printf("control: overlay removed: cell row %u column %u %s the stacked expectation\n", row, column, + differs ? "differs from" : "matches"); + } + } + } + + const HRESULT removed = gpu.device->GetDeviceRemovedReason(); + if (FAILED(removed)) { + ++failures; + std::printf("FAIL: device removed 0x%08lx\n", static_cast(removed)); + } + if (failures) { + std::printf("startup_present_composite: FAIL (%d)\n", failures); + return 1; + } + if (control) { + std::printf("control ok: baseline matched, %u fences completed, removing the overlay changed %u of %u cells as expected\n", + gpu.fences, control_differences, rows * columns); + return 0; + } + std::puts("startup_present_composite: ok (baseline, stacked and skipped planes on WARP)"); + return 0; +} diff --git a/tests/startup_present_planes_check.cpp b/tests/startup_present_planes_check.cpp new file mode 100644 index 0000000000..88473d3c6c --- /dev/null +++ b/tests/startup_present_planes_check.cpp @@ -0,0 +1,89 @@ +// Checks src/startup_stubs/present_planes.h on synthetic plane records: two 0x48-byte records, each +// with a frame token, a resource count and a pointer to its resource array. +// Also checks the window composite order (composite_steps) on synthetic plane surfaces. +// --control reads the records with a 0x40-byte stride (the record size before the second plane was +// measured) and composites plane 0 alone (the window present before planes were composited); the +// second-plane rows must print FAIL. +#include "startup_stubs/present_planes.h" + +#include +#include + +namespace { +int failures; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void put(unsigned char* at, std::uint64_t value) { std::memcpy(at, &value, 8); } +} // namespace + +int main(int argc, char** argv) +{ + const bool control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + const std::size_t stride = control ? 0x40 : x2w_startup::present_plane_stride; + const std::uint64_t first_plane[] = {0x1111}, second_plane[] = {0x2222, 0x3333}; + alignas(8) unsigned char records[2 * 0x48] = {}; + alignas(8) unsigned char empty[0x48] = {}; + // Readable: only this fixture's own records and resource arrays. + const auto inside = [](const void* address, std::size_t bytes, const void* base, std::size_t size) { + const auto* a = static_cast(address); + const auto* b = static_cast(base); + return a >= b && a + bytes <= b + size; + }; + const auto readable = [&](const void* address, std::size_t bytes) { + return inside(address, bytes, records, sizeof(records)) || inside(address, bytes, empty, sizeof(empty)) || + inside(address, bytes, first_plane, sizeof(first_plane)) || inside(address, bytes, second_plane, sizeof(second_plane)); + }; + put(records + 0x00, 7); // frame token + put(records + 0x08, 1); + put(records + 0x10, reinterpret_cast(first_plane)); + put(records + 0x48, 7); + put(records + 0x50, 2); + put(records + 0x58, reinterpret_cast(second_plane)); + + using x2w_startup::present_plane_resource; + check("plane 0 resource", present_plane_resource(records, 2, 0, readable, stride) == 0x1111); + check("plane 1 resource (the second record starts at +0x48)", present_plane_resource(records, 2, 1, readable, stride) == 0x2222); + check("a plane past the count has no resource", present_plane_resource(records, 1, 1, readable, stride) == 0); + check("no records", present_plane_resource(nullptr, 2, 0, readable, stride) == 0); + + put(empty + 0x10, reinterpret_cast(first_plane)); + check("a plane with no resources has none", present_plane_resource(empty, 1, 0, readable, stride) == 0); + const auto unreadable = [](const void*, std::size_t) { return false; }; + check("an unreadable record has no resource", present_plane_resource(records, 2, 0, unreadable, stride) == 0); + + // Composite order: the lowest shown plane is opaque, later ones blend over it. + using x2w_startup::PlaneStep; + const auto composite = [&](const std::uint64_t* resources, unsigned count, PlaneStep* steps) { + return x2w_startup::composite_steps(resources, control && count > 1 ? 1 : count, steps, 4); + }; + PlaneStep steps[4]; + const std::uint64_t two[] = {0x1111, 0x2222}; + unsigned n = composite(two, 2, steps); + check("two planes give two steps", n == 2); + check("plane 0 is drawn first, opaque", n >= 1 && steps[0].plane == 0 && !steps[0].blended); + check("plane 1 is drawn over plane 0, blended", n >= 2 && steps[1].plane == 1 && steps[1].blended); + const std::uint64_t missing_base[] = {0, 0x2222}; + n = composite(missing_base, 2, steps); + check("with plane 0 not shown, plane 1 is the opaque base", n == 1 && steps[0].plane == 1 && !steps[0].blended); + const std::uint64_t repeated[] = {0x1111, 0x1111}; + n = x2w_startup::composite_steps(repeated, 2, steps, 4); + check("a surface presented twice is drawn once", n == 1 && steps[0].plane == 0); + const std::uint64_t one[] = {0x1111}; + n = composite(one, 1, steps); + check("one plane is one opaque step", n == 1 && steps[0].plane == 0 && !steps[0].blended); + check("no planes, no steps", x2w_startup::composite_steps(nullptr, 2, steps, 4) == 0); + + if (failures) { + std::printf("startup_present_planes: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_present_planes: ok"); + return 0; +}