diff --git a/CMakeLists.txt b/CMakeLists.txt index f64675faeb..afe9f56a4b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -881,6 +881,11 @@ target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) target_link_libraries(startup_stream_depth PRIVATE d3d12_xs_shim d3d12 dxgi) +# Depth target binding for translated draws (list slot 50, #1999 item D): depth values and debug-layer +# messages after the fence, and an unresolved depth handle. +add_executable(startup_draw_depth_target tests/startup_draw_depth_target.cpp $) +target_compile_features(startup_draw_depth_target PRIVATE cxx_std_17) +target_link_libraries(startup_draw_depth_target PRIVATE d3d12_xs_shim d3d12 dxgi) # Console queue Wait (slot 17) waits on the GPU instead of signalling the fence. add_executable(startup_queue_wait tests/startup_queue_wait.cpp) @@ -2588,6 +2593,15 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py" "$" "${backend}") set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # The drop control draws the bound case with an unresolved depth handle and must fail only its picture. + add_test(NAME startup_draw_depth_target_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_depth_target_check.py" + "$" "${backend}" check) + add_test(NAME startup_draw_depth_target_drop_control_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_draw_depth_target_check.py" + "$" "${backend}" drop) + set_tests_properties(startup_draw_depth_target_${backend} startup_draw_depth_target_drop_control_${backend} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(compiler IN ITEMS fxc dxc) add_test(NAME startup_mrt_${compiler}_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mrt_check.py" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e7cd7261b0..13386a8f38 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -63,6 +63,24 @@ error, and it leaves one query open at Close. `startup_list_queries_default_{war without the switch: the slots stay no-ops and it must report the untouched sentinel in the first word. `command_list_slot_names.h` still names 56 to 58 as the query methods by the plus-four rule. +## Depth target on translated draws + +List slot 50 (`OMSetRenderTargets`) passes a bound depth-stencil view to the desktop list in the same call +as the colour targets, and the translated pipeline takes its `DSVFormat` from that view. A depth handle that +holds 0 maps to no descriptor: the colour targets are bound without depth, and the stand-in logs it and +counts it in `x2w_d3d12_render_target_stats`. A depth handle in no descriptor heap, or one that is not a +depth-stencil view, refuses the whole bind (also logged and counted), so nothing is drawn onto targets the +title did not ask for. `ctest --preset release --no-tests=error -R "^startup_draw_depth_target_" -V` draws a +near and a far triangle with a depth-tested stream pipeline and reads back the colour and the D32 depth +values after the fence. With the view bound, the near triangle wins, depth is 0.25 where drawn, and the +debug layer reports no message. With a zero handle, the far triangle overwrites and depth keeps its clear +value. With an unknown handle, nothing is drawn. Each unresolved handle is counted once. The `_drop_control` +draws the bound case with a zero handle and passes only when the intended colour and depth mismatch appears. + +Mesh pipelines reach the stand-in only as native desktop-bytecode streams, which must have a pixel stage +and no depth format. A depth-only mesh pass (no colour target, no pixel stage) is therefore refused when +the pipeline is created, and no fixture binds a depth target for one. + ## Default viewport and scissor A desktop command list that never sets a viewport or scissor rectangle draws no pixel. A translated diff --git a/tests/startup_draw_depth_target.cpp b/tests/startup_draw_depth_target.cpp new file mode 100644 index 0000000000..a80e285702 --- /dev/null +++ b/tests/startup_draw_depth_target.cpp @@ -0,0 +1,324 @@ +// Depth target binding for translated draws (#1999 item D). A depth-tested stream pipeline (LESS, writes on) +// draws a near green triangle (z 0.25) and then a far red one (z 0.75) through the stand-in, with the colour +// target and a D32 depth target bound by list slot 50 (OMSetRenderTargets). The colour target and the depth +// values are read back after the fence. Source-built: the shaders come from tests/startup_draw_depth_target_check.py. +// +// Cases, one per process so each run's debug-layer messages belong to it: +// request create the pipelines only (publishes the translation requests) +// bound the depth handle resolves: green in front, depth 0.25 where drawn, 1.0 elsewhere +// null the depth handle holds 0, which maps to no descriptor: the stand-in binds the colour target +// without depth (logged, counted once), so red overwrites green and the depth target keeps 1.0 +// unknown the depth handle is in no descriptor heap: the stand-in refuses the whole bind (logged, +// counted once), so nothing is drawn +// drop the bound case's draw with the null handle, for the negative control +// After the read-back an empty list is executed, so the stand-in drains the debug-layer messages of the case. +// Prints "binds +, unresolved +" (x2w_d3d12_render_target_stats before and after the draw). +// +// usage: startup_draw_depth_target +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stream_setup.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_render_target_stats(unsigned* binds, unsigned* unresolved); + +namespace { + +struct alignas(8) StageSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_SHADER_BYTECODE shader; +}; +struct alignas(8) RootSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + ID3D12RootSignature* signature; +}; +struct alignas(8) DepthStencilSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_DEPTH_STENCIL_DESC desc; +}; +struct alignas(8) DsvFormatSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + DXGI_FORMAT format; +}; +struct DepthStream { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; + DepthStencilSubobject ds; + DsvFormatSubobject dsv_format; +}; + +using Word = std::uint64_t; +template Word ptr_arg(T* p) { return reinterpret_cast(p); } +constexpr UINT width = 8, height = 4; + +bool read_bytes(const char* path, std::vector& out) +{ + std::ifstream file(path, std::ios::binary); + out.assign(std::istreambuf_iterator(file), {}); + return !out.empty(); +} + +int pick_adapter(bool hardware, ComPtr& adapter) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, const std::vector& ps) +{ + D3D12_DEPTH_STENCIL_DESC less{}; + less.DepthEnable = TRUE; + less.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + less.DepthFunc = D3D12_COMPARISON_FUNC_LESS; + less.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + less.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + less.FrontFace = less.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + DepthStream stream{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, less}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_D32_FLOAT}, + }; + using CreateStream = HRESULT (WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + auto create = reinterpret_cast((*static_cast(device))[86]); + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + void* pso = nullptr; + return SUCCEEDED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso)) ? pso : nullptr; +} + +// Runs `record` on a desktop direct list and waits for it. +template int submit_desktop(ID3D12Device* desktop, Record record) +{ + D3D12_COMMAND_QUEUE_DESC qd{}; + ComPtr queue; + ComPtr alloc; + ComPtr list; + ComPtr fence; + if (FAILED(desktop->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.Get(), nullptr, IID_PPV_ARGS(&list))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 41; + record(list.Get()); + if (FAILED(list->Close())) return 42; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 43; + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!ev) return 44; + const bool ok = SUCCEEDED(fence->SetEventOnCompletion(1, ev)) && WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0; + CloseHandle(ev); + return ok ? 0 : 45; +} + +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* tex, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); +} + +// Clears the depth target to 1 on the desktop device, leaving it in COMMON. +int clear_depth(ID3D12Device* desktop, ID3D12Resource* tex) +{ + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + ComPtr heap; + if (FAILED(desktop->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))) return 40; + const D3D12_DEPTH_STENCIL_VIEW_DESC view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap->GetCPUDescriptorHandleForHeapStart(); + desktop->CreateDepthStencilView(tex, &view, handle); + return submit_desktop(desktop, [&](ID3D12GraphicsCommandList* list) { + transition(list, tex, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE); + list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); + transition(list, tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COMMON); + }); +} + +// Writes the D32 depth values, row by row, to `path`. +int read_depth(ID3D12Device* desktop, ID3D12Resource* tex, const std::string& path) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + const auto desc = tex->GetDesc(); + desktop->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + ComPtr readback; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))) return 46; + if (const int rc = submit_desktop(desktop, [&](ID3D12GraphicsCommandList* list) { + transition(list, tex, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION destination{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + destination.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION source{tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr); + transition(list, tex, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + })) return rc; + void* memory = nullptr; + if (FAILED(readback->Map(0, nullptr, &memory))) return 47; + std::ofstream out(path, std::ios::binary); + for (UINT y = 0; y < height; ++y) + out.write(static_cast(memory) + footprint.Footprint.RowPitch * y, width * sizeof(float)); + readback->Unmap(0, nullptr); + return out ? 0 : 48; +} + +int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) +{ + if (FAILED(static_cast(invoke(list, 9)))) return 50; + void* lists[] = {list}; + invoke(queue, 10, 1, ptr_arg(lists)); + if (FAILED(static_cast(invoke(queue, 14, ptr_arg(fence), fence_value)))) return 51; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) >= fence_value ? 0 : 53; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 9) { + std::puts("usage: startup_draw_depth_target " + " "); + return 2; + } + const std::string which = argv[7]; + if (which != "request" && which != "bound" && which != "null" && which != "unknown" && which != "drop") return 2; + std::vector vs_front, vs_back, ps_green, ps_red; + if (!read_bytes(argv[1], vs_front) || !read_bytes(argv[2], vs_back) || !read_bytes(argv[3], ps_green) || !read_bytes(argv[4], ps_red)) + return 3; + const bool hardware = std::strcmp(argv[6], "hardware") == 0; + const std::string prefix = argv[8]; + + ComPtr adapter; + if (const int rc = pick_adapter(hardware, adapter)) return rc; + { + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&desc))) return 4; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls vendor=%04x device=%04x driver=%u.%u.%u.%u\n", desc.Description, desc.VendorId, desc.DeviceId, + HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + std::fflush(stdout); + } + std::array parameters{}; + void* guest = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &guest))) return 5; + + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 6; + std::ofstream(argv[5], std::ios::binary).write(static_cast(blob->GetBufferPointer()), blob->GetBufferSize()); + ID3D12RootSignature* root = nullptr; + if (FAILED(static_cast(invoke(guest, 16, 0, ptr_arg(blob->GetBufferPointer()), blob->GetBufferSize(), + ptr_arg(&__uuidof(ID3D12RootSignature)), ptr_arg(&root))))) return 7; + void* green = create_stream_pso(guest, root, vs_front, ps_green); + void* red = create_stream_pso(guest, root, vs_back, ps_red); + if (!green || !red) return 9; + if (which == "request") return 0; + + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + StreamTarget state{}; + state.count = 1; + state.attachments[0].row_bytes = width * 4; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const float clear_color[] = {0.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_RESOURCE_DESC rtv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 1.0f, 1.0f}}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rtv_tex_desc, D3D12_RESOURCE_STATE_COMMON, &rtv_clear, + IID_PPV_ARGS(&state.attachments[0].texture)))) return 21; + ComPtr depth_tex; + const D3D12_RESOURCE_DESC depth_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + D3D12_CLEAR_VALUE depth_clear{}; + depth_clear.Format = DXGI_FORMAT_D32_FLOAT; + depth_clear.DepthStencil = {1.0f, 0}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &depth_desc, D3D12_RESOURCE_STATE_COMMON, &depth_clear, + IID_PPV_ARGS(&depth_tex)))) return 21; + + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } + rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}, dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}, 0, 0}; + void* dsv_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap)))) || + FAILED(static_cast(invoke(guest, 14, ptr_arg(&dsv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&dsv_heap))))) + return 22; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(state.rtv_heap, 9))}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv{static_cast(invoke(dsv_heap, 9))}; + // A zero handle maps to no descriptor; an address in no descriptor heap is not a known view. + static const unsigned char not_a_heap[64] = {}; + const D3D12_CPU_DESCRIPTOR_HANDLE null_handle{0}, unknown_handle{reinterpret_cast(not_a_heap)}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_view{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(guest, 8, ptr_arg(&qd), ptr_arg(&__uuidof(ID3D12CommandQueue)), ptr_arg(&state.queue)))) || + FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, ptr_arg(&__uuidof(ID3D12CommandAllocator)), ptr_arg(&state.allocator)))) || + FAILED(static_cast(invoke(guest, 73, ptr_arg(list_desc), ptr_arg(state.allocator), 0, ptr_arg(&__uuidof(ID3D12GraphicsCommandList)), ptr_arg(&state.list)))) || + FAILED(static_cast(invoke(guest, 36, 0, 0, ptr_arg(&__uuidof(ID3D12Fence)), ptr_arg(&state.fence))))) + return 23; + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT rect{0, 0, 4, static_cast(height)}; + + if (const int rc = clear_depth(desktop.Get(), depth_tex.Get())) return rc; + unsigned binds_before = 0, unresolved_before = 0, binds_after = 0, unresolved_after = 0; + x2w_d3d12_render_target_stats(&binds_before, &unresolved_before); + if (FAILED(static_cast(invoke(state.allocator, 8)))) return 24; + if (FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; + invoke(state.list, 52, rtv.ptr, ptr_arg(clear_color)); + invoke(state.list, 21, 1, ptr_arg(&viewport)); + invoke(state.list, 22, 1, ptr_arg(&rect)); + invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_CPU_DESCRIPTOR_HANDLE* depth_handle = which == "bound" ? &dsv : which == "unknown" ? &unknown_handle : &null_handle; + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, ptr_arg(depth_handle)); + invoke(state.list, 25, ptr_arg(green)); + invoke(state.list, 12, 3, 1); + invoke(state.list, 25, ptr_arg(red)); + invoke(state.list, 12, 3, 1); + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, 1)) return rc; + x2w_d3d12_render_target_stats(&binds_after, &unresolved_after); + if (const int rc = read_stream_target(desktop.Get(), state, (prefix + ".rgba").c_str())) return rc; + if (const int rc = read_depth(desktop.Get(), depth_tex.Get(), prefix + ".depth")) return rc; + // An empty list after the fence: executing it drains the debug-layer messages stored so far. + if (FAILED(static_cast(invoke(state.allocator, 8))) || FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) + return 26; + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, 2)) return rc; + std::printf("binds +%u, unresolved +%u\n", binds_after - binds_before, unresolved_after - unresolved_before); + return 0; +} diff --git a/tests/startup_draw_depth_target_check.py b/tests/startup_draw_depth_target_check.py new file mode 100644 index 0000000000..72f455119b --- /dev/null +++ b/tests/startup_draw_depth_target_check.py @@ -0,0 +1,165 @@ +"""Depth target binding for translated draws (#1999 item D). + +usage: startup_draw_depth_target_check.py [check|drop] +Exit codes: 0 pass, 1 unexpected result, 2 broken run, 77 no hardware. + +tests/startup_draw_depth_target.cpp draws a near green triangle (z 0.25), then a far red one (z 0.75), with a +depth-tested stream pipeline (LESS, writes on), and reads back the colour target and the D32 depth target. + +"check" (the default) runs three cases, each in its own process: + bound the depth handle resolves: green in front, depth 0.25 in the drawn half and 1.0 elsewhere, + one bind and nothing unresolved, and no debug-layer message of any severity after the fence + (when the debug layer is installed; otherwise the script says the message check did not run) + null the depth handle holds 0, which maps to no descriptor: the stand-in logs it and counts it once + and binds the colour target without depth, so red overwrites green and the depth target keeps 1.0 + unknown the depth handle is in no descriptor heap: the stand-in logs it, counts it once and refuses the + whole bind, so nothing is drawn (the colour target keeps its clear colour, depth keeps 1.0) + +"drop" is the negative control: the bound case's draw with the null handle, checked against the +bound case's expectations. The control passes only when the expected mismatch appears (red in front, +depth untouched, and one colour target bind). A broken run or an unexpected picture fails CTest. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_depth_check import vertex +from startup_stream_draw_check import pixel + +GREEN, RED, CLEAR = bytes((0, 255, 0, 255)), bytes((255, 0, 0, 255)), bytes((0, 0, 255, 255)) + + +def target(color): + return (color * 4 + CLEAR * 4) * 4 + + +def depth(drawn): + return (struct.pack("<4f", *[drawn] * 4) + struct.pack("<4f", *[1.0] * 4)) * 4 + + +BOUND = (target(GREEN), depth(0.25)) +UNBOUND = (target(RED), depth(1.0)) +REFUSED = (CLEAR * 32, depth(1.0)) +NO_DEPTH_LOG = "maps to no descriptor; binding no depth" +REFUSED_LOG = "OMSetRenderTargets refused: depth handle is not a known depth stencil view" + + +class Broken(Exception): + pass + + +def prepare(directory, program, backend): + cache = directory / "cache" + cache.mkdir(parents=True) + paths = [directory / name for name in ("vs_front", "vs_back", "ps_green", "ps_red", "root")] + paths[0].write_bytes(vertex(0x3e800000)) # z = 0.25f + paths[1].write_bytes(vertex(0x3f400000)) # z = 0.75f + paths[2].write_bytes(pixel(True)) + paths[3].write_bytes(pixel(False)) + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_D3D12_DEBUG="1", + X2W_SHADER_CACHE=str(cache)) + args = [program, *map(str, paths), backend] + request = subprocess.run(args + ["request", str(directory / "request")], env=env, capture_output=True, text=True) + if backend == "hardware" and request.returncode == 77: + return None + if request.returncode: + raise Broken(f"request run failed on {backend}: {request.returncode}\n{request.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + return args, env + + +def run_case(directory, args, env, case): + out = directory / case + run = subprocess.run(args + [case, str(out)], env=env, capture_output=True, text=True) + print(f"[{case}] " + run.stdout.strip().replace("\n", f"\n[{case}] ")) + debug = [line for line in run.stderr.splitlines() if "x2w-d3d12-debug " in line] + for line in run.stderr.splitlines(): + if "x2w-d3d12-debug " in line or "OMSetRenderTargets" in line or "translator error" in line: + print(f"[{case}] {line}") + if run.returncode or (case != "unknown" and "-> drawn;" not in run.stderr): + raise Broken(f"{case} run failed: {run.returncode}\n{run.stderr}") + counts = re.search(r"binds \+(\d+), unresolved \+(\d+)", run.stdout) + if not counts: + raise Broken(f"{case}: no counter line\n{run.stdout}") + return { + "colour": Path(f"{out}.rgba").read_bytes(), + "depth": Path(f"{out}.depth").read_bytes(), + "binds": int(counts[1]), + "unresolved": int(counts[2]), + "logged": NO_DEPTH_LOG in run.stderr, + "refused": REFUSED_LOG in run.stderr, + "debug": debug, + "debug_layer": "x2w-d3d12 debug layer: 0x00000000 enabled" in run.stderr, + } + + +def describe(result): + values = struct.unpack("<32f", result["depth"]) + return f"colour {result['colour'][:16].hex()}..., depth row 0 {values[:8]}" + + +def main(): + program, backend = sys.argv[1], sys.argv[2] + mode = sys.argv[3] if len(sys.argv) > 3 else "check" + if mode not in ("check", "drop"): + print(__doc__) + return 64 + try: + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + prepared = prepare(directory, program, backend) + if prepared is None: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + args, env = prepared + if mode == "drop": + result = run_case(directory, args, env, "drop") + failures = [] + if (result["colour"], result["depth"]) != BOUND: + failures.append("picture") + stated = failures == ["picture"] and (result["colour"], result["depth"]) == UNBOUND and result["binds"] == 1 + print(f"control drop: {describe(result)} -> " + + ("failed for the stated reason" if stated else "did NOT fail for the stated reason")) + return 0 if stated else 1 + failed = [] + bound = run_case(directory, args, env, "bound") + if (bound["colour"], bound["depth"]) != BOUND: + failed.append(f"bound: {describe(bound)}") + if bound["binds"] != 1 or bound["unresolved"] or bound["logged"]: + failed.append(f"bound: binds +{bound['binds']}, unresolved +{bound['unresolved']}, logged {bound['logged']}") + if bound["debug"]: + failed.append(f"bound: {len(bound['debug'])} debug-layer message(s)") + debug_note = ("no debug-layer message" if bound["debug_layer"] + else "debug layer NOT available, so the message check did not run") + if not bound["debug_layer"]: + print("note: the D3D12 debug layer is not installed; the debug-message check did not run") + null = run_case(directory, args, env, "null") + if (null["colour"], null["depth"]) != UNBOUND: + failed.append(f"null: {describe(null)}") + if null["binds"] != 1 or null["unresolved"] != 1 or not null["logged"]: + failed.append(f"null: binds +{null['binds']}, unresolved +{null['unresolved']}, logged {null['logged']}") + unknown = run_case(directory, args, env, "unknown") + if (unknown["colour"], unknown["depth"]) != REFUSED: + failed.append(f"unknown: {describe(unknown)}") + if unknown["binds"] or unknown["unresolved"] != 1 or not unknown["refused"]: + failed.append(f"unknown: binds +{unknown['binds']}, unresolved +{unknown['unresolved']}, refused {unknown['refused']}") + except (Broken, OSError, subprocess.CalledProcessError) as error: + # A broken run cannot count as seeing the expected mismatch. + print(f"error: {error}") + return 2 + for line in failed: + print("FAIL", line) + if failed: + return 1 + print(f"{backend}: bound depth target occluded red with depth 0.25 and {debug_note}; a zero depth " + "handle bound the colour target without depth; an unknown one refused the bind; each logged and counted once") + return 0 + + +if __name__ == "__main__": + sys.exit(main())