diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d9886fdfc..a859516133 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4791,6 +4791,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_copied_vertex_srv_check.py" "$" "${backend}") set_tests_properties(startup_copied_vertex_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_table_alias_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_table_alias_check.py" + "$" "${backend}") + set_tests_properties(startup_table_alias_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_direct_index_late_write_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_direct_index_late_write_check.py" "$" "${backend}") diff --git a/docs/experiments/startup-table-srv-alias.md b/docs/experiments/startup-table-srv-alias.md new file mode 100644 index 0000000000..7b8e51cfca --- /dev/null +++ b/docs/experiments/startup-table-srv-alias.md @@ -0,0 +1,104 @@ +# Table buffer views over aliased placed buffers (opt-in) + +A translated draw copies every buffer it reads from the title's descriptor table into the upload ring +(`frame_copy`, see [Copies of title memory within a frame](../startup-runtime.md#copies-of-title-memory-within-a-frame)). +Within a frame the copy is reused only after a full comparison with the bytes it was made from, and the copy is +cut at 16 MiB. Vertex streams and live indices in a slot 133 placed buffer that aliases title memory bind that +alias instead (#2724, #2834). `X2W_D3D12_TABLE_ALIAS=1` does the same for table buffer views. + +## What the switch changes + +- In the `draw_translated` view loop, a table buffer view (`source 0`) that is not a formatted load, with a + nonzero range of at most 512 MiB, looks its whole range up with `placed_buffer_range`. When that finds one live + placement of kind `aliased_buffer` and the view starts 16-byte aligned in it, the draw keeps the alias alive + with the recording, requires the shader-resource states and creates a raw view over the full range. +- The raw view covers whole DWORDs, so the lookup uses the range rounded up to 4 bytes. A view whose rounded + range would run past the placement keeps the copy. +- When the same alias is also the draw's live index buffer, it is put in the index-buffer and both + shader-resource states at once, so neither binding leaves the other in a wrong state. +- The GPU then reads the title's bytes at execution. A title write between recording and submission is visible + to the draw, as on the console, where the GPU reads the same memory when the work runs. With the copy, each + draw sees the bytes as they were when it was recorded. +- Ranges past 16 MiB are bound in full; the copy reads zeros there. +- Everything else keeps the copy: formatted loads, views outside a placement or across its end, placements + that are copied or shared (`X2W_D3D12_LINEAR_BUFFERS`), released resources, unaligned offsets. +- Unset, nothing changes. + +## Fixture + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -j 1 -R '^startup_table_alias_(warp|hardware)$' -V +``` + +`X2W_TEST_TABLE_ALIAS_WRITE`: a 256-byte slot 133 buffer placed on `VirtualAlloc` memory, a raw view the title +creates over it (device slot 18) at table entry 0, and a vertex shader that reads one 8-byte record. The title +writes 40, draws the left half, writes 80, draws the right half, and writes 120 after recording, before the +list runs. + +- Unset: left 40, right 80 (each draw's copy). +- Set: both halves 120 (the alias, read at execution). +- Negative control: the same fixture with the buffer in image memory (a static array) is placed "not aliased", + and the set arm then reads 40 | 80 and fails. + +Two more cases run with the switch set. The fixture skips (77) when the adapter has no existing heaps. + +- `shared-index`: the buffer also holds the indices of one indexed draw (indices 0–2 at offset 0, index view + over the same placement). It runs under the debug layer with GPU-based validation + (`X2W_TEST_DEBUG_LAYER=1 X2W_TEST_GPU_VALIDATION=1`) and must report no error and draw 40. +- `odd-size`: a 254-byte buffer under a structured view of 127 two-byte records. The 256-byte raw view would + run past the alias, so the draw takes the copy and shows 40, not the value 120 written after recording. + +## Startup run of the main executable + +Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, release +build of this change on top of #2949 with `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, warm shader cache, +`run.ps1 -Render` without `-Translate`, scripted input, 250 s. One build; only `X2W_D3D12_TABLE_ALIAS` differs. +Two pairs, the second in reverse order. Aggregates only; logs stay local. + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | +|---|---|---|---| +| unset, pair 1 / pair 2 | 8.9 / 8.6 | 5.1 / 7.8 | 3.7 / 4.2 | +| set, pair 1 / pair 2 | 11.5 / 9.8 | 8.0 / 11.2 | 6.6 / 6.1 | + +| per run, pair 1 / pair 2 | unset | set | +|---|---|---| +| translated draws | 64,296 / 88,027 | 97,419 / 100,254 | +| list executes | 14,774 / 18,151 | 22,979 / 21,373 | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| null bindings per 1,000 load-phase draws (all cause `token`) | 53.8 / 46.5 | 54.0 / 50.8 | +| process commit peak | 18.1 / 17.1 GiB | 17.9 / 18.1 GiB | +| device removal | none | none | + +- Before 150 s (intro and menus) both settings run at about 30 fps. +- Where the time went, from local timers that are not part of this change (150–240 s, threads busy): + - unset: about 1.9 threads waited for `draw_lock`; the lock was held about 58 % of the time, mostly by + `draw_translated`, and 86 % of that hold was `frame_copy`; + - 97 % of the `frame_copy` time was one view: 16 MiB (cut from a 90 MiB slot 133 placed buffer that aliases + title memory) compared in full on about 140 draws per second, almost always unchanged; + - set: the lock waits fell to about 0.1–0.3 threads and the copy of that view was gone. +- A user watching the set run saw no visual difference or glitches. + +Retest after the review fixes (index state, rounded range), same settings, two more pairs (the second again in +reverse order), build = this branch after merging `main` `fb955a51`, on top of #2949: + +| frames per second, 30 s windows | 150–180 s | 180–210 s | 210–240 s | mean | +|---|---|---|---|---| +| unset, pair 3 / pair 4 | 6.3 / 7.9 | 9.3 / 4.5 | 3.8 / 4.0 | 6.5 / 5.5 | +| set, pair 3 / pair 4 | 11.9 / 11.7 | 7.9 / 10.8 | 6.5 / 8.0 | 8.8 / 10.2 | + +| per run, pair 3 / pair 4 | unset | set | +|---|---|---| +| translated draws | 73,904 / 89,833 | 120,081 / 122,176 | +| list executes | 16,022 / 21,080 | 28,516 / 25,474 | +| not drawn in the load (missing translations) | 47 % / 50 % | 50 % / 49 % | +| null bindings with cause `buffer` | 0 / 0 | 0 / 0 | +| process commit peak | 17.5 / 17.3 GiB | 17.6 / 17.5 GiB | +| device removal | none | none | + +- `draw_lock` waits 150–240 s: unset 1.0–1.5 threads, set 0.08–0.14; the draw hold 0.4–0.56 vs 0.07–0.09. +- Unset, the 16 MiB view is again 83–86 % of `frame_copy` time; set, no copy above 64 KiB remains. +- The pair 4 set arm reached the load later (27.8 fps at 120–150 s vs 19.2), which favours its later windows. + +Not established: other titles, AMD adapters, and whether any draw in this title depends on a value written +between recording and submission (none was seen). diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2563133bb5..61edc055a6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -517,6 +517,17 @@ one address between two draws of a frame, such as a dynamic constant buffer, gav data. The comparison uses the kept bytes because the ring is write-combined memory that is slow to read. `startup_frame_copy_{warp,hardware}` rewrites a constant buffer between two draws and checks both halves. +A table buffer view (an SRV read from the title's descriptor table) is copied the same way, at most 16 MiB of it. +For a large view the comparison costs a full read of the kept bytes on every draw, under `draw_lock`. With +`X2W_D3D12_TABLE_ALIAS=1` (opt-in, render mode), a table buffer whose whole range lies in a slot 133 placed buffer +that aliases title memory binds that alias instead, as vertex streams and live indices already do: no copy, no +comparison, and no 16 MiB cut. The GPU then reads the bytes as they are when the list runs, not as they were when +the draw was recorded, so a title write between recording and submission becomes visible to the draw (on the +console, the GPU also reads the shared memory at execution). Formatted loads, views over other memory and +unaligned offsets keep the copy. `startup_table_alias_{warp,hardware}` writes a record, draws, rewrites it, draws +again and rewrites it after recording: unset, the halves show the first two values; set, both show the third. See +[the experiment note](experiments/startup-table-srv-alias.md). + ## Root signature changes and dropped root constants Command-list slot 34 (`SetGraphicsRootSignature`) clears the translated draw's cached descriptor tables, root @@ -1480,6 +1491,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | +| `X2W_D3D12_TABLE_ALIAS=1` | opt-in, render mode: a translated draw's table buffer view whose whole range lies in a slot 133 placed buffer that aliases title memory binds that alias instead of a per-draw frame copy, so the GPU reads the bytes at execution and the view is not cut at 16 MiB (`startup_table_alias_*`). Unset, every table buffer view is copied as before. See [Copies of title memory within a frame](#copies-of-title-memory-within-a-frame) | | `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 | diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index e1107e281b..51115114cd 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2312,6 +2312,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI const bool indices_ok = indexed && !indirect && pass.ib.BufferLocation && readable_window(index_address, index_total) >= index_total; D3D12_INDEX_BUFFER_VIEW live_indices{}; ID3D12Resource* live_index_resource = nullptr; + bool index_read_as_table = false; // live_index_resource is also bound as a table SRV (X2W_D3D12_TABLE_ALIAS) const auto stream_needs_slicing = [&](const Translation::Srv& srv) { if (srv.source != 1) return false; if (srv.a < 0 || srv.a >= 8) return true; @@ -2559,6 +2560,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } + const std::size_t view_bytes = bytes; // before the 16 MiB copy cap if (bytes > (16u << 20)) { bytes = 16u << 20; // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. @@ -2581,6 +2583,31 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI buffer_facts.bound = bound; count_null_binding(x2w_local::classify_null_binding(buffer_facts)); }; + // X2W_D3D12_TABLE_ALIAS=1: a table buffer whose whole range lies in a placed buffer that aliases title memory + // binds that alias, as vertex streams do, instead of a frame copy. The GPU then reads the bytes at execution, + // not as they were when the draw was recorded, and the range is not cut at 16 MiB. + static const bool table_alias = x2w_local::env_on("X2W_D3D12_TABLE_ALIAS"); + // The raw view covers whole DWORDs, so the alias must hold the rounded range. + const std::size_t raw_bytes = (view_bytes + 3) & ~std::size_t{3}; + if (table_alias && srv.source == 0 && !formatted.entry && address && view_bytes && raw_bytes <= (512u << 20)) { + const auto table_placed = placed_buffer_range(self->own().list_device, address, raw_bytes); + if (!table_placed.reject && table_placed.alias && table_placed.owner && + InterlockedCompareExchange(&table_placed.owner->own().refs, 0, 0)) { + const u64 view_offset = address - reinterpret_cast(table_placed.owner->own().title_memory); + if (view_offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT == 0 && + retain_with_recording(self, x2w_startup::ComPtr(table_placed.alias))) { + // The same alias can also be this draw's live index buffer; it then keeps both read states. + const bool shared_index = table_placed.alias == live_index_resource; + index_read_as_table |= shared_index; + require_state(self, table_placed.alias, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | + (shared_index ? D3D12_RESOURCE_STATE_INDEX_BUFFER : D3D12_RESOURCE_STATE_COMMON)); + buffer_view(dest, table_placed.alias, view_offset, raw_bytes); + count_buffer(true); + continue; + } + } + } if (placed.reject || (placed.owner && !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0))) { buffer_view(dest, nullptr, 0, 0); count_buffer(false); @@ -2728,7 +2755,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ID3D12Resource* index_chunk = nullptr; auto view = live_indices; if (live_index_resource) { - require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER | + (index_read_as_table ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + : D3D12_RESOURCE_STATE_COMMON)); } else if (indices_ok && frame_copy(self, index_address, index_total, &offset, &index_chunk) && index_chunk) { view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(index_total), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 183f25d0a8..38ba6ec090 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -485,6 +486,105 @@ int draw_formatted_view(void* guest, void* list) return 0; } +// X2W_TEST_TABLE_ALIAS_WRITE: a buffer view the title creates over a placed buffer, at table entry 0 +// (tests/startup_table_alias_check.py). +// 1 a raw view of the whole 256-byte buffer. The title writes the record, draws the left half, writes +// it again, draws the right half, and writes it a third time after recording, before the list runs. +// A per-draw copy shows the first two values; a live alias shows the third in both halves. +// shared-index the same buffer is also the index buffer of one indexed draw (indices 0-2 at offset 0). The alias +// must be in both the index-buffer and the shader-resource states at that draw. +// odd-size a 254-byte buffer under a structured view of 127 two-byte records. The desktop raw view covers +// 256 bytes, past the alias, so the draw takes a copy: it shows the value written before recording. +// With X2W_TEST_DEBUG_LAYER, errors the debug layer stored for the device from the fixture's start +// (ID3D12InfoQueue; the message callback of ID3D12InfoQueue1 needs a newer runtime). +ID3D12InfoQueue* table_alias_messages = nullptr; + +void table_alias_debug_report() +{ + if (!table_alias_messages) return; + int errors = 0; + const UINT64 stored = table_alias_messages->GetNumStoredMessages(); + for (UINT64 i = 0; i < stored; ++i) { + SIZE_T bytes = 0; + if (FAILED(table_alias_messages->GetMessage(i, nullptr, &bytes)) || !bytes) continue; + std::vector storage(bytes); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(table_alias_messages->GetMessage(i, message, &bytes)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) + continue; + if (++errors <= 8) std::printf("debug layer id %d: %.300s\n", static_cast(message->ID), message->pDescription); + } + std::printf("table alias debug layer errors: %d\n", errors); +} + +int draw_table_alias_writes(ID3D12Device* desktop, void* guest, void* list) +{ + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps))) || !heaps.Supported) + return 77; + if (GetEnvironmentVariableW(L"X2W_TEST_DEBUG_LAYER", nullptr, 0)) { + if (FAILED(desktop->QueryInterface(IID_PPV_ARGS(&table_alias_messages)))) { + std::printf("no debug layer message queue: skipped\n"); + return 77; + } + table_alias_messages->SetMessageCountLimit(4096); + table_alias_messages->ClearStoredMessages(); + } + char mode[16]{}; + GetEnvironmentVariableA("X2W_TEST_TABLE_ALIAS_WRITE", mode, sizeof(mode)); + const bool shared_index = !std::strcmp(mode, "shared-index"); + const bool odd_size = !std::strcmp(mode, "odd-size"); + if (!shared_index && !odd_size && std::strcmp(mode, "1")) return 70; + // VirtualAlloc memory, so the placement can alias it (an existing heap cannot open image memory). + auto* const records = static_cast(VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!records) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, odd_size ? 254u : 256u, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + void* placed = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(records), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + D3D12_SHADER_RESOURCE_VIEW_DESC view{odd_size ? DXGI_FORMAT_UNKNOWN : DXGI_FORMAT_R32_TYPELESS, + D3D12_SRV_DIMENSION_BUFFER, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.NumElements = odd_size ? 127 : 64; + view.Buffer.StructureByteStride = odd_size ? 2 : 0; + view.Buffer.Flags = odd_size ? D3D12_BUFFER_SRV_FLAG_NONE : D3D12_BUFFER_SRV_FLAG_RAW; + invoke(guest, 18, ptr(placed), ptr(&view), cpu); + if (shared_index || odd_size) { + auto* const indices = reinterpret_cast(records); + for (std::uint16_t i = 0; i < 3; ++i) indices[i] = i; + records[4] = 40; + records[5] = 41; + const D3D12_RECT full{0, 0, 8, 4}; + invoke(list, 22, 1, ptr(&full)); + if (shared_index) { + const D3D12_INDEX_BUFFER_VIEW index_view{ptr(records), 6, DXGI_FORMAT_R16_UINT}; + invoke(list, 47, ptr(&index_view)); + invoke(list, 13, 3, 1, 0, 0, 0); + } else { + invoke(list, 12, 3, 1); + records[4] = 120; // after recording: only a live alias would show it + records[5] = 121; + } + return 0; + } + const auto write = [&](std::uint32_t value) { + records[4] = value; + records[5] = value + 1; + }; + const auto draw = [&](LONG left, LONG right) { + const D3D12_RECT strip{left, 0, right, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + write(40); + draw(0, 4); + write(80); + draw(4, 8); + write(120); // after recording: only a binding that reads at execution sees it + return 0; +} + int draw_copied_vertex_buffer_srv(void* guest, void* list) { constexpr UINT full_bytes = 512; diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 26b37f639f..a70e0d20f9 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -507,6 +507,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0)) { extern int draw_formatted_view(void*, void*); if (const int result = draw_formatted_view(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern int draw_table_alias_writes(ID3D12Device*, void*, void*); + if (const int result = draw_table_alias_writes(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_COPIED_VERTEX_SRV", nullptr, 0)) { extern int draw_copied_vertex_buffer_srv(void*, void*); if (const int result = draw_copied_vertex_buffer_srv(guest, list)) return result; @@ -687,6 +690,10 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* extern int root_heap_report(); if (const int rc = root_heap_report()) return rc; } + if (GetEnvironmentVariableW(L"X2W_TEST_TABLE_ALIAS_WRITE", nullptr, 0)) { + extern void table_alias_debug_report(); + table_alias_debug_report(); + } return read_stream_target(desktop.Get(), frame, pixels); } diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 929f4d3e24..2e05936d37 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -117,6 +117,15 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char return 77; } debug->EnableDebugLayer(); + // X2W_TEST_GPU_VALIDATION=1: also check the states of resources reached through descriptor tables. + ComPtr debug1; + if (GetEnvironmentVariableW(L"X2W_TEST_GPU_VALIDATION", nullptr, 0)) { + if (FAILED(debug.As(&debug1))) { + std::printf("no GPU-based validation: skipped\n"); + return 77; + } + debug1->SetEnableGPUBasedValidation(TRUE); + } } if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; diff --git a/tests/startup_table_alias_check.py b/tests/startup_table_alias_check.py new file mode 100644 index 0000000000..2e07c583be --- /dev/null +++ b/tests/startup_table_alias_check.py @@ -0,0 +1,109 @@ +"""A table buffer view over a placed buffer: per-draw copies by default, a live alias with X2W_D3D12_TABLE_ALIAS=1. + +Cases (X2W_TEST_TABLE_ALIAS_WRITE in tests/startup_address_srv.cpp): + writes records rewritten between two draws and after recording: copies show 40 | 80, the alias 120. + shared-index the alias is also the draw's index buffer. Run with the debug layer and GPU-based validation; no + error may be reported, so the alias must hold both the index-buffer and shader-resource states. + odd-size a 254-byte buffer under a 127 x 2-byte structured view: the 256-byte raw view does not fit the + alias, so even with the switch the draw reads a copy (40), not the later write (120). +""" +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_address_srv_check import draw_texture, prepare_draw_cache + +VERTEX = """ +ByteAddressBuffer records : register(t0); +struct Vertex { + float4 position : SV_Position; + nointerpolation uint2 values : TEXCOORD0; +}; +Vertex main(uint id : SV_VertexID) { + const float2 corners[3] = {float2(-1, 1), float2(3, 1), float2(-1, -3)}; + Vertex output; + output.position = float4(corners[id], 0.5, 1); + output.values = uint2(records.Load(16), records.Load(20)); + return output; +} +""" + +PIXEL = """ +float4 main(float4 position : SV_Position, nointerpolation uint2 values : TEXCOORD0) : SV_Target { + return float4(float2(values) / 255.0, 0, 1); +} +""" + +BINDING = "srv 0 buf table 0 0" +VALIDATION = {"X2W_TEST_DEBUG_LAYER": "1", "X2W_TEST_GPU_VALIDATION": "1"} + + +def texel(value): + return bytes((value, value + 1, 0, 255)) + + +def run(folder, consumer, backend, modes): + """Pixels and stdout of one consumer run, or (None, "") for a capability skip.""" + try: + env, args, output = prepare_draw_cache(folder, consumer, PIXEL, modes, BINDING, vertex_hlsl=VERTEX) + except subprocess.CalledProcessError as error: + if error.returncode == 77: # no existing heaps, debug layer or GPU-based validation + return None, "" + raise + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return None, "" + if result.returncode: + raise RuntimeError(f"consumer failed ({result.returncode})\n{result.stderr[-5000:]}") + return output.read_bytes(), result.stdout + + +def debug_errors(stdout, name): + found = re.search(r"^table alias debug layer errors: (\d+)$", stdout, re.M) + if not found: + raise AssertionError(f"{name}: no debug layer message count") + return int(found.group(1)) + + +def check(directory, consumer, backend): + # The fixture writes 40, draws the left half, writes 80, draws the right half, then writes 120 before the list runs. + cases = ( + # The copy case clears the switch, so it keeps testing the default when the switch is set in the environment. + ("copy", {"X2W_D3D12_TABLE_ALIAS": "0"}, texel(40) * 4 + texel(80) * 4), + ("alias", {"X2W_D3D12_TABLE_ALIAS": "1"}, texel(120) * 8), + ) + for name, switches, row in cases: + folder = directory / name + folder.mkdir() + pixels = draw_texture(folder, consumer, backend, PIXEL, {"X2W_TEST_TABLE_ALIAS_WRITE": "1", **switches}, + binding=BINDING, vertex_hlsl=VERTEX) + if pixels is None: + return 77 + expected = row * 4 + if pixels != expected: + raise AssertionError(f"{backend}: {name} table buffer got {pixels.hex()}, expected {expected.hex()}") + print(f"{backend}: 32 pixels matched the {name} reading of a rewritten table buffer") + + for name, extra, value in (("shared-index", VALIDATION, 40), ("odd-size", VALIDATION, 40)): + folder = directory / name + folder.mkdir() + modes = {"X2W_TEST_TABLE_ALIAS_WRITE": name, "X2W_D3D12_TABLE_ALIAS": "1", **extra} + pixels, stdout = run(folder, consumer, backend, modes) + if pixels is None: + return 77 + expected = texel(value) * 32 + if pixels != expected: + raise AssertionError(f"{backend}: {name} got {pixels.hex()}, expected {expected.hex()}") + errors = debug_errors(stdout, name) + if errors: + raise AssertionError(f"{backend}: {name}: {errors} debug layer errors") + print(f"{backend}: {name}: 32 pixels exact, no debug layer errors") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:]))