diff --git a/CMakeLists.txt b/CMakeLists.txt index 17aa9d3505..4d5a48e2a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -940,6 +940,10 @@ 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) +# X2W_DEPTH_STATE draw fixture (#1999, item A): slot 57 pipelines with depth-stencil register words. +add_executable(startup_slot57_depth tests/startup_slot57_depth.cpp $) +target_compile_features(startup_slot57_depth PRIVATE cxx_std_17) +target_link_libraries(startup_slot57_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 $) @@ -1425,6 +1429,13 @@ target_compile_features(startup_pipeline_state_check PRIVATE cxx_std_17) add_test(NAME startup_pipeline_state COMMAND startup_pipeline_state_check) add_test(NAME startup_pipeline_state_offset_control COMMAND startup_pipeline_state_check --mutate offset) set_tests_properties(startup_pipeline_state_offset_control PROPERTIES WILL_FAIL TRUE) +# X2W_DEPTH_STATE (src/startup_stubs/depth_state_apply.h): off takes nothing from the block, on takes a decodable one. +add_executable(startup_depth_state_check tests/startup_depth_state_check.cpp) +target_include_directories(startup_depth_state_check PRIVATE src) +target_compile_features(startup_depth_state_check PRIVATE cxx_std_17) +add_test(NAME startup_depth_state COMMAND startup_depth_state_check) +add_test(NAME startup_depth_state_switch_control COMMAND startup_depth_state_check --mutate switch) +set_tests_properties(startup_depth_state_switch_control PROPERTIES WILL_FAIL TRUE) # Root table handles resolved against a logical view heap, and the records a translated draw reads # from the window (src/startup_stubs/logical_view_table.h). add_executable(startup_logical_view_table_check tests/startup_logical_view_table_check.cpp) @@ -2668,6 +2679,10 @@ 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) + add_test(NAME startup_slot57_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot57_depth_check.py" + "$" "${backend}") + set_tests_properties(startup_slot57_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" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9fe8f5f497..458ad4bc77 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -864,6 +864,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}` and, when needed, RTV variants `req_.rtv`. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | +| `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_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). | @@ -1597,7 +1598,8 @@ These are measured on one executable; treat them as hypotheses for others. reason of each refusal. Its `_dest_alpha_control` run, which expects a destination alpha factor in its colour form, is the negative control (`ctest --preset dev --no-tests=error -R "^startup_cb_blend_decode" -V`). -- Depth-stencil registers are decoded but not applied yet (#1999, item A). State block A of a +- Depth-stencil registers are decoded, and applied only with `X2W_DEPTH_STATE=1` (#1999, item A; + see the next bullet). State block A of a slot 57 pipeline holds `DB_DEPTH_CONTROL` at +0xB8, `DB_STENCIL_CONTROL` at +0xBC and `DB_STENCILREFMASK` / `_BF` at +0xC0 / +0xC4, measured locally. Other pipeline layouts are not covered. `src/startup_stubs/pipeline_state_decode.h` @@ -1609,6 +1611,37 @@ These are measured on one executable; treat them as hypotheses for others. each compare function and each stencil op with a D3D12 form, the refusals and a synthetic block. Its `_offset_control` run (words one word later) is the negative control (`ctest --preset dev --no-tests=error -R "^startup_pipeline_state" -V`). +- `X2W_DEPTH_STATE=1` (off by default) takes that decoded state for translated draws of slot 57 + pipelines (`src/startup_stubs/depth_state_apply.h`, applied in `translation_for` in + `d3d12_draw.inl`). A slot 57 pipeline has no desktop `DEPTH_STENCIL` subobject, so there is no + desktop state to outrank; a state found first is kept regardless. When the decoder refuses the + words, or the block is too short, the pipeline keeps the desktop default (depth and stencil off) + and one line says why (`depth-stencil registers not used (...)`). The decoded state needs a depth + view: a draw with none bound keeps the desktop default. The stencil reference is list state in + D3D12, so each draw of such a pipeline with an enabled stencil test calls `OMSetStencilRef` with + the decoded value for that draw and restores the guest's list reference immediately after it. + A successful list reset restores the default reference of zero. The mixed-pipeline test sets a + distinct guest reference before the slot 57 draw, then checks a desktop-state stencil draw on + the same list without another reference call. The pipeline key includes the + decoded description. With the switch off nothing reads the words: no description, key or + reference changes, and no log line appears. That is checked device-free + (`startup_depth_state`, with `startup_depth_state_switch_control` as the negative control) and by + the draw fixture's switch-off run, and the existing `startup_stream_depth_*` and + `startup_slot57_blend_draw_*` tests, which run without the switch, still pass. + `tests/startup_slot57_depth.cpp` and `tests/startup_slot57_depth_check.py` draw two overlapping + triangles of unequal depth (z 0.25 and 0.75, same synthetic shaders and vertex program) into an + 8x4 target with a D24S8 view, with the same renderer on WARP and on a hardware adapter. With + reversed-Z words (GREATER, depth cleared to 0) the nearer triangle wins (red); with the switch off + the last-drawn triangle wins (green); with LESS, the wrong direction for that clear, nothing + passes (blue); a forward-Z LESS case reverses the draw order and shows green with the switch on, + red with it off. Stencil is checked separately: EQUAL against a stored 0x5A passes with reference + 0x5A and fails with 0x5B (the list's own reference is 0, so only the decoded one explains it), and + REPLACE 7 followed by EQUAL 7 or EQUAL 8 leaves green or red. Words with a colour-write tie or a + stencil `ONES` op fall back to the desktop result. Measured on WARP (10.0.26100.9818) and an + NVIDIA GeForce RTX 3080 (driver 32.0.16.2124), Windows 11 10.0.26200 + (`ctest --preset dev --no-tests=error -R "^startup_(depth_state|slot57_depth)" -V`). Not covered: + raster bias, depth bounds, back-face-only state, the title's own `OMSetStencilRef` order, clears + (#1806), and any pipeline layout other than the measured one. - Audio produces no output from the console audio path. A separate desktop render sink exists (see "Audio output"); nothing connects the console path to it yet. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 63702a7c64..4165e93774 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -34,6 +34,9 @@ struct BoundPipeline { D3D12_BLEND_DESC blend{}; bool has_depth_stencil = false; D3D12_DEPTH_STENCIL_DESC depth_stencil{}; + bool depth_from_registers = false; // X2W_DEPTH_STATE: depth_stencil was decoded from state block A (slot 57) + bool has_stencil_ref = false; // ... and its stencil test is on: stencil_ref goes on the list with each draw + std::uint8_t stencil_ref = 0; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map pipelines; // by target formats }; @@ -389,6 +392,29 @@ BoundPipeline* translation_for(Wrapper* pipeline) } bound->dsv_format = info->stream_dsv_format; } + // X2W_DEPTH_STATE=1 (#1999, item A): the depth-stencil registers of a slot 57 pipeline's state block A. A slot 57 + // pipeline has no desktop DEPTH_STENCIL subobject, so has_depth_stencil can only be set here; the test keeps any + // desktop state that was found first. A block the decoder refuses leaves the desktop default (depth and stencil off). + if (info && info->path == 57 && !bound->has_depth_stencil && x2w_local::env_on("X2W_DEPTH_STATE")) { + const auto chosen = x2w_pipeline_state::select_depth_stencil(true, info->state_a.data(), info->state_a.size()); + static LONG logged_applied, logged_refused; + if (chosen.applied) { + bound->depth_stencil = chosen.desc; + bound->has_depth_stencil = bound->depth_from_registers = true; + bound->has_stencil_ref = chosen.has_stencil_ref; + bound->stencil_ref = chosen.stencil_ref; + } + if (first_calls(chosen.applied ? logged_applied : logged_refused, 24)) { + if (chosen.applied) + log("x2w-draw pipeline %p: depth-stencil from state block A: depth %d func %d write %d, stencil %d reference 0x%x%s%s", + static_cast(pipeline), chosen.desc.DepthEnable, chosen.desc.DepthFunc, chosen.desc.DepthWriteMask, + chosen.desc.StencilEnable, chosen.stencil_ref, chosen.depth_bounds ? "; depth bounds not applied" : "", + chosen.masks_differ ? "; back-face masks or reference differ, front used" : ""); + else + log("x2w-draw pipeline %p: depth-stencil registers not used (%s); keeping the desktop state", static_cast(pipeline), + chosen.reason); + } + } if (info && info->path == 57 && info->desc.size() >= 0x60) { u64 words[12]; std::memcpy(words, info->desc.data(), sizeof(words)); @@ -461,13 +487,21 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) return entry; } +// The depth format a translated draw uses: the pass's own view, else the one the pipeline was created with. +inline DXGI_FORMAT pass_dsv_format(const BoundPipeline& bound, const Pass& pass) +{ + return pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; +} + ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const Pass& pass) { - const DXGI_FORMAT dsv_format = pass.dsv_format != DXGI_FORMAT_UNKNOWN ? pass.dsv_format : bound.dsv_format; + const DXGI_FORMAT dsv_format = pass_dsv_format(bound, pass); u64 key = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) key = key * 131 + static_cast(pass.target_formats[i]); key = fnv_bytes(&dsv_format, sizeof(dsv_format), key); - if (bound.has_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); + // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. + const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); + if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; @@ -486,7 +520,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P bound.pipelines[key] = nullptr; return nullptr; } - if (bound.has_depth_stencil) desc.DepthStencilState = bound.depth_stencil; + if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; @@ -1161,6 +1195,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } list->SetPipelineState(pipeline); + // X2W_DEPTH_STATE: the reference of the decoded stencil test is list state in D3D12. It replaces the one a + // preceding OMSetStencilRef set, for draws of this pipeline only when a depth view is bound. + const bool scoped_stencil_ref = bound->depth_from_registers && bound->has_stencil_ref && + pass_dsv_format(*bound, pass) != DXGI_FORMAT_UNKNOWN && + bound->stencil_ref != pass.stencil_reference; + if (scoped_stencil_ref) list->OMSetStencilRef(bound->stencil_ref); list->SetGraphicsRootSignature(tr->root); ID3D12DescriptorHeap* samplers = tr->samplers.heap ? pass.sampler_heap.Get() : nullptr; if (!pass.heap_set || pass.bound_sampler_heap != samplers) { @@ -1188,6 +1228,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI list->DrawInstanced(rect ? count / 3 * 6 : count, instances ? instances : 1, 0, start_instance); drawn = true; } + if (scoped_stencil_ref) list->OMSetStencilRef(pass.stencil_reference); if (drawn) draw_dump_after(self, list, tr->key, count); ReleaseSRWLockExclusive(&draw_lock); if (first_calls(tr->logged_draws, 10) || (count > 100 && first_calls(tr->logged_large, 12))) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index df3043b73e..0411cf699b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -20,6 +20,7 @@ #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/translated_sampler_bindings.h" #include "startup_stubs/export_write_mask.h" +#include "startup_stubs/depth_state_apply.h" #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/bc7_4k_s.h" #include "startup_stubs/bc64_chain.h" @@ -1070,7 +1071,7 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec // Everything else on a list is still dropped. void release_targets(Wrapper* self); void end_open_queries(Wrapper* self, ID3D12GraphicsCommandList* list); -void reset_viewport_state(Wrapper* self); +void reset_list_dynamic_state(Wrapper* self); void discard_draw_sampler_heaps(ID3D12CommandList* list); void use_as_target(Wrapper* self, ID3D12Resource* resource); bool is_container(const void* p); @@ -1348,7 +1349,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) } ReleaseSRWLockExclusive(&allocator_lock); if (SUCCEEDED(hr)) { - reset_viewport_state(self); + reset_list_dynamic_state(self); discard_draw_sampler_heaps(previous); if (draw_dump_frame()) draw_dumps().discard(previous); } @@ -1884,6 +1885,7 @@ struct Pass { D3D12_INDEX_BUFFER_VIEW ib = {}; DXGI_FORMAT target_formats[8] = {}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + UINT stencil_reference = 0; // last guest OMSetStencilRef on this recording UINT target_count = 0; ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) bool heap_set = false; @@ -1949,10 +1951,11 @@ void release_targets(Wrapper* self) pass = Pass{}; } -// A reset list starts without a viewport or scissor, whatever the previous recording set. -void reset_viewport_state(Wrapper* self) +// A reset list has no viewport or scissor and uses the default stencil reference. +void reset_list_dynamic_state(Wrapper* self) { if (!self->own().pass) return; + pass_of(self).stencil_reference = 0; pass_of(self).viewport_set = false; pass_of(self).scissor_set = false; pass_of(self).default_viewport_w = pass_of(self).default_scissor_w = 0; @@ -2450,7 +2453,10 @@ void __stdcall list_blend_factor(Wrapper* self, const float* factor) // List slot 24, OMSetStencilRef(reference): list state that the stencil test of the next draws compares against. void __stdcall list_stencil_ref(Wrapper* self, UINT reference) { - if (auto* list = recording(self)) list->OMSetStencilRef(reference); + if (auto* list = recording(self)) { + pass_of(self).stencil_reference = reference; + list->OMSetStencilRef(reference); + } } // List slot 44 (desktop 40 + 4), SetGraphicsRootShaderResourceView(parameter, title GPU address). void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) diff --git a/src/startup_stubs/depth_state_apply.h b/src/startup_stubs/depth_state_apply.h new file mode 100644 index 0000000000..b806b1e4aa --- /dev/null +++ b/src/startup_stubs/depth_state_apply.h @@ -0,0 +1,45 @@ +// Experimental (docs/startup-runtime.md): the decision behind X2W_DEPTH_STATE (#1999, item A). +// +// With the switch on, a pipeline created through device slot 57 takes its depth-stencil state from the +// register words of its state block A (pipeline_state_decode.h). With the switch off, or when the block +// is too short or the decoder refuses it, nothing is taken and the caller keeps the state it had before +// (the desktop default: depth and stencil off, no reference). Pure, so it can be checked without a device. +#pragma once + +#include "startup_stubs/pipeline_state_decode.h" + +namespace x2w_pipeline_state { + +struct AppliedDepthStencil { + bool applied = false; // desc / stencil_ref / has_stencil_ref are valid and replace the desktop state + const char* reason = nullptr; // why not, when the switch is on (null when it is off) + D3D12_DEPTH_STENCIL_DESC desc{}; + bool has_stencil_ref = false; // the stencil test is enabled: stencil_ref is the list state the draws need + std::uint8_t stencil_ref = 0; + bool depth_bounds = false, masks_differ = false; // decoder flags, reported by the caller +}; + +inline AppliedDepthStencil select_depth_stencil(bool switch_on, const unsigned char* block_a, std::size_t bytes) +{ + AppliedDepthStencil out; + if (!switch_on) return out; + DepthStencilWords words; + if (!read_depth_stencil_words(block_a, bytes, words)) { + out.reason = "state block A too short for the depth-stencil words"; + return out; + } + const DepthStencil decoded = decode_depth_stencil(words.depth, words.stencil, words.refmask, words.refmask_bf); + if (!decoded.ok) { + out.reason = decoded.reason; + return out; + } + out.applied = true; + out.desc = decoded.desc; + out.has_stencil_ref = decoded.desc.StencilEnable != FALSE; + out.stencil_ref = decoded.stencil_ref; + out.depth_bounds = decoded.depth_bounds; + out.masks_differ = decoded.masks_differ; + return out; +} + +} // namespace x2w_pipeline_state diff --git a/tests/startup_depth_state_check.cpp b/tests/startup_depth_state_check.cpp new file mode 100644 index 0000000000..d2571f1f20 --- /dev/null +++ b/tests/startup_depth_state_check.cpp @@ -0,0 +1,98 @@ +// Checks src/startup_stubs/depth_state_apply.h (X2W_DEPTH_STATE, #1999 item A) without a device: with the +// switch off the stand-in takes nothing from state block A, whatever the block holds, so the desktop state +// (depth and stencil off) and the pipeline key stay as they were; with it on, a decodable block is taken, +// a refused or short block is not, and the stencil reference is carried only for an enabled stencil test. +// +// --mutate switch: treats the switch as on in the "off" cases (the check must then fail). +#include "startup_stubs/depth_state_apply.h" + +#include +#include +#include + +namespace { +using namespace x2w_pipeline_state; +int failures, cases; +bool mutate_switch; + +void check(bool ok, const char* name) +{ + ++cases; + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +// A zeroed 0x200-byte state block A with the four depth-stencil words set. +std::vector block(std::uint32_t depth, std::uint32_t stencil, std::uint32_t refmask, std::uint32_t refmask_bf) +{ + std::vector a(0x200, 0); + auto put = [&](std::size_t off, std::uint32_t v) { std::memcpy(a.data() + off, &v, 4); }; + put(a_depth, depth); + put(a_stencil, stencil); + put(a_refmask, refmask); + put(a_refmask_bf, refmask_bf); + return a; +} + +// DB_DEPTH_CONTROL: Z_ENABLE [1], Z_WRITE_ENABLE [2], ZFUNC [6:4], STENCIL_ENABLE [0], STENCILFUNC [10:8] (Mesa gfx10.json). +constexpr std::uint32_t z_control(unsigned zfunc, bool write) { return 2u | (write ? 4u : 0u) | zfunc << 4 | 7u << 8 | 7u << 20; } +constexpr unsigned frag_greater = 4, frag_less = 1, frag_equal = 2; + +bool desc_is_zero(const D3D12_DEPTH_STENCIL_DESC& d) +{ + static const D3D12_DEPTH_STENCIL_DESC zero{}; + return std::memcmp(&d, &zero, sizeof(d)) == 0; +} + +void cases_all() +{ + const auto reversed = block(z_control(frag_greater, true), 0, 0, 0); + // Switch off: nothing applied, nothing reported, the result object is the empty default. + auto off = select_depth_stencil(mutate_switch, reversed.data(), reversed.size()); + check(!off.applied && !off.reason && !off.has_stencil_ref && desc_is_zero(off.desc), "switch off: reversed-Z block not taken"); + const auto refused = block(z_control(frag_greater, true) | 1u << 30, 0, 0, 0); + off = select_depth_stencil(mutate_switch, refused.data(), refused.size()); + check(!off.applied && !off.reason, "switch off: refused block not even decoded"); + off = select_depth_stencil(mutate_switch, nullptr, 0); + check(!off.applied && !off.reason, "switch off: no block"); + + // Switch on: reversed-Z taken, function and write mask as decoded. + auto on = select_depth_stencil(true, reversed.data(), reversed.size()); + check(on.applied && on.desc.DepthEnable && on.desc.DepthFunc == D3D12_COMPARISON_FUNC_GREATER && + on.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL && !on.has_stencil_ref, "switch on: GREATER with write"); + // The compare direction is not symmetric: LESS must decode to a different function. + const auto less = block(z_control(frag_less, true), 0, 0, 0); + on = select_depth_stencil(true, less.data(), less.size()); + check(on.applied && on.desc.DepthFunc == D3D12_COMPARISON_FUNC_LESS, "switch on: LESS differs from GREATER"); + // Stencil on: the reference is carried; with the stencil test off it is not (the word's reference is then unused). + const auto stencil = block(1u | frag_equal << 8 | 1u << 7 | frag_equal << 20, 0, 0x5a | 0xff << 8 | 0xff << 16 | 1u << 24, 0x5a | 0xff << 8 | 0xff << 16 | 1u << 24); + on = select_depth_stencil(true, stencil.data(), stencil.size()); + check(on.applied && on.has_stencil_ref && on.stencil_ref == 0x5a && on.desc.StencilEnable && + on.desc.FrontFace.StencilFunc == D3D12_COMPARISON_FUNC_EQUAL, "switch on: stencil reference carried"); + const auto no_stencil = block(z_control(frag_greater, false), 0, 0x5a, 0x5a); + on = select_depth_stencil(true, no_stencil.data(), no_stencil.size()); + check(on.applied && !on.has_stencil_ref && on.desc.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ZERO, "switch on: no reference without a stencil test"); + // Refusals keep the desktop state and say why. + on = select_depth_stencil(true, refused.data(), refused.size()); + check(!on.applied && on.reason && desc_is_zero(on.desc), "switch on: colour-write tie refused with a reason"); + on = select_depth_stencil(true, reversed.data(), a_refmask_bf + 3); + check(!on.applied && on.reason, "switch on: short block refused with a reason"); + on = select_depth_stencil(true, nullptr, 0x200); + check(!on.applied && on.reason, "switch on: no block refused with a reason"); +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "switch") == 0) { + mutate_switch = true; + } else if (argc > 1) { + std::printf("usage: startup_depth_state_check [--mutate switch]\n"); + return 2; + } + cases_all(); + std::printf("%d of %d checks failed\n", failures, cases); + return failures ? 1 : 0; +} diff --git a/tests/startup_slot57_depth.cpp b/tests/startup_slot57_depth.cpp new file mode 100644 index 0000000000..e25853ffe7 --- /dev/null +++ b/tests/startup_slot57_depth.cpp @@ -0,0 +1,345 @@ +// Draw fixture for X2W_DEPTH_STATE (#1999, item A): translated draws of device slot 57 pipelines whose state +// block A carries DB_DEPTH_CONTROL / DB_STENCIL_CONTROL / DB_STENCILREFMASK words. The same renderer runs on +// WARP and on hardware; tests/startup_slot57_depth_check.py runs it with the switch on and off and compares. +// +// usage: startup_slot57_depth [] +// +// vs_far / vs_near draw the same triangle at z = 0.25 / 0.75 (the check names them by their depth). Without +// out_dir the run only records the translation requests (the draws are skipped until the shaders are +// translated). With it, every case writes \.bin, the 8x4 RGBA8 target after its draws. +// +// Register layouts: Mesa src/amd/registers/gfx10.json (MIT), as pipeline_state_decode.h documents them. +#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**); + +namespace { +using Word = std::uint64_t; +template Word ptr_arg(T* p) { return reinterpret_cast(p); } + +// ---- register words ---- +constexpr std::uint32_t depth_control(bool stencil, bool z, bool z_write, unsigned zfunc, unsigned sfunc) +{ + return std::uint32_t{stencil} | std::uint32_t{z} << 1 | std::uint32_t{z_write} << 2 | (zfunc & 7) << 4 | (sfunc & 7) << 8 | + (sfunc & 7) << 20; +} +constexpr std::uint32_t stencil_ops(unsigned fail, unsigned zpass, unsigned zfail) +{ + return fail | zpass << 4 | zfail << 8 | fail << 12 | zpass << 16 | zfail << 20; +} +constexpr std::uint32_t ref_mask(unsigned test, unsigned mask, unsigned write) { return test | mask << 8 | write << 16 | 1u << 24; } +// CompareFrag +constexpr unsigned f_less = 1, f_equal = 2, f_greater = 4, f_always = 7; +// StencilOp +constexpr unsigned op_keep = 0, op_replace = 3, op_ones = 2; + +struct Words { std::uint32_t depth = 0, stencil = 0, refmask = 0, refmask_bf = 0; }; + +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; + } + } +} + +// A slot 57 description as the stand-in reads it (see tests/startup_stream_consumer.cpp): 64-bit words 0 (root +// signature), 1-2 (state block A and its size), 5-6 and 9-10 (the two shaders). +void* make_slot57(void* device, void* root, const std::vector& vs, const std::vector& ps, const Words& w) +{ + struct Block { alignas(8) unsigned char a[0x200]; alignas(8) unsigned char desc[0x60]; }; + static std::vector keep; // the stand-in copies both, but keep them for the process lifetime anyway + auto* b = new Block{}; + keep.push_back(b); + auto put = [&](std::size_t off, std::uint32_t v) { std::memcpy(b->a + off, &v, 4); }; + put(0x0b8, w.depth); + put(0x0bc, w.stencil); + put(0x0c0, w.refmask); + put(0x0c4, w.refmask_bf); + const Word words[12] = {ptr_arg(root), ptr_arg(b->a), sizeof(b->a), 0, 0, ptr_arg(vs.data()), vs.size(), 0, 0, + ptr_arg(ps.data()), ps.size(), 0}; + std::memcpy(b->desc, words, sizeof(words)); + using Create = HRESULT (WINAPI*)(void*, const void*, REFIID, void**); + void* pso = nullptr; + if (FAILED(reinterpret_cast((*static_cast(device))[57])(device, b->desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + return pso; +} + +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; +}; + +void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, const std::vector& ps) +{ + D3D12_DEPTH_STENCIL_DESC stencil{}; + stencil.DepthEnable = FALSE; + stencil.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + stencil.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + stencil.StencilEnable = TRUE; + stencil.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + stencil.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + stencil.FrontFace = stencil.BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_EQUAL}; + 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, stencil}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, DXGI_FORMAT_D24_UNORM_S8_UINT}, + }; + 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; +} + +int clear_depth_stencil(ID3D12Device* desktop, ID3D12Resource* tex, float depth, UINT8 stencil) +{ + 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_D24_UNORM_S8_UINT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_CPU_DESCRIPTOR_HANDLE handle = heap->GetCPUDescriptorHandleForHeapStart(); + desktop->CreateDepthStencilView(tex, &view, handle); + + 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; + + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {tex, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE}; + list->ResourceBarrier(1, &b); + list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, depth, stencil, 0, nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + list->ResourceBarrier(1, &b); + 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; +} + +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 != 7 && argc != 8) return 2; + std::vector vs_far, vs_near, ps_green, ps_red; + if (!read_bytes(argv[1], vs_far) || !read_bytes(argv[2], vs_near) || !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 out_dir = argc == 8 ? argv[7] : ""; + + 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; + + // ---- pipelines: (shader pair, register words) ---- + const Words none{}; // every word zero: depth and stencil off + const Words greater{depth_control(false, true, true, f_greater, f_always), 0, 0, 0}; // reversed-Z, written + const Words less{depth_control(false, true, true, f_less, f_always), 0, 0, 0}; // the other direction + Words tied = greater; + tied.depth |= 1u << 30; // ENABLE_COLOR_WRITES_ON_DEPTH_FAIL: refused + const Words st_equal_5a{depth_control(true, false, false, f_always, f_equal), stencil_ops(op_keep, op_keep, op_keep), ref_mask(0x5a, 0xff, 0), ref_mask(0x5a, 0xff, 0)}; + const Words st_equal_5b{depth_control(true, false, false, f_always, f_equal), stencil_ops(op_keep, op_keep, op_keep), ref_mask(0x5b, 0xff, 0), ref_mask(0x5b, 0xff, 0)}; + const Words st_replace_7{depth_control(true, false, false, f_always, f_always), stencil_ops(op_keep, op_replace, op_keep), ref_mask(0x07, 0xff, 0xff), ref_mask(0x07, 0xff, 0xff)}; + const Words st_equal_7{depth_control(true, false, false, f_always, f_equal), stencil_ops(op_keep, op_keep, op_keep), ref_mask(0x07, 0xff, 0), ref_mask(0x07, 0xff, 0)}; + const Words st_equal_8{depth_control(true, false, false, f_always, f_equal), stencil_ops(op_keep, op_keep, op_keep), ref_mask(0x08, 0xff, 0), ref_mask(0x08, 0xff, 0)}; + const Words st_ones{depth_control(true, false, false, f_always, f_equal), stencil_ops(op_ones, op_keep, op_keep), ref_mask(0x5b, 0xff, 0), ref_mask(0x5b, 0xff, 0)}; + + auto far_green = [&](const Words& w) { return make_slot57(guest, root, vs_far, ps_green, w); }; + auto near_red = [&](const Words& w) { return make_slot57(guest, root, vs_near, ps_red, w); }; + + struct Case { + const char* name; + float depth_clear; + UINT8 stencil_clear; + bool bind_depth; + std::vector draws; // in draw order + UINT guest_stencil_ref = 0; + }; + const std::vector cases = { + // Depth. The near triangle (z 0.75, red) is drawn first except in fz_less. + {"rz_greater", 0.0f, 0, true, {near_red(greater), far_green(greater)}}, // reversed-Z, cleared to 0: red wins + {"rz_less_wrong", 0.0f, 0, true, {near_red(less), far_green(less)}}, // wrong direction: nothing passes + {"fz_less", 1.0f, 0, true, {far_green(less), near_red(less)}}, // forward-Z, cleared to 1: green wins + {"rz_greater_no_dsv", 0.0f, 0, false, {near_red(greater), far_green(greater)}}, // no depth view: desktop default + {"rz_refused", 0.0f, 0, true, {near_red(tied), far_green(tied)}}, // refused words: desktop default + {"rz_none", 0.0f, 0, true, {near_red(none), far_green(none)}}, // zero words (depth off): same as the default + // Stencil. Depth off in all of them; the target is drawn in green or red over blue. + {"st_equal_hit", 1.0f, 0x5a, true, {far_green(st_equal_5a)}}, // stored 0x5A, reference 0x5A: drawn + {"st_equal_miss", 1.0f, 0x5a, true, {far_green(st_equal_5b)}}, // stored 0x5A, reference 0x5B: not drawn + {"st_replace_hit", 1.0f, 0, true, {near_red(st_replace_7), far_green(st_equal_7)}}, // REPLACE 7, then EQUAL 7: green + {"st_replace_miss", 1.0f, 0, true, {near_red(st_replace_7), far_green(st_equal_8)}}, // REPLACE 7, then EQUAL 8: red stays + {"st_ref_restore", 1.0f, 0x5a, true, + {near_red(st_equal_5b), create_stream_pso(guest, root, vs_far, ps_green)}, 0x5a}, + {"st_ref_reset", 1.0f, 0, true, + {near_red(st_equal_5b), create_stream_pso(guest, root, vs_far, ps_green)}}, + {"st_refused", 1.0f, 0x5a, true, {far_green(st_ones)}}, // ONES has no D3D12 form: desktop default, drawn + }; + for (const auto& c : cases) + for (void* pso : c.draws) if (!pso) return 9; + + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + constexpr UINT width = 8, height = 4; + 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; + const D3D12_RESOURCE_DESC dsv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_D24_UNORM_S8_UINT, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + + 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))}; + 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_D24_UNORM_S8_UINT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.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)}; + + UINT64 fence_value = 0; + for (const auto& c : cases) { + // A fresh depth-stencil texture per case, cleared on the desktop device with the case's values. + ComPtr depth_tex; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; + clear.DepthStencil = {c.depth_clear, c.stencil_clear}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &dsv_tex_desc, + D3D12_RESOURCE_STATE_COMMON, &clear, IID_PPV_ARGS(&depth_tex)))) return 21; + if (const int rc = clear_depth_stencil(desktop.Get(), depth_tex.Get(), c.depth_clear, c.stencil_clear)) return rc; + invoke(guest, 21, ptr_arg(depth_tex.Get()), ptr_arg(&dsv_view), dsv.ptr); + 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); + invoke(state.list, 50, 1, ptr_arg(&rtv), FALSE, c.bind_depth ? ptr_arg(&dsv) : 0); + if (c.guest_stencil_ref) invoke(state.list, 24, c.guest_stencil_ref); + for (void* pso : c.draws) { + invoke(state.list, 25, ptr_arg(pso)); + invoke(state.list, 12, 3, 1); + } + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, ++fence_value)) return rc; + const std::string path = out_dir.empty() ? std::string(argv[5]) + ".request" : out_dir + "\\" + c.name + ".bin"; + if (const int rc = read_stream_target(desktop.Get(), state, path.c_str())) return rc; + std::printf("case %s done\n", c.name); + } + return 0; +} diff --git a/tests/startup_slot57_depth_check.py b/tests/startup_slot57_depth_check.py new file mode 100644 index 0000000000..e268ff44f4 --- /dev/null +++ b/tests/startup_slot57_depth_check.py @@ -0,0 +1,140 @@ +"""Draw two overlapping triangles of unequal depth through device slot 57 pipelines whose state block A carries +depth-stencil register words, with X2W_DEPTH_STATE on and off, and compare every pixel with a known reference. + +usage: startup_slot57_depth_check.py + +The fixture (startup_slot57_depth.cpp) draws the same triangle twice, at z = 0.75 ("near", red) and z = 0.25 +("far", green), into an 8x4 target whose left half is covered. The depth-stencil texture is D24S8, cleared on the +desktop device. Expected winners (B = the blue background, nothing drawn): + + case words clear draw order switch on switch off + rz_greater reversed-Z, GREATER, write depth 0 near, far red green (last wins) + rz_less_wrong LESS (direction intentionally depth 0 near, far blue green + wrong for a depth cleared to 0) + fz_less LESS depth 1 far, near green red (last wins) + rz_greater_no_dsv GREATER, no depth view bound - near, far green green (state not applied) + rz_refused GREATER + colour-write tie depth 0 near, far green green (decoder refuses: desktop state) + rz_none all words zero depth 0 near, far green green + st_equal_hit EQUAL, reference 0x5A stencil 0x5A far green green + st_equal_miss EQUAL, reference 0x5B stencil 0x5A far blue green (reference reached the list) + st_replace_hit REPLACE 7, then EQUAL 7 stencil 0 near, far green green + st_replace_miss REPLACE 7, then EQUAL 8 stencil 0 near, far red green (REPLACE wrote 7, not the list default) + st_refused ONES op (no D3D12 form) stencil 0x5A far green green (decoder refuses: desktop state) + +The depth cases show the winner with reversed-Z, the other result with the switch off and with the compare +direction wrong; the stencil cases are separate and need the decoded reference (the list's own is 0). The same +executable renders on WARP and on hardware. Not covered: raster bias, depth bounds, back-face-only state, and the +title's clears (#1806). +""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import container, gfx2hlsl +from startup_stream_depth_check import vertex +from startup_stream_draw_check import pixel + +BLUE, GREEN, RED = (0, 0, 255, 255), (0, 255, 0, 255), (255, 0, 0, 255) +# case -> (switch on, switch off) +EXPECTED = { + "rz_greater": (RED, GREEN), + "rz_less_wrong": (BLUE, GREEN), + "fz_less": (GREEN, RED), + "rz_greater_no_dsv": (GREEN, GREEN), + "rz_refused": (GREEN, GREEN), + "rz_none": (GREEN, GREEN), + "st_equal_hit": (GREEN, GREEN), + "st_equal_miss": (BLUE, GREEN), + "st_replace_hit": (GREEN, GREEN), + "st_replace_miss": (RED, GREEN), + "st_ref_restore": (GREEN, GREEN), + "st_ref_reset": (GREEN, GREEN), + "st_refused": (GREEN, GREEN), +} +# Pipelines whose state block is taken (switch on), per case: log lines "depth-stencil from state block A". +REFUSED_PIPELINES = 3 # rz_refused: two pipelines, st_refused: one + + +def picture(path, name): + """The drawn colour of an 8x4 RGBA target; the right half must still be the background.""" + pixels = path.read_bytes() + assert len(pixels) == 8 * 4 * 4, f"{name}: {len(pixels)} bytes" + drawn = None + for y in range(4): + for x in range(8): + texel = tuple(pixels[(y * 8 + x) * 4:(y * 8 + x) * 4 + 4]) + if x >= 4: + assert texel == BLUE, f"{name}: background at ({x}, {y}) is {texel}" + elif drawn is None: + drawn = texel + else: + assert texel == drawn, f"{name}: ({x}, {y}) is {texel}, (0, 0) is {drawn}" + return drawn + + +def check(directory, exe, backend): + cache = directory / "cache" + cache.mkdir() + shaders = {name: directory / name for name in ("vs_far", "vs_near", "ps_green", "ps_red", "root")} + shaders["vs_far"].write_bytes(vertex(0x3e800000)) # z = 0.25f + shaders["vs_near"].write_bytes(vertex(0x3f400000)) # z = 0.75f + shaders["ps_green"].write_bytes(pixel(True)) + shaders["ps_red"].write_bytes(pixel(False)) + base_env = {k: v for k, v in os.environ.items() if k != "X2W_DEPTH_STATE"} + env = dict(base_env, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_D3D12_DEBUG="1", + X2W_SHADER_CACHE=str(cache)) + args = [exe, *(shaders[n] for n in ("vs_far", "vs_near", "ps_green", "ps_red", "root")), backend] + + request = subprocess.run(args, env=env, capture_output=True, text=True) + if backend == "hardware" and request.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if request.returncode: + raise RuntimeError(f"request run failed on {backend}: {request.returncode}\n{request.stdout}{request.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + + results = {} + for label, switch in (("off", None), ("on", "1")): + out = directory / label + out.mkdir() + run_env = dict(env) + if switch: + run_env["X2W_DEPTH_STATE"] = switch + run = subprocess.run(args + [str(out)], env=run_env, capture_output=True, text=True) + if run.returncode or "-> drawn;" not in run.stderr: + raise RuntimeError(f"switch {label}: draw failed on {backend}: {run.returncode}\n{run.stdout}{run.stderr}") + assert not re.search(r"x2w-d3d12-debug.*sev=[012]\b", run.stderr), run.stderr + if label == "off": + print(run.stdout.splitlines()[0]) + results[label] = ({case: picture(out / f"{case}.bin", f"{label} {case}") for case in EXPECTED}, run.stderr) + + names = {BLUE: "blue", GREEN: "green", RED: "red"} + for index, label in ((0, "on"), (1, "off")): + pictures, _ = results[label] + for case, expected in EXPECTED.items(): + assert pictures[case] == expected[index], ( + f"switch {label}, {case}: drew {names.get(pictures[case], pictures[case])}, expected {names[expected[index]]}") + # The two results differ wherever the table says they do, and nowhere else. + differing = sorted(case for case, (on, off) in EXPECTED.items() if on != off) + assert differing == ["fz_less", "rz_greater", "rz_less_wrong", "st_equal_miss", "st_replace_miss"], differing + + # Default behaviour: with the switch off the stand-in logs nothing about depth-stencil registers. + assert "depth-stencil from state block A" not in results["off"][1] and "registers not used" not in results["off"][1] + # Switch on: every decodable pipeline logs its state; every refusal is logged with the reason and keeps the desktop state. + log_on = results["on"][1] + refused = re.findall(r"depth-stencil registers not used \((.*?)\); keeping the desktop state", log_on) + assert len(refused) == REFUSED_PIPELINES, refused + assert sum("colour writes" in r for r in refused) == 2 and sum("stencil op" in r for r in refused) == 1, refused + assert "depth-stencil from state block A: depth 1 func 5 write 1" in log_on, "reversed-Z state not logged" # GREATER = 5 + + print(f"startup_slot57_depth: PASS on {backend}: switch on {len(EXPECTED)} cases as tabulated, " + f"{len(differing)} differ with the switch off ({', '.join(differing)}), {REFUSED_PIPELINES} refusals fall back to the desktop state") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:]))