diff --git a/CMakeLists.txt b/CMakeLists.txt index 276e73c3c6..11254f6eeb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1255,6 +1255,7 @@ target_link_libraries(startup_stream_consumer PRIVATE d3d12_xs_shim startup_stub target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_memory_srv_diag.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_pixel_uav.cpp) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) @@ -4422,6 +4423,12 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_d16_srv_check.py" "$" "${backend}") set_tests_properties(startup_d16_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + # A translated pixel-stage image store bound from the title's table (#1996 item F): the stored texel and + # every other word of four textures read back, each refusal by its reason, and the exec controls. + add_test(NAME startup_pixel_uav_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_pixel_uav_check.py" + "$" "${backend}") + set_tests_properties(startup_pixel_uav_${backend} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) add_test(NAME startup_frame_copy_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_frame_copy_check.py" "$" ${backend}) diff --git a/docs/experiments.md b/docs/experiments.md index 652dc6185d..eee9ee2efa 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -262,7 +262,7 @@ to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on ha ## Offline vertex buffer stores -`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses version 2 manifests, so no store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. +`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses the `raw` uav line by name (it binds only pixel-stage `tex2d` stores), so no buffer store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. The descriptor modifications that compute buffer stores accept are accepted here too, with the same checks: the stride clear of DW1 and the structured-to-raw conversion (stride DW1[29:16] extracted, optionally clamped to at least 1, DW2 NUM_RECORDS scaled by it, DW3 OOB_SELECT set to 3, stride cleared), all four words from one descriptor load. The store and manifest are those of the unmodified descriptor. In the vertex stage, as in compute, a descriptor load through a pointer other than the untouched pair is tagged with the constant high word of a 32-bit table pointer, or otherwise with its own load, so the conversion cannot mix words of two loads. Any other modification stays refused. As for compute, matching out-of-range behavior would need a UAV view sized to the converted byte count; the runtime binds no vertex-stage UAV yet. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 87d0417b3a..ae92a10043 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2204,11 +2204,30 @@ These are measured on one executable; treat them as hypotheses for others. `uav tex2d table ` line. The cache-policy bits are accepted. A partial channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, `lwe`, `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads - and stores the same image are refused by name. The runtime does not bind UAVs on the translated - graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. A + and stores the same image are refused by name. A hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. +- **Binding pixel-stage image stores.** A translated draw binds each `uav N tex2d table P O` line + as a UAV range `u0..` placed after the SRVs in the translated root signature's view table. The view is made from the unordered-access + view the title created at that table entry (`resolve_pixel_uavs` in `d3d12_draw.inl`), on + mip 0 of a 2D texture, and the texture is in `UNORDERED_ACCESS` for the draw. Refusals are logged + with their reason and nothing is bound in place of the view. When the manifest is loaded, the + translation is not used for another image kind, a buffer line (`uav N raw table P O`, + the vertex-stage store of #2059), a view qualifier (`float`, `uint`, `sint`, as in the compute line), another source, extra fields such as + `channels`, an index out of order or more than eight views. At draw time, + the draw is not translated for no table at the parameter, an entry outside the bound table, an + entry without a view, a view that is not a UAV, a resource without `ALLOW_UNORDERED_ACCESS`, an + array, 3D, 1D or multisampled resource, a view of another dimension, mip or plane, an integer, + sRGB or non-colour format, a format without typed UAV store, and a texture that is also an SRV, + a render target or the depth texture of the draw; these checks run before any view of the draw is + written or any texture changes state. Indirect draws refuse a translation with a `uav` line. Compute UAVs and barriers between + draws that write and read the same texture are not covered. `tests/startup_pixel_uav_check.py` + draws the program above through the runtime with four 4x4 two-mip textures in which every word is + a distinct sentinel. The texel lands only in the texture the table names, and every other word of + the four textures stays unchanged; each refusal leaves every word unchanged. The exec-off variant + leaves the texel, and must fail once recompiled without its guard. Run + `ctest --preset release --no-tests=error -R '^startup_pixel_uav_' -V`. - **Explicit mip loads.** For 2D textures, 2D arrays and 3D textures, `image_load_mip` passes the final address register to `Texture.Load` as the mip level (`int4(x, y, slice, mip)` for an array, whose four registers are x, y, slice and mip). Ordinary `image_load` still reads mip zero. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 04830e6c10..a8d84d8e0d 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,6 +9,111 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. +// A pixel-stage image store (#1996 item F): tools/startup/gfx2hlsl.py writes 'uav N tex2d table P O' for the +// RWTexture2D at u, whose descriptor is at byte O of the title's root table P. Only that form is +// read; a view qualifier or a 'channels' field, as in the compute line, is refused. +struct PixelUav { + unsigned index = 0, parameter = 0, offset = 0; +}; +constexpr unsigned pixel_uav_limit = 8; + +// Returns nullptr and fills out, or the reason the line is refused. +const char* read_pixel_uav_line(const std::string& line, PixelUav& out) +{ + std::vector w; + for (std::size_t at = line.find_first_not_of(' '); at != std::string::npos; at = line.find_first_not_of(' ', at)) { + const std::size_t end = line.find(' ', at); + w.push_back(line.substr(at, end == std::string::npos ? std::string::npos : end - at)); + at = end == std::string::npos ? line.size() : end; + } + const auto number = [](const std::string& text, unsigned& value) { + if (text.empty() || text.size() > 9 || text.find_first_not_of("0123456789") != std::string::npos) return false; + value = static_cast(std::strtoul(text.c_str(), nullptr, 10)); + return true; + }; + if (w.size() < 2 || w[0] != "uav" || !number(w[1], out.index)) return "malformed view index"; + if (w.size() < 3) return "missing view kind"; + if (w[2] == "raw" || w[2] == "table") return "buffer view (raw uav) is not bound"; + if (w[2] != "tex2d") return "only tex2d views are bound"; + if (w.size() > 3 && (w[3] == "float" || w[3] == "uint" || w[3] == "sint")) return "a view qualifier is not read for pixel stores"; + if (w.size() < 4 || w[3] != "table") return "view source is not a table"; + if (w.size() < 6) return "missing table parameter or offset"; + if (w.size() > 6) return "unexpected field after the table offset"; + if (!number(w[4], out.parameter) || out.parameter >= 16) return "table parameter out of range"; + if (!number(w[5], out.offset)) return "malformed table offset"; + return nullptr; +} + +// Formats a RWTexture2D store converts to: float, UNORM and SNORM colour formats. +bool float_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32_FLOAT: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R32G32_FLOAT: + case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R11G11B10_FLOAT: case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_SNORM: + case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R8_UNORM: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_B5G6R5_UNORM: case DXGI_FORMAT_B5G5R5A1_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B4G4R4A4_UNORM: + return true; + default: + return false; + } +} + +bool integer_uav_format(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: case DXGI_FORMAT_R32G32B32_UINT: + case DXGI_FORMAT_R32G32B32_SINT: case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: case DXGI_FORMAT_R10G10B10A2_UINT: + case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SINT: case DXGI_FORMAT_R16G16_UINT: + case DXGI_FORMAT_R16G16_SINT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SINT: + return true; + default: + return false; + } +} + +bool srgb_uav_format(DXGI_FORMAT format) +{ + return format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB || + format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; +} + +// The view of mip 0 of a 2D texture for a pixel UAV. resource is the desktop description, title_view the title's +// own view (nullptr when it passed none) with console format values already mapped. Returns nullptr and fills +// out, or the reason the binding is refused. +const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& resource, + const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, D3D12_UNORDERED_ACCESS_VIEW_DESC& out) +{ + if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return "resource is not a 2D texture"; + if (resource.DepthOrArraySize != 1) return "resource is a texture array"; + if (resource.SampleDesc.Count != 1) return "resource is multisampled"; + if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "resource lacks ALLOW_UNORDERED_ACCESS"; + DXGI_FORMAT format = resource.Format; + if (title_view) { + if (title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D) return "view is not a 2D texture view"; + if (title_view->Texture2D.MipSlice != 0) return "view names a mip other than 0"; + if (title_view->Texture2D.PlaneSlice != 0) return "view names a plane other than 0"; + if (title_view->Format != DXGI_FORMAT_UNKNOWN) format = title_view->Format; + } + if (integer_uav_format(format)) return "integer format for a float view"; + if (srgb_uav_format(format)) return "sRGB format"; + if (!float_uav_format(format)) return "format is not a float colour format"; + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{format}; + if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) || + !(support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + return "format has no typed UAV store on this device"; + out = {}; + out.Format = format; + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + return nullptr; +} + struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; @@ -16,6 +121,7 @@ struct Translation { int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. std::vector srvs; + std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) @@ -168,14 +274,11 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } matched_rtv = true; - } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1") { - // Version 2 adds `uav` lines for vertex-stage stores. This runtime does not bind them, - // so it must not draw a translation whose stores it would silently skip (#1723). + } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1" && line != "x2w-manifest 2") { + // Version 2 adds `uav` lines. Each one is bound (a pixel-stage tex2d store) or refused by name below, + // so a translation whose stores would be silently skipped is never drawn (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (line.compare(0, 4, "uav ") == 0) { - log("x2w-draw unsupported uav line for %016llx", tr.key); - return; } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { Translation::Ud ud{-1, x, y}; if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; @@ -203,11 +306,17 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } } else if (line.compare(0, 4, "uav ") == 0) { - // tools/startup/gfx2hlsl.py lowers a pixel-stage image_store to a u-register store, but the - // translated root signature has no UAV range and no view is made from the title's descriptor yet. - log("x2w-draw pipeline %016llx stores to an image (%s); pixel-stage UAVs are not bound yet, translation not used", - tr.key, line.c_str()); - return; + // A pixel-stage image_store: the view is made at draw time from the title's unordered-access view at + // that table entry (resolve_pixel_uavs). + PixelUav uav; + const char* refusal = read_pixel_uav_line(line, uav); + if (!refusal && uav.index != tr.uavs.size()) refusal = "view index out of order"; + if (!refusal && tr.uavs.size() >= pixel_uav_limit) refusal = "too many views"; + if (refusal) { + log("x2w-draw pipeline %016llx uav line refused (%s): %s; translation not used", tr.key, refusal, line.c_str()); + return; + } + tr.uavs.push_back(uav); } else if (!tr.samplers.read_manifest_line(line.c_str())) { log("x2w-draw invalid sampler heap manifest for %016llx", tr.key); return; @@ -226,7 +335,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) if (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs))) return; if (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps))) return; const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root); + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); return; @@ -234,8 +343,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) tr.state = 1; if (previously_missing) InterlockedDecrement(&translation_missing); InterlockedIncrement(&translation_ready); - log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu static samplers, sampler_heap=%u", - tr.key, tr.uds.size(), tr.srvs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); + log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable textures, %zu static samplers, sampler_heap=%u", + tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } // draw_lock held. Both pipeline forms use the same request writer and shader cache. @@ -1886,6 +1995,85 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB return true; } +struct PixelUavBinding { + ID3D12Resource* resource = nullptr; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; +}; + +// draw_lock held. The writable textures of tr (#1996 F), from the unordered-access views the title created at +// their table entries (pixel_uav_view). False, with the reason logged, when one cannot be bound as the program +// expects: the draw is then not translated, and no other view is bound in its place. +bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding* out) +{ + const auto refuse = [&](std::size_t i, const char* reason, unsigned long long detail) { + static LONG refused; + if (first_calls(refused, 16)) + log("x2w-draw %016llx uav %zu refused: %s (0x%llx); draw not translated", tr.key, i, reason, detail); + return false; + }; + for (std::size_t i = 0; i < tr.uavs.size(); ++i) { + const PixelUav& uav = tr.uavs[i]; + const x2w_startup::ViewTable& table = pass.view_tables[uav.parameter]; + if (!table.address) return refuse(i, "no descriptor table at the parameter", uav.parameter); + const u64 entry = table.record(uav.offset, 32); + if (!entry) return refuse(i, "table entry outside the bound table", uav.offset); + std::uint32_t words[8] = {}; + if (!x2w_local::readable(reinterpret_cast(entry), 32)) return refuse(i, "table entry unreadable", entry); + std::memcpy(words, reinterpret_cast(entry), 32); + if (words[0] != view_token_magic) return refuse(i, "table entry holds no view", words[0]); + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = words[1] < view_records().size(); + if (known) record = view_records()[words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known) return refuse(i, "unknown view token", words[1]); + if (record.slot != 19) return refuse(i, "table entry is not an unordered-access view", record.slot); + Wrapper* resource = as_wrapper(reinterpret_cast(record.resource)); + if (!resource || resource->own().kind != resource_kind || !resource->own().real) return refuse(i, "view has no resource", record.resource); + if (resource->own().tiled_address_srv) return refuse(i, "resource is a texture by title address", record.resource); + auto* texture = static_cast(resource->own().real); + D3D12_UNORDERED_ACCESS_VIEW_DESC title_view{}; + const bool described = record.desc_bytes >= sizeof(title_view); + if (record.desc_bytes && !described) return refuse(i, "truncated view description", record.desc_bytes); + if (described) { + std::memcpy(&title_view, record.desc, sizeof(title_view)); + title_view.Format = desktop_format(title_view.Format); + } + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, out[i].view); + if (reason) { + static LONG refused_view; + if (first_calls(refused_view, 16)) + log("x2w-draw %016llx uav %zu refused: %s (view %s dimension %d mip %u format %d; resource dimension %d array %u " + "flags 0x%x format %d); draw not translated", tr.key, i, reason, described ? "described" : "default", + title_view.ViewDimension, title_view.Texture2D.MipSlice, title_view.Format, desc.Dimension, + static_cast(desc.DepthOrArraySize), static_cast(desc.Flags), desc.Format); + return false; + } + // A texture the draw also renders to or reads cannot be bound for writing. Checked here, before the + // draw records any view or state change. + const bool target = std::find(pass.bound_targets, pass.bound_targets + pass.target_count, texture) != + pass.bound_targets + pass.target_count; + if (target || (pass.bound_depth && pass.bound_depth == texture)) + return refuse(i, "the texture is also a render or depth target of this draw", reinterpret_cast(texture)); + for (std::size_t s = 0; s < tr.srvs.size(); ++s) { + const Translation::Srv& srv = tr.srvs[s]; + if (srv.kind < 1 || srv.kind > 4 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) continue; + const u64 srv_entry = pass.view_tables[srv.a].record(static_cast(srv.b), 32); + std::uint32_t srv_words[8] = {}; + if (!srv_entry || !x2w_local::readable(reinterpret_cast(srv_entry), 32)) continue; + std::memcpy(srv_words, reinterpret_cast(srv_entry), 32); + if (srv_words[0] != view_token_magic) continue; + AcquireSRWLockShared(¬e_lock); + const u64 srv_resource = srv_words[1] < view_records().size() ? view_records()[srv_words[1]].resource : 0; + ReleaseSRWLockShared(¬e_lock); + if (srv_resource && srv_resource == record.resource) return refuse(i, "the texture is also an SRV of this draw", s); + } + out[i].resource = texture; + } + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { @@ -1925,6 +2113,12 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + if (!tr->uavs.empty()) { + indirect->set_refusal("translated draw with a writable texture is not bound for indirect draws", + indirect_refusal_code::unsupported_resource_or_entry); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } auto& entry = indexed ? tr->indexed_indirect_entry : tr->independent_indirect_entry; if (!entry.has_value()) { bool found_base = !indexed; @@ -1960,11 +2154,17 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + PixelUavBinding uav_bindings[pixel_uav_limit]; + if (!resolve_pixel_uavs(*tr, pass, uav_bindings)) { + ReleaseSRWLockExclusive(&draw_lock); + return false; + } const UINT n = static_cast(tr->srvs.size()); - UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; - if (first + n > draw_heap_size) { + const UINT views = n + static_cast(tr->uavs.size()); // the SRVs, then the UAVs, in one table + UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(views))) % draw_heap_size; + if (first + views > draw_heap_size) { first = 0; - InterlockedExchange(&draw_heap_cursor, static_cast(n)); + InterlockedExchange(&draw_heap_cursor, static_cast(views)); } std::uint32_t strides[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). @@ -2256,6 +2456,15 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI have ? "bound" : "NULL", head); } } + for (UINT j = 0; j < tr->uavs.size(); ++j) { + const D3D12_CPU_DESCRIPTOR_HANDLE dest{draw_heap->GetCPUDescriptorHandleForHeapStart().ptr + SIZE_T{first + n + j} * draw_heap_increment}; + require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + device_of(the_device)->CreateUnorderedAccessView(uav_bindings[j].resource, nullptr, &uav_bindings[j].view, dest); + static LONG shown; + if (first_calls(shown, 6)) + log("x2w-draw %016llx uav %u: resource %p format %d mip 0", tr->key, j, static_cast(uav_bindings[j].resource), + uav_bindings[j].view.Format); + } static LONG checks; if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); std::uint32_t values[32] = {}; @@ -2311,8 +2520,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI pass.bound_sampler_heap = samplers; } list->SetGraphicsRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); - if (n) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); - if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(n), samplers->GetGPUDescriptorHandleForHeapStart()); + if (views) list->SetGraphicsRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); + if (samplers) list->SetGraphicsRootDescriptorTable(x2w_startup::sampler_root_parameter(views), samplers->GetGPUDescriptorHandleForHeapStart()); list->IASetPrimitiveTopology(pass.topology == 5 ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); bool drawn = false; if (indirect) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ff4dc8978a..ae3cd6be96 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2503,6 +2503,8 @@ struct Pass { ID3D12Resource* target0 = nullptr; // desktop resource of render target 0 (for per-draw dumps) ID3D12Resource* trace_targets[8]{}; ID3D12Resource* trace_depth = nullptr; + ID3D12Resource* bound_targets[8]{}; // the last accepted bind: targets [0, target_count) and the depth texture + ID3D12Resource* bound_depth = nullptr; bool heap_set = false; x2w_startup::SamplerSource title_samplers; std::unique_ptr sampler_snapshot; @@ -3578,6 +3580,8 @@ void __stdcall list_targets(Wrapper* self, UINT count, const D3D12_CPU_DESCRIPTO } if (dsv_target) require_state(self, dsv_target, dsv_state); pass.target_count = count; + std::copy_n(targets, 8, pass.bound_targets); + pass.bound_depth = dsv_target; pass.dsv_format = dsv_format; const auto single_sample = [](ID3D12Resource* resource) { const auto samples = resource->GetDesc().SampleDesc; diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 8d06fa71a6..10149b3c1d 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -110,8 +110,10 @@ inline std::vector decode_statics(const TranslatedSam return statics; } -inline UINT sampler_root_parameter(UINT srvs) { return srvs ? 2u : 1u; } +// views: the SRVs and UAVs of the view table together. +inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } +// Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.. right after them. inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0) { diff --git a/tests/startup_pixel_uav.cpp b/tests/startup_pixel_uav.cpp new file mode 100644 index 0000000000..36a6546293 --- /dev/null +++ b/tests/startup_pixel_uav.cpp @@ -0,0 +1,299 @@ +// X2W_TEST_PIXEL_UAV= (tests/startup_pixel_uav_check.py): a translated pixel program that stores to a +// 2D image (#1996 item F) drawn through d3d12_xs.dll, with the image bound from the title's descriptor table. +// +// Four committed 4x4 textures with two mips each, every word of every texel a distinct sentinel: +// A R32G32B32A32_FLOAT with ALLOW_UNORDERED_ACCESS, B the same, C without the flag, D R32G32B32A32_TYPELESS. +// One shader-visible heap of eight entries: +// 0 UAV of A (explicit 2D view, mip 0) 1 UAV of B (no description: the default view) +// 2 UAV of C (the stand-in skips the desktop call and keeps the title's view) +// 3 UAV of D as R32G32B32A32_UINT 4 left unwritten +// 5 SRV of A 6 UAV of A, mip 1 +// 7 UAV of A as a one-slice 2D array 8 UAV of E, a 4x4 R8G8B8A8_UNORM render target with the flag +// The case names the table bound at root parameter 0 (and, for srv-and-uav, parameter 1); one draw follows. +// The target case binds E as the draw's render target first. +// After the fence every subresource of the four textures is written to .uav, and the debug layer's +// errors are counted when it is on. +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Word = std::uint64_t; +Word invoke(void*, unsigned, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0, Word = 0); + +namespace { +using Microsoft::WRL::ComPtr; +template Word ptr(T* value) { return reinterpret_cast(value); } + +constexpr UINT side = 4, mips = 2, textures = 4; + +// The sentinel of word c of texel (x, y) of mip m of texture t; tests/startup_pixel_uav_check.py makes the same. +std::uint32_t sentinel(UINT t, UINT m, UINT texel, UINT c) { return 0xc0000000u | (t << 12) | (m << 8) | (texel << 2) | c; } + +struct Fixture { + ID3D12Device* desktop = nullptr; + void* resources[textures]{}; + ComPtr natives[textures]; +} fixture; + +ComPtr native_of(void* guest, void* wrapped) +{ + // The stand-in forwards SetPrivateDataInterface with the desktop object behind its argument. + constexpr GUID key{0x5e1f0b42, 0x2d8c, 0x4f61, {0x9a, 0x37, 0x0c, 0x71, 0x52, 0x88, 0xe4, 0x1d}}; + if (FAILED(static_cast(invoke(guest, 5, ptr(&key), ptr(wrapped))))) return nullptr; + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = fixture.desktop->GetPrivateData(key, &bytes, stored.GetAddressOf()); + invoke(guest, 5, ptr(&key), 0); + ComPtr result; + if (FAILED(read) || FAILED(stored.As(&result))) return nullptr; + return result; +} + +D3D12_RESOURCE_DESC texture_desc(UINT t) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, mips, + t == 3 ? DXGI_FORMAT_R32G32B32A32_TYPELESS : DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 2 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; +} + +struct Copier { + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + bool open(ID3D12Device* device) + { + const D3D12_COMMAND_QUEUE_DESC desc{}; + return SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(&list))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); + } + bool run() + { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return false; + const ULONGLONG deadline = GetTickCount64() + 10000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < deadline) Sleep(1); + return fence->GetCompletedValue() == 1; + } +}; + +void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) +{ + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &b); +} + +ComPtr buffer(ID3D12Device* device, D3D12_HEAP_TYPE type, UINT64 bytes, D3D12_RESOURCE_STATES state) +{ + const D3D12_HEAP_PROPERTIES heap{type}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + ComPtr result; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(&result)))) + return nullptr; + return result; +} + +// Fills every subresource of the four textures with its sentinels (to_textures) or copies them all back. +bool copy_all(ID3D12Device* device, bool to_textures, std::vector* words) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[mips]{}; + UINT64 total = 0; + const auto desc = texture_desc(0); + device->GetCopyableFootprints(&desc, 0, mips, 0, footprints, nullptr, nullptr, &total); + if (!total || total == ~UINT64{0}) return false; + auto staging = buffer(device, to_textures ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, total * textures, + to_textures ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + unsigned char* memory = nullptr; + if (to_textures) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n; ++x) + for (UINT c = 0; c < 4; ++c) { + const std::uint32_t value = sentinel(t, m, y * n + x, c); + std::memcpy(memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + (x * 4 + c) * 4, + &value, 4); + } + } + staging->Unmap(0, nullptr); + } + for (UINT t = 0; t < textures; ++t) { + auto* texture = fixture.natives[t].Get(); + const auto state = to_textures ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, state); + for (UINT m = 0; m < mips; ++m) { + D3D12_TEXTURE_COPY_LOCATION placed{staging.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed.PlacedFootprint = footprints[m]; + placed.PlacedFootprint.Offset += t * total; + D3D12_TEXTURE_COPY_LOCATION subresource{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + subresource.SubresourceIndex = m; + if (to_textures) copier.list->CopyTextureRegion(&subresource, 0, 0, 0, &placed, nullptr); + else copier.list->CopyTextureRegion(&placed, 0, 0, 0, &subresource, nullptr); + } + barrier(copier.list.Get(), texture, state, D3D12_RESOURCE_STATE_COMMON); + } + if (!copier.run()) return false; + if (to_textures) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT t = 0; t < textures; ++t) + for (UINT m = 0; m < mips; ++m) { + const UINT n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n * 4; ++x) { + std::uint32_t value = 0; + std::memcpy(&value, memory + t * total + footprints[m].Offset + y * footprints[m].Footprint.RowPitch + x * 4, 4); + words->push_back(value); + } + } + staging->Unmap(0, nullptr); + return true; +} + +ID3D12InfoQueue* debug_messages() +{ + static ComPtr queue; + if (!queue && fixture.desktop) fixture.desktop->QueryInterface(IID_PPV_ARGS(&queue)); + return queue.Get(); +} +} // namespace + +int draw_pixel_uavs(ID3D12Device* desktop, void* guest, void* list) +{ + char mode[32]{}; + GetEnvironmentVariableA("X2W_TEST_PIXEL_UAV", mode, sizeof(mode)); + const std::string which(mode); + fixture.desktop = desktop; + for (UINT t = 0; t < textures; ++t) { + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = texture_desc(t); + const auto create = reinterpret_cast((*static_cast(guest))[127]); + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[t])) || !fixture.resources[t]) + return 70; + fixture.natives[t] = native_of(guest, fixture.resources[t]); + if (!fixture.natives[t]) return 71; + } + if (!copy_all(desktop, true, nullptr)) return 72; + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 9, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&heap))))) + return 73; + const Word cpu = invoke(heap, 9), gpu = invoke(heap, 10); + const UINT stride = static_cast(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + + D3D12_UNORDERED_ACCESS_VIEW_DESC view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&view), cpu + 0 * stride); + invoke(guest, 19, ptr(fixture.resources[1]), 0, 0, cpu + 1 * stride); + invoke(guest, 19, ptr(fixture.resources[2]), 0, ptr(&view), cpu + 2 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC integer = view; + integer.Format = DXGI_FORMAT_R32G32B32A32_UINT; + invoke(guest, 19, ptr(fixture.resources[3]), 0, ptr(&integer), cpu + 3 * stride); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + invoke(guest, 18, ptr(fixture.resources[0]), ptr(&srv), cpu + 5 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC mip1 = view; + mip1.Texture2D.MipSlice = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&mip1), cpu + 6 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC array{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY}; + array.Texture2DArray.ArraySize = 1; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&array), cpu + 7 * stride); + + // E: a 4x4 R8G8B8A8_UNORM texture that is both a render target and writable; entry 8 is its UAV. The target + // case binds it as the draw's render target and names that entry. + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + static void* target = nullptr; + if (FAILED(reinterpret_cast((*static_cast(guest))[127])(guest, &default_heap, 0, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, __uuidof(ID3D12Resource), &target)) || !target) + return 70; + D3D12_UNORDERED_ACCESS_VIEW_DESC target_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(target), 0, ptr(&target_view), cpu + 8 * stride); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + void* rtv_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&rtv_heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&rtv_heap))))) + return 73; + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC target_rtv{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(guest, 20, ptr(target), ptr(&target_rtv), rtv.ptr); + + struct Case { const char* name; int entry; int srv_entry; }; + static const Case cases[] = { + {"a", 0, -1}, {"b", 1, -1}, {"no-ua", 2, -1}, {"uint", 3, -1}, {"missing", 4, -1}, {"srv", 5, -1}, + {"mip1", 6, -1}, {"array", 7, -1}, {"out-of-range", 7, -1}, {"no-table", -1, -1}, {"srv-and-uav", 0, 5}, + {"target", 8, -1}, + }; + const Case* chosen = nullptr; + for (const Case& c : cases) + if (which == c.name) chosen = &c; + if (!chosen) return 74; + std::printf("pixel uav case %s: table entry %d, title descriptor stride %u\n", chosen->name, chosen->entry, stride); + if (which == "target") invoke(list, 50, 1, ptr(&rtv)); + invoke(list, 32, 1, ptr(&heap)); + if (chosen->entry >= 0) invoke(list, 36, 0, gpu + Word(chosen->entry) * stride); + if (chosen->srv_entry >= 0) invoke(list, 36, 1, gpu + Word(chosen->srv_entry) * stride); + invoke(list, 12, 3, 1); + return 0; +} + +// After the fence: every word of every subresource of the four textures, texture by texture, mip by mip, row by +// row, to .uav; then the debug layer's error count. +int report_pixel_uavs(const char* pixels) +{ + std::vector words; + const bool copied = copy_all(fixture.desktop, false, &words); + if (copied) { + std::ofstream out(std::string(pixels) + ".uav", std::ios::binary); + out.write(reinterpret_cast(words.data()), static_cast(words.size() * 4)); + if (!out) return 76; + } + const HRESULT removed = fixture.desktop->GetDeviceRemovedReason(); + std::printf("device removed reason: 0x%08lx\n", static_cast(removed)); + auto* messages = debug_messages(); + if (!messages) { + std::printf("debug layer: absent\n"); + return copied ? 0 : 75; + } + UINT errors = 0; + for (UINT64 i = 0; i < messages->GetNumStoredMessages(); ++i) { + SIZE_T size = 0; + if (FAILED(messages->GetMessage(i, nullptr, &size)) || !size) continue; + std::vector storage(size); + auto* message = reinterpret_cast(storage.data()); + if (FAILED(messages->GetMessage(i, message, &size)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) continue; + if (++errors <= 8) std::printf("debug layer error id %d: %.300s\n", static_cast(message->ID), message->pDescription); + } + std::printf("debug layer: on, errors: %u\n", errors); + return copied ? 0 : 75; +} diff --git a/tests/startup_pixel_uav_check.py b/tests/startup_pixel_uav_check.py new file mode 100644 index 0000000000..4d02c50f1d --- /dev/null +++ b/tests/startup_pixel_uav_check.py @@ -0,0 +1,270 @@ +"""Bind a translated pixel-stage image store through the runtime (#1996 item F, runtime slice). + +The pixel program is the hand-assembled gfx1013 one of tests/startup_pixel_image_store_check.py: it loads an +image descriptor from table 0, stores 1.0, 2.0, 3.0 and 4.0 at texel (1, 2) and exports the same values. It is +published by startup_stream_consumer, translated by tools/startup/gfx2hlsl.py --pending (manifest line +'uav 0 tex2d table 0 0') and drawn through d3d12_xs.dll with X2W_TEST_PIXEL_UAV= +(tests/startup_pixel_uav.cpp). Each case is its own process. After the fence the fixture writes every word of +both mips of four 4x4 textures (A and B writable, C without ALLOW_UNORDERED_ACCESS, D typeless), each word a +distinct sentinel, and the debug layer's error count when the layer is on. + +Drawn: the table names A (case a) or B (case b, a view without a description). Texel (1, 2) of mip 0 of that +texture holds the four values; every other word of all four textures, both mips, keeps its sentinel. +Refused, each by its logged reason, with every word unchanged and no translated draw: a table entry with no +view, an SRV, a texture without ALLOW_UNORDERED_ACCESS, an integer view, a view of mip 1, a 2D-array view, an +entry outside the bound table, no table at the parameter, the same texture also bound as an SRV of the draw, and +a texture E that is also the draw's render target (bound through list slot 50). +Manifest lines: a view qualifier (float, uint, and the compute line with 'channels 4'), another image kind, a buffer +line, a 'channels' field and a view index out of order are refused when the manifest is loaded. +Exec: the v_cmpx variants of the program, through the same runtime path: exec on writes the texel, exec off +leaves it. Control: the exec-off shader recompiled with the guard removed from the store must write the texel, +and the check must report it. +""" +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +from startup_stream_check import container, gfx2hlsl # noqa: E402 +from startup_stream_draw_check import vertex # noqa: E402 +from startup_pixel_image_store_check import BITS, EXEC_OFF, EXEC_ON, GUARDED_LINE, STORE_LINE, WORDS # noqa: E402 + +SIDE, MIPS, TEXTURES = 4, 2, 4 +WRITTEN = [int(b, 16) for b in BITS] +CLEAR, WHITE = bytes((0, 0, 255, 255)), bytes((255, 255, 255, 255)) +DRAWN_LINE = 'x2w-draw draw(3, 1, start 0, base 0) pipeline' + +# case: (table entry the fixture binds, texture written or None, reason logged, manifest edit) +CASES = { + 'a': (0, 0, None, None), + 'b': (1, 1, None, None), + 'missing': (4, None, 'uav 0 refused: table entry holds no view', None), + 'srv': (5, None, 'uav 0 refused: table entry is not an unordered-access view', None), + # The device skips a UAV over a resource without ALLOW_UNORDERED_ACCESS (#2649): no view is recorded, so the draw sees an empty entry. + 'no-ua': (2, None, 'uav 0 refused: table entry holds no view', None), + 'uint': (3, None, 'uav 0 refused: integer format for a float view', None), + 'mip1': (6, None, 'uav 0 refused: view names a mip other than 0', None), + 'array': (7, None, 'uav 0 refused: view is not a 2D texture view', None), + 'out-of-range': (7, None, 'uav 0 refused: table entry outside the bound table', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 4096')), + 'no-table': (None, None, 'uav 0 refused: no descriptor table at the parameter', None), + 'srv-and-uav': (0, None, 'uav 0 refused: the texture is also an SRV of this draw', + ('uav 0 tex2d table 0 0', 'uav 0 tex2d table 0 0\nsrv 0 tex2d table 1 0')), + 'target': (8, None, 'uav 0 refused: the texture is also a render or depth target of this draw', None), +} + +# case: (replacement of 'uav 0 tex2d table 0 0', texture written or None, reason logged) +LINES = ( + ('a.float-line', 'uav 0 tex2d float table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.compute-line', 'uav 0 tex2d float table 0 0 channels 4', None, + 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.tex2da-line', 'uav 0 tex2da table 0 0', None, 'uav line refused (only tex2d views are bound)'), + ('a.buffer-line', 'uav 0 raw table 0 0', None, 'uav line refused (buffer view (raw uav) is not bound)'), + ('a.uint-line', 'uav 0 tex2d uint table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), + ('a.channels-field', 'uav 0 tex2d table 0 0 channels 4', None, + 'uav line refused (unexpected field after the table offset)'), + ('a.second-view', 'uav 1 tex2d table 0 0', None, 'uav line refused (view index out of order)'), +) + + +def sentinel(t, m, texel, c): + return 0xc0000000 | t << 12 | m << 8 | texel << 2 | c + + +def expected_words(written): + words = [] + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + for texel in range(n * n): + for c in range(4): + hit = t == written and m == 0 and texel == 2 * n + 1 + words.append(WRITTEN[c] if hit else sentinel(t, m, texel, c)) + return words + + +def describe(index): + """texture, mip, texel and channel of word index of the .uav file.""" + for t in range(TEXTURES): + for m in range(MIPS): + n = SIDE >> m + if index < n * n * 4: + texel, c = divmod(index, 4) + return 'texture %s mip %d texel (%d, %d) word %d' % ('ABCD'[t], m, texel % n, texel // n, c) + index -= n * n * 4 + return 'word past the end' + + +class Program: + """One pixel program published and translated into its own cache.""" + + def __init__(self, directory, consumer, words, env): + self.directory, self.consumer = directory, consumer + directory.mkdir() + self.cache = directory / 'cache' + self.cache.mkdir() + self.vs, self.ps, self.root = (directory / name for name in ('vs', 'ps', 'root')) + self.vs.write_bytes(vertex()) + self.ps.write_bytes(container(0, list(struct.unpack('<%dI' % (len(words) // 4), words)))) + publish = dict(env, X2W_SHADER_CACHE=str(self.cache), X2W_TEST_PIXEL_UAV='a') + publish.pop('X2W_TEST_DEBUG_LAYER', None) + subprocess.run([consumer, self.vs, self.ps, self.root], env=publish, check=True) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', self.cache], env=publish, check=True) + self.manifest, = self.cache.glob('*.txt') + lines = self.manifest.read_text(encoding='ascii').splitlines() + assert lines[0] == 'x2w-manifest 2' and 'uav 0 tex2d table 0 0' in lines and not any( + line.startswith('srv ') for line in lines), lines + + +def run_case(program, name, env, backend, cache=None): + """Returns (returncode, stdout, trap log, render target bytes, texture words).""" + folder = program.directory / name + folder.mkdir() + output, trap = folder / 'pixels', folder / 'trap.log' + case_env = dict(env, X2W_SHADER_CACHE=str(cache or program.cache), X2W_TEST_PIXEL_UAV=name.split('.')[0], + X2W_TRAP_LOG=str(trap)) + run = subprocess.run([program.consumer, program.vs, program.ps, program.root, backend, output], env=case_env, + capture_output=True, text=True) + if run.returncode == 77 and 'no debug layer: skipped' in run.stdout and 'X2W_TEST_DEBUG_LAYER' in env: + # Rule of the neighbouring fixtures: the debug layer is a condition, not a requirement. + print('%s: no debug layer on this machine, run without it' % name) + shutil.rmtree(folder) + env.pop('X2W_TEST_DEBUG_LAYER') + return run_case(program, name, env, backend, cache) + log = trap.read_text(errors='replace') if trap.exists() else '' + pixels = output.read_bytes() if output.exists() else b'' + uav = Path(str(output) + '.uav') + words = list(struct.unpack('<%dI' % (uav.stat().st_size // 4), uav.read_bytes())) if uav.exists() else [] + return run.returncode, run.stdout + run.stderr, log, pixels, words + + +def verdict(name, result, written, reason, drawn): + """None when the case holds, otherwise the first difference.""" + returncode, out, log, pixels, words = result + if returncode: + return 'consumer exited %d\n%s' % (returncode, out[-3000:]) + if 'device removed reason: 0x00000000' not in out: + return 'device removed or no report\n%s' % out[-3000:] + if 'debug layer: on' in out and 'debug layer: on, errors: 0' not in out: + return 'debug layer errors\n%s' % out[-3000:] + want = expected_words(written) + if len(words) != len(want): + return '%d texture words read back, expected %d' % (len(words), len(want)) + for i, (got, expected) in enumerate(zip(words, want)): + if got != expected: + return 'texel_mismatch %s: got %08x, expected %08x' % (describe(i), got, expected) + if (DRAWN_LINE in log) != drawn: + return 'translated draw %s' % ('missing' if drawn else 'present although refused') + if reason and reason not in log: + return 'reason "%s" not logged\n%s' % (reason, log[-3000:]) + if drawn is not None and name in ('a', 'b'): + rows = [pixels[i:i + 32] for i in range(0, len(pixels), 32)] + want_row = WHITE * 4 + CLEAR * 4 + if len(rows) != 4 or any(row != want_row for row in rows): + return 'render target %s, expected the left half white' % pixels.hex() + if not drawn and pixels != CLEAR * 32: + return 'render target changed by a refused draw: %s' % pixels.hex() + return None + + +def recompile_without_guard(program, folder): + """A copy of the exec-off cache whose pixel shader stores without the exec guard.""" + cache = folder / 'cache_unguarded' + shutil.copytree(program.cache, cache) + hlsl, = cache.glob('*.ps.hlsl') + text = hlsl.read_text() + assert (' ' + GUARDED_LINE) in text, text + hlsl.write_text(text.replace(GUARDED_LINE, STORE_LINE)) + fxc = gfx2hlsl.find_fxc() + if not fxc: + return None + cso = hlsl.with_name(hlsl.name.replace('.hlsl', '.cso')) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', str(cso), str(hlsl)], check=True, + capture_output=True) + return cache + + +def check(directory, consumer, backend): + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='0', X2W_D3D12_DEVICE_NOOP='1', X2W_TEST_DEBUG_LAYER='1') + if os.environ.get('X2W_PIXEL_UAV_NO_DEBUG') == '1': + env.pop('X2W_TEST_DEBUG_LAYER') + store = Program(directory / 'store', consumer, WORDS, env) + failures = [] + + def expect(program, name, written, reason, drawn, cache=None): + result = run_case(program, name, env, backend, cache) + if result[0] == 77: + print(result[1]) + sys.exit(77) + problem = verdict(name, result, written, reason, drawn) + adapter = next((line for line in result[1].splitlines() if line.startswith('adapter=')), '') + layer = next((line for line in result[1].splitlines() if line.startswith('debug layer:')), 'debug layer: ?') + stride = next((line.rsplit(' ', 1)[1] for line in result[1].splitlines() if 'title descriptor stride' in line), '?') + layer += '; descriptor stride ' + stride + if problem: + failures.append('%s: %s' % (name, problem)) + print('FAIL %s: %s' % (name, problem.splitlines()[0])) + for line in result[1].splitlines(): + if line.startswith(('debug layer', 'device removed')): + print(' ' + line) + else: + what = ('texel (1, 2) of texture %s written, every other word unchanged' % 'ABCD'[written] if written is not None + else 'every word unchanged') + print('%-13s %s; %s%s [%s; %s]' % (name + ':', 'drawn' if drawn else 'refused', what, + (' (' + reason + ')') if reason else '', adapter, layer)) + return problem + + for name, (_, written, reason, edit) in CASES.items(): + if edit: + text = store.manifest.read_text(encoding='ascii') + assert edit[0] in text + store.manifest.write_text(text.replace(edit[0], edit[1]), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + if edit: + store.manifest.write_text(text, encoding='ascii') + # Other forms of the manifest line, table entry 0: load_translation refuses the translation and nothing is drawn. + text = store.manifest.read_text(encoding='ascii') + for name, replacement, written, reason in LINES: + store.manifest.write_text(text.replace('uav 0 tex2d table 0 0', replacement), encoding='ascii') + try: + expect(store, name, written, reason, written is not None) + finally: + store.manifest.write_text(text, encoding='ascii') + + exec_on = Program(directory / 'exec_on', consumer, EXEC_ON, env) + exec_off = Program(directory / 'exec_off', consumer, EXEC_OFF, env) + for program in (exec_on, exec_off): + assert (' ' + GUARDED_LINE) in next(program.cache.glob('*.ps.hlsl')).read_text() + expect(exec_on, 'a.exec-on', 0, None, True) + expect(exec_off, 'a.exec-off', None, None, True) + # Control: the exec-off shader without the guard writes the texel, and the check above must catch it. + unguarded = recompile_without_guard(exec_off, directory) + if unguarded is None: + print('control exec guard removed: no fxc, not run') + else: + result = run_case(exec_off, 'a.exec-off-unguarded', env, backend, unguarded) + problem = verdict('a', result, None, None, True) + needle = 'texel_mismatch texture A mip 0 texel (1, 2) word 0: got %08x, expected %08x' % (WRITTEN[0], sentinel(0, 0, 9, 0)) + if not problem or not problem.startswith(needle): + failures.append('control exec guard removed was not detected: %s' % problem) + else: + print('control exec guard removed: fails as expected (%s)' % problem) + if failures: + raise SystemExit('\n'.join(failures)) + print('%s: %d cases and the exec guard control' % (backend, len(CASES) + len(LINES) + 2)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) != 3: + raise SystemExit(__doc__) + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 6be711e5e9..8d672d3853 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -483,7 +483,8 @@ int main(int argc, char** argv) const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0 || - GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0; + GetEnvironmentVariableW(L"X2W_TEST_JOINED_TABLE", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index ed6e4717b8..3f2405a97a 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -347,6 +347,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { extern int draw_d16_srvs(ID3D12Device*, void*, void*); if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int draw_pixel_uavs(ID3D12Device*, void*, void*); + if (const int result = draw_pixel_uavs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_VERTEX_FETCH", nullptr, 0)) { // TEXCOORD float3 in slot 0 and POSITION float3 in slot 1, 12 bytes each; vertices 0-2 are unused. Vertices // 3-8 are drawn from start vertex 3: positions cover pixels [1, 3) x [1, 3) of the 8x4 target, texture @@ -492,6 +495,10 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* last = 2; } if (const int rc = submit(last)) return rc; + if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { + extern int report_pixel_uavs(const char*); + if (const int rc = report_pixel_uavs(pixels)) return rc; + } if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_CBV", nullptr, 0)) { extern int root_heap_report(); if (const int rc = root_heap_report()) return rc;