diff --git a/CMakeLists.txt b/CMakeLists.txt index ad93d3a12f..5426f8b499 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -614,6 +614,30 @@ target_compile_features(startup_null_texture_view_check PRIVATE cxx_std_17) add_test(NAME startup_null_texture_view COMMAND startup_null_texture_view_check) add_test(NAME startup_null_texture_view_unchecked_fallback_control COMMAND startup_null_texture_view_check --mutate unchecked-fallback) set_tests_properties(startup_null_texture_view_unchecked_fallback_control PROPERTIES WILL_FAIL TRUE) +# Device views with ViewDimension 0 (UNKNOWN) or a dimension that does not fit the resource +# (src/startup_stubs/view_dimension.h). The control must FAIL. +add_executable(startup_view_dimension tests/startup_view_dimension_check.cpp) +target_include_directories(startup_view_dimension PRIVATE src) +target_compile_features(startup_view_dimension PRIVATE cxx_std_17) +add_test(NAME startup_view_dimension COMMAND startup_view_dimension) +add_test(NAME startup_view_dimension_control COMMAND startup_view_dimension --control) +set_tests_properties(startup_view_dimension_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# The same through d3d12_xs.dll: an unknown-dimension SRV samples its texture's colour, an incompatible explicit SRV is +# refused without device removal, and a refused replacement leaves a null descriptor, not the slot's old view. The +# off control (X2W_D3D12_VIEW_DEFAULTS=off) must fail on the missing default view alone, with the device not removed. +add_executable(startup_view_dimension_device tests/startup_view_dimension_device.cpp) +target_compile_features(startup_view_dimension_device PRIVATE cxx_std_17) +target_link_libraries(startup_view_dimension_device PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_view_dimension_${backend} COMMAND startup_view_dimension_device ${backend}) + set_tests_properties(startup_view_dimension_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0") +endforeach() +add_test(NAME startup_view_dimension_off_control_warp COMMAND startup_view_dimension_device warp off) +set_tests_properties(startup_view_dimension_off_control_warp PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_DEBUG=0;X2W_D3D12_VIEW_DEFAULTS=off" + PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) default view reads 0\\.000 0\\.000 0\\.000 0\\.000, expected 0\\.200 0\\.600 0\\.800 1\\.000; device not removed.*cases complete" + FAIL_REGULAR_EXPRESSION "FAIL: setup|FAIL: \\(b\\)|FAIL: \\(c\\)|FAIL: \\(d\\)|DEVICE REMOVED|removed the device") # The slot and label of the x2w-render totals line each null-binding cause is counted under # (src/startup_stubs/null_binding_cause.h). The mutated run is the negative control. add_executable(startup_null_cause_labels_check tests/startup_null_cause_labels_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e38af186e6..8c855dd14d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -285,6 +285,52 @@ dimensions, formats, resources and counters that are left alone. A rewrite must field of the description. `startup_null_texture_view_unchecked_fallback_control` rewrites without asking about R8G8B8A8 and must fail. +## Unknown and mismatched view dimensions + +A view description with `ViewDimension` 0 (UNKNOWN) makes desktop D3D12 remove the device instead of +failing the call, and so does a dimension that does not suit the resource (debug layer: "The +ViewDimension in the View Desc is incompatible with the type of the Resource"). Measured: a console +package module made such SRVs on 2D RGBA8 textures. Views of device slots 18 to 21 (shader resource, +unordered access, render target, depth stencil) are now checked before they are forwarded: + +- an SRV (slot 18) with dimension 0 gets the resource's default view (a null description) where + desktop allows one: a texture with a typed format that is not a depth format. The default view + replaces the whole description, including its format and component mapping. Only this SRV case is + measured. With dimension 0 every other view is skipped; +- a dimension whose resource dimension differs from the resource's is skipped. + +The default view for UAV, RTV and DSV descriptions with dimension 0 is an explicit experiment, +`X2W_D3D12_VIEW_DEFAULTS=all`: it is unmeasured, and it drops the requested format the same way. +`X2W_D3D12_VIEW_DEFAULTS=off` skips the SRV case too. Any other value, or none, keeps the SRV +default. + +A refused SRV, for any reason, writes a null SRV (R8G8B8A8_UNORM, the requested dimension where it +is a texture dimension, else 2D) into its destination descriptor. Otherwise the slot would keep the +view it held before. That view would still be bindable and would be copied by `CopyDescriptors`, +although the slot's record no longer keeps its resource alive. Translated draws already resolve the +slot to nothing. + +A refused UAV, RTV or DSV leaves the previous descriptor and its tracking record in place. + +The first of each are logged (`x2w-d3d12 Device::slot view dimension ...`), and when a view still +removes the device, its forwarded description and the resource's shape are logged +(`removing view desc`). Run +`ctest --preset dev --no-tests=error -R '^startup_view_dimension(_control)?$'` +(`src/startup_stubs/view_dimension.h`); the control swaps the resource dimension of the mismatched +cases for the matching one and must print `FAIL:`. + +`startup_view_dimension_warp` goes through `d3d12_xs.dll` on WARP. A compute shader samples each +descriptor of a shader-visible heap through the wrapper's desktop heap. The fixture checks three +cases. An unknown-dimension SRV of a texture filled with one distinct colour must read back that +colour. An explicit TEXTURE3D SRV of a 2D texture must be refused with the device not removed. +A descriptor slot that held a valid view of a second colour, then receives a refused TEXTURE2D +SRV of a buffer, must read zero, and so must a `CopyDescriptorsSimple` copy of it. The slot gate +for UAV, RTV and DSV is checked without a device by `startup_view_dimension`. +`startup_view_dimension_off_control_warp` runs the same fixture with +`X2W_D3D12_VIEW_DEFAULTS=off`. It must print `FAIL: (a) default view` with `device not removed`, +so it fails on the missing default view and not on setup or a removed device. Both return 77 +without WARP. + ## 16-bit packed targets A description that asks for a B5G5R5A1_UNORM, B4G4R4A4_UNORM or B5G6R5_UNORM render target is created as @@ -1349,6 +1395,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | +| `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_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) | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 50a37c5aa6..8e344c8e0c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -48,6 +48,7 @@ #include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" +#include "startup_stubs/view_dimension.h" #include "startup_stubs/list_copy.h" #include "startup_stubs/d3d12_teardown.h" #include "startup_stubs/rect_indirect_args.h" @@ -4095,6 +4096,39 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR return S_OK; } +// A null R8G8B8A8_UNORM SRV of a texture dimension (2 to 10; any other value gives texture 2D). A null resource +// reads no more of the description than its format and dimension. +D3D12_SHADER_RESOURCE_VIEW_DESC null_srv_desc(unsigned dimension) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.ViewDimension = static_cast(x2w_view_dimension::refused_srv_null_dimension(dimension)); + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; + default: desc.Texture2D.MipLevels = 1; break; + } + return desc; +} + +// X2W_D3D12_VIEW_DEFAULTS (view_dimension.h): which slots give an unknown-dimension view the resource's default view. +x2w_view_dimension::DefaultViews view_defaults_mode() +{ + static const x2w_view_dimension::DefaultViews mode = [] { + char value[8]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", value, sizeof(value)); + return x2w_view_dimension::default_views_mode(n && n < sizeof(value) ? value : nullptr); + }(); + return mode; +} + // Device view slots: forwarded with the destination CPU handle (argument D, 0-based after the // object) translated from title to desktop. // Desktop removes the device (DXGI_ERROR_INVALID_CALL) on view calls it rejects, so they are checked @@ -4124,6 +4158,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) described_bytes, title_dest, args[D], materialized); }; const char* skip = nullptr; + bool default_view = false; if (N == 17) skip = "constant buffer view (title GPU address)"; if (N >= 18 && N <= 21 && args[0]) { const UINT flags = reinterpret_cast(args[0])->GetDesc().Flags; @@ -4131,9 +4166,56 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if (N == 19 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) skip = "resource lacks unordered access"; if (N == 20 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) skip = "resource lacks render target"; if (N == 21 && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) skip = "resource lacks depth stencil"; + // Every view description of slots 18-21 starts with Format, then ViewDimension. + const u64 described = N == 19 ? args[2] : args[1]; + UINT view_dimension = 0; + if (!skip && described && x2w_local::readable(reinterpret_cast(described), 8)) { + std::memcpy(&view_dimension, reinterpret_cast(described) + 4, sizeof(view_dimension)); + const D3D12_RESOURCE_DESC resource_desc = reinterpret_cast(args[0])->GetDesc(); + const auto dimension = static_cast(resource_desc.Dimension); + if (view_dimension == 0) { + // UNKNOWN: desktop refuses it; make the resource's default view where that is allowed. By default only + // SRVs (slot 18) get one; UAV, RTV and DSV need X2W_D3D12_VIEW_DEFAULTS=all (view_dimension.h). + const auto mode = view_defaults_mode(); + if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), mode)) + default_view = true; + else if (x2w_view_dimension::default_view_allowed(N, dimension, static_cast(resource_desc.Format), + x2w_view_dimension::DefaultViews::all)) + skip = mode == x2w_view_dimension::DefaultViews::off + ? "unknown view dimension, and default views are off (X2W_D3D12_VIEW_DEFAULTS=off)" + : "unknown view dimension; a default view of this type needs X2W_D3D12_VIEW_DEFAULTS=all"; + else + skip = "unknown view dimension, and the resource has no default view"; + static LONG unknown_dimension; + if (first_calls(unknown_dimension, 6)) + log("x2w-d3d12 Device::slot%d view dimension 0 (unknown), view format %u, resource dim=%u fmt=%d -> %s", N, + *reinterpret_cast(described), dimension, resource_desc.Format, + default_view ? "default view" : "skipped"); + } else if (!x2w_view_dimension::fits(N, view_dimension, dimension)) { + skip = "view dimension does not suit the resource"; + static LONG mismatched; + if (first_calls(mismatched, 6)) + log("x2w-d3d12 Device::slot%d view dimension %u needs resource dimension %u, resource has %u", N, view_dimension, + x2w_view_dimension::needed(N, view_dimension), dimension); + } + } } + // Replace a refused SRV in both the desktop heap and the descriptor record. A skipped UAV, RTV or DSV + // does not write a replacement to the desktop heap, so its previous descriptor record must stay live. + const auto refuse_view = [&] { + if constexpr (N == 18) { + UINT requested = D3D12_SRV_DIMENSION_TEXTURE2D; + if (args[1] && x2w_local::readable(reinterpret_cast(args[1]), 8)) + std::memcpy(&requested, reinterpret_cast(args[1]) + 4, sizeof(requested)); + const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = null_srv_desc(requested); + device_of(self)->CreateShaderResourceView(nullptr, &null_view, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(args[D])}); + record_view(false); + } else if constexpr (N == 17) { + record_view(false); // Translated constant-buffer views use only the descriptor record. + } + }; if (skip) { - record_view(false); + refuse_view(); static LONG skipped; if (first_calls(skipped, 6)) log("x2w-d3d12 Device::slot%d view skipped: %s", N, skip); return 0; @@ -4155,7 +4237,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) const auto actual = resource->GetDesc().Format; const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); if (verdict == x2w_startup::PackedView::refused) { - record_view(false); + refuse_view(); static LONG refused; if (first_calls(refused, 6)) log("x2w-d3d12 Device::slot%d view skipped: packed format %d on a texture of format %d that does not stand in for it", @@ -4183,6 +4265,8 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) *reinterpret_cast(b), null_rtv)) args[1] = reinterpret_cast(&null_rtv); } + if (default_view) args[desc_index] = 0; + const LONG removed_before = removal_reported; const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view @@ -4199,6 +4283,19 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) if ((N == 20 || N == 21) && args[0] && created) note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); + if (!removed_before && removal_reported && N >= 18 && N <= 21) { + // The view that removed the device: its forwarded description and the resource's shape. + char bytes[3 * 40 + 1] = {}; + const u64 described = args[desc_index]; + if (described) hex_text(reinterpret_cast(described), 40, bytes, sizeof(bytes)); + log("x2w-d3d12 Device::slot%d removing view desc %s", N, described ? bytes : "(null)"); + if (args[0]) { + const D3D12_RESOURCE_DESC rd = reinterpret_cast(args[0])->GetDesc(); + log("x2w-d3d12 Device::slot%d removing view resource: dim=%d %llux%u depth/array=%u mips=%u fmt=%d samples=%u flags=0x%x", N, + rd.Dimension, static_cast(rd.Width), rd.Height, rd.DepthOrArraySize, rd.MipLevels, rd.Format, + rd.SampleDesc.Count, static_cast(rd.Flags)); + } + } static LONG calls; if (first_calls(calls)) log("x2w-d3d12 Device::slot%d view(0x%llx, 0x%llx, 0x%llx, 0x%llx) dest 0x%llx -> 0x%llx", N, a, b, c, d, @@ -4863,28 +4960,9 @@ void retire_resource(Wrapper* w) // resolves to nothing). A null resource reads no more of the description than its format and dimension. D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) { - D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - if (record.desc_bytes >= 40) { - D3D12_SRV_DIMENSION dimension; - std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); - if (dimension >= D3D12_SRV_DIMENSION_TEXTURE1D && dimension <= D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) - desc.ViewDimension = dimension; - } - switch (desc.ViewDimension) { - case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; - case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; - case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; - default: desc.Texture2D.MipLevels = 1; break; - } - return desc; + unsigned dimension = D3D12_SRV_DIMENSION_TEXTURE2D; + if (record.desc_bytes >= 40) std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); + return null_srv_desc(dimension); } // True when the release-time fence of every queue has passed (retire_lock held). diff --git a/src/startup_stubs/view_dimension.h b/src/startup_stubs/view_dimension.h new file mode 100644 index 0000000000..52bf92e385 --- /dev/null +++ b/src/startup_stubs/view_dimension.h @@ -0,0 +1,105 @@ +// Experimental (docs/startup-runtime.md): whether a view description's ViewDimension suits the +// resource it is made on. Desktop D3D12 removes the device (DXGI_ERROR_INVALID_CALL, debug-layer +// message "The ViewDimension in the View Desc is incompatible with the type of the Resource") +// instead of failing the call, so the stand-in checks first and skips such a view with a log. +// Values are the public d3d12.h enumerations. Pure, no Windows calls, so a control can check it. +#pragma once + +namespace x2w_view_dimension { + +enum ResourceDimension : unsigned { unknown = 0, buffer = 1, texture1d = 2, texture2d = 3, texture3d = 4 }; + +// Which resource dimension one view dimension needs, by the device slot that makes the view +// (18 shader resource, 19 unordered access, 20 render target, 21 depth stencil). unknown when the +// view dimension is not one of that view type's values (or is 0); such a view is not judged here. +inline unsigned needed(int slot, unsigned view_dimension) noexcept +{ + switch (slot) { + case 18: // D3D12_SRV_DIMENSION + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: case 9: case 10: return texture2d; // 2D, arrays, MS, cube, cube array + case 8: return texture3d; + default: return unknown; // 11 is a raytracing structure, made with a null resource + } + case 19: // D3D12_UAV_DIMENSION + case 20: // D3D12_RTV_DIMENSION (same numbering) + switch (view_dimension) { + case 1: return buffer; + case 2: case 3: return texture1d; + case 4: case 5: case 6: case 7: return texture2d; + case 8: return texture3d; + default: return unknown; + } + case 21: // D3D12_DSV_DIMENSION + switch (view_dimension) { + case 1: case 2: return texture1d; + case 3: case 4: case 5: case 6: return texture2d; + default: return unknown; + } + default: + return unknown; + } +} + +// False only when the view dimension names a resource dimension other than the resource's. +inline bool fits(int slot, unsigned view_dimension, unsigned resource_dimension) noexcept +{ + const unsigned need = needed(slot, view_dimension); + return need == unknown || need == resource_dimension; +} + +// A description with ViewDimension 0 (UNKNOWN) is always refused by desktop D3D12. Measured: a +// title module makes one on a two-dimensional RGBA8 texture (format R32G32B32A32_FLOAT, default +// component mapping). The stand-in makes the resource's default view instead (a null description), +// which desktop allows only for a texture with a typed format, and for a shader resource view not +// a depth format. Whether the console gives UNKNOWN that meaning is a hypothesis. +inline bool typeless(unsigned format) noexcept +{ + switch (format) { + case 1: case 5: case 9: case 15: case 19: case 23: case 27: case 33: case 39: case 44: case 48: case 53: case 59: + case 70: case 73: case 76: case 79: case 82: case 90: case 92: case 94: case 97: + return true; + default: + return false; + } +} + +inline bool depth_format(unsigned format) noexcept { return format == 20 || format == 40 || format == 45 || format == 55; } + +// Which slots may get the default view. It is measured only for shader resource views (slot 18) of +// typed textures, so that is the default. The default view also drops the requested format and +// component mapping, so for the other view types it stays an explicit experiment +// (X2W_D3D12_VIEW_DEFAULTS=all). off: every unknown-dimension view is skipped. +enum class DefaultViews : unsigned { off, srv, all }; + +// X2W_D3D12_VIEW_DEFAULTS: "all" or "off"; anything else, or unset, is srv. +inline DefaultViews default_views_mode(const char* value) noexcept +{ + if (!value) return DefaultViews::srv; + if (value[0] == 'a' && value[1] == 'l' && value[2] == 'l' && value[3] == 0) return DefaultViews::all; + if (value[0] == 'o' && value[1] == 'f' && value[2] == 'f' && value[3] == 0) return DefaultViews::off; + return DefaultViews::srv; +} + +inline bool default_view_allowed(int slot, unsigned resource_dimension, unsigned resource_format, DefaultViews mode) noexcept +{ + if (slot < 18 || slot > 21) return false; + if (mode == DefaultViews::off || (mode == DefaultViews::srv && slot != 18)) return false; + if (resource_dimension == unknown || resource_dimension == buffer) return false; + if (resource_format == 0 || typeless(resource_format)) return false; + if (slot == 18 && depth_format(resource_format)) return false; + return true; +} + +// The dimension of the null SRV that replaces a refused one in its destination slot, so that the slot +// cannot keep the view it held before (a skipped call would otherwise leave that descriptor in place, +// bindable and copyable, after the slot's record has dropped its resource). The requested dimension +// when it is a texture dimension (2 to 10), else texture 2D (4). +inline unsigned refused_srv_null_dimension(unsigned requested) noexcept +{ + return requested >= 2 && requested <= 10 ? requested : 4; +} + +} // namespace x2w_view_dimension diff --git a/tests/startup_view_dimension_check.cpp b/tests/startup_view_dimension_check.cpp new file mode 100644 index 0000000000..a4b328a7af --- /dev/null +++ b/tests/startup_view_dimension_check.cpp @@ -0,0 +1,122 @@ +// Source-built control for view_dimension.h: whether a view's ViewDimension suits the dimension of +// the resource it is made on (desktop D3D12 removes the device for a mismatch). Values are the +// public d3d12.h enumerations. --control swaps the resource dimension of the mismatched cases for +// the matching one and enables default views for every slot in the gated cases, so the checks +// that expect a refusal must print FAIL. +#include +#include + +#include "startup_stubs/view_dimension.h" + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +// A refusal case: in the control the resource is given the dimension the view needs. +bool refused(int slot, unsigned view_dimension, unsigned resource_dimension) +{ + using namespace x2w_view_dimension; + if (control) resource_dimension = needed(slot, view_dimension); + return !fits(slot, view_dimension, resource_dimension); +} +} // namespace + +int main(int argc, char** argv) +{ + using namespace x2w_view_dimension; + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + + // Matching shapes are accepted. + check("SRV texture 2D on a 2D texture", fits(18, 4, texture2d)); + check("SRV cube on a 2D texture", fits(18, 9, texture2d)); + check("SRV cube array on a 2D texture", fits(18, 10, texture2d)); + check("SRV texture 3D on a 3D texture", fits(18, 8, texture3d)); + check("SRV buffer on a buffer", fits(18, 1, buffer)); + check("SRV texture 1D array on a 1D texture", fits(18, 3, texture1d)); + check("UAV texture 2D array on a 2D texture", fits(19, 5, texture2d)); + check("UAV texture 3D on a 3D texture", fits(19, 8, texture3d)); + check("RTV buffer on a buffer", fits(20, 1, buffer)); + check("RTV texture 2D on a 2D texture", fits(20, 4, texture2d)); + check("DSV texture 1D on a 1D texture", fits(21, 1, texture1d)); + check("DSV texture 2D on a 2D texture", fits(21, 3, texture2d)); + + // Values this check does not judge pass on: unknown dimension, raytracing structure, other slots. + check("SRV unknown dimension is not judged", fits(18, 0, texture3d)); + check("SRV raytracing structure is not judged", fits(18, 11, unknown)); + check("out-of-range SRV dimension is not judged", fits(18, 99, buffer)); + check("DSV dimension 7 is not judged", fits(21, 7, buffer)); + check("sampler slot is not judged", fits(22, 4, buffer)); + + // Mismatches are refused (the control turns each into a match, so these print FAIL). + check("SRV texture 2D on a 3D texture is refused", refused(18, 4, texture3d)); + check("SRV texture 3D on a 2D texture is refused", refused(18, 8, texture2d)); + check("SRV buffer on a 2D texture is refused", refused(18, 1, texture2d)); + check("SRV cube on a 3D texture is refused", refused(18, 9, texture3d)); + check("UAV texture 2D on a buffer is refused", refused(19, 4, buffer)); + check("RTV texture 3D on a 2D texture is refused", refused(20, 8, texture2d)); + check("DSV texture 2D on a 1D texture is refused", refused(21, 3, texture1d)); + + // ViewDimension 0 (unknown): a default view only where desktop allows a null description. Under + // X2W_D3D12_VIEW_DEFAULTS=all (experimental) every view type may get one. + const auto all = DefaultViews::all, srv = DefaultViews::srv, off = DefaultViews::off; + check("default SRV of an RGBA8 2D texture", default_view_allowed(18, texture2d, 28, all)); + check("default RTV of an RGBA8 2D texture", default_view_allowed(20, texture2d, 28, all)); + check("default DSV of a D32 2D texture", default_view_allowed(21, texture2d, 40, all)); + check("default SRV of a 3D texture", default_view_allowed(18, texture3d, 10, all)); + const auto no_default = [all](int slot, unsigned dimension, unsigned format) { + if (control) dimension = texture2d, format = 28; // a texture that has a default view + return !default_view_allowed(slot, dimension, format, all); + }; + check("no default view of a buffer", no_default(18, buffer, 28)); + check("no default view of a typeless texture", no_default(18, texture2d, 27)); + check("no default view of a typeless BC7 texture", no_default(19, texture2d, 97)); + check("no default SRV of a depth texture", no_default(18, texture2d, 40)); + check("no default view of an unknown format", no_default(18, texture2d, 0)); + check("no default view on the constant-buffer slot", !default_view_allowed(17, texture2d, 28, all)); + + // The default (srv): only the measured typed-SRV case; UAV, RTV and DSV need the experiment. + // The control enables all slots, so the three refusals print FAIL. + const auto gated = [all, srv](int slot, unsigned dimension, unsigned format) { + return !default_view_allowed(slot, dimension, format, control ? all : srv); + }; + check("default SRV of an RGBA8 2D texture without the experiment", default_view_allowed(18, texture2d, 28, srv)); + check("default SRV of a 3D texture without the experiment", default_view_allowed(18, texture3d, 10, srv)); + check("no default SRV of a depth texture without the experiment", !default_view_allowed(18, texture2d, 40, srv)); + check("no default UAV without the experiment", gated(19, texture2d, 28)); + check("no default RTV without the experiment", gated(20, texture2d, 28)); + check("no default DSV without the experiment", gated(21, texture2d, 40)); + check("off: no default SRV", !default_view_allowed(18, texture2d, 28, off)); + check("off: no default RTV", !default_view_allowed(20, texture2d, 28, off)); + + // X2W_D3D12_VIEW_DEFAULTS parsing: exact "all" or "off", anything else is the default. + check("unset is srv", default_views_mode(nullptr) == srv); + check("empty is srv", default_views_mode("") == srv); + check("all", default_views_mode("all") == all); + check("off", default_views_mode("off") == off); + check("ALL is srv", default_views_mode("ALL") == srv); + check("allx is srv", default_views_mode("allx") == srv); + check("1 is srv", default_views_mode("1") == srv); + + // A refused SRV's null descriptor keeps a texture dimension and turns the rest into texture 2D. + check("null for a refused 3D view is 3D", refused_srv_null_dimension(8) == 8); + check("null for a refused cube array is a cube array", refused_srv_null_dimension(10) == 10); + check("null for a refused 1D view is 1D", refused_srv_null_dimension(2) == 2); + check("null for a refused unknown view is 2D", refused_srv_null_dimension(0) == 4); + check("null for a refused buffer view is 2D", refused_srv_null_dimension(1) == 4); + check("null for a refused raytracing view is 2D", refused_srv_null_dimension(11) == 4); + + if (failures) { + std::printf("startup_view_dimension: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_view_dimension: ok"); + return 0; +} diff --git a/tests/startup_view_dimension_device.cpp b/tests/startup_view_dimension_device.cpp new file mode 100644 index 0000000000..823b6c7c77 --- /dev/null +++ b/tests/startup_view_dimension_device.cpp @@ -0,0 +1,425 @@ +// Device slot 18 (CreateShaderResourceView) through d3d12_xs.dll with view descriptions whose ViewDimension is +// unknown or does not suit the resource (src/startup_stubs/view_dimension.h, docs/startup-runtime.md#unknown-and- +// mismatched-view-dimensions). +// +// startup_view_dimension_device [off] +// +// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue +// samples texel (0,0) through a slot of a shader-visible guest heap, by the desktop heap behind it. A null +// descriptor reads zero. +// (a) an SRV with ViewDimension 0 and a requested format that differs from the texture's (R32G32B32A32_FLOAT on an +// R8G8B8A8_UNORM texture) gets the texture's default view: the slot samples the texture's distinct colour. +// (b) an explicit TEXTURE3D SRV of the 2D texture is refused: the device is not removed. +// (c) a slot that holds a valid view of a second texture (its colour is read first) receives a refused TEXTURE2D +// SRV of a buffer. The device is not removed and the slot reads zero: the refusal leaves a null SRV, not the +// old descriptor. A CopyDescriptorsSimple copy of the slot over another valid view reads zero too. +// (d) a refused UAV replacement leaves the prior descriptor and its title token intact. +// +// `off` is the negative control and needs X2W_D3D12_VIEW_DEFAULTS=off: (a) must then fail, printing +// "FAIL: (a) default view reads 0.000 0.000 0.000 0.000 ... device not removed", and nothing else may fail. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +constexpr UINT side = 4, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr std::uint8_t colour_a[4] = {51, 153, 204, 255}; // 0.2 0.6 0.8 1.0 +constexpr std::uint8_t colour_b[4] = {255, 64, 0, 128}; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: setup: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +constexpr char probe_shader[] = R"( +Texture2D source : register(t0); +SamplerState point_sampler : register(s0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.SampleLevel(point_sampler, float2(0.125, 0.125), 0))); +} +)"; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + UINT64 value = 0; + HANDLE event = nullptr; + ComPtr upload, readback, probe_out; + ComPtr root; + ComPtr pso; + ComPtr heap; + ComPtr heap_real; + UINT64 heap_cpu = 0; + UINT increment = 0; + + bool run() + { + if (!require(list->Close(), "list close")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!require(queue->Signal(fence.Get(), ++value), "signal")) return false; + if (fence->GetCompletedValue() >= value) return true; + if (!require(fence->SetEventOnCompletion(value, event), "fence event")) return false; + if (WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0) return true; + std::puts("FAIL: setup: queue timed out"); + return false; + } + bool begin() { return require(allocator->Reset(), "allocator reset") && require(list->Reset(allocator.Get(), nullptr), "list reset"); } + ComPtr committed(const D3D12_RESOURCE_DESC& desc, const char* name) + { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + const GUID iid = __uuidof(ID3D12Resource); + ComPtr out; + if (!require(invoke(guest, 127, &props, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid, out.GetAddressOf()), name)) + out.Reset(); + return out; + } + // Fills every texel of a guest 2D texture with one colour through its desktop object. + bool fill(IUnknown* texture, const std::uint8_t (&colour)[4]) + { + const auto real = desktop_object(guest, device, texture); + if (!real) { + std::puts("FAIL: setup: texture has no desktop object"); + return false; + } + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast(mapped); + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < side; ++x) std::memcpy(dst + y * pitch + x * 4, colour, 4); + upload->Unmap(0, nullptr); + if (!begin()) return false; + D3D12_TEXTURE_COPY_LOCATION to{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + to.SubresourceIndex = 0; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + from.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + list->ResourceBarrier(1, &b); + return run(); + } + // Samples texel (0,0) through the desktop descriptor behind slot `index` of the guest heap. + bool read_slot(UINT index, float (&texel)[4]) + { + if (!begin()) return false; + ID3D12DescriptorHeap* bound = heap_real.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = heap_real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + list->SetDescriptorHeaps(1, &bound); + list->SetComputeRootSignature(root.Get()); + list->SetPipelineState(pso.Get()); + list->SetComputeRootDescriptorTable(0, gpu); + list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + list->ResourceBarrier(1, &b); + list->CopyBufferRegion(readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + list->ResourceBarrier(1, &b); + if (!run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + readback->Unmap(0, nullptr); + return true; + } + const char* device_state() + { + return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)) ? "device not removed" + : "DEVICE REMOVED"; + } + bool device_ok() { return SUCCEEDED(device->GetDeviceRemovedReason()) && SUCCEEDED(invoke(guest, 37)); } + // want: the colour the slot must sample, or nullptr for null (all zero). *failed is set on a mismatch; false is + // returned only when the probe itself could not run. + bool expect(UINT index, const std::uint8_t* want, const char* what, bool* failed) + { + float texel[4]{}; + if (!read_slot(index, texel)) return false; + bool match = true; + for (int i = 0; i < 4; ++i) { + const float expected = want ? want[i] / 255.0f : 0.0f; + if (std::fabs(texel[i] - expected) > 0.5f / 255.0f) match = false; + } + if (match) { + std::printf("%s: reads %.3f %.3f %.3f %.3f as expected\n", what, texel[0], texel[1], texel[2], texel[3]); + return true; + } + std::printf("FAIL: %s reads %.3f %.3f %.3f %.3f, expected ", what, texel[0], texel[1], texel[2], texel[3]); + if (want) std::printf("%.3f %.3f %.3f %.3f", want[0] / 255.0f, want[1] / 255.0f, want[2] / 255.0f, want[3] / 255.0f); + else std::printf("null (all zero)"); + std::printf("; %s\n", device_state()); + *failed = true; + return true; + } + UINT64 slot(UINT index) const { return heap_cpu + std::uint64_t{index} * increment; } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture2d_view() +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + return srv; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off"))) + return 2; + const bool off = argc == 3; + char mode[8]{}; + const DWORD mode_n = GetEnvironmentVariableA("X2W_D3D12_VIEW_DEFAULTS", mode, sizeof(mode)); + const bool env_off = mode_n == 3 && std::strcmp(mode, "off") == 0; + if (env_off != off || (!off && mode_n)) { + std::puts("FAIL: setup: X2W_D3D12_VIEW_DEFAULTS must be unset, or off with the `off` argument"); + return 2; + } + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls debug_layer=off view_defaults=%s\n", adapter_desc.Description, off ? "off" : "unset (srv)"); + + Context c{guest.Get(), device.Get()}; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}, + default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC out_desc = buffer; + out_desc.Width = 256; + out_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.queue)), "queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.allocator)), "allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.allocator.Get(), nullptr, IID_PPV_ARGS(&c.list)), "list") || + !require(c.list->Close(), "list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.fence)), "fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback") || + !require(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe output")) + return 4; + + // The probe: samples (0,0) through descriptor table slot 0 with a point sampler. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER root_parameters[2]{}; + root_parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + root_parameters[0].DescriptorTable = {1, &range}; + root_parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + root_parameters[1].Descriptor = {0, 0}; + D3D12_STATIC_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, root_parameters, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), IID_PPV_ARGS(&c.root)), + "root signature") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe shader")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.pso)), "probe pipeline")) return 4; + + // A shader-visible guest heap of four SRV slots. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + if (!require(invoke(c.guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), c.heap.GetAddressOf()), "guest heap")) return 4; + c.heap_real = desktop_object(c.guest, device.Get(), c.heap.Get()); + if (!c.heap_real) { + std::puts("FAIL: setup: guest heap has no desktop object"); + return 4; + } + c.heap_cpu = invoke(c.heap.Get(), 9); + + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC small_buffer = buffer; + small_buffer.Width = 256; + const auto texture_a = c.committed(texture_desc, "texture A"); + const auto texture_b = c.committed(texture_desc, "texture B"); + const auto buffer_c = c.committed(small_buffer, "buffer"); + if (!texture_a || !texture_b || !buffer_c || !c.fill(texture_a.Get(), colour_a) || !c.fill(texture_b.Get(), colour_b)) + return 4; + if (!c.device_ok()) { + std::puts("FAIL: setup: device removed before the cases"); + return 4; + } + + bool failed = false; + // (a) ViewDimension 0 with another format: the texture's default view. + D3D12_SHADER_RESOURCE_VIEW_DESC unknown{}; + unknown.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + unknown.ViewDimension = D3D12_SRV_DIMENSION_UNKNOWN; + unknown.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + invoke(c.guest, 18, texture_a.Get(), &unknown, c.slot(0)); + if (!c.device_ok()) { + std::puts("FAIL: (a) the unknown-dimension SRV removed the device"); + return 5; + } + if (!c.expect(0, colour_a, "(a) default view", &failed)) return 4; + + // (b) an explicit TEXTURE3D SRV of the 2D texture: refused, the device stays. + D3D12_SHADER_RESOURCE_VIEW_DESC volume = texture2d_view(); + volume.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume.Texture3D = {0, 1, 0.0f}; + invoke(c.guest, 18, texture_a.Get(), &volume, c.slot(1)); + if (!c.device_ok()) { + std::puts("FAIL: (b) the incompatible explicit SRV was forwarded and removed the device"); + return 5; + } + std::puts("(b) TEXTURE3D SRV of a 2D texture: refused, device not removed"); + + // (c) a refused replacement over a valid view, and a copy of the slot over another valid view. + const auto valid = texture2d_view(); + invoke(c.guest, 18, texture_b.Get(), &valid, c.slot(2)); + invoke(c.guest, 18, texture_b.Get(), &valid, c.slot(3)); + bool setup_failed = false; + if (!c.expect(2, colour_b, "(c) valid view before the replacement", &setup_failed) || + !c.expect(3, colour_b, "(c) valid copy target before the copy", &setup_failed)) + return 4; + if (setup_failed) { + std::puts("FAIL: setup: valid views do not read their texture"); + return 4; + } + invoke(c.guest, 18, buffer_c.Get(), &valid, c.slot(2)); // TEXTURE2D of a buffer + if (!c.device_ok()) { + std::puts("FAIL: (c) the refused replacement removed the device"); + return 5; + } + if (!c.expect(2, nullptr, "(c) slot after the refused replacement", &failed)) return 4; + invoke(c.guest, 24, 1u, c.slot(3), c.slot(2), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!c.expect(3, nullptr, "(c) copy of the refused slot", &failed)) return 4; + + auto uav_desc = texture_desc; + uav_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto uav_texture = c.committed(uav_desc, "UAV texture"); + if (!uav_texture) return 4; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; + uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + const auto uav_slot = c.slot(1); + invoke(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + if (!c.device_ok()) return 5; + std::array before{}, after{}; + std::memcpy(before.data(), reinterpret_cast(uav_slot), sizeof(before)); + if (!before[0] || before[2] != 19) { + std::puts("FAIL: (d) no valid UAV token before the replacement"); + return 4; + } + uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + uav.Texture3D = {0, 0, 1}; + invoke(c.guest, 19, uav_texture.Get(), static_cast(nullptr), &uav, uav_slot); + std::memcpy(after.data(), reinterpret_cast(uav_slot), sizeof(after)); + if (after != before) { + std::puts("FAIL: (d) refused UAV replacement changed the live descriptor token"); + failed = true; + } else { + std::puts("(d) refused UAV replacement kept the live descriptor token"); + } + + if (!c.device_ok()) { + std::puts("FAIL: device removed after the cases"); + return 5; + } + std::printf("cases complete, %s\n", failed ? "with failures" : "all passed"); + if (failed) return 1; + std::puts("startup_view_dimension_device: default SRV samples its texture; refused SRVs leave null descriptors; " + "device not removed"); + return 0; +}