From 74bf391fdae4e5d5c81314b8abe05412807d4f69 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:46:46 -0600 Subject: merge follow-up: the test tree builds again - xmem.cpp: rt::xmem::commit_physical_range and commit_physical_pages exist for the run-mapped xmem too (pages are committed when allocated, so they only check the range), and main.cpp registers the slot 133 hook as main does. - vk_test_device.h: VK_EXT_external_memory_host and host_pointer_alignment are back next to the A8 render target probe; d3d12_existing_heap_test and d3d12_xmem_placed_test use them. - xs_proxy_mock_test.cpp: the stack's version, which tests the proxy that is in the tree (the automatic merge left two list mocks in one switch). - d3d12_xs_device.cpp: no include of vulkan_replay.h, which the proxy tests without Vulkan headers could not compile, and the diagnostic that needed it is gone. Every target builds with clang-cl 22.1.8 + xwin. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/src/main.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'runtime/src/main.cpp') diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 7d0dbfd88..63bd016e8 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -177,8 +177,7 @@ int wmain(int argc, wchar_t** argv) { } rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. - // MERGE NOTE: main registers rt::xmem::commit_physical_range here for its commit-on-touch xmem. This branch keeps - // the run-mapped xmem (pages are committed when allocated), so there is nothing to commit before slot 133. + rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); -- cgit v1.2.3 From db19bbd3455a757c3fe986c6e6db36998f275150 Mon Sep 17 00:00:00 2001 From: Rain156 <77776581+Rain156@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:19:30 +0800 Subject: runtime: connect native pipelines and title resources to the offline first-run UI Build on the public frame-loop integration in #321. Carry the texture-view and depth work from #213 and #261, the layout provider from #461, the responsive window from #526, and the rectangle generator from #682. Integrate the Xbox constant-buffer row addressing measured in #513 and the draw-time rectangle selection in #722. Keep all fixtures synthetic. The Windows GPU path resolves title-owned shader objects, retires geometry uploads per submission, materializes texture views on use, maps linear surfaces, and delivers completed GPU label writes. A first-run UI launch selects the tested settings for these paths. --- docs/d3d12_vulkan.md | 99 +- docs/runtime_imports.md | 20 +- docs/testing.md | 24 +- runtime/CMakeLists.txt | 159 ++- runtime/shims/d3d12_com.cpp | 159 ++- runtime/shims/d3d12_com.h | 32 +- runtime/shims/d3d12_vulkan_device.cpp | 1776 +++++++++++++++++++++---- runtime/shims/d3d12_xs_device.cpp | 495 +++++-- runtime/shims/d3d12_xs_device.h | 62 +- runtime/shims/d3d12_xs_native_pso.h | 234 ++++ runtime/shims/d3d12_xs_placed_depth.h | 134 ++ runtime/shims/d3d12_xs_pso_stream.cpp | 340 +++++ runtime/shims/d3d12_xs_pso_stream.h | 85 ++ runtime/shims/dstorage.cpp | 28 +- runtime/shims/file_system.cpp | 36 + runtime/shims/present_window.h | 72 + runtime/shims/xg_xs.cpp | 490 ++++++- runtime/shims/xgameruntime_offline.cpp | 67 +- runtime/shims/xmem.cpp | 386 ++++-- runtime/shims/xmem.h | 3 + runtime/src/command_list.h | 9 +- runtime/src/console_texture_layout.h | 610 +++++++++ runtime/src/depth24_fragment.h | 18 +- runtime/src/frame_pacer.h | 23 +- runtime/src/gfx10_descriptors.h | 20 + runtime/src/gpu_label_memory.h | 77 ++ runtime/src/main.cpp | 46 +- runtime/src/native_pso.h | 332 +++++ runtime/src/queue_families.h | 10 + runtime/src/rect_list_geometry.h | 108 +- runtime/src/rgba4_fragment.h | 81 ++ runtime/src/title_va_alias.h | 30 +- runtime/src/vulkan13_features.h | 6 + runtime/src/vulkan_backend.h | 79 +- runtime/src/vulkan_bindless.h | 81 +- runtime/src/vulkan_gpu_labels.h | 156 +++ runtime/src/vulkan_graphics_shader_modules.h | 61 + runtime/src/vulkan_replay.h | 342 ++++- runtime/src/vulkan_scratch.h | 9 +- runtime/test/bindless_sizing_test.cpp | 52 +- runtime/test/d3d12_bundle_test.cpp | 89 +- runtime/test/d3d12_compute_test.cpp | 8 +- runtime/test/d3d12_depth_stencil_uav_test.cpp | 556 ++++++++ runtime/test/d3d12_depth_stencil_uav_views.h | 79 ++ runtime/test/d3d12_draw_test.cpp | 41 +- runtime/test/d3d12_m2_textured_test.cpp | 252 +++- runtime/test/d3d12_mesh_test.cpp | 3 + runtime/test/d3d12_native_graphics_fixture.h | 55 + runtime/test/d3d12_placed_depth_test.h | 141 ++ runtime/test/d3d12_r9g9b9e5_uav_test.cpp | 98 +- runtime/test/d3d12_rect_list_test.cpp | 125 +- runtime/test/d3d12_test_shaders.h | 15 +- runtime/test/d3d12_texture1d_target_test.cpp | 4 + runtime/test/d3d12_texture1d_test.cpp | 15 +- runtime/test/d3d12_texture_uav_oracle.h | 279 ++++ runtime/test/d3d12_texture_uav_test.cpp | 629 +++++++++ runtime/test/d3d12_title_va_test.cpp | 146 +- runtime/test/d3d12_translated_draw_test.cpp | 67 +- runtime/test/d3d12_xmem_placed_test.cpp | 110 +- runtime/test/device_proxy_test.cpp | 16 + runtime/test/file_system_test.cpp | 59 + runtime/test/frame_pacer_test.cpp | 23 + runtime/test/glsl/cs_depth_stencil_uav.comp | 55 + runtime/test/glsl/cs_r9g9b9e5_uav.comp | 21 +- runtime/test/glsl/cs_user_data.comp | 18 +- runtime/test/pso_stream_test.cpp | 268 ++++ runtime/test/replay_texture_barrier_test.cpp | 175 +++ runtime/test/replay_uav_clear_offset_test.cpp | 38 + runtime/test/shaders/check.py | 30 +- runtime/test/shaders/cs_cbv_vector_rows.asm | 42 + runtime/test/shaders/cs_imgatomic3d.asm | 4 +- runtime/test/shaders/cs_imgload_mip.asm | 44 + runtime/test/shaders/cs_texture_uav.asm | 105 ++ runtime/test/shaders/ps_imgatomic.asm | 4 +- runtime/test/vk_bindless_test.cpp | 62 +- runtime/test/vk_pipeline_check.cpp | 63 +- runtime/test/vk_store_test.cpp | 99 +- runtime/test/vk_test_device.h | 72 +- runtime/test/vulkan_scratch_test.cpp | 8 +- runtime/test/xbox_cbv_vector_test.cpp | 55 + runtime/test/xbox_d16s8_surface_test.cpp | 48 + runtime/test/xbox_depth_storage_test.cpp | 243 ++++ runtime/test/xbox_gpu_label_test.cpp | 59 + runtime/test/xg_xs_test.cpp | 391 +++++- runtime/test/xmem_test.cpp | 285 +++- scripts/run_gpu_tests.py | 17 +- tests/test_run_gpu_tests.py | 71 + tests/test_shader_checks.py | 27 +- 88 files changed, 10907 insertions(+), 1058 deletions(-) create mode 100644 runtime/shims/d3d12_xs_native_pso.h create mode 100644 runtime/shims/d3d12_xs_placed_depth.h create mode 100644 runtime/shims/d3d12_xs_pso_stream.cpp create mode 100644 runtime/shims/d3d12_xs_pso_stream.h create mode 100644 runtime/shims/present_window.h create mode 100644 runtime/src/console_texture_layout.h create mode 100644 runtime/src/gpu_label_memory.h create mode 100644 runtime/src/native_pso.h create mode 100644 runtime/src/rgba4_fragment.h create mode 100644 runtime/src/vulkan_gpu_labels.h create mode 100644 runtime/src/vulkan_graphics_shader_modules.h create mode 100644 runtime/test/d3d12_depth_stencil_uav_test.cpp create mode 100644 runtime/test/d3d12_depth_stencil_uav_views.h create mode 100644 runtime/test/d3d12_native_graphics_fixture.h create mode 100644 runtime/test/d3d12_placed_depth_test.h create mode 100644 runtime/test/d3d12_texture_uav_oracle.h create mode 100644 runtime/test/d3d12_texture_uav_test.cpp create mode 100644 runtime/test/glsl/cs_depth_stencil_uav.comp create mode 100644 runtime/test/pso_stream_test.cpp create mode 100644 runtime/test/shaders/cs_cbv_vector_rows.asm create mode 100644 runtime/test/shaders/cs_imgload_mip.asm create mode 100644 runtime/test/shaders/cs_texture_uav.asm create mode 100644 runtime/test/xbox_cbv_vector_test.cpp create mode 100644 runtime/test/xbox_d16s8_surface_test.cpp create mode 100644 runtime/test/xbox_depth_storage_test.cpp create mode 100644 runtime/test/xbox_gpu_label_test.cpp (limited to 'runtime/src/main.cpp') diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2eb07eeb8..38913f313 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -610,7 +610,8 @@ What is implemented (all of it testable without the game): Descriptors and the bindless set (milestone M2, without the pipelines that will bind the set), from the shader's side inwards: -- **`runtime/src/vulkan_bindless.h`**: set 0 includes the twenty bindings the translator declares, and +- **`runtime/src/vulkan_bindless.h`**: set 0 includes the single-sample bindings the translator declares, optional + multisample bindings, and `DescriptorTable` (`runtime/src/descriptor_table.h`, section 5.1) behind binding 2. One set for the device. The translator declares every array as a runtime array, so the counts are the runtime's choice. Details: - The device sizes the arrays once, when it creates the set. It does not recreate the set, because pipeline @@ -624,7 +625,7 @@ side inwards: - samplers: up to 4096, and at most `maxSamplerAllocationCount` less 64 for samplers outside the set. That covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. - 2D images: up to 65536. - - storage arrays: up to 4096 each. + - storage arrays: up to 4096 each, capped by their dimension's sampled array or by 256 for storage-only 1D arrays. Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be @@ -640,17 +641,19 @@ side inwards: shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that the next view and sampler are refused. The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type - and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 - descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and - `bindless_sizing_test` checks the rules on synthetic limits. - - An image has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS or 2DMS array), shared by the + and 4000 samplers) the sizing rules give 65536 2D images, 3936 samplers and 4096 storage indices in 2D: + 94561 descriptors with all MS classes, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts + it chose, and `bindless_sizing_test` checks the rules on synthetic limits. + - An image view has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS, 2DMS array or 1D array), shared by the bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers. The runtime enables pairs that fit the device's descriptor limits and have a multisampled zero fallback of the matching numeric class. A missed key reads zero at texel (0, 0), layer 0, sample 0. + The 1D-array dimension uses storage bindings 26–28 and has no sampled binding. - The storage arrays are shorter (`BindlessSet::storage_capacity`). Each array holds at most as many images as its dimension, and the 2D r32ui array is the same size as the other 2D storage arrays. So an image with a storage view gets an index the storage arrays hold, and a read-only one goes above where there is room. + Index 0 is reserved, so 256 descriptors hold 255 live views in each 1D-array storage binding. - Index 0 of every array is a fallback (a 1x1 image of zeros, a nearest clamping sampler), because a miss is index 0. - Changes are queued and written by `flush()`, one write a slot, so a view that is removed before the next @@ -672,8 +675,8 @@ side inwards: written as zero. - **Device**: `CreateShaderResourceView` and `CreateUnorderedAccessView` of textures write a T# into the slot, `CreateSampler` an S#; each then makes sure set 0 has the view or sampler and the table has the key. Details: - - The key is the descriptor's bytes, so a copied descriptor needs nothing more, and an unordered-access view - and a shader-resource view of the same mip are one entry. + - The key is the descriptor's bytes, so a copied descriptor needs nothing more. An SRV and UAV with identical + bytes can share an entry; a partial 3D UAV carries a W-range tag and remains separate from the unsliced SRV. - A D3D12 comparison sampler with function NEVER and an ordinary sampler both encode zero in the hardware depth comparison field. The layer marks the NEVER comparison in S# word 3, bit 12 (unused with DERIV_ADJUST_EN clear) to give it a separate lookup key and a comparison-enabled Vulkan sampler. @@ -689,7 +692,7 @@ side inwards: images and storage buffers. The standalone device enables them where the GPU has them. - Every `ExecuteCommandLists` flushes the set before its commands are written. - `rt::d3d12::bindless_set` and `bindless_set_layout` hand out the set and its layout: what a pipeline whose - shader declares set-0 bindings is created with and binds. Nothing in the layer creates such a pipeline yet. + shader declares set-0 bindings is created with and binds. - **Layouts.** A descriptor in set 0 has one image layout for as long as it lives, but D3D12 lets a texture be sampled in a shader-resource state and also while promoted from `COMMON`, which is `GENERAL` here (section 4.3). So with the bindless set, a texture's shader-resource states use `GENERAL` too @@ -710,7 +713,7 @@ volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_v Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views (the V# a shader would load for them; the structure is in `gfx10_descriptors.h`, the views are not written; buffer UAVs of every kind are, section 3.4 "Buffer UAVs", `d3d12_m4_compute_test` and `d3d12_buffer_uav_test`); -1D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless +1D-array SRVs, other typeless volume formats, multisampled depth/stencil and typeless color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, `R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the depth aspect (the texture's backing format, so X24_8_32_FLOAT for a D24 texture where the layer stores it as @@ -1341,13 +1344,19 @@ and any validation error fails them. - That set 0 holds them: a compute shader (`test/glsl/cs_sample.comp`, GLSL, compiled with `glslangValidator`; skipped without it) is handed a slot's T# and the sampler's S#, looks them up in the hash table as a translated shader does, and samples. The sampler wraps in U and the shader samples one tile to the right, - so a missed S# shows too: the fallback sampler clamps. The layer has no pipelines yet, so the test creates - this one in Vulkan and binds the device's set. It reads the texture through the view's own slot and through + so a missed S# shows too: the fallback sampler clamps. The test creates the pipeline in Vulkan and binds + the device's set. It reads the texture through the view's own slot and through a copy of it, and gets the fallback from a slot of bytes no view was made for and, after the texture is destroyed, from the view's own bytes. - Capacity: 5000 distinct SRVs of that texture and one more, and 2100 distinct wrapping samplers in two 2048-slot heaps. The last view through the last sampler reads the texture one tile to the right. With the sizes of before, both were past their arrays ("array is full") and the shader read the fallback. +- `d3d12_texture_uav_test` (D3D-78): creates 1D, 1D-array, 3D and 2D control UAVs through the D3D12 device, + checks rejected descriptors, copies descriptors between slots, and dispatches a translated hand-written + shader from a Vulkan compute pipeline on the actual set 0, not through D3D12 `Dispatch`. It reads back every + texel; the UINT read/modify/write cases (not atomics) also run on Windows WARP. The D3D12 command-list path + is used separately to flush the set and to test clears. + The tests dispatch past the selected array/W range, so writes to an adjacent layer or slice fail the check. - `d3d12_compute_test`: the compute path through the proxy. It creates a root signature from the PC serializer's blob, and a PSO through slot 62 from a container shaped like the game's, found in a translator-style index by its FSSM hash (an unknown program is refused). It sets root constants, a root UAV and a descriptor table whose @@ -1745,10 +1754,31 @@ The layer's descriptor model: If the logical device lacks the feature, the runtime logs the unsupported view and its descriptor resolves to the fallback. A clamp at or below the first mip needs no extension. Above the last mip, the view retains its dimensions and maps sampled channels to zero while preserving constant channels. +- D3D-78: a `Texture1DArray` UAV gets a 1D-array view with the requested array subrange and storage bindings + 26–28 (float, UINT, SINT); `ArraySize = UINT_MAX` selects the remaining layers. A non-array `Texture1D` + view of a 1D array selects layer 0, as checked on native D3D12. A `Texture3D` UAV gets a 3D view with a single mip + and Vulkan array range `{0, 1}`. + A partial W range requires `VK_EXT_image_sliced_view_of_3d` and `robustImageAccess` on the logical device: + `VkImageViewSlicedCreateInfoEXT` rebases storage-image Z to `FirstWSlice` and limits it to `WSize` (`UINT_MAX` + means the remaining mip depth). It does not slice the sampled view. The generated T# tags the W range for + whole-mip and partial UAVs, distinguishes them from SRVs in the hash table, and rebases typed sampled fetches; + see the contract in `docs/design.md`. + Without those features a partial W view is logged and left null, not made writable across the whole mip. + Shader-visible 1D, 1D-array and 3D UAVs require both formatless storage read and write support for the actual + Vulkan view format. `image_load ... glc` uses the storage view for 1D and 3D, and 1D-array loads always use it. + The emulated RGB9E5 raw `R32_UINT` storage view is formatted and is exempt. Vulkan 1.3 permits these SPIR-V + capabilities even without the legacy `shaderStorageImage{Read,Write}WithoutFormat` feature bits. The + caller-owned device test leaves both legacy bits off and masks each per-format bit to verify safe rejection. + `ClearUnorderedAccessView*` refuses partial W ranges and 1D/3D format reinterprets: the transfer clear + cannot target a slice interval or guarantee preserving the reinterpreted bits. + Shader access to the new UAVs requires `robustImageAccess` (whole-mip CPU clears do not). + A separate native D3D12 probe on the RTX 4090 and UHD 770 clipped typed writes to the view's W range. + WARP 10.0.26100.9818 rebased the view but did not clip writes past a finite `WSize` in that probe. The + regression compares in-range writes with WARP and checks preservation of out-of-range slices independently. - Set 0 is a fixed bindless layout, sized once when the device creates it. The defaults are 4096 sampled 2D images, 1024 samplers, 1024 2D-array images, 256 1D, 256 3D and 256 per storage dimension/class. The 2D, sampler and - storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (see `vulkan_bindless.h` - above). The set is not recreated to grow, because recreating it would invalidate the pipeline + storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (1D-array storage stays + capped at 256; see `vulkan_bindless.h` above). The set is not recreated to grow, because recreating it would invalidate the pipeline layouts built on it. Use `UPDATE_AFTER_BIND` and `PARTIALLY_BOUND` so a new view does not require rewriting every descriptor; without those features, rebuild the set when it changes. - The command buffer binds set 0 once; descriptor-heap changes only update the arrays and the hash table. @@ -2182,7 +2212,7 @@ The trace will enumerate them. ### Console rectangle and quad lists The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). -- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes three corners and emits two triangles with their original winding. It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. For axis-aligned rectangles the stage finds the right angle opposite the longest edge in normalized device coordinates. Both output triangles begin at the first submitted vertex so flat inputs retain its value. The integration override `LEONIDA_RECT_FOURTH=v1v3` still forces the second input to be the right-angle corner. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. - **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still @@ -2272,16 +2302,13 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv and resolve bits also require the format's image-usage/sample-count query to succeed. D3D12's per-format rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): - `MIP` wherever the image can have more than one level. - - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM`. Its swizzled R8 view gathered the same four - alpha values as native D3D12 and WARP on 49 footprints. `d3d12_descriptor` also verifies a view that forces - alpha to zero. - - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`), - not a storage-image read. Typed buffer UAVs: the layer now writes their V# (section 3.4, "Buffer UAVs"); the - gap left is `rdna2spirv.py` `FORMATS`, which decodes only some buffer formats (the 32-bit SINT ones, but no - 8/16-bit SINT/UINT other than the RGBA8 and RGBA16 UINT ones, and no 10_11_11). - - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today - that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the - layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view. + - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM` where the 49-footprint WARP regression verified alpha selection. + - `UAV_TYPED_LOAD` with every typed UAV. Ordinary typed UAV texture reads use the sampled binding + (`image_read_typed`), while coherent `glc` loads and storage-only 1D-array loads use storage-image reads. + Typed buffer UAVs: the layer writes their V# (section 3.4, "Buffer UAVs"); `rdna2spirv.py` `FORMATS` + still limits decoded buffer formats (including gaps in 8/16-bit and 10_11_11 formats). + - The UAV atomic bits other than exchange for `R32_UINT` where Vulkan supports storage image atomics. + The translator and set 0 use the formatted `r32ui` views for 2D and 3D; `R32_SINT` has no `r32ui` view. - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. @@ -2599,6 +2626,24 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; images copy dimension, format, mip levels, array layers and sample count. +- Xbox depth textures with `ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS` can use legacy committed creation + (slot 76), `CreateCommittedResource3` (forwarded by Xbox slot 127 in the boot stack), or placement at a guest + address (slot 133). Device10 and slot 133 take an initial `D3D12_BARRIER_LAYOUT`. Both check the layout + against the logical texture flags and validate the optimized clear against the native depth format. + Xbox allocation queries return the attachment's placement size for XMem accounting; the writable + planes are private backend allocations. The supported shapes are single-sample, single-mip 2D + textures and 2D arrays. For `R32G8X24_TYPELESS`, use `R32_FLOAT` on depth plane 0 and `R8_UINT` on stencil + plane 1. For `R16_TYPELESS`, use `R16_UINT` on plane 0 to access the raw D16 bits. An array UAV selects a + contiguous range of layers. The depth/stencil and shader-resource views continue to use the attachment image. + Slot 133 keeps the guest address. Identical, live placements share their image and writable planes across + distinct COM objects. A partial overlap or incompatible reinterpretation is refused. +- Legacy and enhanced texture transitions copy the selected planes and layers to or from their storage images. + Fence-ordered graphics and compute queues can share UAV access. A dedicated compute family can perform + the plane transfer itself when `VK_KHR_maintenance10` and the format's depth/stencil copy flags allow it. + Otherwise the graphics queue issues the explicit transitions on either side of the compute work. The two + queue-specific COMMON layouts allow implicit UAV access, so replay refuses them for these textures. + Generic COMMON remains available for copies, shader reads and queue handoffs. + `d3d12_depth_stencil_uav_test` verifies these paths with a synthetic shader and per-pixel readback. - Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`; @@ -3655,9 +3700,9 @@ store, load, mesh, geometry and BVH tests; this layer is the other half. | `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. | | `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. | | Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. Implemented in `runtime/src/descriptor_table.h` (`DescriptorTable`). The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. | -| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones, as the translator expects. | +| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; typed single-sample shader declarations alias the same binding numbers. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones. The runtime also reserves optional MS SRV pairs at 20–25; the translator does not use them yet. | | Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. | -| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. | +| Storage images (bindings 4, 7, 8–19, 26–28) | Bindings 4 and 7 are formatted `r32ui` for 2D and 3D atomics. Bindings 8–19 are float/UINT/SINT triples for 2D, 2D-array, 3D and 1D. Bindings 26–28 are the float/UINT/SINT triple for 1D arrays, which have no sampled binding. The translator picks the numeric class from the T# format; the arrays for a dimension share the same index. | | Buffer/image binding | Descriptors contain console VAs, never host BDAs. Buffers are in the arena at their VA; images are keyed by T# through the hash table. | | Vertex fetch | PSO input layout + ISG1 signature; location = D3D input register; format from `DXGI_FORMAT`; instance step rate from the layout. The fetch subroutine is already replaced by Vulkan inputs. | | PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 5cba370c6..51aba517c 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -165,13 +165,19 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: `XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. +(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). `runtime/shims/xg_xs.cpp` answers them +from a model of the console's texture layouts, `runtime/src/console_texture_layout.h` (AMD addrlib's GFX10 rules for +the linear, 256 B, 4 KiB and 64 KiB modes: block shapes, mip tails, the micro tile patterns, a separate stencil plane), +ported with the computer's method table and layout structure from Marvisak/VIctory (GPL-3.0, `xg.rs` and `texture.rs` +at `d2a4bae1f`). `XGSuggestSwizzleMode` writes `0x100 | mode` (linear for 1D, `64KB_Z_X` for depth, `64KB_R_X` for +render targets, else `4KB_S`); the computer fills the layout (slot 2), gives an element's offset (slot 6), copies a +subresource into (slot 8) and out of (slot 9) tiled memory, and reports the 64 KiB tiling (slot 10). Not modelled: +compression metadata planes, and addressing or copies for the pipe/bank XOR modes and MSAA (`E_NOTIMPL`). A description +it cannot lay out still gets a computer in the out pointer with `E_INVALIDARG`, because two of the four callers ignore +the HRESULT and call through the object at once; that object answers every slot with `E_NOTIMPL` and writes nothing. +`xg_xs_test` covers the model (hand-checked addresses, mip tails, a bijection and round trip over every element) and the +shim's slots. The table above was measured before this shim and still lists these two as unimplemented; they are served +now. Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, diff --git a/docs/testing.md b/docs/testing.md index 71edca6cc..eff61f475 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -178,7 +178,29 @@ python -I runtime/test/shaders/build.py vs_ids ps_mullit python -I runtime/test/shaders/mullit_readback.py ``` -For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). +For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with +validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is +installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal +the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). + +On Windows, `run_gpu_tests.py` assembles and translates the D3D-78 fixture and runs the UAV readback and WARP +comparison from the same build folder. Use `--filter cs_texture_uav` to run only this case: + +```powershell +$env:LEONIDA_VK_VALIDATION = "1" +python -I scripts/run_gpu_tests.py --build runtime/build --filter cs_texture_uav +``` + +Use the actual configuration subfolder for the executables with a multi-config generator. The native Windows +case reports SKIP without WARP or a sufficiently capable Vulkan device; failed translation, a missing test +executable on Windows, and readback mismatches fail the runner. Devices without sliced 3D views still run the 1D, +array and whole-mip cases and check that partial views are refused. + +CTest runs the same D3D-78 descriptor creation, copy, range/refusal and clear checks with `--descriptors-only`. +That mode requires Vulkan, but not a translated shader or WARP. The GPU runner still exercises dispatch and readback. + +Use `--filter cs_imgload_mip` to check 2D `image_load_mip` on FLOAT (UNORM), UINT and SINT sampled views with +both full-width and D16 loads; mip 0 contains decoy data and mip 1 holds the expected texels. `vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test` through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index a094719f9..2b4174cc8 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -118,7 +118,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xg_xs.cpp shims/acphal.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp shims/xgameruntime.cpp shims/xgameruntime_user.cpp shims/xgameruntime_gamesave.cpp @@ -172,7 +172,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) test/root_sig_test.cpp shims/registry.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -196,7 +196,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) test/device_proxy_test.cpp shims/registry.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -209,7 +209,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # patches its own import table to inject failures, so the proxy source is compiled into it alone. add_executable(xs_proxy_mock_test test/xs_proxy_mock_test.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) @@ -668,7 +668,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -809,7 +809,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(test_pe_loader_bounds PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -833,7 +833,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(pe_loader_fuzz PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -1079,6 +1079,10 @@ if(BUILD_TESTING) if(TARGET device_proxy_test) add_test(NAME device_proxy COMMAND device_proxy_test) + add_executable(pso_stream_test test/pso_stream_test.cpp shims/d3d12_xs_pso_stream.cpp) + target_include_directories(pso_stream_test PRIVATE shims) + add_test(NAME pso_stream_records COMMAND pso_stream_test) + set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) # With --trace-d3d12 the 24 D3D12XboxCreateDevice parameter words still print (docs/boot.md, question 1), # and the line with run-specific pointers does not. @@ -1183,7 +1187,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1200,7 +1204,7 @@ if(BUILD_TESTING) shims/registry.cpp shims/xmem.cpp shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) @@ -1430,7 +1434,7 @@ if(LEONIDA_D3D12_SHIM_TESTS) test/d3d12_xs_root_signature_test.cpp shims/d3d12_xs.cpp shims/registry.cpp - shims/d3d12_xs_device.cpp + shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ) target_include_directories(d3d12_xs_root_signature_test PRIVATE shims) target_compile_definitions(d3d12_xs_root_signature_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -1775,7 +1779,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} COMMENT "Generating D3D12 COM stubs" VERBATIM) - add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp + add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp shims/xbox_present.cpp shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) @@ -2100,6 +2104,10 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) + add_test(NAME xbox_linear_texture_map COMMAND d3d12_xmem_placed_test --linear-map) + add_test(NAME xbox_linear_gpu_staging COMMAND d3d12_xmem_placed_test --linear-staging) + set_tests_properties(xbox_linear_gpu_staging PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. @@ -2259,6 +2267,14 @@ if(TARGET Vulkan::Headers) set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_REGULAR_EXPRESSION "SKIP: ") endif() + # Test descriptor creation and clears in CTest without shader tools. The GPU runner passes the translated + # cs_texture_uav.spv to also exercise dispatches through set 0 and compare texels with Windows WARP. + add_executable(d3d12_texture_uav_test test/d3d12_texture_uav_test.cpp) + target_link_libraries(d3d12_texture_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_texture_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_texture_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_texture_uav COMMAND d3d12_texture_uav_test --descriptors-only) + set_tests_properties(d3d12_texture_uav PROPERTIES SKIP_RETURN_CODE 77) # What Close returns after one recorded call, against WARP; today's differences are listed in the test. add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -2462,6 +2478,28 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_pipeline_library_host PROPERTIES SKIP_RETURN_CODE 77) # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. + add_executable(xbox_cbv_vector_test test/xbox_cbv_vector_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_cbv_vector_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_cbv_vector_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_cbv_vectors COMMAND xbox_cbv_vector_test) + set_tests_properties(xbox_cbv_vectors PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) + add_executable(xbox_depth_storage_test test/xbox_depth_storage_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_depth_storage_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_depth_storage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_depth_storage COMMAND xbox_depth_storage_test) + add_test(NAME xbox_d16s8_storage COMMAND xbox_depth_storage_test) + set_tests_properties(xbox_d16s8_storage PROPERTIES ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1" SKIP_RETURN_CODE 77 TIMEOUT 30) + set_tests_properties(xbox_depth_storage PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + add_executable(xbox_d16s8_surface_test test/xbox_d16s8_surface_test.cpp) + target_link_libraries(xbox_d16s8_surface_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_d16s8_surface_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME xbox_d16s8_surface COMMAND xbox_d16s8_surface_test) + set_tests_properties(xbox_d16s8_surface PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) + add_executable(xbox_gpu_label_test test/xbox_gpu_label_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) + target_link_libraries(xbox_gpu_label_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_gpu_label_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) + add_test(NAME xbox_gpu_label_completion COMMAND xbox_gpu_label_test) + set_tests_properties(xbox_gpu_label_completion PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20) add_executable(d3d12_present_test test/d3d12_present_test.cpp) target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) @@ -2470,7 +2508,7 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. - add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) @@ -2506,7 +2544,7 @@ if(TARGET Vulkan::Headers) # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. - add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) @@ -2546,17 +2584,21 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m15 and ps_m15 for the translated draw test" VERBATIM) - add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M15_FILES}) target_link_libraries(d3d12_translated_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_translated_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) + add_test(NAME xbox_native_base_draw COMMAND d3d12_translated_draw_test --native-pso) + add_test(NAME xbox_derived_mask_zero COMMAND d3d12_translated_draw_test --derived-zero) + add_test(NAME xbox_derived_mask_restore COMMAND d3d12_translated_draw_test --derived-restore) + set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. - add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M15_FILES}) target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") @@ -2612,13 +2654,31 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" VERBATIM) - add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M2_FILES}) target_link_libraries(d3d12_m2_textured_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m2_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M2_DIR="${LEONIDA_M2_DIR}") target_compile_options(d3d12_m2_textured_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_m2_textured COMMAND d3d12_m2_textured_test) + add_test(NAME xbox_visible_texture_views COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_visible_texture_views PROPERTIES ENVIRONMENT "LEONIDA_TEST_VISIBLE_VIEWS=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_staged_texture_views COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_staged_texture_views PROPERTIES ENVIRONMENT "LEONIDA_TEST_STAGED_VIEWS=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_placed_texture_first_use COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_placed_texture_first_use PROPERTIES ENVIRONMENT "LEONIDA_TEST_PLACED_FIRST_USE=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_raw_2d_stripes COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_raw_2d_stripes PROPERTIES ENVIRONMENT "LEONIDA_TEST_LARGE_RAW_TEXTURE=1" SKIP_RETURN_CODE 77 TIMEOUT 35) + add_test(NAME xbox_raw_2d_surface COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_raw_2d_surface PROPERTIES ENVIRONMENT "LEONIDA_TEST_RAW_TEXTURE=1" SKIP_RETURN_CODE 77 TIMEOUT 25) + add_test(NAME xbox_packed4444_clear_sample COMMAND d3d12_m2_textured_test) + set_tests_properties(xbox_packed4444_clear_sample PROPERTIES ENVIRONMENT "LEONIDA_TEST_FIXED4=1" SKIP_RETURN_CODE 77) + add_test(NAME d3d12_m2_sampler_refresh COMMAND d3d12_m2_textured_test --refresh-samplers) + add_test(NAME d3d12_m2_unbounded_sampler_refresh COMMAND d3d12_m2_textured_test --refresh-unbounded-samplers) + set_tests_properties(d3d12_m2_sampler_refresh d3d12_m2_unbounded_sampler_refresh PROPERTIES + SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_m2_sampler_refresh_off COMMAND d3d12_m2_textured_test --refresh-samplers-off) + set_tests_properties(d3d12_m2_sampler_refresh_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") set_tests_properties(d3d12_m2_textured PROPERTIES SKIP_RETURN_CODE 77) # M2, formats: BC1 and BC7 textures with mip chains and an R8G8B8A8 2D array through the same descriptor path. @@ -2640,7 +2700,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating vs_m2, ps_m2 and ps_m2_array for the M2 formats test" VERBATIM) - add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M2F_FILES}) target_link_libraries(d3d12_m2_formats_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m2_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -2672,7 +2732,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating M3 frame and single-output occlusion-probe shaders" VERBATIM) - add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) + add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M3_FILES}) target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") @@ -2705,7 +2765,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" VERBATIM) - add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) + add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_M4_FILES}) target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") @@ -2735,7 +2795,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/../tools/rdna2spirv.py COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" VERBATIM) - add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) + add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_BUFFER_UAV_FILES}) target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") @@ -2756,7 +2816,7 @@ if(TARGET Vulkan::Headers) # Console Xbox CreateDescriptorHeap extended ABI (issue #313 comment 7107265058): the title passes address/size # after the PC desc and expects GetCPU/GPUDescriptorHandleForHeapStart() == address. Synthetic test; no title-memory # aliasing / §3.3 backing coverage. - add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) + add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp) target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) @@ -2890,7 +2950,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp COMMENT "Compiling the compute test shader" VERBATIM) - add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") @@ -2898,15 +2958,25 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. - add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_api_descriptor_copy COMMAND d3d12_title_va_test --api-descriptor-copy) + set_tests_properties(d3d12_api_descriptor_copy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_api_descriptor_copy_off COMMAND d3d12_title_va_test --api-descriptor-copy-off) + set_tests_properties(d3d12_api_descriptor_copy_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") + add_test(NAME d3d12_rebound_tables COMMAND d3d12_title_va_test --rebound-tables) + set_tests_properties(d3d12_rebound_tables PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") + add_test(NAME d3d12_rebound_tables_off COMMAND d3d12_title_va_test --rebound-tables-off) + set_tests_properties(d3d12_rebound_tables_off PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=0") + add_test(NAME d3d12_rebound_second_device COMMAND d3d12_title_va_test --rebound-second-device) + set_tests_properties(d3d12_rebound_second_device PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_DESC_MIRROR=1") # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. - add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") @@ -2933,7 +3003,7 @@ if(TARGET Vulkan::Headers) COMMENT "Compiling the draw test shader ${source}" VERBATIM) endforeach() - add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} + add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -2943,6 +3013,8 @@ if(TARGET Vulkan::Headers) LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_draw COMMAND d3d12_draw_test) + add_test(NAME xbox_geometry_upload_batch COMMAND d3d12_draw_test) + set_tests_properties(xbox_geometry_upload_batch PROPERTIES ENVIRONMENT "LEONIDA_TEST_GEOMETRY_BATCH=1" SKIP_RETURN_CODE 77 TIMEOUT 40) set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} @@ -3013,7 +3085,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_conservative_tier3 COMMAND d3d12_conservative_tier3_test) set_tests_properties(d3d12_inner_coverage_guards d3d12_inner_coverage_native d3d12_conservative_tier3 PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_msaa_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3022,7 +3094,7 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. - add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3049,7 +3121,7 @@ if(TARGET Vulkan::Headers) COMMENT "Compiling the D24 draw test shader ${source}" VERBATIM) endforeach() - add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} ${LEONIDA_TEST_GS_DEPTH}) target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) @@ -3071,7 +3143,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp COMMENT "Compiling the set-0 compute test shader" VERBATIM) - add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS_SET0_SAMPLE}) target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3079,9 +3151,28 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) + set(depth_uav_shader ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_depth_stencil_uav.comp) + foreach(variant IN ITEMS DEPTH_STENCIL_2D DEPTH_STENCIL_ARRAY DEPTH16_2D DEPTH16_ARRAY) + set(spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_depth_uav_${variant}.spv) + add_custom_command(OUTPUT ${spv} + COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_CURRENT_BINARY_DIR}/generated + COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -D${variant}=1 + -o ${spv} ${depth_uav_shader} + DEPENDS ${depth_uav_shader} VERBATIM) + list(APPEND depth_uav_shaders ${spv}) + list(APPEND depth_uav_definitions LEONIDA_${variant}_SPV="${spv}") + endforeach() + add_executable(d3d12_depth_stencil_uav_test test/d3d12_depth_stencil_uav_test.cpp + shims/d3d12_xs_device.cpp ${depth_uav_shaders}) + target_link_libraries(d3d12_depth_stencil_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_depth_stencil_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + ${depth_uav_definitions}) + target_compile_options(d3d12_depth_stencil_uav_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_depth_stencil_uav COMMAND d3d12_depth_stencil_uav_test) + set_tests_properties(d3d12_depth_stencil_uav PROPERTIES SKIP_RETURN_CODE 77) # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). - add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp + add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS_SET0_SAMPLE}) target_link_libraries(d3d12_bindless_churn_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_bindless_churn_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3109,6 +3200,10 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_bundle_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_bundle COMMAND d3d12_bundle_test) set_tests_properties(d3d12_bundle PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME d3d12_root_layout_compact COMMAND d3d12_bundle_test --compact) + add_test(NAME d3d12_root_layout_legacy COMMAND d3d12_bundle_test --legacy) + set_tests_properties(d3d12_root_layout_compact PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_GRAPHICS_STAGE_LAYOUT=1") + set_tests_properties(d3d12_root_layout_legacy PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_GRAPHICS_STAGE_LAYOUT=0") # Calls a bundle may not make, Close of the bundle and of its parent, against the host runtime and WARP. add_executable(d3d12_bundle_forbidden_test test/d3d12_bundle_forbidden_test.cpp) target_link_libraries(d3d12_bundle_forbidden_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -3147,7 +3242,7 @@ if(TARGET Vulkan::Headers) DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh COMMENT "Compiling the mesh test shader ms_draw.mesh" VERBATIM) - add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} + add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_MS} ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX @@ -3215,7 +3310,7 @@ if(TARGET Vulkan::Headers) VERBATIM) list(APPEND LEONIDA_SG_INDEXES ${output}) endforeach() - add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) + add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp shims/d3d12_xs_pso_stream.cpp ${LEONIDA_SG_INDEXES}) target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index a1aa3ccc5..a77b0824a 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -206,6 +206,15 @@ public: const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } + bool needs_all_sampled_views() const { + if (directly_indexed_) return true; + for (const auto& command : list_.commands()) { + if (std::holds_alternative(command)) return true; + if (tables_.empty() && (std::holds_alternative(command) || + std::holds_alternative(command))) return true; + } + return false; + } UINT front_stencil_ref() const { return front_stencil_ref_; } UINT back_stencil_ref() const { return back_stencil_ref_; } D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base() const { return cbv_srv_uav_base_; } @@ -241,6 +250,7 @@ public: invalid_ = false; calls_.clear(); tables_.clear(); + directly_indexed_ = false; release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -506,19 +516,30 @@ public: for (UINT i = 0; i < count; ++i) { const auto& b = barriers[i]; switch (b.Type) { - case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: - check(list_.transition({resource_id(b.Transition.pResource), b.Transition.Subresource, - static_cast(b.Transition.StateBefore), - static_cast(b.Transition.StateAfter)}, - static_cast(b.Flags))); + case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: { + const auto& t = b.Transition; + const auto logical = resource_id(t.pResource); + const bool was_storage = (t.StateBefore & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0; + const bool storage = (t.StateAfter & D3D12_RESOURCE_STATE_UNORDERED_ACCESS) != 0; + const auto pair = (was_storage || storage) ? xbox_depth_storage(t.pResource) : XboxDepthStorage{}; + auto before = t.StateBefore; + if (pair.colour && was_storage != storage && !(b.Flags & D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY)) { + check(copy_depth_storage(logical, pair, storage, {t.Subresource})); + before = D3D12_RESOURCE_STATE_COPY_DEST; + } + check(list_.transition({pair.colour && storage ? pair.colour : logical, t.Subresource, + u(before), u(t.StateAfter)}, u(b.Flags))); break; + } case D3D12_RESOURCE_BARRIER_TYPE_ALIASING: check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), resource_id(b.Aliasing.pResourceAfter)})); break; - case D3D12_RESOURCE_BARRIER_TYPE_UAV: - check(!b.Flags && list_.uav_barrier({resource_id(b.UAV.pResource)})); + case D3D12_RESOURCE_BARRIER_TYPE_UAV: { + const auto pair = xbox_depth_storage(b.UAV.pResource); + check(!b.Flags && list_.uav_barrier({pair.colour ? pair.colour : resource_id(b.UAV.pResource)})); break; + } default: check(false); } @@ -546,12 +567,25 @@ public: case D3D12_BARRIER_TYPE_TEXTURE: { const auto& b = group[g].pTextureBarriers[i]; const auto& r = b.Subresources; - check(list_.barrier(leonida::TextureBarrier{ + leonida::TextureBarrier barrier{ u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), u(b.LayoutAfter), resource_id(b.pResource), {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, - r.NumPlanes}, - u(b.Flags)})); + r.NumPlanes}, u(b.Flags)}; + const bool was_storage = storage_access(b.LayoutBefore, b.AccessBefore); + const bool storage = storage_access(b.LayoutAfter, b.AccessAfter); + const auto pair = (was_storage || storage) ? xbox_depth_storage(b.pResource) : XboxDepthStorage{}; + if (pair.colour) { + if (was_storage != storage && b.SyncAfter != D3D12_BARRIER_SYNC_SPLIT && + b.LayoutBefore != D3D12_BARRIER_LAYOUT_UNDEFINED && !(b.Flags & D3D12_TEXTURE_BARRIER_FLAG_DISCARD)) { + check(copy_depth_storage(barrier.resource, pair, storage, barrier.range)); + barrier.sync_before = leonida::d3d12_sync::copy; + barrier.access_before = leonida::d3d12_access::copy_dest; + barrier.layout_before = leonida::d3d12_layout::copy_dest; + } + if (storage) barrier.resource = pair.colour; + } + check(list_.barrier(barrier)); break; } default: @@ -984,9 +1018,47 @@ public: check(list_.copy_acceleration_structure({dest, source, static_cast(mode)})); } + bool xbox_label(const leonida::label::Write& op) { return list_.write_gpu_label(op); } static GraphicsCommandList* from(IUnknown* object) { return Child::from(object); } private: + static bool storage_access(D3D12_BARRIER_LAYOUT layout, D3D12_BARRIER_ACCESS access) { + return (access & D3D12_BARRIER_ACCESS_UNORDERED_ACCESS) || + layout == D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS || + layout == D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS || + layout == D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS; + } + + bool copy_depth_storage(leonida::ResourceId depth, XboxDepthStorage pair, bool to_storage, + const leonida::BarrierSubresourceRange& r) { + namespace access = leonida::d3d12_access; + namespace sync = leonida::d3d12_sync; + const auto from = to_storage ? depth : pair.colour, to = to_storage ? pair.colour : depth; + // The two images can be in GENERAL for bindless use. Order prior depth writes, unordered writes and + // readers of the destination even when Vulkan does not need a layout transition. + if (!list_.barrier(leonida::GlobalBarrier{sync::all, sync::copy, + access::depth_stencil_write | access::depth_stencil_read | access::unordered_access | + access::shader_resource | access::copy_source | access::copy_dest, + access::copy_source | access::copy_dest})) return false; + if (!r.mip_count && r.index_or_first_mip == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) + return list_.copy_resource({to, from}); + const auto one = [&](UINT subresource) { + leonida::CopyTexture copy{}; + copy.src.resource = from; + copy.dst.resource = to; + copy.src.subresource = copy.dst.subresource = subresource; + return list_.copy_texture(copy); + }; + if (!r.mip_count) return r.index_or_first_mip < pair.mips * pair.layers && one(r.index_or_first_mip); + if (r.first_plane || r.plane_count != 1 || !r.layer_count || + r.first_layer >= pair.layers || r.layer_count > pair.layers - r.first_layer || + r.index_or_first_mip >= pair.mips || r.mip_count > pair.mips - r.index_or_first_mip) return false; + for (UINT layer = r.first_layer; layer < r.first_layer + r.layer_count; ++layer) + for (UINT mip = r.index_or_first_mip; mip < r.index_or_first_mip + r.mip_count; ++mip) + if (!one(layer * pair.mips + mip)) return false; + return true; + } + static bool valid_postbuild_info_type(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE type) { switch (type) { case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE: @@ -1136,12 +1208,24 @@ private: if (g::is_image(words)) { g::Image image{}; if (!g::decode(words, image)) return false; + out.resource = uav_image_resource(resource, image.address); + if (!out.resource) return false; const bool volume = image.type == g::ImageType::image_3d; + const auto pair = xbox_depth_storage(resource); + if (pair.colour) out.resource = pair.colour; + if (g::partial_volume_uav(words, image)) { + // Transfer clears operate on a whole 3D mip, not a storage image view. Refuse instead of + // overwriting slices outside the UAV; a sliced clear needs a separate replay path. + stub("ClearUnorderedAccessView of a partial 3D mip"); + return false; + } out.buffer = false; out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); out.mip = image.first_mip; out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip out.layer_count = volume ? 1 : image.layer_count; + out.exact_clear_format = volume || image.type == g::ImageType::image_1d || + image.type == g::ImageType::image_1d_array; return out.format != VK_FORMAT_UNDEFINED; } g::BufferWords buffer_words{}; @@ -1191,6 +1275,7 @@ private: if (layout && layout == state.layout) return; hold(signature); // state.layout points into it state.layout = layout; + if (layout && (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)) directly_indexed_ = true; state.data = {}; // CreateRootSignature accepted it for the other bind point only (its log line says why). if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { @@ -1261,13 +1346,16 @@ private: // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. if (type == rt::rootsig::ParamType::Descriptor) va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); - else if (va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) - tables_.push_back({va, p->table_descriptors}); + else if (va && p->table_descriptors) { + if (!tables_.empty() && tables_.back().first == va) + tables_.back().second = std::max(tables_.back().second, p->table_descriptors); + else + tables_.emplace_back(va, p->table_descriptors); + } const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); - // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps - // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!((is_compute(state) || local_graphics_stage_layout()) && type == rt::rootsig::ParamType::Table)) + // Stage-packed tables occupy one dword. Legacy tables and root views occupy two. + if (type != rt::rootsig::ParamType::Table || !(is_compute(state) || state.layout->graphics_compact_tables)) write(state, first + 1, std::uint32_t(va >> 32)); } @@ -1290,6 +1378,7 @@ private: leonida::IndexBufferView index_{}; // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares std::vector> tables_; + bool directly_indexed_ = false; // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; @@ -1675,6 +1764,11 @@ public: recorded.push_back(&list->commands()); graphics.push_back(list); } + if (!context_.publish_cpu_textures()) { + last_result_=leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's // console VA before the copies are refreshed for this submission (src/title_va_alias.h). { @@ -1684,12 +1778,40 @@ public: tables[table] = std::max(tables[table], descriptors); if (!tables.empty()) { const auto start = std::chrono::steady_clock::now(); - for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + for (const auto& [table, descriptors] : tables) { + context_.scan_table(table, descriptors); + if (!context_.prepare_sample_table(table, descriptors)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method, "failed"); + return; + } + } leonida::title_va_aliases().note_scan(std::uint64_t( std::chrono::duration_cast(std::chrono::steady_clock::now() - start) .count())); } } + for (const auto* list : graphics) { + for (const auto& command : list->commands().commands()) { + leonida::ResourceId resource = 0; + if (const auto* b=std::get_if(&command)) { + if (b->after & (D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE|D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)) + resource=b->resource; + } else if (const auto* b=std::get_if(&command)) { + if (b->access_after & D3D12_BARRIER_ACCESS_SHADER_RESOURCE) resource=b->resource; + } + if (resource && !context_.prepare_sample_table(resource,0)) { + last_result_=leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } + } + if (list->needs_all_sampled_views() && !context_.prepare_sample_table(0,0)) { + last_result_ = leonida::ReplayResult::unresolved_resource; + d3d12_trace::record(method,"failed"); + return; + } + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) @@ -1980,6 +2102,11 @@ private: } // namespace +bool record_gpu_label(ID3D12GraphicsCommandList* list,const leonida::label::Write& write) { + auto* own=GraphicsCommandList::from(list); + return own && own->xbox_label(write); +} + HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family, const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, IUnknown* device, const QueueClock& clock, std::shared_ptr queue_lease) { diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2811ed1f3..33f8ac549 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -5,7 +5,7 @@ // interfaces as far as is known; docs/d3d12_vulkan.md section 3.1 lists what is still unverified. // // Contracts with the rest of the layer (the device proxy that will hand these objects out): -// - an ID3D12Resource's leonida::ResourceId is its pointer value; the device registers it with the VulkanContext; +// - a resource's ID is its backing pointer value (identical Xbox depth placements share storage and layouts); // - so is an ID3D12QueryHeap's leonida::QueryHeapId, registered with its VkQueryPool; // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once @@ -17,6 +17,7 @@ #include #include +#include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" #include "../src/vulkan_backend.h" @@ -35,7 +36,9 @@ class VulkanPresenter; struct PresentPlanes; } +namespace leonida::label { struct Write; } namespace rt::d3d12 { +bool record_gpu_label(ID3D12GraphicsCommandList* list, const leonida::label::Write& write); // How a queue answers GetClockCalibration. With `calibrated` (vkGetCalibratedTimestampsKHR or its EXT alias, on a // device whose time domains include DEVICE and QUERY_PERFORMANCE_COUNTER) both clocks are read in one call. Without @@ -72,6 +75,14 @@ std::shared_ptr tile_heap(ID3D12Heap* heap, c bool image, std::uint32_t memory_types); bool is_sparse_image(ID3D12Resource* resource); +// Colour image used for unordered accesses to an Xbox single-plane depth surface. +struct XboxDepthStorage { + leonida::ResourceId colour = 0; + UINT mips = 0; + UINT layers = 0; +}; +XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource); + // The Vulkan objects a D3D12 device runs on. Vulkan 1.3 with dynamicRendering, synchronization2, timelineSemaphore // and (when separate_depth_stencil_layouts is set) separateDepthStencilLayouts enabled. struct VulkanDeviceInfo { @@ -137,6 +148,9 @@ struct VulkanDeviceInfo { // Optional device features the caller enabled. Without occlusionQueryPrecise, D3D12_QUERY_TYPE_OCCLUSION counts // are only zero or non-zero; without pipelineStatisticsQuery, pipeline-statistics query heaps are refused. bool occlusion_query_precise = false; + bool first_use_backend_pipelines = false; + bool prepare_on_bind = false; + bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. bool pipeline_statistics_query = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are @@ -161,6 +175,7 @@ struct VulkanDeviceInfo { // VK_KHR_maintenance5, enabled where its VK_FORMAT_A8_UNORM_KHR can be sampled and is a colour attachment the GPU // can blend: A8_UNORM render targets are then stored in that format (other A8_UNORM textures stay R8_UNORM). bool a8_render_target = false; + bool maintenance10 = false; // VK_KHR_maintenance10 enabled: query depth/stencil copy support per format // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they // do nothing. bool debug_utils = false; @@ -171,6 +186,10 @@ struct VulkanDeviceInfo { // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. bool ray_tracing = false; + // robustImageAccess is enabled on `device`, so typed 1D-family and 3D UAV loads are range checked. + bool robust_image_access = false; + // VK_EXT_image_sliced_view_of_3d (imageSlicedViewOf3D) is also enabled for partial 3D UAVs. + bool sliced_3d_uav = false; // BuildRaytracingAccelerationStructure writes the console's XDXR BVH4 records into the destination buffer // (src/xdxr_build.h), the layout the game's translated traversal shaders read, instead of building a // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it @@ -236,6 +255,8 @@ HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIP // The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. VkImage vulkan_image(ID3D12Resource* resource); +// Resolves the resource that a UAV clear writes. Xbox depth/stencil UAVs name one of two color images by T#. +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address); // The VkBuffer behind a buffer created by such a device, or VK_NULL_HANDLE. For tests. VkBuffer vulkan_buffer(ID3D12Resource* resource); // What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. @@ -248,7 +269,7 @@ bool device_supports_ray_tracing(ID3D12Device* device); // what the GPU reads. A buffer description only; E_NOTIMPL on a device that is not the Vulkan layer, without the // extension, or for a texture. HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear = nullptr); // The VkAccelerationStructureKHR registered for `va` on `device`, or VK_NULL_HANDLE. For tests. VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va); @@ -402,12 +423,13 @@ struct RootArgumentLayout { std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR - // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of - // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + // Declared span for submission-time heap refresh. Views are capped at 1024 slots and samplers at the + // shader-visible sampler heap limit. Zero for a parameter without a table. std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob + bool graphics_compact_tables = false; // the selected graphics layout uses one dword per table bool graphics_ok = true; bool compute_ok = true; }; @@ -452,7 +474,7 @@ bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); inline leonida::ResourceId resource_id(const ID3D12Resource* resource) { - return reinterpret_cast(resource); + return reinterpret_cast(rt::d3d12_xs::texture_backing(resource)); } // A query heap's ID in the command-list IR and the VulkanContext: its pointer value, as for resources. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1a9f1d6e4..efa29df0c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -7,6 +7,7 @@ #ifndef VK_USE_PLATFORM_WIN32_KHR #define VK_USE_PLATFORM_WIN32_KHR #endif +#include "../src/vulkan_graphics_shader_modules.h" #include "d3d12_com.h" #include "d3d12_feature_compat.h" @@ -14,10 +15,12 @@ #include "d3d12_com_object.h" #include "d3d12_trace.h" #include "d3d12_xs_device.h" +#include "d3d12_xs_native_pso.h" #include "dxgi_com.h" #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rgba4_fragment.h" #include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" @@ -29,6 +32,7 @@ #include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" +#include "../src/console_texture_layout.h" #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" @@ -43,6 +47,7 @@ #endif #include +#include #include #include #include @@ -57,6 +62,7 @@ #include #include #include +#include #include #include #include @@ -111,20 +117,22 @@ std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, return to; } -// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at -// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. -std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { - if (param.type != rt::rootsig::ParamType::Table) return 0; - constexpr std::uint32_t kUnbounded = 1024; +// The furthest range end is the span to refresh at submission. Sampler ranges use their full hardware +// heap limit. Buffer-view translation retains its existing per-table budget. +constexpr std::uint32_t kViewScanLimit = 1024; +std::uint32_t table_descriptor_count(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table || param.ranges.empty()) return 0; + const std::uint32_t limit = param.ranges.front().range_type == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER + ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : UINT_MAX; std::uint64_t next = 0, end = 0; for (const auto& range : param.ranges) { const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next - : range.offset_in_table; - const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? limit : range.num_descriptors; next = start + count; - if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + end = std::max(end, next); } - return std::uint32_t(std::min(end, kUnbounded)); + return std::uint32_t(std::min(end, limit)); } // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the @@ -433,6 +441,11 @@ constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; #endif +// Xbox DXGI values published by Microsoft's DirectXTex (DirectXTexP.h). +constexpr auto xbox_d16s8=static_cast(118); +constexpr auto xbox_d16_plane=static_cast(119); +constexpr auto xbox_s8_plane=static_cast(120); + struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; @@ -450,6 +463,8 @@ struct Format { VkFormat uint_backed = VK_FORMAT_UNDEFINED; // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). bool rgb96 = false; + bool xbox_depth16_stencil8 = false; + bool rgba4_render_fallback = false; }; // 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal @@ -564,6 +579,9 @@ Format vulkan_format(DXGI_FORMAT format, bool depth) { case DXGI_FORMAT_BC7_UNORM_SRGB: return {VK_FORMAT_BC7_SRGB_BLOCK, color}; case DXGI_FORMAT_D32_FLOAT: return {VK_FORMAT_D32_SFLOAT, d}; case DXGI_FORMAT_D16_UNORM: return {VK_FORMAT_D16_UNORM, d}; + case xbox_d16s8: return {VK_FORMAT_D16_UNORM_S8_UINT, ds}; + case xbox_d16_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, d}; + case xbox_s8_plane: return {VK_FORMAT_D16_UNORM_S8_UINT, VK_IMAGE_ASPECT_STENCIL_BIT}; case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds}; case DXGI_FORMAT_D24_UNORM_S8_UINT: return {VK_FORMAT_D24_UNORM_S8_UINT, ds}; case DXGI_FORMAT_R32_TYPELESS: @@ -763,16 +781,20 @@ std::filesystem::path shader_directory_from_file(const std::filesystem::path& co } // What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. +class Resource; struct DeviceState { + std::mutex mapped_texture_mutex; + std::set mapped_textures; + std::atomic map_count{}; + bool publish_mapped_textures(); + std::mutex title_image_mutex; + std::multimap title_images; VulkanDeviceInfo info; std::vector families; template void share(CreateInfo& create) const { - if (families.size() < 2) return; - create.sharingMode = VK_SHARING_MODE_CONCURRENT; - create.queueFamilyIndexCount = std::uint32_t(families.size()); - create.pQueueFamilyIndices = families.data(); + leonida::share_across_queue_families(create, families); } std::unique_ptr context; VkPhysicalDeviceMemoryProperties memory{}; @@ -967,29 +989,51 @@ struct DeviceState { return true; } - // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. - std::mutex cbv_heap_mutex; - std::map cbv_heaps; - static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + struct ShaderVisibleHeap { + VkDeviceSize end; + D3D12_DESCRIPTOR_HEAP_TYPE type; + }; + std::mutex visible_heap_mutex; + std::map visible_heaps; + std::map cpu_view_heaps; + bool known_view_heap(std::uintptr_t addr) { + std::lock_guard lock(visible_heap_mutex); + const auto mapped = reinterpret_cast(arena.mapped); + if (mapped && addr >= mapped && addr - mapped < arena.size) { + const auto off = addr-mapped; + auto visible = visible_heaps.upper_bound(off); + if (visible != visible_heaps.begin()) { + --visible; + if (visible->second.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && off < visible->second.end && + (off-visible->first)%kDescriptorSize==0) return true; + } + } + auto it = cpu_view_heaps.upper_bound(addr); + if (it == cpu_view_heaps.begin()) return false; + --it; + return addr < it->second && (addr-it->first) % kDescriptorSize == 0; + } // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { VkDeviceSize end = 0; + bool sampler = false; { - std::lock_guard lock(cbv_heap_mutex); - auto it = cbv_heaps.upper_bound(table_va); - if (it == cbv_heaps.begin()) return; + std::lock_guard lock(visible_heap_mutex); + auto it = visible_heaps.upper_bound(table_va); + if (it == visible_heaps.begin()) return; --it; - if (table_va >= it->second) return; - end = std::min( - it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * - kDescriptorSize); + const auto& heap = it->second; + if (table_va >= heap.end || (table_va - it->first) % kDescriptorSize != 0) return; + sampler = heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; + const auto slots = sampler ? descriptors : std::min(descriptors, kViewScanLimit); + end = table_va + std::min(heap.end - table_va, VkDeviceSize(slots) * kDescriptorSize); } auto& aliases = leonida::title_va_aliases(); - // Slots the title wrote in its own backing of this heap, if it gave the heap one. aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); + if (sampler) return; // S# words describe sampling state. They have no buffer address to translate. for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { auto* w = reinterpret_cast(arena.mapped + at); const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; @@ -1136,6 +1180,9 @@ struct DeviceState { std::mutex library_mutex; bool library_tried = false; leonida::ShaderLibrary shader_library; + leonida::GraphicsShaderModules graphics_modules; + + rt::d3d12_xs::NativeGraphicsPipelines native_graphics; const leonida::ShaderLibrary* library() { std::lock_guard lock(library_mutex); @@ -1166,6 +1213,12 @@ struct DeviceState { return shader_library.loaded() ? &shader_library : nullptr; } + VkFormat depth_backing(VkFormat logical) const { + if(logical!=VK_FORMAT_D16_UNORM_S8_UINT)return logical; + for(const auto candidate : {VK_FORMAT_D16_UNORM_S8_UINT,VK_FORMAT_D32_SFLOAT_S8_UINT,VK_FORMAT_D24_UNORM_S8_UINT}) + if(depth_usable(candidate))return candidate; + return VK_FORMAT_UNDEFINED; + } bool depth_usable(VkFormat format) const { VkFormatProperties properties{}; format_properties(info.physical, format, &properties); @@ -1239,6 +1292,14 @@ struct DeviceState { return S_OK; } + VkFormatFeatureFlags2 optimal_features(VkFormat format) const { + if (!format_properties2) return 0; + VkFormatProperties3 features{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &features}; + format_properties2(info.physical, format, &properties); + return features.optimalTilingFeatures; + } + // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. // Read once: std::call_once makes a concurrent first caller wait until the facts are complete. @@ -1398,6 +1459,16 @@ struct DeviceState { Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return {}; + if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && + !color_attachment_usable(format.format)) { + if(!color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; + format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; + return format; + } + if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) { + format.xbox_depth16_stencil8=true;format.format=depth_backing(format.format); + return format; + } format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); @@ -1510,19 +1581,49 @@ struct DeviceState { const std::uint64_t slot_handle = (static_cast(entry.dimension) << 32) | static_cast(entry.index); context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); - context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); + if (entry.sampled) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); } + struct PendingSample { + Resource* owner = nullptr; + leonida::gfx10::Image image{}; + VkFormat view_format{}, channels_format{}; + }; + std::mutex pending_view_mutex; + std::map pending_samples; + std::atomic pending_sample_count{}; + bool materialize_sample(const leonida::DescriptorKey& key); + bool materialize_table(std::uint64_t address,std::uint32_t slots); + void remember_sample(const leonida::DescriptorKey& key, const PendingSample& sample) { + std::lock_guard lock(pending_view_mutex); + if (pending_samples.try_emplace(key,sample).second) { + ++pending_sample_count; + } + } + void retire_samples(Resource* owner) { + std::lock_guard lock(pending_view_mutex); + const auto removed=std::erase_if(pending_samples,[&](const auto& p){return p.second.owner==owner;}); + pending_sample_count -= static_cast(removed); + } + + struct VolumeSlices { + UINT first = 0; + UINT count = 0; // 0: no restriction (ordinary view of the whole mip) + }; + // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders // write through it too (an unordered-access view), so it also goes into the storage arrays, which are // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, - VkFormat image_format, VkImageAspectFlags aspects, bool storage, - bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { + VkFormat view_format, VkFormat channels_format, VkFormat storage_format, + VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); - if (!bindless) return false; + if (!bindless) { + if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); + return false; + } const auto existing = image_entries.find(words); if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; @@ -1533,6 +1634,7 @@ struct DeviceState { case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; + case g::ImageType::image_1d_array: dimension = leonida::ImageDimension::dim_1d_array; break; case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; default: @@ -1541,41 +1643,31 @@ struct DeviceState { } const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; if (storage && depth_or_stencil) { - log_once("storage view not supported for depth-stencil image format:", int(image_format)); + log_once("storage view not supported for depth-stencil image format:", int(view_format)); return false; } - // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan - // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose - // format is 8_UINT reads it from X. - const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; - const VkFormat logical_format = uint_backed ? uint_backed : image_format; - VkFormat view_format = - stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); - VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from - if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 - view_format = rgb96_view_format(image_format, image.format); - channels_format = rgb96_named_format(view_format); - } if (view_format == VK_FORMAT_UNDEFINED || (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); return false; } + // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan + // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose + // format is 8_UINT reads it from X. + const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); return false; } auto& vk = context->vk; + VkImageViewUsageCreateInfo view_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + view_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + view_info.pNext = &view_usage; view_info.image = vk_image; view_info.viewType = g::vulkan_view_type(image.type); view_info.format = view_format; - VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if (uint_backed) { - sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; - view_info.pNext = &sampled_usage; - } auto swizzle = image.swizzle; VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || @@ -1593,8 +1685,7 @@ struct DeviceState { log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); return false; } - clamp.pNext = view_info.pNext; - view_info.pNext = &clamp; + view_usage.pNext = &clamp; } } view_info.components = g::vulkan_swizzle(swizzle, channels_format); @@ -1605,20 +1696,31 @@ struct DeviceState { : VK_IMAGE_ASPECT_COLOR_BIT), image.first_mip, image.mip_count, image.first_layer, image.layer_count}; ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; - if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled) != VK_SUCCESS) return false; + if (sampled) { + const VkResult result = vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled); + if (result != VK_SUCCESS) { + log_once("sampled image view creation failed:", result); + return false; + } + } leonida::StorageViews views{}; if (storage) { VkImageViewCreateInfo storage_info = view_info; storage_info.components = {}; + storage_info.format = storage_format; VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - const VkFormat storage_format = uint_backed ? image_format : view_format; - if (uint_backed) { - storage_info.format = storage_format; - storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; - storage_info.pNext = &storage_usage; - } - if (vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage) != VK_SUCCESS) { - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; + VkImageViewSlicedCreateInfoEXT sliced{VK_STRUCTURE_TYPE_IMAGE_VIEW_SLICED_CREATE_INFO_EXT}; + if (slices.count) { + sliced.sliceOffset = slices.first; + sliced.sliceCount = slices.count; + storage_usage.pNext = &sliced; + } + storage_info.pNext = &storage_usage; + const VkResult result = vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage); + if (result != VK_SUCCESS) { + log_once("storage image view creation failed:", result); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); return false; } const int numeric = numeric_class(storage_format); @@ -1629,7 +1731,7 @@ struct DeviceState { entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); if (!entry.index) { log_once("a bindless image array is full; dimension", int(dimension)); - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); + if (entry.sampled) vk.vkDestroyImageView(info.device, entry.sampled, nullptr); if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); return false; } @@ -1777,6 +1879,11 @@ struct DeviceState { // line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc) { Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + if(format.format==VK_FORMAT_D16_UNORM_S8_UINT) {format.xbox_depth16_stencil8=true;format.format=device.depth_backing(format.format);return format;} + if(desc.Format==DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags&D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !device.color_attachment_usable(format.format)) { + if(!device.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))return {}; + format.format=VK_FORMAT_R8G8B8A8_UNORM;format.rgba4_render_fallback=true; + } if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !device.depth_usable(format.format)) { log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; @@ -1793,7 +1900,7 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc // no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no // other format can be a view format of it, so any other castable format is refused here, before Vulkan. HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, - const DXGI_FORMAT* castable, std::vector& out) { + const DXGI_FORMAT* castable, std::vector& out, bool depth_uav_planes = false) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); @@ -1803,6 +1910,19 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); return E_INVALIDARG; } + if (depth_uav_planes) { + // Attachment and sampled views use the original depth image's VkFormat. Each typed UAV + // already has its own image; putting its colour format on the depth image is invalid. + const DXGI_FORMAT view = castable[i]; + const bool valid = format.format == VK_FORMAT_D16_UNORM + ? view == DXGI_FORMAT_R16_TYPELESS || view == DXGI_FORMAT_D16_UNORM || + view == DXGI_FORMAT_R16_UNORM || view == DXGI_FORMAT_R16_UINT + : view == DXGI_FORMAT_R32G8X24_TYPELESS || view == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS || view == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT || + view == DXGI_FORMAT_R32_FLOAT || view == DXGI_FORMAT_R8_UINT; + if (!valid) return E_INVALIDARG; + continue; + } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); @@ -1825,6 +1945,7 @@ HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, // The typeless format a DXGI format can be cast within, or the format itself when it has no such family. DXGI_FORMAT format_family(DXGI_FORMAT format) { + if (format==xbox_d16s8 || format==xbox_d16_plane || format==xbox_s8_plane) return xbox_d16s8; const int f = int(format); const auto in = [f](int first, int last) { return f >= first && f <= last; }; if (in(1, 4)) return DXGI_FORMAT_R32G32B32A32_TYPELESS; @@ -1856,6 +1977,7 @@ DXGI_FORMAT format_family(DXGI_FORMAT format) { // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { const DXGI_FORMAT family = format_family(format); + if (family==xbox_d16s8) return true; return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; } @@ -2022,8 +2144,9 @@ const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_ } if (desc.Dimension < D3D12_RESOURCE_DIMENSION_TEXTURE1D || desc.Dimension > D3D12_RESOURCE_DIMENSION_TEXTURE3D) return "resource dimension"; - if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) + if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) { return "resource flag combination"; + } if (ds && !depth_stencil_family(desc.Format)) return "depth-stencil format"; if (rt && !render_target_family(desc.Format)) return "render-target format"; const UINT samples = desc.SampleDesc.Count; @@ -2111,20 +2234,30 @@ public: in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); - if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - std::lock_guard lock(device.cbv_heap_mutex); - device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { + std::lock_guard lock(device.visible_heap_mutex); + device.visible_heaps[arena_offset_] = {arena_offset_ + bytes, desc.Type}; } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); } + if (cpu_ && !(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.visible_heap_mutex); + const auto begin = reinterpret_cast(cpu_); + device_.cpu_view_heaps[begin] = begin + bytes; + registered_cpu_views_ = true; + } } ~DescriptorHeap() override { - if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - std::lock_guard lock(device_.cbv_heap_mutex); - device_.cbv_heaps.erase(arena_offset_); + if (registered_cpu_views_) { + std::lock_guard lock(device_.visible_heap_mutex); + device_.cpu_view_heaps.erase(reinterpret_cast(cpu_)); + } + if (in_arena_) { + std::lock_guard lock(device_.visible_heap_mutex); + device_.visible_heaps.erase(arena_offset_); } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); @@ -2148,6 +2281,11 @@ public: return {in_arena_ ? UINT64(arena_offset_) : 0}; } + bool owns_mapped_span(SIZE_T start, SIZE_T bytes) const { + return in_arena_ && start == reinterpret_cast(cpu_) && + bytes == SIZE_T(desc_.NumDescriptors) * kDescriptorSize; + } + const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { if (console_addressed_) return static_cast(console_address_); @@ -2157,6 +2295,7 @@ public: private: DeviceState& device_; D3D12_DESCRIPTOR_HEAP_DESC desc_; + bool registered_cpu_views_ = false; std::unique_ptr storage_; std::uint8_t* cpu_ = nullptr; VkDeviceSize arena_offset_ = 0; @@ -2166,11 +2305,29 @@ private: bool console_addressed_ = false; }; +// Only Xbox depth resources have an alternate storage image. Barriers for other COM objects +// can look it up without dereferencing the pointer or calling into another implementation. +std::mutex depth_storage_mutex; +std::map depth_storage_images; +std::atomic depth_storage_count{0}; + +constexpr bool xbox_depth_storage_desc(const D3D12_RESOURCE_DESC& desc) { + const unsigned usages = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return (unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) == usages && + (desc.Format == DXGI_FORMAT_R16_TYPELESS || desc.Format == DXGI_FORMAT_R32_TYPELESS) && + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN; +} +D3D12_RESOURCE_DESC depth_storage_part(D3D12_RESOURCE_DESC desc, bool colour) { + desc.Flags = colour ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : + D3D12_RESOURCE_FLAGS(unsigned(desc.Flags) & ~unsigned(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + return desc; +} + class Resource final : public Child { public: - // {9b3e5f12-7c48-4d0e-a6b1-2f8d4c7e9a35} - static constexpr GUID kTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + static constexpr GUID kTag = rt::d3d12_xs::kVulkanResourceTag; Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags) @@ -2182,7 +2339,34 @@ public: D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} + void adopt_depth_storage(Resource* colour) { + storage_ = colour; + std::lock_guard lock(depth_storage_mutex); + depth_storage_images.emplace(this, XboxDepthStorage{colour->id(), desc_.MipLevels, desc_.DepthOrArraySize}); + ++depth_storage_count; + } + const Resource* storage_image() const { return storage_; } + ~Resource() override { + { + std::lock_guard guard(device_.mapped_texture_mutex); + if (device_.mapped_textures.erase(this)) --device_.map_count; + } + if (deferred_memory_) device_.retire_samples(this); + if (title_image_registered_) { + std::lock_guard lock(device_.title_image_mutex); + auto [begin,end] = device_.title_images.equal_range(va_); + for (auto it = begin; it != end; ++it) + if (it->second == this) { device_.title_images.erase(it); break; } + } + if (storage_) { + { + std::lock_guard lock(depth_storage_mutex); + depth_storage_images.erase(this); + --depth_storage_count; + } + storage_->Release(); + } if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); @@ -2214,9 +2398,29 @@ public: leonida::ResourceId id() const { return resource_id(this); } VkImage image() const { return image_; } + bool ensure_texture_bound() { + if (!deferred_memory_ || deferred_bound_.load(std::memory_order_acquire)) return true; + std::lock_guard lock(bind_mutex_); + if (deferred_bound_.load(std::memory_order_relaxed)) return true; + VkMemoryPropertyFlags flags{}; + const auto data = device_.allocate(image_need_, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &flags); + if (!data) return false; + auto& vk = device_.context->vk; + if (vk.vkBindImageMemory(device_.info.device, image_, data, 0) != VK_SUCCESS) { + vk.vkFreeMemory(device_.info.device, data, nullptr); + return false; + } + memory_ = data; + memory_flags_ = flags; + deferred_bound_.store(true, std::memory_order_release); + return true; + } + VkImage bound_image() { return ensure_texture_bound() ? image_ : VK_NULL_HANDLE; } + bool deferrable_sample() const { return deferred_memory_; } bool sparse_image() const { return sparse_image_; } VkBuffer buffer() const { return buffer_; } const D3D12_RESOURCE_DESC& desc() const { return desc_; } + bool rgba4_render_backing() const {return desc_.Format==DXGI_FORMAT_B4G4R4A4_UNORM && format_==VK_FORMAT_R8G8B8A8_UNORM;} VkFormat format() const { return format_; } // of the image bool has_view_format_list() const { return !view_formats_.empty(); } bool allows_view_format(VkFormat format) const { @@ -2237,6 +2441,9 @@ public: VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by + const Resource* depth_stencil_uav(UINT plane) const { + return plane < storage_planes_.size() ? storage_planes_[plane].get() : nullptr; + } VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it const DeviceState& device_state() const { return device_; } @@ -2504,6 +2711,17 @@ public: if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; const auto* pages = static_cast(address); + const auto base = reinterpret_cast(address); + if (desc_.Width > UINTPTR_MAX - base) return E_INVALIDARG; + // A CPU-data shadow represents committed contents. With demand-paged XMem the placement + // provider commits its own registered pages before entering the backend. + for (std::uintptr_t cursor = base; cursor < base + desc_.Width;) { + MEMORY_BASIC_INFORMATION region{}; + if (!VirtualQuery(reinterpret_cast(cursor), ®ion, sizeof(region)) || + region.State != MEM_COMMIT || (region.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || + !(region.Protect & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY))) return E_NOTIMPL; + cursor = reinterpret_cast(region.BaseAddress) + region.RegionSize; + } // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset @@ -2683,12 +2901,20 @@ public: return S_OK; } - HRESULT create_texture(const Format& format, const std::vector& castable = {}) { + HRESULT create_texture(const Format& format, const std::vector& castable = {}, bool defer = false) { auto& vk = device_.context->vk; const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; const UINT depth = volume ? desc_.DepthOrArraySize : 1; const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); + const UINT16 mips = full_mips(desc_.Width, desc_.Height, depth); + if (desc_.MipLevels == 0) desc_.MipLevels = mips; + if ((volume || one_d) && (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const UINT extent_limit = volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE1D_U_DIMENSION; + const UINT slice_limit = volume ? extent_limit : D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION; + if (!desc_.Width || desc_.Width > extent_limit || !desc_.Height || desc_.Height > extent_limit || + !desc_.DepthOrArraySize || desc_.DepthOrArraySize > slice_limit || desc_.MipLevels > mips) + return E_INVALIDARG; + } TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); VkImageCreateInfo& info = create.info; if (!castable.empty()) { @@ -2737,11 +2963,23 @@ public: } VkMemoryRequirements requirements{}; vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); - if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) - return E_OUTOFMEMORY; - leonida::ResourceBinding binding{}; + if (defer && !host_transfer_) { + deferred_memory_ = true; + image_need_ = requirements; + binding.residency_owner = this; + binding.ensure_residency = [](void* object) { + auto* r=static_cast(object); + const bool ready=r->ensure_texture_bound(); + if (ready) r->gpu_referenced_.store(true,std::memory_order_release); + return ready; + }; + } else { + memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); + if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) + return E_OUTOFMEMORY; + } + binding.image = image_; binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format binding.castable_view_formats = !view_formats_.empty(); // a castable list made the image mutable @@ -2749,6 +2987,8 @@ public: binding.rgb96 = format.rgb96; binding.depth24_as_float = format.d24_as_float; binding.depth24 = format.d24; + binding.xbox_depth16_stencil8=format.xbox_depth16_stencil8; + binding.rgba4_render_fallback=format.rgba4_render_fallback; binding.format = format.format; binding.aspects = format.aspects; binding.width = std::uint32_t(desc_.Width); @@ -2784,10 +3024,65 @@ public: return S_OK; } + // The Xbox proxy calls this before publishing an allocated depth texture. Each storage plane owns a + // regular color image with its own GFX10 address, so a UAV cannot replace the original SRV in set 0. + HRESULT enable_depth_stencil_uav(D3D12_HEAP_FLAGS storage_heap_flags) { + const bool narrow_stencil = desc_.Format == xbox_d16s8; + const bool depth16 = desc_.Format == DXGI_FORMAT_R16_TYPELESS || narrow_stencil; + if (!image_ || (!depth16 && desc_.Format != DXGI_FORMAT_R32G8X24_TYPELESS) || + !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || + desc_.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc_.MipLevels != 1 || + !desc_.DepthOrArraySize || desc_.SampleDesc.Count != 1) + return E_INVALIDARG; + if (storage_planes_[0]) return S_OK; + try { + decltype(storage_planes_) planes; + D3D12_RESOURCE_DESC plane_desc = desc_; + plane_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // D16 copies through a buffer as raw UNORM bits. R16_UINT lets an Xbox UAV read/write those bits. + const bool widened = narrow_stencil && format_ != VK_FORMAT_D16_UNORM_S8_UINT; + std::unique_ptr conversion; + if (widened) { + const auto blit = VK_FORMAT_FEATURE_2_BLIT_SRC_BIT | VK_FORMAT_FEATURE_2_BLIT_DST_BIT; + if (format_ != VK_FORMAT_D32_SFLOAT_S8_UINT || (device_.optimal_features(VK_FORMAT_R16_UNORM) & blit) != blit || + (device_.optimal_features(VK_FORMAT_R32_SFLOAT) & blit) != blit) return E_NOTIMPL; + auto intermediate = plane_desc; + intermediate.Format = DXGI_FORMAT_R32_FLOAT; + intermediate.Flags = D3D12_RESOURCE_FLAG_NONE; + conversion = std::make_unique(device_, intermediate, heap_, D3D12_HEAP_FLAG_NONE); + const HRESULT hr = conversion->create_texture(device_.texture_format(intermediate)); + if (FAILED(hr)) return hr; + } + const auto depth_format = widened ? DXGI_FORMAT_R16_TYPELESS : depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + const DXGI_FORMAT formats[] = {depth_format, DXGI_FORMAT_R8_UINT}; + const UINT plane_count = depth16 && !narrow_stencil ? 1 : 2; + for (UINT plane = 0; plane < plane_count; ++plane) { + plane_desc.Format = formats[plane]; + planes[plane] = std::make_unique(device_, plane_desc, heap_, storage_heap_flags); + const HRESULT hr = planes[plane]->create_texture(device_.texture_format(plane_desc)); + if (FAILED(hr)) return hr; + } + // Replacing the binding preserves the tracked layout of the original depth/stencil image. + auto binding = binding_; + binding.depth_uav = planes[0]->id(); + binding.depth_conversion = conversion ? conversion->id() : 0; + binding.stencil_uav = planes[1] ? planes[1]->id() : 0; + device_.context->add_resource(id(), binding); + binding_ = binding; + storage_planes_ = std::move(planes); + depth_conversion_ = std::move(conversion); + heap_flags_ |= storage_heap_flags; // GetHeapProperties describes the caller's entire logical texture. + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + return S_OK; + } + // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { D3D12_RESOURCE_DESC desc = desc_; + if (storage_ || storage_planes_[0]) desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; if (!desc.Alignment) { desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT @@ -2795,6 +3090,7 @@ public: } return desc; } + bool belongs_to(const DeviceState& device) const { return &device_ == &device; } // Both sparse resources and the committed fallback report the reserved layout and have no heap of their own. void make_reserved(D3D12_TEXTURE_LAYOUT layout) { @@ -2811,11 +3107,43 @@ public: // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address // through Xbox slot 133 reports that title address, as the console does: a title uses it as the CPU pointer it // clears the texture through (docs/d3d12_vulkan.md 3.3). Any other texture answers 0, as on D3D12. - D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return accel_ ? gpu_va_ : va_; } + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { + const auto result = accel_ ? gpu_va_ : va_; + return result; + } // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's // behavior, measured on a retail title). - void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { va_ = address; } + void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { + if (!image_ || !address || title_image_registered_) return; + std::lock_guard lock(device_.title_image_mutex); + va_ = address; + device_.title_images.emplace(va_, this); + title_image_registered_ = true; + } + // No descriptors have been built for a newly materialized raw surface. + void set_raw_image_address(std::uint64_t address) { image_address_ = address; } + + void use_texture_lease(void* data, std::size_t size, UINT layout) { + if (!image_ || !data) return; + const auto addr = reinterpret_cast(data); + if (va_ && va_ != addr) return; + if ((layout == 1 || layout == 0x100) && desc_.Dimension==D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + // Placement callbacks get a title VA; pin_mapped_data checks its live XMem section on Map. + title_linear_ = true; + title_linear_limit_ = size ? size : SIZE_MAX; + } + if (!size || va_) return; + std::uint64_t lo = 0, hi = 0; + const bool tracked = leonida::title_va_aliases().title_memory(addr, lo, hi) && size <= hi - addr; + MEMORY_BASIC_INFORMATION page{}; + const bool writable = VirtualQuery(data, &page, sizeof(page)) && page.State == MEM_COMMIT && + !(page.Protect & (PAGE_NOACCESS | PAGE_GUARD)) && + ((page.Protect & 0xffu) == PAGE_READWRITE || (page.Protect & 0xffu) == PAGE_WRITECOPY); + if (tracked && writable) { + set_title_address(addr); + } + } // // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime @@ -2853,6 +3181,10 @@ public: // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before // WriteToSubresource/ReadFromSubresource. HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { + if (title_linear_ && data && image_) { + *data = nullptr; + return map_title_texture(subresource, read, data); + } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && @@ -2865,7 +3197,24 @@ public: if (data) *data = mapped_; return S_OK; } - void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE*) override {} + void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { + if (!title_linear_) return; + std::lock_guard lock(title_map_mutex_); + const auto it=title_maps_.find(sub); + if(it==title_maps_.end()) return; + if ((!written || written->End>written->Begin) && (!written || written->End<=it->second.bytes)) + if(!upload_title_map(sub,it->second)) std::fprintf(stderr,"[rt] d3d12: texture upload on Unmap failed, format %u\n",unsigned(desc_.Format)); + if (!--it->second.refs) title_maps_.erase(it); + if (title_maps_.empty()) { + std::lock_guard guard(device_.mapped_texture_mutex); + if(device_.mapped_textures.erase(this)) --device_.map_count; + } + } + bool publish_cpu_writes() { + std::lock_guard lock(title_map_mutex_); + for(auto& [sub,map]:title_maps_) if(!upload_title_map(sub,map)) return false; + return true; + } // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. @@ -2879,6 +3228,83 @@ public: } private: + struct TitleMap { + std::shared_ptr data; + std::uintptr_t address{}; + UINT row{},bytes{},refs{}; + std::string fingerprint; + bool shared_pages = false; + }; + static std::string fingerprint(const TitleMap& map) { + std::string out; + for(std::size_t at=0;at(1u<<20,map.bytes-at)}); + return out; + } + bool upload_title_map(UINT sub, TitleMap& map) { + if (map.shared_pages) { + auto current=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(map.address),map.bytes); + if (!current || current.get()!=map.data.get()) return false; + } + auto hash=fingerprint(map); + if(hash==map.fingerprint) return true; + if(FAILED(cpu_copy(true,sub,nullptr,map.data.get(),map.row,map.bytes))) return false; + map.fingerprint=std::move(hash); + return true; + } + HRESULT map_title_texture(UINT sub, const D3D12_RANGE* read, void** out) { + if (!va_ || desc_.SampleDesc.Count!=1 || aspects_!=VK_IMAGE_ASPECT_COLOR_BIT || binding_.rgba4_render_fallback || + binding_.rgb96 || sub>=UINT(desc_.MipLevels)*desc_.DepthOrArraySize) return E_INVALIDARG; + std::lock_guard lock(title_map_mutex_); + if (auto it=title_maps_.find(sub);it!=title_maps_.end()) { + if(read && read->End>read->Begin && read->End>it->second.bytes) return E_INVALIDARG; + ++it->second.refs;*out=reinterpret_cast(it->second.address);return S_OK; + } + namespace ct=leonida::console_texture; + ct::TextureDesc d{};d.format=unsigned(desc_.Format);d.width=UINT(desc_.Width);d.height=desc_.Height; + d.depth_or_array=desc_.DepthOrArraySize;d.mips=desc_.MipLevels;d.swizzle=ct::kLinear; + const auto shape=ct::Texture::make(d); + if(!shape || shape->planes.size()!=1) return E_INVALIDARG; + const auto& layout=shape->planes[0].layout; + const UINT mip=sub%desc_.MipLevels,slice=sub/desc_.MipLevels; + const auto& level=layout.mips[mip]; + const std::uint64_t row=std::uint64_t(level.pitch)*layout.desc.element_bytes, size=row*level.height; + std::uint64_t offset{}; + if(layout.offset(mip,0,0,slice,offset)!=ct::Error::ok || !size || size>UINT_MAX || offset>title_linear_limit_ || + size>title_linear_limit_-offset || offset>UINTPTR_MAX-va_ || size>UINTPTR_MAX-va_-offset || + (read && read->End>read->Begin && read->End>size)) return E_INVALIDARG; + const auto title_address=std::uintptr_t(va_+offset); + auto pinned=rt::d3d12_xs::pin_texture_pages(reinterpret_cast(title_address),std::size_t(size)); + const bool shared=bool(pinned); + if (shared) previously_pinned_ = true; + else if (previously_pinned_) return E_INVALIDARG; + else { + // A console GPU VA need not name CPU memory on the PC. Map the live Vulkan image by + // staging it through our own allocation. The supplied VA is never dereferenced here. + try { pinned = std::shared_ptr(new std::uint8_t[std::size_t(size)]{},std::default_delete()); } + catch(const std::bad_alloc&) { return E_OUTOFMEMORY; } + } + const auto address=shared ? title_address : reinterpret_cast(pinned.get()); + TitleMap map{std::move(pinned),address,UINT(row),UINT(size),1,{},shared}; + if ((!read || read->End>read->Begin) && (!shared || gpu_referenced_.load(std::memory_order_acquire))) { + const HRESULT hr=cpu_copy(false,sub,nullptr,map.data.get(),map.row,map.bytes); + if(FAILED(hr)) return hr; + map.fingerprint=fingerprint(map); + } + title_maps_.emplace(sub,std::move(map)); + { + std::lock_guard guard(device_.mapped_texture_mutex); + if(device_.mapped_textures.insert(this).second) ++device_.map_count; + } + *out=reinterpret_cast(address); + return S_OK; + } + bool title_linear_ = false; + bool previously_pinned_ = false; + std::uint64_t title_linear_limit_ = 0; + std::atomic gpu_referenced_{false}; + std::mutex title_map_mutex_; + std::map title_maps_; // One subresource region in copy units: rows of texels, or of 4x4 blocks for block-compressed formats. struct Region { VkImageSubresourceLayers layers; @@ -3103,8 +3529,14 @@ private: DeviceState& device_; D3D12_RESOURCE_DESC desc_; + Resource* storage_ = nullptr; + bool title_image_registered_ = false; D3D12_HEAP_PROPERTIES heap_; D3D12_HEAP_FLAGS heap_flags_; + VkMemoryRequirements image_need_{}; + bool deferred_memory_ = false; + std::atomic deferred_bound_{false}; + std::mutex bind_mutex_; VkImage image_ = VK_NULL_HANDLE; VkBuffer buffer_ = VK_NULL_HANDLE; VkDeviceMemory memory_ = VK_NULL_HANDLE; @@ -3129,6 +3561,8 @@ private: bool sparse_image_ = false; bool placed_ = false; leonida::ResourceBinding binding_{}; // a texture's, as registered with the context + std::unique_ptr depth_conversion_; + std::array, 2> storage_planes_; // Xbox depth/stencil UAV, by plane bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address VkDeviceSize arena_offset_ = 0; @@ -3288,6 +3722,83 @@ bool equal_semantic(const std::string& a, const char* b) { // A heap (section 3.3): a range of the GPU address arena, as large as the game asked for, so a placed buffer can // name any 64 KiB-aligned offset in it. Textures placed in it still get their own VkDeviceMemory; the offset is only // their key, which keeps optimal-tiling images out of the arena's memory type. +bool DeviceState::publish_mapped_textures() { + if(!map_count.load(std::memory_order_acquire)) return true; + std::vector pending; + { + std::lock_guard lock(mapped_texture_mutex); + for(auto* r:mapped_textures) if(r->try_add_ref()) pending.push_back(r); + } + bool ok=true; + for(auto* r:pending) { if(!r->publish_cpu_writes()) ok=false; r->Release(); } + return ok; +} +bool DeviceState::materialize_sample(const leonida::DescriptorKey& key) { + if (!pending_sample_count.load(std::memory_order_acquire)) return true; + PendingSample sample{}; + { + std::lock_guard lock(pending_view_mutex); + const auto it = pending_samples.find(key); + if (it == pending_samples.end()) return true; + sample = it->second; + if (!sample.owner->try_add_ref()) return false; + } + const auto image = sample.owner->bound_image(); + const bool ok = image && bind_image(key, sample.image, image, sample.view_format, sample.channels_format, + sample.view_format, sample.owner->aspects(), true, false, {}); + if (ok) { + context->note_shader_image(sample.owner->id()); + std::lock_guard lock(pending_view_mutex); + const auto it=pending_samples.find(key); + if (it!=pending_samples.end() && it->second.owner==sample.owner) { + pending_samples.erase(it); + --pending_sample_count; + } + } + sample.owner->Release(); + return ok; +} + +bool DeviceState::materialize_table(std::uint64_t address, std::uint32_t slots) { + if (!pending_sample_count.load(std::memory_order_acquire)) return true; + if (!slots && address) { + std::vector keys; + { std::lock_guard lock(pending_view_mutex); + for (const auto& [key,view]:pending_samples) + if (view.owner->id() == address) keys.push_back(key); } + for (const auto& key:keys) if (!materialize_sample(key)) return false; + return true; + } + std::uint64_t end = 0; + if (slots) { + std::lock_guard lock(visible_heap_mutex); + auto it = visible_heaps.upper_bound(address); + if (it != visible_heaps.begin()) { + --it; + if (address < it->second.end && (address-it->first)%kDescriptorSize==0) { + if(it->second.type==D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) return true; + end = address + std::min(it->second.end-address, std::uint64_t(slots)*kDescriptorSize); + } + } + } + if (!end) { + // Directly indexed and unrecognized heaps have no trustworthy table extent. + std::vector all; + {std::lock_guard lock(pending_view_mutex);for(const auto& [key,v]:pending_samples) all.push_back(key);} + for(const auto& key:all) if(!materialize_sample(key)) return false; + return true; + } + const auto refreshed = std::min(end-address, std::uint64_t(kViewScanLimit)*kDescriptorSize); + if (end-address>refreshed) + leonida::title_va_aliases().pull_descriptors(arena.mapped+address+refreshed,std::size_t(end-address-refreshed)); + for (auto at=address; at { public: @@ -3816,7 +4327,7 @@ public: if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); - for (VkShaderModule module : modules_) vk.vkDestroyShaderModule(dev, module, nullptr); + modules_.clear(); if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); } @@ -3845,11 +4356,26 @@ public: subgroup_requests_.push_back(request); } - std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } + std::uintptr_t id() const { + return native_owner_ ? native_owner_->id() : reinterpret_cast(static_cast(this)); + } + void share_native_graphics(std::shared_ptr owner) { native_owner_ = std::move(owner); } + bool ensure_native_source(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, + std::span containers) { + std::call_once(native_source_once_,[&]{ + if(rt::d3d12_xs::find_pso_record(this)){native_source_ready_=true;return;} + rt::d3d12_xs::native_pipeline_detail::Stream source; + rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,source); + auto record=rt::d3d12_xs::PsoStreamRecord::capture(source.desc(),containers); + native_source_ready_=record && rt::d3d12_xs::attach_pso_record(this,std::move(record)); + }); + return native_source_ready_; + } void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { + if (native_owner_) return native_owner_->GetCachedBlob(blob); if (!blob) return S_OK; *blob = new CachedBlob(leonida::cached_pso::encode(device_.pso_identity, cache_key_)); return S_OK; @@ -3879,9 +4405,25 @@ public: return S_OK; } - bool compute() const { return registered_ && !is_graphics_; } - bool graphics() const { return registered_ && is_graphics_; } - const std::vector& subgroup_requests() const { return subgroup_requests_; } + void set_pending_stream(bool compute) { pending_stream_kind_=compute?2:1; } + bool resolve_type(bool graphics) { + if(native_owner_)return native_owner_->resolve_type(graphics); + if(pending_stream_kind_) { + if(pending_stream_kind_!=(graphics?1u:2u))return false; + std::call_once(resolve_stream_once_,[&]{ + const auto* record=rt::d3d12_xs::find_pso_record(this); + PipelineStream stream{}; + HRESULT hr=record?parse_pipeline_stream(record->desc(),stream):E_INVALIDARG; + if(SUCCEEDED(hr))hr=stream.has_cs?create_compute(stream.compute):create_graphics(stream.graphics,&stream.ms,&stream.as); + }); + } + return registered_ && (is_graphics_==graphics); + } + bool compute() const { return pending_stream_kind_==2 || (registered_ && !is_graphics_); } + bool graphics() const { return native_owner_ ? native_owner_->graphics() : pending_stream_kind_==1 || (registered_ && is_graphics_); } + const std::vector& subgroup_requests() const { + return native_owner_ ? native_owner_->subgroup_requests() : subgroup_requests_; + } // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the // VS's input signature by semantic name and index: location = the element's register, the translator's rule @@ -4016,6 +4558,14 @@ public: // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), "Recipe::required_sizes needs an entry per graphics stage"); + unsigned packed_color_mask=0; + for(unsigned i=0;i stage_infos; // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. @@ -4027,7 +4577,9 @@ public: const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); - bool depth24_fragment = d24_as_float && desc.DepthStencilState.DepthEnable; + const bool packed16_fallback=desc.DSVFormat==xbox_d16s8 && device_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT)!=VK_FORMAT_D16_UNORM_S8_UINT; + if(packed16_fallback && samples>1 && desc.DepthStencilState.DepthEnable) return E_NOTIMPL; + bool depth24_fragment = (d24_as_float || packed16_fallback) && desc.DepthStencilState.DepthEnable; if (depth24_fragment && samples > 1) { log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", int(samples)); @@ -4035,7 +4587,7 @@ public: } const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, desc.RasterizerState.SlopeScaledDepthBias, - desc.RasterizerState.DepthBiasClamp}; + desc.RasterizerState.DepthBiasClamp,packed16_fallback?65535.0f:16777215.0f}; for (Stage& stage : stages) { if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only stage.fssm = leonida::fssm_program( @@ -4082,6 +4634,7 @@ public: code_stage = &stage; } stage.words = library->spirv(*stage.entry); + if(stage.bit==VK_SHADER_STAGE_FRAGMENT_BIT && packed_color_mask && !leonida::rgba4::quantize(stage.words,packed_color_mask)) return E_INVALIDARG; if (stage.words.empty()) return E_FAIL; const auto inner = leonida::conservative_raster::inner_coverage_requirements(stage.words); if (!inner.valid) return E_INVALIDARG; @@ -4142,12 +4695,11 @@ public: stage.words = std::move(patched); } } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(stage.words); + if (!module) return E_FAIL; + if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && + topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) + rectangle_vertex_ = modules_.back(); VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; info.module = module; @@ -4163,12 +4715,8 @@ public: vs_stage.entry->name.c_str(), why.c_str()); return E_NOTIMPL; } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(words); + if (!module) return E_FAIL; VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; info.module = module; @@ -4177,13 +4725,8 @@ public: } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) - return E_FAIL; - modules_.push_back(module); + const VkShaderModule module = shader_module(words); + if (!module) return E_FAIL; VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; info.module = module; @@ -4392,6 +4935,8 @@ public: graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target ? kA8UnormFormat : vulkan_format(desc.RTVFormats[i], false).format; + if(desc.RTVFormats[i]==DXGI_FORMAT_B4G4R4A4_UNORM && !device_.color_attachment_usable(graphics_.color_formats[i])) + graphics_.color_formats[i]=VK_FORMAT_R8G8B8A8_UNORM; if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { log_once("render-target format not supported yet:", desc.RTVFormats[i]); return E_INVALIDARG; @@ -4401,7 +4946,7 @@ public: Format f = vulkan_format(desc.DSVFormat, true); if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does - graphics_.depth_format = f.format; + graphics_.depth_format = device_.depth_backing(f.format); graphics_.depth_aspects = f.aspects; } if (samples > 1) { @@ -4474,6 +5019,7 @@ public: // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. graphics_.mesh = mesh; + graphics_.base_rectangle_stage = rect_list; recipe_.mesh = mesh; recipe_.stages = std::move(stage_infos); recipe_.attributes = std::move(attributes); @@ -4488,8 +5034,17 @@ public: recipe_.depth = depth; recipe_.blends = std::move(blends); recipe_.blend = blend; - graphics_.pipeline = build(0); - if (!graphics_.pipeline) return E_FAIL; + VkResult compile_status=VK_SUCCESS; + const bool cache_only=device_.info.cold_graphics_compile; + if(device_.info.first_use_backend_pipelines) { + graphics_.pending_base_compile=true; + } else { + graphics_.pipeline=build(0,cache_only?VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT:0,&compile_status); + if(!graphics_.pipeline) { + if(!cache_only || compile_status!=VK_PIPELINE_COMPILE_REQUIRED)return E_FAIL; + graphics_.pending_base_compile=true; + } + } graphics_.variant = [this](std::uint32_t unbound) { return variant(unbound); }; if (code_stage) { @@ -4601,22 +5156,38 @@ public: VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - const VkPipelineCache cache = device_.pipeline_cache(); - const bool checkpoint = cache && startup_cache_checkpoints_enabled(); - const ULONGLONG started = checkpoint ? GetTickCount64() : 0; - if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) - return E_FAIL; - if (checkpoint && GetTickCount64() - started >= 500) { - const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); - if (lock.owns_lock()) { - try { - save_session_pipeline_cache(vk, dev, cache); - } catch (const std::exception& error) { - std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + if(device_.info.first_use_backend_pipelines && (!pipeline_info.stage.pNext || pipeline_info.stage.pNext==&required_size)) { + const bool has_subgroup=pipeline_info.stage.pNext!=nullptr; + pipeline_info.stage.pNext=nullptr; + pipeline_.materialize=[this,pipeline_info,required_size,has_subgroup]() -> VkPipeline { + std::lock_guard lock(compute_compile_mutex_); + if(pipeline_.pipeline)return pipeline_.pipeline; + auto info=pipeline_info; + auto size=required_size;if(has_subgroup)info.stage.pNext=&size; + VkPipeline live=VK_NULL_HANDLE; + const auto result=device_.context->vk.vkCreateComputePipelines(device_.info.device,device_.pipeline_cache(),1,&info,nullptr,&live); + if(result!=VK_SUCCESS){if(live)device_.context->vk.vkDestroyPipeline(device_.info.device,live,nullptr);return VK_NULL_HANDLE;} + pipeline_.pipeline = live; + return live; + }; + } else { + const VkPipelineCache cache = device_.pipeline_cache(); + const bool checkpoint = cache && startup_cache_checkpoints_enabled(); + const ULONGLONG started = checkpoint ? GetTickCount64() : 0; + if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) + return E_FAIL; + if (checkpoint && GetTickCount64() - started >= 500) { + const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); + if (lock.owns_lock()) { + try { + save_session_pipeline_cache(vk, dev, cache); + } catch (const std::exception& error) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + } } } - } + } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). const std::vector& code = program.bytes; @@ -4652,7 +5223,7 @@ private: }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. - VkPipeline build(std::uint32_t unbound) const { + VkPipeline build(std::uint32_t unbound, VkPipelineCreateFlags flags=0, VkResult* status=nullptr) { // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices // from SV_VertexID) leaves it out, since no vkCmdBindVertexBuffers2 would ever set it // (VUID-vkCmdDraw-pStrides-04913). @@ -4718,8 +5289,29 @@ private: } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = r.stages.data(); + std::vector rectangle_stages; + if (unbound & leonida::GraphicsPipeline::rectangle_stage) { + if (!rectangle_vertex_) return VK_NULL_HANDLE; + if (!rectangle_module_) { + std::string why; + const auto words = leonida::rect_list_geometry(rectangle_vertex_->words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); + return VK_NULL_HANDLE; + } + rectangle_module_ = shader_module(words); + if (!rectangle_module_) return VK_NULL_HANDLE; + } + rectangle_stages = r.stages; + VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + geometry.module = rectangle_module_; + geometry.pName = "main"; + rectangle_stages.push_back(geometry); + } + const auto& stages = rectangle_stages.empty() ? r.stages : rectangle_stages; + info.stageCount = std::uint32_t(stages.size()); + info.pStages = stages.data(); info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; info.pViewportState = &viewport; @@ -4728,11 +5320,15 @@ private: info.pDepthStencilState = &r.depth; info.pColorBlendState = &blend; info.pDynamicState = &dynamic; + info.flags=flags; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, - &info, nullptr, &pipeline) != VK_SUCCESS) + const auto result=device_.context->vk.vkCreateGraphicsPipelines(device_.info.device,device_.pipeline_cache(),1,&info,nullptr,&pipeline); + if(status)*status=result; + if(result!=VK_SUCCESS) { + if(pipeline)device_.context->vk.vkDestroyPipeline(device_.info.device,pipeline,nullptr); return VK_NULL_HANDLE; + } return pipeline; } @@ -4756,12 +5352,28 @@ private: std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; - std::vector modules_; + std::mutex compute_compile_mutex_; + std::vector modules_; + leonida::GraphicsShaderModules::Reference rectangle_vertex_; + VkShaderModule rectangle_module_ = VK_NULL_HANDLE; + VkShaderModule shader_module(std::span words) { + auto& vk=device_.context->vk; + auto object = device_.graphics_modules.acquire(device_.info.device, vk.vkCreateShaderModule, + vk.vkDestroyShaderModule, words); + if(!object)return VK_NULL_HANDLE; + const auto h=object->handle;modules_.push_back(std::move(object)); + return h; + } VkDeviceSize code_base_ = 0; VkDeviceSize code_bytes_ = 0; bool registered_ = false; bool is_graphics_ = false; std::vector subgroup_requests_; // one per stage, in creation order + unsigned pending_stream_kind_=0; + std::once_flag resolve_stream_once_; + std::once_flag native_source_once_; + bool native_source_ready_ = false; + std::shared_ptr native_owner_; leonida::cached_pso::Key cache_key_; }; @@ -4789,6 +5401,31 @@ struct TextureView { float min_lod = 0.0f; }; +// The existing mutable Vulkan formats come from these DXGI typeless families. A typed resource cannot be +// reinterpreted by the 1D/3D UAV path; equal texel sizes alone don't make a cast legal. +bool uav_format_compatible(DXGI_FORMAT resource, DXGI_FORMAT view) { + if (view == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || view == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return false; + if (resource == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) return view == DXGI_FORMAT_R8G8B8A8_UNORM; + if (resource == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) return view == DXGI_FORMAT_B8G8R8A8_UNORM; + if (resource == view) return true; + switch (resource) { + case DXGI_FORMAT_R32G32B32A32_TYPELESS: + return view >= DXGI_FORMAT_R32G32B32A32_FLOAT && view <= DXGI_FORMAT_R32G32B32A32_SINT; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: + return view >= DXGI_FORMAT_R16G16B16A16_FLOAT && view <= DXGI_FORMAT_R16G16B16A16_SINT; + case DXGI_FORMAT_R32G32_TYPELESS: return view >= DXGI_FORMAT_R32G32_FLOAT && view <= DXGI_FORMAT_R32G32_SINT; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: return view == DXGI_FORMAT_R10G10B10A2_UNORM || + view == DXGI_FORMAT_R10G10B10A2_UINT; + case DXGI_FORMAT_R8G8B8A8_TYPELESS: return view >= DXGI_FORMAT_R8G8B8A8_UNORM && view <= DXGI_FORMAT_R8G8B8A8_SINT; + case DXGI_FORMAT_R16G16_TYPELESS: return view >= DXGI_FORMAT_R16G16_FLOAT && view <= DXGI_FORMAT_R16G16_SINT; + case DXGI_FORMAT_R8G8_TYPELESS: return view >= DXGI_FORMAT_R8G8_UNORM && view <= DXGI_FORMAT_R8G8_SINT; + case DXGI_FORMAT_R32_TYPELESS: return view >= DXGI_FORMAT_R32_FLOAT && view <= DXGI_FORMAT_R32_SINT; + case DXGI_FORMAT_R16_TYPELESS: return view >= DXGI_FORMAT_R16_FLOAT && view <= DXGI_FORMAT_R16_SINT; + case DXGI_FORMAT_B8G8R8A8_TYPELESS: return view == DXGI_FORMAT_B8G8R8A8_UNORM; + default: return false; + } +} + // In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific // and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs. // As on the host runtime (d3d12_pipeline_library_host_test), a foreign, truncated or corrupt blob is E_INVALIDARG; @@ -5214,9 +5851,14 @@ private: // The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. // False (with a log) for a view set 0 cannot show yet. -bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { +bool image_descriptor(const Resource& resource, const TextureView& view, bool storage, leonida::gfx10::Image& out, + VkFormat& view_format, DeviceState::VolumeSlices& slices) { namespace g = leonida::gfx10; const D3D12_RESOURCE_DESC& desc = resource.desc(); + if (storage && (resource.aspects() & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { + log_once("storage view not supported for depth-stencil texture:", int(desc.Format)); + return false; + } // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. @@ -5228,6 +5870,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // Each stencil view format belongs to its own DXGI family only, as in D3D12: the family is the texture's DXGI // format, not the Vulkan format behind it (a D24 texture may be D32_SFLOAT_S8_UINT underneath). const bool stencil_format_fits = + (view.format==xbox_s8_plane && desc.Format==xbox_d16s8) || (view.format == DXGI_FORMAT_X24_TYPELESS_G8_UINT && (desc.Format == DXGI_FORMAT_R24G8_TYPELESS || desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT)) || (view.format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT && @@ -5236,13 +5879,15 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); return false; } - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool msaa = g::multisampled(view.type); + const bool volume = view.type == g::ImageType::image_3d; const bool line = view.type == g::ImageType::image_1d; - const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : - view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : - D3D12_RESOURCE_DIMENSION_TEXTURE2D; - if (desc.Dimension != dimension || (line && view.layer_count != 1) || msaa != (desc.SampleDesc.Count > 1)) { + const bool line_array = view.type == g::ImageType::image_1d_array; + const bool one_d = line || line_array; + const bool msaa = g::multisampled(view.type); + const auto dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D + : one_d ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + if (desc.Dimension != dimension || (msaa ? desc.SampleDesc.Count <= 1 : desc.SampleDesc.Count != 1) || + (storage ? msaa : line_array) || (line && view.layer_count != 1)) { log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); return false; } @@ -5262,7 +5907,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida } const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); VkFormat named = resource_format; - if (volume) { + if (volume && !storage) { const bool compatible = vulkan_format(desc.Format, false).typeless ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) @@ -5280,6 +5925,7 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida const bool depth_plane = (resource.aspects() & VK_IMAGE_ASPECT_DEPTH_BIT) && !stencil; if (depth_plane) { const bool depth_format_fits = + (desc.Format == xbox_d16s8 && (view.format == DXGI_FORMAT_UNKNOWN || view.format == xbox_d16_plane)) || (desc.Format == DXGI_FORMAT_D16_UNORM && (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R16_UNORM)) || (desc.Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM) || @@ -5297,7 +5943,16 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida return false; } } - if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { + const bool new_uav = storage && (volume || one_d); + if (new_uav) { + const DXGI_FORMAT dxgi = view.format == DXGI_FORMAT_UNKNOWN ? desc.Format : view.format; + const Format format = texture_storage_format(dxgi, false); + if (format.typeless || format.aspects != VK_IMAGE_ASPECT_COLOR_BIT || !uav_format_compatible(desc.Format, dxgi)) { + log_once("unordered-access view format is not compatible with the resource:", dxgi); + return false; + } + named = format.format; + } else if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { log_once("incompatible typed A8 view format:", int(view.format)); return false; @@ -5320,8 +5975,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida } } // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the - // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format: the swizzle below - // then reads alpha as one, and bind_image views the RGBA32 image accordingly. + // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format (alpha reads as + // one), but the format list and Vulkan view use the RGBA32 format that backs it. const bool rgb96 = resource.rgb96(); if (!stencil && !depth_plane) { const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; @@ -5330,31 +5985,45 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("view format outside the texture's 96-bit family:", int(view.format)); return false; } - if (rgb96) named = rgb96_named_format(named); } if (named == VK_FORMAT_UNDEFINED || !resource.allows_view_format(named)) { log_once("view format not in the resource's castable list:", int(view.format)); return false; } - const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(named); - VkFormat view_format = VK_FORMAT_UNDEFINED; + const std::uint32_t code = stencil ? g::stencil_format + : g::format_from_vulkan(rgb96 ? rgb96_named_format(named) : named); + view_format = VK_FORMAT_UNDEFINED; if (stencil) { view_format = resource.format(); - } else if (code && rgb96) { - view_format = named; + } else if (code && (new_uav || rgb96)) { + view_format = rgb96 ? rgb96_view_format(resource.format(), code) : named; } else if (code) { view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); } - if (view_format == VK_FORMAT_UNDEFINED) { + if (!storage && resource.rgba4_render_backing() && (view.format == DXGI_FORMAT_B4G4R4A4_UNORM || view.format == DXGI_FORMAT_UNKNOWN)) + view_format = resource.format(); + if (view_format == VK_FORMAT_UNDEFINED || !resource.allows_view_format(view_format)) { log_once("view format not supported for this texture:", int(view.format)); return false; } - const UINT layers = volume ? 1 : desc.DepthOrArraySize; - if (view.first_mip >= desc.MipLevels || view.first_layer >= layers) { + if (view.first_mip >= desc.MipLevels) { + log_once("view starts past the texture's mips; first mip", int(view.first_mip)); + return false; + } + // SRVs address an entire volume; only a UAV descriptor can specify a W range within its mip. + const UINT layers = volume ? (storage ? std::max(1u, UINT(desc.DepthOrArraySize) >> view.first_mip) : 1u) + : desc.DepthOrArraySize; + if (view.first_layer >= layers) { log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); return false; } - if (msaa && view.layer_count != UINT_MAX && view.layer_count > UINT(desc.DepthOrArraySize) - view.first_layer) { + const UINT remaining = layers - view.first_layer; + const UINT layer_count = view.layer_count == ~0u ? remaining : view.layer_count; + if (new_uav && (!layer_count || layer_count > remaining)) { + log_once("unordered-access view slice count is outside the selected mip:", int(view.layer_count)); + return false; + } + if (msaa && layer_count > remaining) { log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); return false; } @@ -5368,8 +6037,13 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida out.samples = desc.SampleDesc.Count; out.first_mip = view.first_mip; out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); - out.first_layer = view.first_layer; - out.layer_count = std::min(view.layer_count, layers - view.first_layer); + if (volume) { + if (storage && (view.first_layer != 0 || layer_count != layers)) + slices = {view.first_layer, layer_count}; + } else { + out.first_layer = view.first_layer; + out.layer_count = std::min(layer_count, remaining); + } if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes out.resource_mips = desc.MipLevels; out.min_lod = view.min_lod; @@ -5387,7 +6061,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida // order, so then the view's own format places the channels. Depth images keep their own format's channels. const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && named != view_format && !g::is_depth_stencil_format(view_format); - g::Swizzle channels = g::format_swizzle(other_order ? named : view_format); + const VkFormat channels_format = rgb96 ? rgb96_named_format(view_format) : other_order ? named : view_format; + g::Swizzle channels = g::format_swizzle(channels_format); if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; @@ -5576,6 +6251,8 @@ public: info.get_instance_proc(info.instance, "vkGetDeviceProcAddr")); state_.format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); + state_.format_properties2 = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); state_.image_format_properties = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); state_.image_format_properties2 = reinterpret_cast( @@ -5678,14 +6355,44 @@ public: if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; } - leonida::title_va_aliases().set_hooks( + leonida::title_va_aliases().set_resolver( &state_, [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { return static_cast(device)->resolve_title_memory(va, bytes, out); - }, - [](void* device, std::uint64_t table, std::uint32_t descriptors) { - static_cast(device)->scan_title_table(table, descriptors); }); + state_.context->set_cpu_texture_publisher([this]{return state_.publish_mapped_textures();}); + state_.context->set_sample_table_resolver([this](std::uint64_t address, std::uint32_t slots) { + return state_.materialize_table(address, slots); + }); + state_.context->set_table_scanner([this](std::uint64_t table, std::uint32_t descriptors) { + state_.scan_title_table(table, descriptors); + }); + state_.context->set_graphics_family(info.queue_family); +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10 && info.physical) { + const auto get_props = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties2")); + if (get_props) { + const auto aspects = [&](VkFormat format) { + VkFormatProperties3 props{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 query{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &props}; + get_props(info.physical, format, &query); + VkImageAspectFlags mask = 0; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR) + mask |= VK_IMAGE_ASPECT_STENCIL_BIT; + return mask; + }; + state_.context->set_compute_copy_aspects( + [d16 = aspects(VK_FORMAT_D16_UNORM), ds = aspects(VK_FORMAT_D32_SFLOAT_S8_UINT)](VkFormat format) { + if (format == VK_FORMAT_D16_UNORM) return d16; + if (format == VK_FORMAT_D32_SFLOAT_S8_UINT) return ds; + return VkImageAspectFlags{}; + }); + } + } +#endif if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5723,7 +6430,7 @@ public: // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); + }, state_.families); if (info.buffer_device_address && info.physical && info.get_instance_proc) { if (const auto get_props = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { @@ -5875,7 +6582,8 @@ public: "sampler heap (%u of %u besides the fallback): its limits or " "vkGetDescriptorSetLayoutSupport allow no more\n", features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); - state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); + state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features, + state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; @@ -6033,49 +6741,43 @@ public: state_.context->set_heap_base(arena.address); state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); - // Vertex and index views that name the title's own CPU memory are copied into a ring carved from the - // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). - state_.context->set_title_memory( - [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { - static constexpr VkDeviceSize kRing = 16ull << 20; - static std::mutex mutex; - static VkDeviceSize ring_base = 0, ring_next = 0; - static bool tried = false, logged = false; - if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; - // The whole range must be committed, readable host memory. - for (std::uint64_t at = va; at < va + size;) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) return false; - if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || !info.Protect) - return false; - at = reinterpret_cast(info.BaseAddress) + info.RegionSize; - } - std::lock_guard lock(mutex); - if (!tried) { - tried = true; - if (!st->arena_allocate(kRing, 256, ring_base, DeviceState::arena_shader)) ring_base = 0; - } - if (!ring_base) return false; - const VkDeviceSize aligned = (size + 255) & ~VkDeviceSize(255); - if (ring_next + aligned > kRing) ring_next = 0; - std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), - std::size_t(size)); - buffer = st->arena.buffer; - offset = ring_base + ring_next; - ring_next += aligned; - if (!logged) { - logged = true; - std::fprintf(stderr, "[rt] d3d12: vertex/index views in title memory are copied into a " - "%llu MiB ring (first: %llu bytes)\n", - static_cast(kRing >> 20), static_cast(size)); - } - return true; - }); + // Copy only registered title data. Each immutable upload stays alive in the queue command slot + // until that submission's timeline value completes; a large indexed frame cannot wrap over itself. + state_.context->set_geometry_provider([st=&state_](std::uint64_t va,std::uint64_t bytes, + leonida::VulkanContext::GeometryUpload& result) { + if (!va || !bytes || bytes>UINTPTR_MAX-va || !st->arena.mapped || bytes>st->arena.size) return false; + std::uint64_t lo{},hi{}; + if (!leonida::title_va_aliases().title_memory(va,lo,hi) || bytes>hi-va) { + return false; + } + for(std::uint64_t at=va;at(at),®ion,sizeof(region)) || region.State!=MEM_COMMIT || + (region.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || + !(region.Protect & (PAGE_READONLY|PAGE_READWRITE|PAGE_WRITECOPY))) return false; + at=reinterpret_cast(region.BaseAddress)+region.RegionSize; + } + struct Lease { + DeviceState* state{}; + VkDeviceSize offset{},bytes{}; + ~Lease(){if(bytes)state->arena_release(offset,bytes,DeviceState::arena_buffer);} + }; + auto lease=std::make_shared(); + if (!st->arena_allocate(bytes,256,lease->offset,DeviceState::arena_buffer)) return false; + lease->state=st;lease->bytes=bytes; + SIZE_T copied{}; + if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(va),st->arena.mapped+lease->offset, + SIZE_T(bytes),&copied) || copied!=bytes) return false; + result={va,bytes,st->arena.buffer,lease->offset,std::move(lease)}; + return true; + }); return true; } ~Device() override { - leonida::title_va_aliases().clear_hooks(&state_); + raw_images_.clear(); + leonida::label::completions().stop(state_.info.device); + leonida::title_va_aliases().clear_resolver(&state_); { std::lock_guard lock(state_.title_window_mutex); for (const auto& window : state_.title_windows) @@ -6125,6 +6827,100 @@ public: leonida::VulkanContext& context() { return *state_.context; } const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } const DeviceState& state() const { return state_; } + HRESULT create_native_graphics(const leonida::native_pso::GraphicsDesc& desc, REFIID iid, void** out) { + const auto* shaders = state_.library(); + if (!shaders) return E_NOTIMPL; + return state_.native_graphics.create(shaders->directory(), desc, out, [&](const auto& pc, const auto& mesh, const auto& containers) { + return shared_native_graphics(pc, mesh, containers, iid, out); + }); + } + // A fresh public PSO has its own COM identity, private data and name. Equal native descriptions can + // hold one compiled backend PSO while either public object lives. The device only holds weak references. + HRESULT prepare_console_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& source, REFIID iid, void** out, + std::unique_ptr record) { + if (!out)return E_POINTER;*out=nullptr; + PipelineStream stream{}; + if(const auto hr=parse_pipeline_stream(source,stream);FAILED(hr))return hr; + const auto* library=state_.library();if(!library)return E_FAIL; + const auto verify=[&](const char* name,const D3D12_SHADER_BYTECODE& code) { + if(!code.BytecodeLength)return true; + if(!code.pShaderBytecode)return false; + const std::span bytes{static_cast(code.pShaderBytecode),code.BytecodeLength}; + const std::string identity=std::string(name)+leonida::sha256_hex(bytes); + {std::lock_guard lock(verified_program_mutex_);if(verified_programs_.count(identity))return true;} + auto program=leonida::compute_program(bytes); + if(program.bytes.empty())return false; + bool ambiguous=false; + const auto candidates=library->program_candidates(name,program,&ambiguous); + if(candidates.empty() || ambiguous)return false; + {std::lock_guard lock(verified_program_mutex_);verified_programs_.insert(identity);} + return true; + }; + if(stream.has_cs) { + if(!stream.compute.CS.BytecodeLength || !verify("cs",stream.compute.CS))return E_INVALIDARG; + } else { + const auto& g=stream.graphics; + if(stream.as.BytecodeLength || g.HS.BytecodeLength || g.DS.BytecodeLength)return E_NOTIMPL; + if((bool(g.VS.BytecodeLength)==bool(stream.ms.BytecodeLength)) || g.NumRenderTargets>8 || + !verify("vs",g.VS)||!verify("gs",g.GS)||!verify("ms",stream.ms)||!verify("ps",g.PS))return E_INVALIDARG; + } + if(!record) record=rt::d3d12_xs::PsoStreamRecord::capture(source); + if(!record)return E_INVALIDARG; + auto* pipeline=new PipelineState(state_); + pipeline->attach_device(identity()); + pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics)); + if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;} + pipeline->set_pending_stream(stream.has_cs); + return hand_out(pipeline,iid,out); + } + HRESULT shared_native_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh, + std::span containers, + REFIID iid, void** out) { + auto key = pipeline_key(pc); + if (mesh.BytecodeLength) + key += leonida::sha256_hex({static_cast(mesh.pShaderBytecode), mesh.BytecodeLength}); + std::shared_ptr compiled; + { + std::lock_guard lock(native_pipeline_mutex_); + const auto found = native_pipelines_.find(key); + if (found != native_pipelines_.end()) compiled = found->second.lock(); + } + if (!compiled) { + ID3D12PipelineState* raw = nullptr; + HRESULT hr; + if(state_.info.prepare_on_bind) { + rt::d3d12_xs::native_pipeline_detail::Stream native; + rt::d3d12_xs::native_pipeline_detail::build_stream(pc,mesh,native); + const auto source=native.desc(); + auto record=rt::d3d12_xs::PsoStreamRecord::capture(source,containers); + hr=record?prepare_console_stream(source,__uuidof(ID3D12PipelineState),reinterpret_cast(&raw),std::move(record)):E_INVALIDARG; + } else { + hr = mesh.BytecodeLength + ? rt::d3d12_xs::native_pipeline_detail::create_mesh(this, pc, mesh, __uuidof(ID3D12PipelineState), + reinterpret_cast(&raw)) + : CreateGraphicsPipelineState(&pc, IID_PPV_ARGS(&raw)); + } + if (FAILED(hr)) return hr; + if (!raw) return E_FAIL; + auto* owner = PipelineState::from(raw); + if (!owner) { raw->Release(); return E_NOINTERFACE; } + compiled = std::shared_ptr(owner, [](PipelineState* p) { p->Release(); }); + std::lock_guard lock(native_pipeline_mutex_); + if (native_pipelines_.size() >= 16384) native_pipelines_.clear(); + auto& cached = native_pipelines_[key]; + if (auto concurrent = cached.lock()) compiled = std::move(concurrent); + else cached = compiled; + } + if(!compiled->ensure_native_source(pc,mesh,containers)) return E_FAIL; + auto* view = new PipelineState(state_); + view->attach_device(identity()); + if(!rt::d3d12_xs::share_pso_record(compiled.get(),view)) { + view->Release(); + return E_OUTOFMEMORY; + } + view->share_native_graphics(std::move(compiled)); + return hand_out(view, iid, out); + } IUnknown* holder() { return identity(); } // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. @@ -6159,6 +6955,148 @@ public: return ok ? found : nullptr; } + class RawTileReader { + public: + RawTileReader(std::uint64_t address, std::size_t size) + : address_(address), size_(size), cache_(std::min(size, block_size * slots)) { + tags_.fill(SIZE_MAX); + } + bool copy(std::size_t offset, std::uint8_t* to, std::size_t bytes) { + if (offset > size_ || bytes > size_ - offset) return false; + while (bytes) { + const auto block = offset / block_size; + const auto slot = block % slots; + const auto base = block * block_size; + const auto available = std::min(block_size, size_ - base); + auto* window = cache_.data() + slot * block_size; + if (tags_[slot] != block) { + SIZE_T copied{}; + if (!ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(address_+base), + window,available,&copied) || copied!=available) return false; + tags_[slot]=block; + } + const auto n=std::min(bytes,available-(offset-base)); + std::memcpy(to,window+offset-base,n); + offset+=n;to+=n;bytes-=n; + } + return true; + } + private: + static constexpr std::size_t block_size = 64 * 1024, slots = 8; + std::uint64_t address_; + std::size_t size_; + std::vector cache_; + std::array tags_; + }; + + bool raw_texture_view(const D3D12_RESOURCE_DESC& raw, const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + std::uint64_t address, D3D12_CPU_DESCRIPTOR_HANDLE destination) { + namespace ct = leonida::console_texture; + if (!address || !destination.ptr || (address & 255) || raw.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) + return false; + Resource* placed = nullptr; + { + std::lock_guard lock(state_.title_image_mutex); + auto [begin, end] = state_.title_images.equal_range(address); + for (auto it = begin; it != end; ++it) { + const auto& shape = it->second->desc(); + if (raw.Width == shape.Width && raw.Height == shape.Height && raw.Format == shape.Format && + raw.DepthOrArraySize == shape.DepthOrArraySize && raw.MipLevels == shape.MipLevels && + raw.SampleDesc.Count == shape.SampleDesc.Count && it->second->try_add_ref()) { + placed = it->second; + break; + } + } + } + if (placed) { + CreateShaderResourceView(placed, &view, destination); + placed->Release(); + return true; + } + // Raw sampled surfaces have no COM owner. Only consume the full span of a retained title allocation + // and a layout the console texture computer can actually untile. + if (view.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE2D || raw.DepthOrArraySize != 1 || + raw.MipLevels != 1 || raw.SampleDesc.Count != 1 || (unsigned(raw.Flags) & 0x0f) || + raw.Width > ct::kMaxExtent || raw.Height > ct::kMaxExtent || + (view.Format != raw.Format && view.Format != DXGI_FORMAT_UNKNOWN)) return false; + const UINT mode = unsigned(raw.Layout); + if (mode != 0 && mode != 1 && (mode & ~255u) != 256u) return false; + const UINT swizzle = mode == 0 ? ct::kSw4kbS : mode == 1 ? ct::kLinear : mode & 255u; + ct::TextureDesc d{}; + d.width = static_cast(raw.Width); d.height = raw.Height; d.format = unsigned(raw.Format); + d.swizzle = swizzle; + const auto texture = ct::Texture::make(d); + if (!texture || texture->planes.size() != 1 || !texture->planes[0].layout.addressable()) return false; + const auto fmt = ct::format(d.format); + if (!fmt || fmt->stencil) return false; + const auto& level = texture->planes[0].layout; + const auto& mip = level.mips[0]; + const std::size_t row = std::size_t(mip.width) * fmt->bytes, bytes = row * mip.height; + std::uint64_t lo = 0, hi = 0; + if (!bytes || row > UINT_MAX || bytes > UINT_MAX || texture->size > SIZE_MAX || + !leonida::title_va_aliases().title_memory(address, lo, hi) || texture->size > hi - address) return false; + // Bound CPU and transfer scratch per upload. The full title surface can be hundreds of + // megabytes; the title already owns its source, and the copy on the GPU is the one sampled. + RawTileReader source(address,static_cast(texture->size)); + constexpr std::size_t stripe_bytes = 2 * 1024 * 1024; + const UINT max_rows = static_cast(std::min(mip.height, std::max(1,stripe_bytes/row))); + std::vector linear(row*max_rows); + std::vector columns; + if (swizzle != ct::kLinear) { + std::uint64_t origin{}; + if (level.offset(0,0,0,0,origin)!=ct::Error::ok) return false; + columns.resize(mip.width); + for (UINT x=0; x(state_, clean, heap, D3D12_HEAP_FLAG_NONE); + const Format backing = state_.texture_format(clean); + if (backing.format == VK_FORMAT_UNDEFINED || backing.typeless || FAILED(resource->create_texture(backing))) { + raw_images_.erase(key); + return false; + } + resource->set_raw_image_address(address); + cached.resource = std::move(resource); + } + const UINT stripes = (mip.height + max_rows - 1) / max_rows; + cached.fingerprints.resize(stripes); + for (UINT first=0, strip=0; firstbytes,fmt->bytes)) return false; + } + } + const std::span content(linear.data(),used); + const auto digest = leonida::sha256_hex(content); + if (cached.fingerprints[strip] == digest) continue; + const UINT bottom = std::min(raw.Height,(first+rows)*fmt->block); + const D3D12_BOX box{0,first*fmt->block,0,UINT(raw.Width),bottom,1}; + const HRESULT hr = cached.resource->WriteToSubresource(0,&box,linear.data(),UINT(row),UINT(used)); + if (FAILED(hr)) return false; + cached.fingerprints[strip] = digest; + } + CreateShaderResourceView(cached.resource.get(), &view, destination); + return true; + } + UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has @@ -6666,31 +7604,31 @@ public: std::fprintf(stderr, "[rt] d3d12: root signature not understood: %s\n", parsed.error.c_str()); return E_INVALIDARG; } - // Two layouts, one per bind point (RootArgumentLayout): graphics keeps pack(), compute takes the console - // layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. + // Select the graphics layout once. A stage layout that spills falls back to the default packing. const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); + RootArgumentLayout layout; + rt::rootsig::StagePackResult local_stage; + if (local_graphics_stage_layout()) { + local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); + layout.graphics_compact_tables = local_stage.ok; + static std::atomic said{0}; + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", + local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); + } const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); - if (!packed.ok && !compute.ok) { + layout.graphics_ok = layout.graphics_compact_tables || packed.ok; + layout.compute_ok = compute.ok; + layout.flags = parsed.sig.flags; + if (!layout.graphics_ok && !compute.ok) { std::fprintf(stderr, "[rt] d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), compute.error.c_str()); return E_INVALIDARG; } - if (!packed.ok) + if (!layout.graphics_ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); if (!compute.ok) std::fprintf(stderr, "[rt] d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); - RootArgumentLayout layout; - layout.flags = parsed.sig.flags; - layout.graphics_ok = packed.ok; - layout.compute_ok = compute.ok; - const rt::rootsig::StagePackResult local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); - const bool local_stage_layout = local_graphics_stage_layout() && local_stage.ok; - if (local_graphics_stage_layout()) { - static std::atomic said{0}; - if (said.fetch_add(1) < 3) - std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", - local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); - } for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) @@ -6698,10 +7636,10 @@ public: first = d; break; } - if (local_stage_layout) first = local_stage.first_sgpr[i]; + if (layout.graphics_compact_tables) first = local_stage.first_sgpr[i]; layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, - table_view_descriptors(parsed.sig.params[i])}); + table_descriptor_count(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( @@ -6908,6 +7846,8 @@ public: if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) view = {}; + } else if (r && rd.Format==DXGI_FORMAT_B4G4R4A4_UNORM && r->format()==VK_FORMAT_R8G8B8A8_UNORM) { + if(!desc || desc->Format==DXGI_FORMAT_UNKNOWN || desc->Format==rd.Format) view.format=leonida::ColorViewFormat::resource; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. @@ -7058,16 +7998,23 @@ public: // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination) override { + write_constant_buffer_view(desc,destination,false); + } + void write_constant_buffer_view(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE destination, + bool vector_rows) { d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; leonida::gfx10::Buffer buffer{}; buffer.address = desc->BufferLocation; - buffer.stride = 0; - buffer.num_records = desc->SizeInBytes; + const bool indexed = vector_rows && desc->SizeInBytes % 16 == 0; + // A vector ALU fetch selects a 16-byte constant register with IDXEN. Scalar SMEM + // still sees the very same byte extent, NUM_RECORDS * STRIDE. + buffer.stride = indexed ? 16u : 0u; + buffer.num_records = indexed ? desc->SizeInBytes / 16u : desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.oob_select = indexed ? leonida::gfx10::OobSelect::structured_with_offset : leonida::gfx10::OobSelect::raw; buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); @@ -7240,7 +8187,7 @@ public: return; } } - write_image_descriptor(*r, view, destination, false); + write_image_descriptor(*r, view, destination, ImageViewUse::sampled); } // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords @@ -7342,60 +8289,99 @@ public: if (!destination.ptr) return; std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); const Resource* r = Resource::from(resource); - if (!r) { + if (!r || !r->belongs_to(state_)) { if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); return; } + if (r->storage_image()) r = r->storage_image(); if (!r->image()) return write_buffer_uav(resource, counter, desc, destination); if (counter) { log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); return; } - if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { + const bool depth_uav = r->depth_stencil_uav(0) != nullptr; + if (!depth_uav && !(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", int(r->desc().Flags)); return; } TextureView view{}; view.mip_count = 1; + namespace g = leonida::gfx10; if (!desc) { - const bool array = r->desc().DepthOrArraySize > 1; - if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { - view.type = leonida::gfx10::ImageType::image_1d; - view.layer_count = 1; - } else if (array) - view.type = leonida::gfx10::ImageType::image_2d_array; + const auto& shape = r->desc(); + if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) + view.type = g::ImageType::image_3d; + else if (shape.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + view.type = shape.DepthOrArraySize > 1 ? g::ImageType::image_1d_array : g::ImageType::image_1d; + if (view.type == g::ImageType::image_1d) view.layer_count = 1; + } else if (shape.DepthOrArraySize > 1) + view.type = g::ImageType::image_2d_array; } else { view.format = desc->Format; switch (desc->ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: - view.type = leonida::gfx10::ImageType::image_1d; + view.type = g::ImageType::image_1d; view.first_mip = desc->Texture1D.MipSlice; view.layer_count = 1; break; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: + view.type = g::ImageType::image_1d_array; + view.first_mip = desc->Texture1DArray.MipSlice; + view.first_layer = desc->Texture1DArray.FirstArraySlice; + view.layer_count = desc->Texture1DArray.ArraySize; + break; case D3D12_UAV_DIMENSION_TEXTURE2D: view.first_mip = desc->Texture2D.MipSlice; view.layer_count = 1; view.plane = desc->Texture2D.PlaneSlice; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: - view.type = leonida::gfx10::ImageType::image_2d_array; + view.type = g::ImageType::image_2d_array; view.first_mip = desc->Texture2DArray.MipSlice; view.first_layer = desc->Texture2DArray.FirstArraySlice; view.layer_count = desc->Texture2DArray.ArraySize; view.plane = desc->Texture2DArray.PlaneSlice; break; + case D3D12_UAV_DIMENSION_TEXTURE3D: + view.type = g::ImageType::image_3d; + view.first_mip = desc->Texture3D.MipSlice; + view.first_layer = desc->Texture3D.FirstWSlice; + view.layer_count = desc->Texture3D.WSize; + break; default: log_once("unordered-access view dimension not supported:", desc->ViewDimension); return; } } + if (depth_uav) { + const UINT layers = r->desc().DepthOrArraySize; + if (!desc || !(desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || + (desc->ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2D && layers == 1)) || + view.first_mip || !view.layer_count || view.first_layer >= layers || + (view.layer_count != UINT_MAX && view.layer_count > layers - view.first_layer)) { + log_once("Xbox depth-stencil UAV requires a valid mip-zero 2D or array view; dimension", + desc ? int(desc->ViewDimension) : 0); + return; + } + const Resource* storage = r->depth_stencil_uav(view.plane); + const bool raw_narrow = storage && r->desc().Format == xbox_d16s8 && view.plane == 0 && + (view.format == DXGI_FORMAT_R16_UINT || + (storage->desc().Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM)); + if (!storage || (!raw_narrow && view.format != storage->desc().Format)) { + log_once("unsupported Xbox depth-stencil UAV plane or format; format", int(view.format)); + return; + } + view.plane = 0; // The chosen shadow is a single-plane colour image with the same array layers. + write_image_descriptor(*storage, view, destination, ImageViewUse::depth_stencil_uav); + return; + } // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); return; } - write_image_descriptor(*r, view, destination, true); + write_image_descriptor(*r, view, destination, ImageViewUse::storage); state_.context->note_shader_image(r->id()); } @@ -7646,15 +8632,23 @@ public: if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so // a real list is passed through; only buffers are refused. - const D3D12_RESOURCE_DESC base = resource_desc(*desc); + D3D12_RESOURCE_DESC base = resource_desc(*desc); if (const char* why = barrier_layout_refusal(base, layout)) { log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); return d3d12_trace::result(method, E_INVALIDARG); } + // The Xbox slot-127 bridge forwards the logical texture to Device10. Validate its layout above, + // then allocate the depth attachment and enable the typed storage planes before returning it. + std::optional storage_heap_flags; + if (xbox_depth_uav(base)) { + storage_heap_flags = heap_flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + heap_flags &= ~*storage_heap_flags; + base.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the // legacy CreateCommittedResource path. Buffers here start COMMON, as before. return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, - castable_count, castable, riid, out); + castable_count, castable, riid, out, storage_heap_flags); } // Device9. The creator ID only groups queues for tools; one creator is as good as another here. @@ -7797,7 +8791,7 @@ public: } HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, - void** out) { + void** out, const D3D12_CLEAR_VALUE* clear) { constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the @@ -7815,11 +8809,13 @@ public: // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); - HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, - 0, nullptr, riid, out); + const bool defer = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, clear, + 0, nullptr, riid, out, std::nullopt, defer); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out); + D3D12_RESOURCE_STATE_COMMON, clear, 0, nullptr, riid, out, std::nullopt, defer); if (SUCCEEDED(hr) && out && *out) { // The console answers the texture's GetGPUVirtualAddress with the title's address; without it a // title that clears the texture through that pointer writes at address 0 (XCL measured this on a @@ -7865,7 +8861,8 @@ public: int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); + D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out, + std::nullopt)); } return d3d12_trace::result(method, hand_out(resource, riid, out)); } @@ -8167,7 +9164,7 @@ public: : D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); offset = align(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); DXGI_FORMAT footprint_format = desc->Format; - if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : DXGI_FORMAT_R32_TYPELESS; + if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : (desc->Format==xbox_d16s8?DXGI_FORMAT_R16_TYPELESS:DXGI_FORMAT_R32_TYPELESS); const UINT slices = std::max(1u, depth >> (mip & 31)); if (layouts) layouts[i] = {base + offset, @@ -8497,6 +9494,9 @@ public: auto* info = static_cast(data); // Plane count describes the DXGI layout even when the backend cannot create the texture. switch (info->Format) { + case xbox_d16s8: + case xbox_d16_plane: + case xbox_s8_plane: case DXGI_FORMAT_R32G8X24_TYPELESS: case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: @@ -8534,7 +9534,7 @@ public: // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers). const UINT format_value = static_cast(fs->Format); - if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && + if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && !(format_value>=118 && format_value<=120) && (format_value < 189 || format_value > 191)) return d3d12_trace::result(method, E_FAIL); if (fs->Format == DXGI_FORMAT_UNKNOWN) { @@ -8545,14 +9545,15 @@ public: // R24G8/R32G8X24 and D24S8/D32S8 textures) have no image of their own, so the lookups below find nothing. // The host reports them as sampled 2D and cube textures with mips, the depth plane also filtered and // compared. Left out, as for the depth formats themselves: 1D, and multisample loads. - const bool depth_plane = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || + const bool depth_plane = fs->Format == xbox_d16_plane || fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - if (depth_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || + if (depth_plane || fs->Format == xbox_s8_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || fs->Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) { const bool d24 = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; VkFormat family = vulkan_format(d24 ? DXGI_FORMAT_D24_UNORM_S8_UINT : DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true).format; + if(fs->Format==xbox_d16_plane || fs->Format==xbox_s8_plane)family=state_.depth_backing(VK_FORMAT_D16_UNORM_S8_UINT); if (family == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(family)) family = VK_FORMAT_D32_SFLOAT_S8_UINT; VkFormatProperties props{}; @@ -8573,6 +9574,7 @@ public: // Report what creation makes: a D24 texture on a GPU without Vulkan D24 (AMD) is a D32_SFLOAT_S8_UINT // image (texture_format), so its features are D32S8's. Asking D24 itself gave Support1 = 0 there, // although CreateCommittedResource(ALLOW_DEPTH_STENCIL) succeeds. + vk_fmt=state_.depth_backing(vk_fmt); if (vk_fmt == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(vk_fmt)) vk_fmt = VK_FORMAT_D32_SFLOAT_S8_UINT; if (vk_fmt == VK_FORMAT_UNDEFINED || !state_.format_properties) { @@ -8652,7 +9654,7 @@ public: } if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; - // A D3D12 multisample resolve needs the same image usages as texture_create_info(): colour + // A D3D12 multisample resolve needs the same image usages as TextureCreateInfo: colour // attachment plus transfer source/destination (and the ordinary sampled usage). VkImageFormatProperties image_properties{}; const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | @@ -8670,6 +9672,8 @@ public: s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; } } + if(fs->Format==DXGI_FORMAT_B4G4R4A4_UNORM && !(optimal&VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) && + state_.color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM))s1|=D3D12_FORMAT_SUPPORT1_RENDER_TARGET; if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) { s1 |= D3D12_FORMAT_SUPPORT1_BLENDABLE; } @@ -8781,7 +9785,7 @@ public: // output untouched; a known format clears it before the sample count is checked. const UINT format_id = UINT(levels->Format); if (levels->Format == DXGI_FORMAT_R1_UNORM || - !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || + !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || (format_id>=118 && format_id<=120) || (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE && format_id <= DXGI_FORMAT_A4B4G4R4_UNORM))) return d3d12_trace::result(method, E_FAIL); @@ -8963,6 +9967,10 @@ private: return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; } + bool xbox_depth_uav(const D3D12_RESOURCE_DESC& desc) const { + return rt::d3d12_xs::depth_uav_description(desc) && rt::d3d12_xs::is_device_proxy(outer_); + } + // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and // saturates near 2^64 rather than wrapping. @@ -8972,7 +9980,13 @@ private: D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; bool failed = count && !descs; for (UINT i = 0; i < count; ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); + D3D12_RESOURCE_ALLOCATION_INFO one = kInvalidAllocation; + if (!failed) { + auto desc = get(i); + // The boot stack charges XMem for the guest placement; storage planes are private to Vulkan. + if (xbox_depth_uav(desc)) desc.Flags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + one = allocation(desc); + } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; @@ -8989,6 +10003,12 @@ private: // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { + if (xbox_depth_storage_desc(desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_)) { + const auto depth = allocation(depth_storage_part(desc, false)); + const auto colour = allocation(depth_storage_part(desc, true)); + if (depth.SizeInBytes == UINT64_MAX || colour.SizeInBytes == UINT64_MAX) return kInvalidAllocation; + return {std::max(depth.SizeInBytes, colour.SizeInBytes), std::max(depth.Alignment, colour.Alignment)}; + } constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, @@ -9138,18 +10158,87 @@ private: return std::min(fallback, align_up(total, alignment)); } + enum class ImageViewUse { sampled, storage, depth_stencil_uav }; + // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be // shown leaves the slot a null descriptor. void write_image_descriptor(const Resource& resource, const TextureView& view, - D3D12_CPU_DESCRIPTOR_HANDLE destination, bool storage) { - leonida::gfx10::Image image{}; - if (!image_descriptor(resource, view, image)) return; - const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), - resource.aspects(), storage, resource.has_view_format_list(), - resource.uint_backed()); - if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); - if (leonida::gfx10::multisampled(image.type) && !registered) return; + D3D12_CPU_DESCRIPTOR_HANDLE destination, ImageViewUse use) { + const bool storage = use != ImageViewUse::sampled; + const bool storage_plane = use == ImageViewUse::depth_stencil_uav; + namespace g = leonida::gfx10; + g::Image image{}; + VkFormat view_format{}; + DeviceState::VolumeSlices slices{}; + if (!image_descriptor(resource, view, storage, image, view_format, slices)) { + return; + } + const bool sampled = view.type != g::ImageType::image_1d_array && + !(resource.desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); + const bool new_uav = storage && (view.type == g::ImageType::image_3d || view.type == g::ImageType::image_1d || + view.type == g::ImageType::image_1d_array); + const bool packed_storage = storage && resource.desc().Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && resource.uint_backed(); + const VkFormat storage_format = storage && resource.uint_backed() ? resource.format() : view_format; + if (storage) { + if (!state_.storage_usable(storage_format)) { + log_once("texture view format does not support storage images:", storage_format); + return; + } + if (new_uav && state_.info.robust_image_access) { + if (sampled && !state_.sampled_usable(view_format)) { + log_once("texture view format does not support sampled access:", view_format); + return; + } + // All three dimensions use Unknown-format storage writes and can use Unknown-format reads + // (image_load glc, or any image_load on a 1D array). Check the actual storage view's format. + // Packed RGB9E5 only exposes formatted raw R32_UINT storage, so it does not need these bits. + if (!packed_storage) { + constexpr auto required = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT | + VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + if ((state_.optimal_features(storage_format) & required) != required) { + log_once("texture view format lacks the required formatless storage image access:", storage_format); + return; + } + } + } + } + if (slices.count && !(state_.info.sliced_3d_uav && state_.info.robust_image_access)) { + log_once("partial Texture3D UAV requires imageSlicedViewOf3D and robustImageAccess; mip", view.first_mip); + return; + } + g::ImageWords words = g::encode(image); + if (storage && view.type == g::ImageType::image_3d) { + words[4] |= g::volume_uav_flag; + const UINT mip_depth = std::max(1u, image.depth >> image.first_mip); + words[7] = g::volume_uav_word(slices.first, slices.count ? slices.count : mip_depth); + } + if (new_uav && packed_storage) { + words[4] |= g::volume_uav_flag; + if (view.type != g::ImageType::image_3d) words[7] = g::volume_uav_word(0, 1); + words[7] |= g::packed_uav_flag; + log_once("packed RGB9E5 UAV: translated storage operations are not implemented; type", int(view.type)); + } + const VkFormat channels_format = resource.rgba4_render_backing() ? VK_FORMAT_A4R4G4B4_UNORM_PACK16 : + (resource.rgb96() ? rgb96_named_format(view_format) : view_format); + if (new_uav && !state_.info.robust_image_access) { + log_once("shader access to 1D and 3D UAVs requires robustImageAccess; type", int(view.type)); + } else { + const bool known_heap = state_.known_view_heap(destination.ptr); + if (!storage && resource.deferrable_sample() && state_.info.prepare_on_bind && known_heap && + !g::multisampled(image.type)) { + state_.remember_sample(words,{const_cast(&resource),image,view_format,channels_format}); + std::memcpy(reinterpret_cast(destination.ptr),words.data(),sizeof(words)); + return; + } + const auto bound = const_cast(resource).bound_image(); + if (!bound) { log_once("unable to make a placed shader image resident; format", int(resource.desc().Format)); return; } + const bool registered = state_.bind_image(words, image, bound, view_format, + channels_format, storage_format, resource.aspects(), + sampled, storage, slices); + if (registered && (resource.sparse_image() || storage_plane)) state_.context->note_shader_image(resource.id()); + if (!registered && (g::multisampled(image.type) || storage_plane)) return; + } + // The CPU UAV used by ClearUnorderedAccessView is independent of set 0. std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -9158,10 +10247,29 @@ private: HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags = std::nullopt, + bool defer_placed_memory = false) { const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; if (out) *out = nullptr; if (!heap || !desc) return finish(E_INVALIDARG); + if (xbox_depth_storage_desc(*desc) && outer_ && rt::d3d12_xs::is_device_proxy(outer_) && + heap->Type == D3D12_HEAP_TYPE_DEFAULT && (!castable_count || !castable)) { + const auto depth_desc = depth_storage_part(*desc, false), colour_desc = depth_storage_part(*desc, true); + const bool initial_uav = state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + ID3D12Resource *depth = nullptr, *colour = nullptr; + HRESULT hr = create_committed_validated(nullptr, heap, heap_flags, &depth_desc, + initial_uav ? D3D12_RESOURCE_STATE_COMMON : state, clear, 0, nullptr, IID_PPV_ARGS(&depth)); + if (FAILED(hr)) return finish(hr); + hr = create_committed_validated(nullptr, heap, heap_flags, &colour_desc, + initial_uav ? state : D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, IID_PPV_ARGS(&colour)); + if (SUCCEEDED(hr)) { + Resource::from(depth)->adopt_depth_storage(Resource::from(colour)); + hr = out ? depth->QueryInterface(riid, out) : S_FALSE; + } + depth->Release(); + return finish(hr); + } if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, acceleration_structures(), state_.uma)) { log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") @@ -9180,7 +10288,8 @@ private: int(desc->Dimension)); return finish(E_INVALIDARG); } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, + storage_heap_flags, defer_placed_memory)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list @@ -9189,7 +10298,8 @@ private: // runtime. HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { + UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out, + std::optional storage_heap_flags, bool defer_placed_memory = false) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { @@ -9233,9 +10343,10 @@ private: hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); - if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats, storage_heap_flags.has_value()); + if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats, defer_placed_memory); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); + if (SUCCEEDED(hr) && storage_heap_flags) hr = resource->enable_depth_stencil_uav(*storage_heap_flags); } } if (FAILED(hr)) { @@ -9417,8 +10528,6 @@ private: const VkDevice dev = state_.info.device; const auto properties2 = reinterpret_cast( state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); - state_.format_properties2 = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceFormatProperties2")); const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); const auto transition = @@ -9471,7 +10580,18 @@ private: std::vector queue_users_; std::vector compute_users_; std::vector copy_users_; + std::mutex verified_program_mutex_; + std::unordered_set verified_programs_; + std::mutex native_pipeline_mutex_; + std::unordered_map> native_pipelines_; DeviceState state_; + struct RawImage { + std::unique_ptr resource; + std::vector fingerprints; + }; + std::mutex raw_image_mutex_; + using RawKey = std::tuple; + std::map raw_images_; std::atomic removed_{false}; OwnedRuntime owned_; IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device @@ -9496,14 +10616,39 @@ std::shared_ptr tile_heap(ID3D12Heap* heap, c return object ? object->tiles(context, image, memory_types) : nullptr; } +XboxDepthStorage xbox_depth_storage(ID3D12Resource* resource) { + if (!resource || !depth_storage_count.load(std::memory_order_acquire)) return {}; + std::lock_guard lock(depth_storage_mutex); + const auto it = depth_storage_images.find(resource); + return it == depth_storage_images.end() ? XboxDepthStorage{} : it->second; +} + bool is_sparse_image(ID3D12Resource* resource) { const auto* object = Resource::from(resource); return object && object->sparse_image(); } +static HRESULT enable_depth_stencil_uav(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags) { + Resource* r = Resource::from(resource); + return r ? r->enable_depth_stencil_uav(storage_heap_flags) : E_INVALIDARG; +} + +leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t address) { + const Resource* r = Resource::from(resource); + if (!r || !r->depth_stencil_uav(0)) return resource_id(resource); + for (UINT plane = 0; plane < 2; ++plane) { + const Resource* storage = r->depth_stencil_uav(plane); + if (storage && storage->image_address() == address) return storage->id(); + } + return 0; +} + void set_device_outer(ID3D12Device* device, IUnknown* outer) { Device* d = Device::from(device); if (!d) return; + const auto& label_info=d->state().info; + leonida::label::completions().initialize(label_info.device,reinterpret_cast(label_info.get_instance_proc(label_info.instance,"vkGetDeviceProcAddr"))); + // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked // for IDXGIDevice1: the device's outer identity is the proxy itself either way. if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); @@ -9521,6 +10666,48 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; + rt::d3d12_xs::set_constant_view_provider(outer, [](ID3D12Device* real, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE target) { + auto* device=Device::from(real); + if (!device) return false; + device->write_constant_buffer_view(desc,target,true); + return true; + }); + rt::d3d12_xs::set_raw_texture_view_provider(outer, [](ID3D12Device* real, const D3D12_RESOURCE_DESC& desc, + const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t va, D3D12_CPU_DESCRIPTOR_HANDLE out) { + auto* device = Device::from(real); + try { + return device && device->raw_texture_view(desc, view, va, out); + } catch (const std::bad_alloc&) { + return false; + } + }); + rt::d3d12_xs::set_texture_lease_provider(outer, [](IUnknown* object, void* data, std::size_t bytes, UINT layout) { + if (auto* resource = Resource::from(object)) resource->use_texture_lease(data, bytes, layout); + }); + rt::d3d12_xs::set_descriptor_mapping_provider(outer, [](ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes) { + const auto* object = DescriptorHeap::from(heap); + return object && object->owns_mapped_span(start, bytes); + }); + if(d->state().info.prepare_on_bind) { + rt::d3d12_xs::set_native_stream_factory(outer,[](ID3D12Device* real,const D3D12_PIPELINE_STATE_STREAM_DESC& desc,REFIID iid,void** out,std::unique_ptr record){ + return Device::from(real)->prepare_console_stream(desc,iid,out,std::move(record)); + }); + } + rt::d3d12_xs::set_device_native_graphics_factory(outer, [](ID3D12Device* real, const leonida::native_pso::GraphicsDesc& desc, + REFIID iid, void** out) { + return Device::from(real)->create_native_graphics(desc, iid, out); + }); + rt::d3d12_xs::set_depth_stencil_uav_provider(outer, &enable_depth_stencil_uav, + [](const D3D12_RESOURCE_DESC& native, std::uint32_t layout, const D3D12_CLEAR_VALUE* clear) { + auto logical = native; + logical.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if (barrier_layout_refusal(logical, static_cast(layout))) return false; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + return !committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, + clear, false, false); + }); rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { IDXGIFactory1* factory = nullptr; HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); @@ -9541,13 +10728,13 @@ const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) } std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->compute() ? p->id() : 0; + auto* p=PipelineState::from(pipeline); + return p && p->resolve_type(false) ? p->id() : 0; } std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->graphics() ? p->id() : 0; + auto* p=PipelineState::from(pipeline); + return p && p->resolve_type(true) ? p->id() : 0; } const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { @@ -9568,7 +10755,7 @@ IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP VkImage vulkan_image(ID3D12Resource* resource) { const Resource* r = Resource::from(resource); - return r ? r->image() : VK_NULL_HANDLE; + return r ? const_cast(r)->bound_image() : VK_NULL_HANDLE; } VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { @@ -9589,13 +10776,13 @@ const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { } HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out) { + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear) { if (out) *out = nullptr; if (!device || !out) return E_POINTER; ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); auto* d = Device::from(real ? real : device); if (!d) return E_NOTIMPL; - return d->create_at_host_address(address, desc, layout, riid, out); + return d->create_at_host_address(address, desc, layout, riid, out, clear); } bool device_supports_ray_tracing(ID3D12Device* device) { @@ -10234,10 +11421,24 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, v13.compute_full_subgroups, info.subgroup); + const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); + const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; + v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; + info.cold_graphics_compile = v13.enable_pipeline_cache_control; + info.prepare_on_bind = mode == "on-demand"; + info.first_use_backend_pipelines = info.prepare_on_bind || mode == "first-use"; + void* v13_chain = v13.enable(ext_chain); + // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. + if (v13.core) { + VkPhysicalDeviceVulkan13Features supported{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.robust_image_access = supported.robustImageAccess == VK_TRUE; + static_cast(v13_chain)->robustImageAccess = supported.robustImageAccess; + } // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, - v13.enable(ext_chain)}; + VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_chain}; enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; if (!chosen_draw_params) std::fprintf(stderr, "[rt] d3d12: the GPU has no shaderDrawParameters\n"); VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; @@ -10406,12 +11607,25 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin std::fprintf(stderr, "[rt] d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); } - // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and - // the two after it). Each is queried, and enabled with its feature where the GPU has it. const auto has_device_extension = [&](const char* name) { return std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); }; + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (info.robust_image_access && has_device_extension(sliced_name)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (info.sliced_3d_uav) { + sliced.pNext = *v13.next(); + *v13.next() = &sliced; + } + } + + // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and + // the two after it). Each is queried, and enabled with its feature where the GPU has it. VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { @@ -10470,6 +11684,19 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + VkPhysicalDeviceMaintenance10FeaturesKHR maintenance10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + // Vulkan 1.3 makes the 64-bit optimal tiling format features used by this path core. + if (v13.core && has_device_extension(VK_KHR_MAINTENANCE_10_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance10}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + info.maintenance10 = maintenance10.maintenance10 == VK_TRUE; + if (info.maintenance10) { + maintenance10.pNext = *v13.next(); + *v13.next() = &maintenance10; + } + } +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature @@ -10508,16 +11735,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.depthClamp = chosen_features.depthClamp; enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of - // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores - // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples - // (MinLod), and the layer or viewport a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has - // them; without one, vkCreateShaderModule reports the capability (VUID-...-pCode-08740). + // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, formatless image + // reads and writes, gather offsets (ImageGatherExtended), LOD-clamped samples (MinLod), and the layer or viewport + // a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has them; without one, vkCreateShaderModule + // reports the capability (VUID-...-pCode-08740). enable.shaderInt64 = chosen_features.shaderInt64; enable.shaderFloat64 = chosen_features.shaderFloat64; enable.shaderInt16 = chosen_features.shaderInt16; enable.shaderClipDistance = chosen_features.shaderClipDistance; enable.shaderCullDistance = chosen_features.shaderCullDistance; enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; + enable.shaderStorageImageExtendedFormats = chosen_features.shaderStorageImageExtendedFormats; enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; @@ -10614,6 +11842,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (info.conditional_rendering) device_extensions.push_back(conditional_extension); if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); + if (info.sliced_3d_uav) device_extensions.push_back(sliced_name); if (info.fragment_shader_barycentric) device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); @@ -10623,6 +11852,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME if (info.a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif +#ifdef VK_KHR_MAINTENANCE_10_EXTENSION_NAME + if (info.maintenance10) device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 9bfa5ea7f..02a03b07b 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -27,7 +27,13 @@ #include "../src/title_va_alias.h" #include "title_window.h" #include "d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "present_window.h" +#endif +#include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" +#include "../src/native_pso.h" +#include "d3d12_xs_pso_stream.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" #include "../src/frame_pacer.h" @@ -67,8 +73,7 @@ namespace rt::d3d12_xs { namespace { -// The retail title calls device slots well past ID3D12Device14 (slot 133 at least); every slot past the PC device's -// vtable goes through the generic thunk and is refused with E_NOTIMPL, so the table must outlast the highest one. +// The retail title calls beyond ID3D12Device14. Cover the measured slots and refuse unknown ones in the thunk. constexpr unsigned kMaxSlots = 192; static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail title calls (up to 133)"); static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); @@ -99,7 +104,16 @@ struct DeviceProxy { // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; + DescriptorMappingProvider descriptor_mapping = nullptr; + NativeGraphicsFactory native_graphics = nullptr; + NativeStreamFactory prepare_stream = nullptr; + TextureLeaseProvider texture_lease_provider = nullptr; + RawTextureViewProvider raw_texture_view = nullptr; + ConsoleConstantView constant_view = nullptr; ResourceByVaProvider resource_provider; // slot 70: a buffer by console VA; null leaves slot 70 on the null view + DepthStencilUavProvider depth_stencil_uav_provider = nullptr; + ValidateDepthPlacement validate_depth_placement = nullptr; + PlacedDepthTextures placed_depth_textures; std::atomic gpu_thread_priority; std::atomic max_frame_latency; // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; @@ -108,6 +122,8 @@ struct DeviceProxy { std::atomic frame_interval_us{0}; std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; + std::atomic frame_event_offset_us{0}; + std::mutex presentation_mutex; std::shared_ptr frame_tokens = std::make_shared(); }; @@ -135,6 +151,8 @@ struct DescriptorRange { SIZE_T custom_start; SIZE_T custom_end; // exclusive SIZE_T real_start; + SIZE_T stride; + bool mapped; const DeviceProxy* device; const HeapProxy* heap; }; @@ -162,12 +180,13 @@ DescriptorHeapBackingFree g_heap_free = nullptr; bool g_heap_alloc_explicit = false; bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, SIZE_T custom_start, - SIZE_T byte_size, SIZE_T real_start) { + SIZE_T byte_size, SIZE_T real_start, SIZE_T stride) { if (custom_start == 0 || byte_size == 0 || custom_start > (std::numeric_limits::max)() - byte_size) return false; + const bool mapped = device->descriptor_mapping && device->descriptor_mapping(heap->real, real_start, byte_size); try { std::lock_guard lock(descriptor_range_mutex()); - descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); + descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, stride, mapped, device, heap}); g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); return true; } catch (const std::bad_alloc&) { @@ -236,17 +255,58 @@ bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { if (!local_desc_mirror() || !custom.ptr || !count) return; - const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); - if (real.ptr == custom.ptr) return; - if (!local_accessible(real.ptr, count * kLocalDescriptorBytes, false) || - !local_accessible(custom.ptr, count * kLocalDescriptorBytes, true)) + if (!g_custom_range_count.load(std::memory_order_acquire)) return; + std::lock_guard lock(descriptor_range_mutex()); + const auto& ranges = descriptor_ranges(); + for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) { + if (it->device != device || custom.ptr < it->custom_start || custom.ptr >= it->custom_end) continue; + const SIZE_T offset = custom.ptr - it->custom_start; + if (!it->stride || offset % it->stride || count > (it->custom_end - custom.ptr) / it->stride) return; + const SIZE_T bytes = count * it->stride; + if (offset > (std::numeric_limits::max)() - it->real_start) return; + const SIZE_T real = it->real_start + offset; + // On Wine, VirtualQuery can report a live vkMapMemory span as MEM_FREE. + if (real == custom.ptr || (!it->mapped && !local_accessible(real, bytes, false)) || + !local_accessible(custom.ptr, bytes, true)) return; + std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real), bytes); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " + "title's address\n"); return; - std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), - count * kLocalDescriptorBytes); - static std::atomic said{false}; - if (!said.exchange(true)) - std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " - "title's address\n"); + } +} + +// Caller holds descriptor_range_mutex, keeping the backing alive for the complete copy. +std::uint64_t copy_title_slots(std::uint8_t* dest, SIZE_T source, SIZE_T bytes) { + const SIZE_T slots = bytes / kLocalDescriptorBytes; + if (!local_accessible(source, bytes, false)) return 0; + std::uint64_t copied = 0; + for (SIZE_T i = 0; i < slots; ++i) { + const SIZE_T at = i * kLocalDescriptorBytes; + const auto* from = reinterpret_cast(source + at); + if (!(from[0] | from[1] | from[2] | from[3])) continue; // keep slots populated only in the real heap + std::memcpy(dest + at, from, kLocalDescriptorBytes); + ++copied; + } + return copied; +} + +// The queue already bounds this scan by the root signature and real heap. Resolve the CPU address again at +// submission so a list can be recorded once and see successive writes to its title-backed descriptors. +std::uint64_t pull_title_descriptors(void*, std::uint8_t* real, std::size_t bytes) { + if (!local_desc_mirror() || !bytes || !g_custom_range_count.load(std::memory_order_acquire)) return 0; + const auto addr = reinterpret_cast(real); + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + const SIZE_T size = range.custom_end - range.custom_start; + if (addr < range.real_start || addr - range.real_start >= size) continue; + const SIZE_T offset = addr - range.real_start; + if (offset % kLocalDescriptorBytes) return 0; + // real is the queue's live vkMapMemory destination. Wine can report it as free to VirtualQuery. + return copy_title_slots(real, range.custom_start + offset, std::min(bytes, size - offset)); + } + return 0; } D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap); @@ -261,17 +321,10 @@ void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); - if (!local_accessible(range.custom_start + offset, slots * kLocalDescriptorBytes, false) || - !local_accessible(range.real_start + offset, slots * kLocalDescriptorBytes, true)) - return; - std::uint64_t copied = 0; - for (std::uint64_t i = 0; i < slots; ++i) { - const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); - if (!(from[0] | from[1] | from[2] | from[3])) continue; // nothing the title wrote: keep the real slot - std::memcpy(reinterpret_cast(range.real_start + offset + i * kLocalDescriptorBytes), from, - kLocalDescriptorBytes); - ++copied; - } + const SIZE_T copy_bytes = slots * kLocalDescriptorBytes; + if (!local_accessible(range.real_start + offset, copy_bytes, true)) return; + const auto copied = copy_title_slots(reinterpret_cast(range.real_start + offset), + range.custom_start + offset, copy_bytes); static std::atomic said{0}; if (said.fetch_add(1) < 4) std::fprintf(stderr, "[rt] d3d12_xs: local: table at heap offset 0x%llx: %llu of %llu slots taken from the " @@ -350,6 +403,7 @@ const char* slot_name(unsigned slot) { case 48: return "Xbox CreateCommandQueueX (32-byte desc) -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; case 56: return "GetResourceAllocationInfo1 (C or PC form)"; + case 57: return "Xbox native graphics pipeline / PC lifetime tracker"; case 61: return "Xbox CreateSamplerX -> PC CreateSampler"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; @@ -828,7 +882,7 @@ void** get_heap_vtable() { HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out, SIZE_T custom_cpu_start = 0, SIZE_T custom_byte_size = 0, SIZE_T real_cpu_start = 0, - DescriptorHeapBackingFree custom_free = nullptr) { + DescriptorHeapBackingFree custom_free = nullptr, SIZE_T stride = 0) { if (!real || !device) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -847,7 +901,7 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII proxy_add_ref(device); // the heap keeps its Xbox-ABI device alive for GetDevice if (custom_cpu_start != 0 && - !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start)) { + !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start, stride)) { delete proxy; proxy_release(device); return E_OUTOFMEMORY; @@ -1388,9 +1442,7 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { #ifdef LEONIDA_VULKAN_DEVICE struct PresentState { - ~PresentState() { - if (window) DestroyWindow(window); // the presentation and its window die with the device proxy - } + rt::d3d12_xs::PresentWindow owner; HWND window = nullptr; std::unique_ptr xbox; bool tried = false; // creation is attempted once; a null xbox means this device cannot present @@ -1400,29 +1452,16 @@ void destroy_present_state(void* present_state) { delete static_cast(present_state); } -LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { - return DefWindowProcW(window, message, wparam, lparam); -} - // Lazily builds the window, presenter and XboxPresentation a console PresentX needs, once per device. Returns the // state even when `xbox` stays null (no presentation support): the failure is logged once, not retried. PresentState* present_state_for(DeviceProxy* device) { + std::lock_guard lock(device->presentation_mutex); if (auto* state = static_cast(device->present_state)) return state; auto* state = new (std::nothrow) PresentState; if (!state) return nullptr; device->present_state = state; state->tried = true; - WNDCLASSW window_class{}; - window_class.lpfnWndProc = present_window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaPresentX"; - if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { - std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); - return state; - } - state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, - window_class.hInstance, nullptr); + state->window = state->owner.create(); if (!state->window) { std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); return state; @@ -1440,7 +1479,7 @@ PresentState* present_state_for(DeviceProxy* device) { } } else { target = state->window; - ShowWindow(target, SW_SHOWNOACTIVATE); + ShowWindowAsync(target, SW_SHOWNOACTIVATE); } auto presenter = rt::d3d12::create_window_presenter(device->real, target); if (!presenter) { @@ -1449,9 +1488,29 @@ PresentState* present_state_for(DeviceProxy* device) { } // The device's token source: the title takes its frame tokens from device slot 80 (#7685). state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + // The title registers its interval and origin event before the first PresentX builds this. + if (const std::uint32_t interval = device->frame_interval_us.load(std::memory_order_relaxed); interval && std::getenv("LEONIDA_FRAME_PACING")) { + const HRESULT set = state->xbox->SetFrameIntervalX(nullptr, interval, + device->frame_latency.load(std::memory_order_relaxed), 0); + const HRESULT armed = device->frame_event_scheduled.load(std::memory_order_relaxed) + ? state->xbox->ScheduleFrameEventX( + rt::d3d12::xbox_frame_event_origin, + device->frame_event_offset_us.load(std::memory_order_relaxed), 0) + : S_FALSE; + std::fprintf(stderr, "[rt] d3d12_xs: frame interval %u us replayed (0x%08lx), origin event (0x%08lx)\n", + interval, static_cast(set), static_cast(armed)); + } std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); return state; } +rt::d3d12::XboxPresentation* device_presentation(DeviceProxy* device) { + static const bool enabled=[] {const auto* p=std::getenv("LEONIDA_FRAME_PACING");return p && *p=='1';}(); + if(!enabled)return nullptr; + std::lock_guard lock(device->presentation_mutex); + const auto* state=static_cast(device->present_state); + return state ? state->xbox.get() : nullptr; +} + std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, std::uint64_t params) { @@ -2118,6 +2177,18 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t note_list_slot(Slot, a1, a2, a3, a4, self->device->console_layout.load(std::memory_order_relaxed)); constexpr unsigned pc = console_to_pc_list_slot(Slot); if constexpr (pc == kListNotForwarded) { +#ifdef LEONIDA_VULKAN_DEVICE + if constexpr (Slot == 71 || Slot == 72) { + if (leonida::label::enabled()) { + const unsigned width = Slot == 71 ? 4u : 8u; + const unsigned clock = Slot == 72 ? ((a4 & 1) ? 1u : ((a4 & 2) ? 2u : 0u)) : 0u; + auto target = leonida::label::memory().capture(a1, width); + if (target.owner.lock()) + rt::d3d12::record_gpu_label(reinterpret_cast(self->real), + {std::move(target), a2, clock}); + } + } +#endif if constexpr (Slot == kConsoleAllocateUpload) { return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk } @@ -2414,20 +2485,26 @@ HRESULT proxy_create_command_queue_xbox(DeviceProxy* self, const std::uint32_t* // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, std::uint64_t latency, std::uint64_t flags) { - (void)output; - (void)flags; self->frame_interval_us.store(static_cast(interval_us), std::memory_order_relaxed); self->frame_latency.store(static_cast(latency ? latency : 1), std::memory_order_relaxed); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->SetFrameIntervalX(reinterpret_cast(output), static_cast(interval_us), + static_cast(latency), static_cast(flags)); +#endif return S_OK; } // Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, std::uint64_t flags) { - (void)event; - (void)offset_us; - (void)flags; + self->frame_event_offset_us.store(static_cast(offset_us), std::memory_order_relaxed); self->frame_event_scheduled.store(true, std::memory_order_relaxed); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->ScheduleFrameEventX(static_cast(event), static_cast(offset_us), + static_cast(flags)); +#endif return S_OK; } @@ -2436,12 +2513,14 @@ HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std // a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter. HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, std::uint64_t flags, std::uint64_t token_word) { - (void)event; - (void)timeout_ms; - (void)flags; auto* token = reinterpret_cast(token_word); if (!token) return E_POINTER; - *token = self->frame_tokens->issue(); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) + return presentation->WaitFrameEventX(static_cast(event), static_cast(timeout_ms), + static_cast(flags), token); +#endif + *token=self->frame_tokens->issue(); return S_OK; } @@ -2501,6 +2580,44 @@ struct RawSrvShape { D3D12_GPU_VIRTUAL_ADDRESS va; }; +static bool readable_range(const void* ptr, std::size_t bytes) { + if (!ptr || !bytes) return false; + const auto* p = static_cast(ptr); + std::size_t remaining = bytes; + while (remaining) { + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return false; + const DWORD protect = mbi.Protect & 0xffu; + if (protect == PAGE_NOACCESS || (mbi.Protect & PAGE_GUARD) || protect == PAGE_EXECUTE) return false; + const auto base = reinterpret_cast(mbi.BaseAddress); + const auto addr = reinterpret_cast(p); + const std::size_t avail = static_cast(base + mbi.RegionSize - addr); + if (avail >= remaining) return true; + remaining -= avail; + p += avail; + } + return true; +} + +HRESULT proxy_create_native_graphics(DeviceProxy* self, const void* raw, REFIID riid, void** out) { + namespace np = leonida::native_pso; + if (!out) return E_POINTER; + *out = nullptr; + if (!self->native_graphics) return E_NOTIMPL; + if (!readable_range(raw, sizeof(np::GraphicsDesc))) return E_INVALIDARG; + np::GraphicsDesc desc{}; + std::memcpy(&desc, raw, sizeof(desc)); + const auto readable_pair = [](const np::Pair& pair) { + const auto state = np::pair_state(pair); + return state == np::PairState::absent || + (state == np::PairState::present && readable_range(pair.data, static_cast(pair.size))); + }; + if (!readable_pair(desc.state_b)) return E_INVALIDARG; + for (const auto& stage : desc.stages) + if (!readable_pair(stage.records)) return E_INVALIDARG; + return self->native_graphics(self->real, desc, riid, out); +} + bool readable(std::uint64_t address, std::size_t bytes) { MEMORY_BASIC_INFORMATION info{}; if (!address || !VirtualQuery(reinterpret_cast(address), &info, sizeof(info))) return false; @@ -2553,10 +2670,16 @@ void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } } local_write_back{self, destination}; // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. - destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; + const D3D12_CPU_DESCRIPTOR_HANDLE title_slot{static_cast(destination)}; + destination = translate_cpu_handle(self, title_slot).ptr; RawSrvShape shape{}; const char* why = parse_raw_srv(texture_words, view_desc, shape); + if (shape.resource.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && self->raw_texture_view && shape.va && + self->raw_texture_view(self->real, shape.resource, shape.view, shape.va, {static_cast(destination)})) { + local_write_through(self, title_slot, 1); + return; + } if (why || !self->resource_provider) { log_slot70_null_once(why ? why : "no resource provider", texture_words, view_desc); write_null_srv(self, destination); @@ -2746,6 +2869,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H SIZE_T custom_cpu_start = 0; SIZE_T custom_byte_size = 0; SIZE_T real_cpu_start = 0; + SIZE_T stride = 0; DescriptorHeapBackingAlloc alloc_fn = nullptr; DescriptorHeapBackingFree free_fn = nullptr; { @@ -2763,6 +2887,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H if (addr <= (std::numeric_limits::max)() - byte_size) { custom_cpu_start = addr; custom_byte_size = byte_size; + stride = inc; real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; } else if (free_fn) { free_fn(backing, kXmemDescriptorHeapAttributes); @@ -2772,7 +2897,7 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H } hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, - custom_cpu_start ? free_fn : nullptr); + custom_cpu_start ? free_fn : nullptr, stride); if (FAILED(hr)) { heap->Release(); if (custom_cpu_start && free_fn) @@ -2787,7 +2912,9 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(17); - self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); + const auto target = translate_cpu_handle(self,dest); + if (!self->constant_view || !self->constant_view(self->real,desc,target)) + self->real->CreateConstantBufferView(desc,target); local_write_through(self, dest, 1); } @@ -3104,7 +3231,7 @@ private: // `created` is the object a slot 76/127 creation returned (any interface of the resource). Nothing happens without // installed hooks, for a size the PC device refuses, or when the hooks return null; creation never fails here. -void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc) { +void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc, UINT layout) { if (!created) return; DescriptorHeapBackingAlloc alloc_fn = nullptr; DescriptorHeapBackingFree free_fn = nullptr; @@ -3128,7 +3255,9 @@ void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_R free_fn(memory, kXmemCommittedResourceAttributes); return; } - object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); // the resource's reference + const HRESULT kept = object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); + if (SUCCEEDED(kept) && self->texture_lease_provider && clean_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + self->texture_lease_provider(static_cast(created), memory, static_cast(size), layout); object->Release(); lease->Release(); // ours; from here the resource's reference is the only one static std::atomic logged{false}; @@ -3139,6 +3268,53 @@ void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_R static_cast(size)); } +bool supports_depth_uav(const DeviceProxy* self, const D3D12_RESOURCE_DESC& desc) { + return self->depth_stencil_uav_provider && depth_uav_description(desc); +} + +D3D12_RESOURCE_DESC depth_image_desc(D3D12_RESOURCE_DESC desc) { + // Keep desktop resource flags up to RTAS and USE_TIGHT_ALIGNMENT. Xbox stores additional flags above them. + desc.Flags = static_cast((UINT(desc.Flags) & 0x5ffu) & + ~UINT(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return desc; +} + +D3D12_RESOURCE_STATES depth_image_state(D3D12_RESOURCE_STATES requested) { + return requested == D3D12_RESOURCE_STATE_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_COMMON : requested; +} + +HRESULT create_depth_uav_backing(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS flags, + const D3D12_RESOURCE_DESC& native, D3D12_RESOURCE_STATES initial, + const D3D12_CLEAR_VALUE* clear, ID3D12Resource** out) { + // The logical Xbox texture has a UAV. Its writable planes take ALLOW_SHADER_ATOMICS, which the PC + // rejects on the depth-only attachment. Upload/readback heaps cannot hold a UAV on either API. + if (props && (props->Type == D3D12_HEAP_TYPE_UPLOAD || props->Type == D3D12_HEAP_TYPE_READBACK)) + return E_INVALIDARG; + const auto storage_flags = flags & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; + HRESULT hr = self->real->CreateCommittedResource(props, flags & ~storage_flags, &native, initial, clear, + IID_PPV_ARGS(out)); + if (FAILED(hr)) return hr; + hr = self->depth_stencil_uav_provider(*out, storage_flags); + if (FAILED(hr)) { + (*out)->Release(); + *out = nullptr; + } + return hr; +} + +HRESULT proxy_create_placed_depth(DeviceProxy* self, UINT64 address, const D3D12_RESOURCE_DESC& desc, + std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) { + const auto native = depth_image_desc(desc); + if (!self->validate_depth_placement(native, layout, clear)) return E_INVALIDARG; + const auto alloc = self->real->GetResourceAllocationInfo(0, 1, &native); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + return self->placed_depth_textures.create(address, native, alloc, clear, desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN, riid, out, [&](ID3D12Resource** backing) { + return create_depth_uav_backing(self, &heap, D3D12_HEAP_FLAG_NONE, native, D3D12_RESOURCE_STATE_COMMON, + clear, backing); + }); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -3167,9 +3343,19 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } + if (supports_depth_uav(self, *xbox_desc)) { + ID3D12Resource* resource = nullptr; + HRESULT hr = create_depth_uav_backing(self, heap_properties, heap_flags, depth_image_desc(pc_desc), + depth_image_state(initial_state), clear_value, &resource); + if (FAILED(hr)) return hr; + hr = resource->QueryInterface(*riid, out); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc, unsigned(xbox_desc->Layout)); + resource->Release(); + return hr; + } const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, *riid, out); - if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc, unsigned(xbox_desc->Layout)); return hr; } @@ -3261,7 +3447,7 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap plain.SampleDesc = pc_desc.SampleDesc; plain.Layout = pc_desc.Layout; plain.Flags = pc_desc.Flags; - lease_title_resource_memory(self, *out, plain); + lease_title_resource_memory(self, *out, plain, xbox_layout); } return hr; } @@ -3404,14 +3590,85 @@ std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) } // Xbox slot 86: CreatePipelineState(desc, riid, out), forwarded to PC ID3D12Device2::CreatePipelineState (PC slot 47). +void keep_pso_stream(IUnknown* pso, const D3D12_PIPELINE_STATE_STREAM_DESC& desc) { + ID3D12Object* object = nullptr; + if (FAILED(pso->QueryInterface(__uuidof(ID3D12Object), reinterpret_cast(&object))) || !object) return; + auto record = PsoStreamRecord::capture(desc); + static std::atomic logged{false}; + if (!record || !attach_pso_record(object, std::move(record))) { + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: a pipeline state stream is not kept for derivation (unmodelled subobject or allocation failure); slot 55 refuses that PSO as a base\n"); + } + object->Release(); +} + +// The PC CreatePipelineState (PC slot 47) that slots 86 and 55 share: on success the stream is kept on the PSO. +HRESULT create_pso_from_stream(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, + void** out, std::unique_ptr derived = {}) { + if (!riid) return E_POINTER; + if(self->prepare_stream && desc && out && IsEqualIID(*riid,__uuidof(ID3D12PipelineState))) + return self->prepare_stream(self->real,*desc,*riid,out,std::move(derived)); + + // Through the queried ID3D12Device2 (#8517): supporting an interface does not make its pointer or vtable the + // base device's. + ID3D12Device2* device2 = nullptr; + const HRESULT query = self->real->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast(&device2)); + if (FAILED(query) || !device2) return FAILED(query) ? query : E_NOINTERFACE; + const HRESULT hr = device2->CreatePipelineState(desc, *riid, out); + device2->Release(); + if (SUCCEEDED(hr) && out && *out && desc) { + if (!derived) { + keep_pso_stream(static_cast(*out), *desc); + } else { + auto* pipeline = static_cast(*out); + if (!attach_pso_record(pipeline, std::move(derived))) { + pipeline->Release(); + *out = nullptr; + return E_OUTOFMEMORY; + } + } + } + return hr; +} + HRESULT proxy_create_pipeline_state(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, void** out) { note_slot(86); if (out) *out = nullptr; if (self->slot_count <= 47) return refuse_beyond_device(86, self->slot_count); // predates ID3D12Device2 - if (!riid) return E_POINTER; - using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); - return reinterpret_cast(self->real_vtable[47])(self->real, desc, riid, out); + return create_pso_from_stream(self,desc,riid,out); +} + +HRESULT refuse_derived(unsigned reason, const char* why, HRESULT hr) { + static std::atomic logged[4]{}; + if (!logged[reason].exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: derived pipeline state (device slot 55) refused: %s\n", why); + return hr; +} + +// Xbox slot 55: CreateDerivedPipelineState(pBasePSO, n, pRecords, riid, ppv). The base must be a PSO that slot 86 or +// slot 55 created with a kept stream; n is 1..4 records of 0x14c bytes (d3d12_xs_pso_stream.h). The patched stream +// goes through the slot 86 path. Every refusal leaves *ppv null and returns a failure, never a fake success. +HRESULT proxy_create_derived_pso(DeviceProxy* self, ID3D12PipelineState* base, std::uint32_t count, + const unsigned char* records, const IID* riid, void** out) { + note_slot(55); + if (out) *out = nullptr; + if (self->slot_count <= 47) return refuse_beyond_device(55, self->slot_count); // predates ID3D12Device2 + if (!out || !riid || !records) return E_POINTER; + if (!count || count>kDerivedMaxRecords) return E_INVALIDARG; + if (!readable_range(records, std::size_t(count)*kDerivedRecordSize)) return E_INVALIDARG; + const PsoStreamRecord* base_record = base ? find_pso_record(base) : nullptr; + if (!base_record) return refuse_derived(0, "base PSO has no kept stream", E_FAIL); + std::vector patched; + switch (derive_stream(*base_record, records, count, patched)) { + case DeriveStatus::ok: break; + case DeriveStatus::unknown_tag: return refuse_derived(1, "record tag not known", E_INVALIDARG); + case DeriveStatus::missing_state: return refuse_derived(2, "base has no subobject for a record", E_INVALIDARG); + case DeriveStatus::malformed: return refuse_derived(3, "record count or base stream malformed", E_INVALIDARG); + } + auto record = PsoStreamRecord::derived(*base_record, std::move(patched)); + const auto desc = record->desc(); + return create_pso_from_stream(self, &desc, riid, out, std::move(record)); } // Xbox slot 101: CreateStateObject(desc, riid, out), forwarded to PC ID3D12Device5::CreateStateObject (PC slot 62, @@ -3491,25 +3748,27 @@ std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64 return reinterpret_cast(ret); } -// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail +// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, layout, clear, riid, out), measured on the retail // executable (docs/retail_boot_chain.md, section 3.4). `va` is the start of a physical-page range the title has just -// mapped, `desc` a 56-byte description with Xbox bits above the PC resource flags and an Xbox layout word, and -// `state` is 0xFFFFFFFF, which is no PC state. The resource is a buffer on those pages, made by the handler the -// device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made -// ROW_MAJOR, as slot 76 does. +// mapped. `desc` has an Xbox texture layout word and flags above the PC resource flags. The separate initial +// barrier layout is passed through to the applicable provider, including 0xFFFFFFFF (UNDEFINED). std::atomic g_placed_at_va{nullptr}; std::atomic g_placed_at_va_pages{nullptr}; +std::atomic g_pin_texture_pages{nullptr}; std::atomic g_console_descriptor_heap{nullptr}; HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, - std::uint32_t state, const IID* riid, void** out) { + std::uint32_t layout, const D3D12_CLEAR_VALUE* clear, const IID* riid, void** out) { note_slot(133); if (out) *out = nullptr; - // Without a handler (a PC device behind the proxy, or none registered) the slot refuses like any slot past the - // PC vtable, whatever its arguments. + // An unhandled slot past the PC vtable is refused before inspecting any of its arguments. const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); - if (!handler) return E_NOTIMPL; + const bool can_place_depth = self->depth_stencil_uav_provider && self->validate_depth_placement; + if (!handler && !can_place_depth) return E_NOTIMPL; if (!out || !xbox_desc || !riid) return E_POINTER; + if (can_place_depth && depth_uav_description(*xbox_desc)) + return proxy_create_placed_depth(self, reinterpret_cast(va), *xbox_desc, layout, clear, *riid, out); + if (!handler) return E_NOTIMPL; // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression // for clang-cl with SDK 10.0.26100 (found in review). The cast is applied to the masked value at run time. // The PC flags up to RAYTRACING_ACCELERATION_STRUCTURE (0x100) and USE_TIGHT_ALIGNMENT (0x400); 0x200 is @@ -3526,9 +3785,9 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ if (!logged.exchange(true, std::memory_order_relaxed)) { std::fprintf(stderr, "[rt] d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " - "state=0x%x -> a buffer on the title's pages\n", + "layout=0x%x\n", va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), - xbox_flags, state); + xbox_flags, layout); } // The buffer's pages are committed before the handler walks them (set_placed_at_va_pages_hook). const PlacedAtVaPagesHook pages = g_placed_at_va_pages.load(std::memory_order_acquire); @@ -3540,7 +3799,8 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_ va, static_cast(pc_desc.Width), GetLastError()); } } - return handler(self->real, va, pc_desc, state, *riid, out); + const bool clearable = pc_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); + return handler(self->real, va, pc_desc, layout, *riid, out, clearable ? clear : nullptr); } template @@ -3641,10 +3901,26 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 133) { - return hr_to_u64(proxy_create_placed_resource_x( - self, a1, reinterpret_cast(a2), static_cast(a3), - reinterpret_cast(a4), reinterpret_cast(a5), - reinterpret_cast(a6))); + const auto* desc = reinterpret_cast(a2); + const auto* iid = reinterpret_cast(a5); + auto** out = reinterpret_cast(a6); + // The live Vulkan backend owns the resource on the title's pages. Keep the PC fallback + // for backends with no placement provider and retain the six-argument Xbox ABI. + const bool depth = self->depth_stencil_uav_provider && self->validate_depth_placement && desc && + depth_uav_description(*desc); + const bool generic = g_placed_at_va.load(std::memory_order_acquire) && desc && + (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || !self->raw_texture_view); + const HRESULT hr = depth || generic + ? proxy_create_placed_resource_x(self, reinterpret_cast(a1), desc, static_cast(a3), + reinterpret_cast(a4), iid, out) + : proxy_create_placed_resource_x(self, a1, desc, static_cast(a3), + reinterpret_cast(a4), iid, out); + if (SUCCEEDED(hr) && desc) { + if (a1 && out && *out && self->texture_lease_provider && desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (unsigned(desc->Layout)==1u || unsigned(desc->Layout)==0x100u)) + self->texture_lease_provider(static_cast(*out),reinterpret_cast(a1),0,unsigned(desc->Layout)); + } + return hr_to_u64(hr); } else if constexpr (Slot == kCreateCommittedResource3X) { return hr_to_u64(proxy_create_committed_resource3_x(self, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } else if constexpr (Slot == 70) { @@ -3680,6 +3956,25 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 static_cast(a2), static_cast(static_cast(a3)))); } note_slot(Slot); + if constexpr (Slot == 55) { + const auto* iid=reinterpret_cast(a4); + if(readable_range(iid,sizeof(IID)) && IsEqualIID(*iid,__uuidof(ID3D12PipelineState))) { + HRESULT hr; + try { hr=proxy_create_derived_pso(self,reinterpret_cast(a1), + static_cast(a2),reinterpret_cast(a3),iid,reinterpret_cast(a5)); } catch(const std::bad_alloc&) { hr=E_OUTOFMEMORY; } + return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateDerivedPipelineState",hr)); + } + } + if constexpr (Slot == 57) { + const auto* iid = reinterpret_cast(a2); + if (!readable_range(iid, sizeof(IID))) return hr_to_u64(E_POINTER); + // The title requests a PSO here. Other interfaces retain their ordinary forwarding path. + if (IsEqualIID(*iid, __uuidof(ID3D12PipelineState))) { + const HRESULT hr = proxy_create_native_graphics(self, reinterpret_cast(a1), *iid, + reinterpret_cast(a3)); + return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateNativeGraphicsPipelineState", hr)); + } + } // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. @@ -3912,6 +4207,8 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool co delete proxy; return hr; } + // The source consults the process-wide heap registry; it holds no pointer to this device. + leonida::title_va_aliases().set_descriptor_source(nullptr, pull_title_descriptors); if (!d3d12_trace::enabled()) std::fprintf(stderr, "[rt] d3d12_xs: device proxy %p wraps PC device %p (%u PC vtable slots)\n", static_cast(proxy), static_cast(real), slot_count); @@ -3945,6 +4242,19 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } +void set_constant_view_provider(void* device, ConsoleConstantView provider) { + if (auto* proxy=static_cast(device_proxy_primary(device))) proxy->constant_view=provider; +} +void set_raw_texture_view_provider(void* device, RawTextureViewProvider provider) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->raw_texture_view = provider; +} +void set_texture_lease_provider(void* device, TextureLeaseProvider provider) { + if (is_device_proxy(device)) static_cast(device)->texture_lease_provider = provider; +} +void set_descriptor_mapping_provider(void* device, DescriptorMappingProvider provider) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->descriptor_mapping = provider; +} + bool set_device_resource_provider(void* device, ResourceByVaProvider provider) { auto* proxy = static_cast(device_proxy_primary(device)); if (!proxy) { @@ -3956,6 +4266,21 @@ bool set_device_resource_provider(void* device, ResourceByVaProvider provider) { return true; } +void set_native_stream_factory(void* device, NativeStreamFactory factory) { + if (auto* proxy=static_cast(device_proxy_primary(device)))proxy->prepare_stream=factory; +} +void set_device_native_graphics_factory(void* device, NativeGraphicsFactory factory) { + if (auto* proxy = static_cast(device_proxy_primary(device))) proxy->native_graphics = factory; +} + +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, ValidateDepthPlacement validate) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) return false; + proxy->depth_stencil_uav_provider = provider; + proxy->validate_depth_placement = validate; + return true; +} + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } @@ -3993,6 +4318,12 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler) { g_placed_at_va.store(handler, std::memory_order_release); } +void set_texture_page_provider(PinnedTexturePages hook) { g_pin_texture_pages.store(hook,std::memory_order_release); } +std::shared_ptr pin_texture_pages(const void* address, std::size_t size) { + const auto hook=g_pin_texture_pages.load(std::memory_order_acquire); + return hook ? hook(address,size) : std::shared_ptr{}; +} + void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { g_placed_at_va_pages.store(hook, std::memory_order_release); } @@ -4015,7 +4346,7 @@ std::shared_ptr device_frame_tokens(const void* devic bool device_slot_overridden(unsigned slot) { if (slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || - slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || + slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 57 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == kCreateCommittedResource3X || slot == 133 || slot == 41 || slot == 61 || slot == 74 || slot == 86 || slot == 101 || slot == 108) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index f5cbc7658..611c967c5 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -107,6 +107,7 @@ #include +#include #include #include #include @@ -115,6 +116,8 @@ namespace leonida { class FrameTokenSource; } +namespace leonida::native_pso { struct GraphicsDesc; } + namespace rt::d3d12_xs { // Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to @@ -142,6 +145,13 @@ bool is_device_proxy(const void* device); using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); +// The Vulkan backend installs its own graphics PSO factory on its outer Xbox device. +class PsoStreamRecord; +using NativeStreamFactory = HRESULT (*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC&, REFIID, void**, + std::unique_ptr); +void set_native_stream_factory(void* device, NativeStreamFactory factory); +using NativeGraphicsFactory = HRESULT (*)(ID3D12Device*, const leonida::native_pso::GraphicsDesc&, REFIID, void**); +void set_device_native_graphics_factory(void* device, NativeGraphicsFactory factory); // Finds the buffer resource that holds a console GPU virtual address, for device slot 70. `real` is the device behind // the proxy; `bytes` is how many bytes from `va` the caller wants, so a resource that holds all of them is preferred // over a shorter alias. Returns the resource with a reference added (the proxy releases it), or null when no resource holds @@ -151,6 +161,46 @@ using ResourceByVaProvider = ID3D12Resource* (*)(ID3D12Device* real, std::uint64 // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither. Without a provider slot // 70 writes only the null view. bool set_device_resource_provider(void* device, ResourceByVaProvider provider); +using TextureLeaseProvider = void (*)(IUnknown* resource, void* pages, std::size_t size, UINT layout); +void set_texture_lease_provider(void* device, TextureLeaseProvider provider); +using RawTextureViewProvider = bool (*)(ID3D12Device*, const D3D12_RESOURCE_DESC&, const D3D12_SHADER_RESOURCE_VIEW_DESC&, + std::uint64_t, D3D12_CPU_DESCRIPTOR_HANDLE); +void set_raw_texture_view_provider(void* device, RawTextureViewProvider provider); +using ConsoleConstantView = bool (*)(ID3D12Device*, const D3D12_CONSTANT_BUFFER_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE); +void set_constant_view_provider(void* device, ConsoleConstantView provider); +// Installed by the Vulkan backend before handing the device to callers. Reports whether the exact +// CPU span belongs to the heap's live mapped allocation. PC descriptor handles may be opaque. +using DescriptorMappingProvider = bool (*)(ID3D12DescriptorHeap* heap, SIZE_T start, SIZE_T bytes); +void set_descriptor_mapping_provider(void* device, DescriptorMappingProvider provider); +// Called before publishing an Xbox resource when the backend can implement its depth/stencil UAV views. +using DepthStencilUavProvider = HRESULT (*)(ID3D12Resource* resource, D3D12_HEAP_FLAGS storage_heap_flags); +inline bool depth_uav_description(const D3D12_RESOURCE_DESC& desc) { + constexpr auto flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return (desc.Flags & flags) == flags && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_R16_TYPELESS || + desc.Format == static_cast(118)) && + desc.DepthOrArraySize && desc.MipLevels == 1 && desc.SampleDesc.Count == 1; +} +using ValidateDepthPlacement = bool (*)(const D3D12_RESOURCE_DESC& native, std::uint32_t layout, + const D3D12_CLEAR_VALUE* clear); +bool set_depth_stencil_uav_provider(void* device, DepthStencilUavProvider provider, + ValidateDepthPlacement validate_placement = nullptr); + +// The Vulkan implementation uses this private interface to look up an image for view creation. +inline constexpr GUID kVulkanResourceTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; + +// Identically placed Xbox depth textures have distinct COM identities but refer to one GPU image and layout. +// Only these wrappers carry a backing pointer. Every other resource retains its ordinary pointer-valued IR ID. +struct PlacedDepthInterface : ID3D12Resource { + ID3D12Resource* backing = nullptr; +}; +inline std::atomic placed_depth_vtable{nullptr}; +inline const ID3D12Resource* texture_backing(const ID3D12Resource* resource) { + const void* vtable = placed_depth_vtable.load(std::memory_order_acquire); + if (resource && vtable && *reinterpret_cast(resource) == vtable) + return static_cast(resource)->backing; + return resource; +} // The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. @@ -185,14 +235,13 @@ ID3D12Device* device_proxy_real_device(const void* device); // this file that is handed a title's object, like the XboxBvhBuilder shim's command lists. IUnknown* real_object_behind_proxy(const void* object); std::shared_ptr device_frame_tokens(const void* device); -// Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does -// not create it itself: the device behind it does, through this handler, which the Vulkan layer registers -// (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot -// answers E_NOTIMPL. +// Device slot 133 (the console's CreatePlacedResourceX) routes supported depth UAVs to the proxy's depth provider. +// Other resources use this handler, registered by the Vulkan layer (rt::d3d12::create_buffer_at_host_address). +// It creates buffers on the title's pages at `va`. With no applicable provider the slot answers E_NOTIMPL. // `layout` is the title's third argument, a D3D12_BARRIER_LAYOUT (0xFFFFFFFF = UNDEFINED), measured on a retail // boot: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, as PC CreatePlacedResource2 takes it. using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); + std::uint32_t layout, REFIID riid, void** out, const D3D12_CLEAR_VALUE* clear); void set_placed_at_va_handler(PlacedAtVaHandler handler); // Called by slot 133 for a buffer, before the handler, with the buffer's range [va, va + width). gta6rt registers @@ -202,6 +251,9 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler); // called. With none registered nothing is done. using PlacedAtVaPagesHook = bool (*)(const void* va, std::size_t bytes); void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook); +using PinnedTexturePages = std::shared_ptr (*)(const void*, std::size_t); +void set_texture_page_provider(PinnedTexturePages hook); +std::shared_ptr pin_texture_pages(const void* address, std::size_t size); // Device slot 14's console-extended CreateDescriptorHeap: the description is the PC 16-byte shape followed by a // console VA and a size (issue #313). The proxy does not create the heap itself: the device behind it registers this diff --git a/runtime/shims/d3d12_xs_native_pso.h b/runtime/shims/d3d12_xs_native_pso.h new file mode 100644 index 000000000..fce79ea8c --- /dev/null +++ b/runtime/shims/d3d12_xs_native_pso.h @@ -0,0 +1,234 @@ +#pragma once + +// Xbox native graphics pipeline state, adapted from enx/leonida's slot-57 implementation. +// The state and stage resolution are in native_pso.h. All stage bytecode handed to D3D12 +// comes from the user's carved DXBC containers and is translated by the normal Vulkan PSO path. +#include "../src/native_pso.h" +#include "d3d12_xs_pso_stream.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { +namespace native_pipeline_detail { +namespace np = leonida::native_pso; + +inline void fill_fixed_state(const np::FixedState& s, D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc) { + for (auto& rt : pc.BlendState.RenderTarget) rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pc.SampleMask = s.sample_mask ? s.sample_mask : UINT_MAX; + pc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pc.RasterizerState.DepthClipEnable = TRUE; + pc.DSVFormat = static_cast(s.dsv_format); + pc.DepthStencilState.DepthEnable = pc.DSVFormat != DXGI_FORMAT_UNKNOWN; + pc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + pc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pc.PrimitiveTopologyType = s.topology_type ? static_cast(s.topology_type) + : D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pc.NumRenderTargets = s.rt_count; + for (unsigned i = 0; i < s.rt_count; ++i) pc.RTVFormats[i] = static_cast(s.rtv_formats[i]); + pc.SampleDesc.Count = s.sample_count; +} + +template +struct alignas(void*) Subobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type = T; + P value{}; +}; + +struct MeshStream { + Subobject root; + Subobject ms; + Subobject ps; + Subobject blend; + Subobject sample_mask; + Subobject raster; + Subobject depth; + Subobject rtvs; + Subobject dsv; + Subobject sample; +}; + +inline HRESULT create_mesh(ID3D12Device* real, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, + D3D12_SHADER_BYTECODE ms, const IID& riid, void** out) { + ID3D12Device2* device2 = nullptr; + if (FAILED(real->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast(&device2))) || !device2) + return E_NOTIMPL; + MeshStream s; + s.root.value = pc.pRootSignature; + s.ms.value = ms; + s.ps.value = pc.PS; + s.blend.value = pc.BlendState; + s.sample_mask.value = pc.SampleMask; + s.raster.value = pc.RasterizerState; + s.depth.value = pc.DepthStencilState; + s.rtvs.value.NumRenderTargets = pc.NumRenderTargets; + for (unsigned i = 0; i < 8; ++i) s.rtvs.value.RTFormats[i] = pc.RTVFormats[i]; + s.dsv.value = pc.DSVFormat; + s.sample.value = pc.SampleDesc; + const D3D12_PIPELINE_STATE_STREAM_DESC stream{sizeof(s), &s}; + const HRESULT hr = device2->CreatePipelineState(&stream, riid, out); + device2->Release(); + return hr; +} + +// A pipeline state stream: each subobject is a type word, then its payload at its own alignment, padded to 8 bytes +// (d3dx12's alignas(void*) subobjects). +class Stream { +public: + template + void add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type, const P& payload) { + const std::size_t at = size_; + const std::size_t offset = (at + sizeof(type) + alignof(P) - 1) & ~(alignof(P) - 1); + size_ = (offset + sizeof(P) + 7) & ~std::size_t(7); + words_.resize(size_ / 8); + auto* bytes = reinterpret_cast(words_.data()); + std::memcpy(bytes + at, &type, sizeof(type)); + std::memcpy(bytes + offset, &payload, sizeof(P)); + } + D3D12_PIPELINE_STATE_STREAM_DESC desc() { return {size_, words_.data()}; } + +private: + std::vector words_; + std::size_t size_ = 0; +}; + +// The stream of a graphics description; an MS stage makes a mesh pipeline (no input layout or topology). +inline void build_stream(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE ms, Stream& s) { + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, pc.pRootSignature); + const bool mesh = ms.pShaderBytecode != nullptr; + if (mesh) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + if (pc.VS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, pc.VS); + if (pc.GS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, pc.GS); + if (pc.PS.pShaderBytecode) s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, pc.PS); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, pc.BlendState); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, pc.SampleMask); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, pc.RasterizerState); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, pc.DepthStencilState); + if (!mesh) { + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, pc.InputLayout); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, pc.PrimitiveTopologyType); + } + D3D12_RT_FORMAT_ARRAY rtvs{}; + rtvs.NumRenderTargets = pc.NumRenderTargets; + for (unsigned i = 0; i < 8; ++i) rtvs.RTFormats[i] = pc.RTVFormats[i]; + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, rtvs); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, pc.DSVFormat); + s.add(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, pc.SampleDesc); +} + + +} // namespace native_pipeline_detail + +// One instance per Vulkan device. The catalog is immutable once loaded; repeated pipeline +// descriptions can share the source containers without sharing mutable COM pipeline objects. +class NativeGraphicsPipelines { +public: + template + HRESULT create(const std::filesystem::path& folder, const leonida::native_pso::GraphicsDesc& desc, + void** out, Create&& create_pipeline) { + using namespace native_pipeline_detail; + *out = nullptr; + try { + std::call_once(load_, [&] { + std::ifstream file(folder / L"native_hashes.txt", std::ios::binary); + if (!file) { + std::fprintf(stderr, "[rt] d3d12_xs: slot 57 needs native_hashes.txt from the shaders stage\n"); + return; + } + const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; + std::string error; + if (!catalog_.parse(text, &error)) std::fprintf(stderr, "[rt] d3d12_xs: slot 57: %s\n", error.c_str()); + }); + const auto plan = np::plan(desc, catalog_); + if (plan.status == np::PlanStatus::malformed) return E_INVALIDARG; + if (plan.status != np::PlanStatus::ok) return E_NOTIMPL; + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pc{}; + pc.pRootSignature = static_cast(const_cast(desc.root_signature)); + fill_fixed_state(plan.state, pc); + std::vector elements; + for (const auto& e : plan.state.elements) { + elements.push_back({e.name.c_str(), e.semantic_index, static_cast(e.format), e.input_slot, + e.aligned_byte_offset, static_cast(e.classification), + e.step_rate}); + } + pc.InputLayout = {elements.data(), static_cast(elements.size())}; + + std::array code; + D3D12_SHADER_BYTECODE mesh{}; + for (const auto& stage : plan.stages) { + auto& bytes = code[stage.block]; + bytes = container(folder, *stage.shader); + if (!bytes) return E_INVALIDARG; + const D3D12_SHADER_BYTECODE view{bytes->data(), bytes->size()}; + if (stage.shader->stage == "vs") pc.VS = view; + else if (stage.shader->stage == "ps") pc.PS = view; + else if (stage.shader->stage == "gs") pc.GS = view; + else mesh = view; // plan() admits only VS/PS/GS or MS/PS. + } + return create_pipeline(pc, mesh, code); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } catch (const std::exception&) { + return E_INVALIDARG; + } + } + +private: + using Container = std::shared_ptr>; + Container container(const std::filesystem::path& folder, const leonida::native_pso::ShaderRef& ref) { + { + std::lock_guard lock(mutex_); + if (const auto it = containers_.find(ref.digest); it != containers_.end()) return it->second; + } + // A catalog names files inside the shader workspace. Checking only its components lets a + // reader with access to the two shader directories work without opening their ancestors. + if (ref.path.find_first_of("\\:\r\n\t") != std::string::npos || ref.path.find('\0') != std::string::npos) + return {}; + const auto path = std::filesystem::u8path(ref.path); + if (path.has_root_path() || path.extension() != ".dxbc") return {}; + const auto workspace = folder.parent_path(); + const auto resolved = (folder / path).lexically_normal(); + const auto relative = resolved.lexically_relative(workspace); + if (relative.empty() || *relative.begin() == "..") return {}; + auto component = workspace; + for (const auto& part : relative) { + component /= part; + const DWORD attrs = GetFileAttributesW(component.c_str()); + if (attrs == INVALID_FILE_ATTRIBUTES || (attrs & FILE_ATTRIBUTE_REPARSE_POINT)) return {}; + } + std::ifstream in(resolved, std::ios::binary | std::ios::ate); + const std::streamoff size = in ? static_cast(in.tellg()) : 0; + if (size <= 0 || size > (64 << 20)) return {}; + auto result = std::make_shared>(static_cast(size)); + in.seekg(0); + if (!in.read(reinterpret_cast(result->data()), size)) return {}; + const auto hash = leonida::dxbc_part(*result, "HASH"); + if (hash.size() < 20 || std::memcmp(hash.data() + 4, ref.digest.data(), ref.digest.size())) return {}; + std::lock_guard lock(mutex_); + if (const auto it = containers_.find(ref.digest); it != containers_.end()) return it->second; + constexpr std::size_t budget = std::size_t{256} << 20; + if (result->size() <= budget - cached_bytes_) { + containers_.emplace(ref.digest, result); + cached_bytes_ += result->size(); + } + return result; + } + + std::once_flag load_; + leonida::native_pso::HashMap catalog_; + std::mutex mutex_; + std::map containers_; + std::size_t cached_bytes_ = 0; +}; + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_placed_depth.h b/runtime/shims/d3d12_xs_placed_depth.h new file mode 100644 index 000000000..73bc28eb7 --- /dev/null +++ b/runtime/shims/d3d12_xs_placed_depth.h @@ -0,0 +1,134 @@ +// GPU backing for slot-133 depth/UAV textures, keyed by the Xbox placement range on one device. +#pragma once + +#include "d3d12_com_object.h" +#include "d3d12_xs_device.h" + +#include +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +class PlacedDepthTexture final + : public d3d12::Object { +public: + static constexpr GUID kTag{0x64472a85, 0x967d, 0x46bc, {0x96, 0xaf, 0x68, 0x1f, 0x50, 0x35, 0x64, 0x71}}; + + PlacedDepthTexture(std::shared_ptr owner, UINT64 address) + : owner_(std::move(owner)), address_(address) { + backing = owner_.get(); + placed_depth_vtable.store(*reinterpret_cast(this), std::memory_order_release); + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** out) override { + if (iid == kVulkanResourceTag) return backing->QueryInterface(iid, out); + return Object::QueryInterface(iid, out); + } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID iid, void** out) override { return backing->GetDevice(iid, out); } + D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { return backing->GetDesc(); } + D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return address_; } + HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS* flags) override { + return backing->GetHeapProperties(props, flags); + } + HRESULT STDMETHODCALLTYPE Map(UINT index, const D3D12_RANGE* read, void** data) override { + return backing->Map(index, read, data); + } + void STDMETHODCALLTYPE Unmap(UINT index, const D3D12_RANGE* written) override { backing->Unmap(index, written); } + HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT index, const D3D12_BOX* box, const void* data, + UINT row_pitch, UINT depth_pitch) override { + return backing->WriteToSubresource(index, box, data, row_pitch, depth_pitch); + } + HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, + UINT index, const D3D12_BOX* box) override { + return backing->ReadFromSubresource(data, row_pitch, depth_pitch, index, box); + } + +private: + std::shared_ptr owner_; + UINT64 address_; +}; + +class PlacedDepthTextures { +public: + // The initial barrier layout and optimized clear are checked for each caller before looking up an alias. + // Reusing a live compatible placement retains both the attachment image and its writable plane images. + template + HRESULT create(UINT64 address, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_ALLOCATION_INFO allocation, + const D3D12_CLEAR_VALUE* clear, bool opaque_layout, REFIID iid, void** out, Create create_backing) { + if (!address || !allocation.Alignment || address % allocation.Alignment || !allocation.SizeInBytes || + allocation.SizeInBytes > UINT64_MAX - address) + return E_INVALIDARG; + const UINT64 end = address + allocation.SizeInBytes; + // Placed RT/DS textures can inherit contents only when their optimized clear values also match. + // Compare the defined fields. D3D12_CLEAR_VALUE has union padding, and D16 has no stencil plane. + std::optional optimized; + if (clear) optimized = OptimizedClear{clear->Format, std::bit_cast(clear->DepthStencil.Depth), + desc.Format == DXGI_FORMAT_R16_TYPELESS ? UINT8(0) : clear->DepthStencil.Stencil}; + std::shared_ptr owner; + try { + { + std::lock_guard lock(mutex_); + // Weak ownership avoids keeping GPU images or the device alive just because an address was used. + std::erase_if(ranges_, [](const auto& entry) { return entry.second.backing.expired(); }); + // At the same offset two differently shaped opaque depth targets may alternate after + // an aliasing barrier and reinitialization. The API promises data inheritance only for + // identical descriptions and optimized clears. Keep that matching backing alive even + // when another shape is also registered at this address. + const auto limit = ranges_.lower_bound(end); + for (auto it = ranges_.begin(); it != limit; ++it) { + const auto& range = it->second; + if (range.end <= address) continue; + if (it->first != address) return E_NOTIMPL; + const bool same_shape = compatible(desc, range.desc); + if (range.end == end && same_shape && range.optimized == optimized) { + if (auto live = range.backing.lock()) owner = std::move(live); + } else if (!opaque_layout || !range.opaque_layout || same_shape) { + return E_NOTIMPL; + } + } + if (!owner) { + ID3D12Resource* resource = nullptr; + const HRESULT hr = create_backing(&resource); + if (FAILED(hr)) return hr; + owner = {resource, [](ID3D12Resource* r) { r->Release(); }}; + ranges_.emplace(address, Range{end, desc, optimized, owner, opaque_layout}); + } + } + auto* alias = new PlacedDepthTexture(std::move(owner), address); + return d3d12::hand_out(alias, iid, out); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + } + +private: + // Dimension, mip/sample counts and layout are fixed by the slot handler. The effective alignment and byte + // interval have already been validated. All remaining usage and image geometry must match for data inheritance. + static bool compatible(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) { + return a.Format == b.Format && a.Width == b.Width && a.Height == b.Height && + a.DepthOrArraySize == b.DepthOrArraySize && a.SampleDesc.Quality == b.SampleDesc.Quality && + a.Flags == b.Flags; + } + struct OptimizedClear { + DXGI_FORMAT format; + UINT depth_bits; + UINT8 stencil; + bool operator==(const OptimizedClear&) const = default; + }; + struct Range { + UINT64 end; + D3D12_RESOURCE_DESC desc; + std::optional optimized; + std::weak_ptr backing; + bool opaque_layout; + }; + std::mutex mutex_; + std::multimap ranges_; +}; + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.cpp b/runtime/shims/d3d12_xs_pso_stream.cpp new file mode 100644 index 000000000..fa2941ef5 --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -0,0 +1,340 @@ +#include "d3d12_xs_pso_stream.h" + +#include +#include + +namespace rt::d3d12_xs { +namespace { + +// Tag 5 and the DEPTH_STENCIL offsets of its two stencil mask bytes (StencilReadMask, StencilWriteMask). +constexpr std::uint32_t kStencilMaskTag = 5; +constexpr std::size_t kStencilReadMaskOffset = 0x10; +constexpr std::size_t kStencilWriteMaskOffset = 0x11; + +// Streams beyond this are refused: a title's PSO stream is a few kilobytes. +constexpr std::size_t kMaxStreamBytes = 64 * 1024; + +// Private-data GUIDs (random, fixed for this shim). The record pointer is found by GetPrivateData; the owner is an +// IUnknown the object releases when it is destroyed, which frees the record with it. +constexpr GUID kRecordPointerGuid{0x3c1f9a2e, 0x5b7d, 0x4e08, {0x8f, 0x12, 0x6a, 0x4d, 0x9c, 0x2b, 0x71, 0xe3}}; +constexpr GUID kRecordOwnerGuid{0x9e4b2d17, 0x0a6c, 0x4f35, {0xb1, 0x8d, 0x23, 0x7e, 0x5f, 0xc9, 0x40, 0x6a}}; + +struct Layout { + std::size_t size; + std::size_t align; +}; + +// Size and alignment of each subobject payload this module walks (the SDK's D3D12_PIPELINE_STATE_SUBOBJECT_TYPE). +// VIEW_INSTANCING and unknown types are not modelled: a stream with one is not captured. +bool layout_of(unsigned type, Layout& out) { + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: out = {8, 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: + out = {sizeof(D3D12_SHADER_BYTECODE), 8}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: out = {sizeof(D3D12_STREAM_OUTPUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: out = {sizeof(D3D12_BLEND_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: out = {4, 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: out = {sizeof(D3D12_RASTERIZER_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: out = {sizeof(D3D12_DEPTH_STENCIL_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: out = {sizeof(D3D12_INPUT_LAYOUT_DESC), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: + out = {4, 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: + out = {sizeof(D3D12_RT_FORMAT_ARRAY), 4}; + return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: out = {sizeof(DXGI_SAMPLE_DESC), 4}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: out = {sizeof(D3D12_CACHED_PIPELINE_STATE), 8}; return true; + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: out = {sizeof(D3D12_DEPTH_STENCIL_DESC1), 4}; return true; + default: return false; + } +} + +std::size_t align_up(std::size_t value, std::size_t align) { return (value + align - 1) / align * align; } + +struct Subobject { + unsigned type; + std::size_t payload; // offset of the payload in the stream + std::size_t size; +}; + +// Walks a stream laid out as the console does: u32 type, payload at its natural alignment, next entry 8-aligned +// (the measured console offsets: BLEND payload +0x8c, DEPTH_STENCIL1 entry at +0x210). False when a type is unknown +// or the entries do not end exactly at `size`. +bool walk(const unsigned char* stream, std::size_t size, std::vector& out) { + out.clear(); + std::size_t off = 0; + while (off < size) { + if (size - off < 4) return false; + unsigned type; + std::memcpy(&type, stream + off, 4); + Layout layout{}; + if (!layout_of(type, layout)) return false; + const std::size_t payload = align_up(off + 4, layout.align); + if (payload > size || layout.size > size - payload) return false; + out.push_back({type, payload, layout.size}); + off = align_up(payload + layout.size, 8); + } + return off == size; +} + +// Copies `count` bytes into a new owned blob and returns its address (stable: the blob's buffer does not move). +const unsigned char* own_blob(std::vector>& blobs, const void* bytes, std::size_t count) { + const auto* src = static_cast(bytes); + blobs.emplace_back(src, src + count); + return blobs.back().data(); +} + +// Holds a PsoStreamRecord as an IUnknown: the object keeps one reference, the creation code drops its own. +class RecordOwner final : public IUnknown { +public: + explicit RecordOwner(std::unique_ptr record) : record_(std::move(record)) {} + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (riid == __uuidof(IUnknown)) { + *out = static_cast(this); + AddRef(); + return S_OK; + } + *out = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = --refs_; + if (left == 0) delete this; + return left; + } + PsoStreamRecord* record() { return record_.get(); } + +private: + ~RecordOwner() = default; + std::atomic refs_{1}; + std::unique_ptr record_; +}; + +// A record's target: the subobject it patches, a fallback subobject type (0 for none), and the payload bytes it carries. +struct Target { + unsigned primary_type; + unsigned fallback_type; + std::size_t bytes; +}; + +bool target_of_tag(std::uint32_t tag, Target& out) { + switch (tag) { + case 0: // D3D12_DEPTH_STENCIL_DESC: DEPTH_STENCIL, or the prefix of DEPTH_STENCIL1 + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, + sizeof(D3D12_DEPTH_STENCIL_DESC)}; + return true; + case 1: // D3D12_RASTERIZER_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, 0, sizeof(D3D12_RASTERIZER_DESC)}; + return true; + case 2: // D3D12_BLEND_DESC + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, 0, sizeof(D3D12_BLEND_DESC)}; + return true; + case 3: // sample mask (UINT) + out = {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, 0, sizeof(UINT)}; + return true; + default: return false; + } +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target); + +// Tag 5: the two stencil mask bytes of the record overwrite the base's DEPTH_STENCIL (or DEPTH_STENCIL1) masks; the +// rest of the record's zeros are not applied. False when the base has no depth-stencil subobject. +bool overlay_stencil_masks(const std::vector& subs, const unsigned char* record, + std::vector& out) { + const Target depth{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, 0}; + const Subobject* sub = find_subobject(subs, depth); + if (!sub) return false; + for (std::size_t field : {kStencilReadMaskOffset, kStencilWriteMaskOffset}) + out[sub->payload + field] = record[kDerivedRecordPayload + field]; + return true; +} + +const Subobject* find_subobject(const std::vector& subs, const Target& target) { + for (const Subobject& sub : subs) + if (sub.type == target.primary_type) return ⊂ + if (target.fallback_type) + for (const Subobject& sub : subs) + if (sub.type == target.fallback_type) return ⊂ + return nullptr; +} + +} // namespace + +PsoStreamRecord::Payloads::~Payloads() { + for (ID3D12RootSignature* root : roots) + if (root) root->Release(); +} + +std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::span shaders) { + if (!desc.pPipelineStateSubobjectStream || desc.SizeInBytes == 0 || desc.SizeInBytes > kMaxStreamBytes) + return nullptr; + const auto* source = static_cast(desc.pPipelineStateSubobjectStream); + std::vector subs; + if (!walk(source, desc.SizeInBytes, subs)) return nullptr; + + std::unique_ptr record(new PsoStreamRecord()); + record->payloads_ = std::make_shared(); + for (const auto& shader : shaders) if (shader) record->payloads_->shaders.push_back(shader); + record->bytes_.assign(source, source + desc.SizeInBytes); + for (const Subobject& sub : subs) { + if (!record->copy_pointed_data(sub.type, sub.payload)) return nullptr; + } + return record; +} + +// Replaces the pointers in one subobject's payload with copies of what they point to. +// The derived overrides touch value subobjects only. Shader bytes, semantic names and root +// signature references have the lifetime of the shared payload even after releasing the base PSO. +std::unique_ptr PsoStreamRecord::derived(const PsoStreamRecord& base, std::vector stream) { + std::unique_ptr record(new PsoStreamRecord()); + record->bytes_ = std::move(stream); + record->payloads_ = base.payloads_; + return record; +} + +bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_offset) { + unsigned char* payload = bytes_.data() + payload_offset; + switch (type) { + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: { + ID3D12RootSignature* root = nullptr; + std::memcpy(&root, payload, sizeof(root)); + if (root) { + payloads_->roots.push_back(root); + root->AddRef(); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: { + D3D12_SHADER_BYTECODE code{}; + std::memcpy(&code, payload, sizeof(code)); + if (code.pShaderBytecode && code.BytecodeLength) { + for (const auto& shader : payloads_->shaders) + if (shader->data() == code.pShaderBytecode && shader->size() == code.BytecodeLength) return true; + code.pShaderBytecode = own_blob(payloads_->blobs, code.pShaderBytecode, code.BytecodeLength); + std::memcpy(payload, &code, sizeof(code)); + } + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: { + D3D12_STREAM_OUTPUT_DESC so{}; + std::memcpy(&so, payload, sizeof(so)); + if (so.pSODeclaration && so.NumEntries) + so.pSODeclaration = reinterpret_cast( + own_blob(payloads_->blobs, so.pSODeclaration, so.NumEntries * sizeof(D3D12_SO_DECLARATION_ENTRY))); + if (so.pBufferStrides && so.NumStrides) + so.pBufferStrides = reinterpret_cast( + own_blob(payloads_->blobs, so.pBufferStrides, so.NumStrides * sizeof(UINT))); + std::memcpy(payload, &so, sizeof(so)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: { + D3D12_INPUT_LAYOUT_DESC layout{}; + std::memcpy(&layout, payload, sizeof(layout)); + if (!layout.pInputElementDescs || !layout.NumElements) return true; + const std::size_t bytes = layout.NumElements * sizeof(D3D12_INPUT_ELEMENT_DESC); + auto* elements = reinterpret_cast( + const_cast(own_blob(payloads_->blobs, layout.pInputElementDescs, bytes))); + for (UINT i = 0; i < layout.NumElements; ++i) { + if (!elements[i].SemanticName) continue; + const std::size_t len = std::strlen(elements[i].SemanticName) + 1; + elements[i].SemanticName = + reinterpret_cast(own_blob(payloads_->blobs, elements[i].SemanticName, len)); + } + layout.pInputElementDescs = elements; + std::memcpy(payload, &layout, sizeof(layout)); + return true; + } + case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: { + D3D12_CACHED_PIPELINE_STATE cached{}; + std::memcpy(&cached, payload, sizeof(cached)); + if (cached.pCachedBlob && cached.CachedBlobSizeInBytes) { + cached.pCachedBlob = own_blob(payloads_->blobs, cached.pCachedBlob, cached.CachedBlobSizeInBytes); + std::memcpy(payload, &cached, sizeof(cached)); + } + return true; + } + default: return true; // no pointers in this payload + } +} + +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out) { + if (!records || count == 0 || count > kDerivedMaxRecords) return DeriveStatus::malformed; + out = base.bytes(); + std::vector subs; + if (!walk(out.data(), out.size(), subs)) return DeriveStatus::malformed; + + for (unsigned i = 0; i < count; ++i) { + const unsigned char* record = records + i * kDerivedRecordSize; + std::uint32_t tag; + std::memcpy(&tag, record, sizeof(tag)); + if (tag == kStencilMaskTag) { + if (!overlay_stencil_masks(subs, record, out)) return DeriveStatus::missing_state; + continue; + } + Target target{}; + if (!target_of_tag(tag, target)) return DeriveStatus::unknown_tag; + const Subobject* sub = find_subobject(subs, target); + if (!sub) return DeriveStatus::missing_state; + std::memcpy(out.data() + sub->payload, record + kDerivedRecordPayload, target.bytes); + } + return DeriveStatus::ok; +} + +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record) { + if (!object || !record) return false; + RecordOwner* owner = new RecordOwner(std::move(record)); // one reference: ours + if (FAILED(object->SetPrivateDataInterface(kRecordOwnerGuid, owner))) { + owner->Release(); + return false; + } + // The object holds its own reference now; drop ours. The pointer below is for lookups only. + owner->Release(); + RecordOwner* pointer = owner; + return SUCCEEDED(object->SetPrivateData(kRecordPointerGuid, sizeof(pointer), &pointer)); +} + +bool share_pso_record(ID3D12Object* source, ID3D12Object* target) { + UINT size=sizeof(RecordOwner*); + RecordOwner* owner=nullptr; + if(!source || !target || FAILED(source->GetPrivateData(kRecordPointerGuid,&size,&owner)) || + size!=sizeof(owner) || !owner) return false; + if(FAILED(target->SetPrivateDataInterface(kRecordOwnerGuid,owner))) return false; + return SUCCEEDED(target->SetPrivateData(kRecordPointerGuid,sizeof(owner),&owner)); +} + +const PsoStreamRecord* find_pso_record(ID3D12Object* object) { + if (!object) return nullptr; + UINT size = sizeof(RecordOwner*); + RecordOwner* owner = nullptr; + if (FAILED(object->GetPrivateData(kRecordPointerGuid, &size, &owner)) || size != sizeof(RecordOwner*) || !owner) + return nullptr; + return owner->record(); +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h new file mode 100644 index 000000000..7a299989f --- /dev/null +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -0,0 +1,85 @@ +// Xbox derived pipeline states (device slot 55) over PC pipeline state streams. +// +// Slot 86 creates a PSO from a D3D12_PIPELINE_STATE_STREAM_DESC. The proxy keeps a deep copy of that stream on the +// PSO it returns (ID3D12Object private data, so the copy is freed with the PSO). Slot 55 takes a base PSO and up to +// three state records; it patches a copy of the base stream and creates the new PSO through the same path. +// +// Record layout (TomBox's create_derived_pso_x, GPL-3.0): 0x14c bytes, a u32 tag, then the state payload at +4. +// tag 0: D3D12_DEPTH_STENCIL_DESC (0x34) -> the DEPTH_STENCIL or DEPTH_STENCIL1 subobject (first 0x34 bytes) +// tag 1: D3D12_RASTERIZER_DESC (0x2c) +// tag 2: D3D12_BLEND_DESC (0x148) +// tag 3: sample mask (u32) +// tag 5: the StencilReadMask and StencilWriteMask bytes (payload +0x10, +0x11) overwrite those two bytes of the base's +// DEPTH_STENCIL / DEPTH_STENCIL1; the title writes no other byte of it (read from the retail build's record writes) +// Any other tag is refused: its meaning is not known. +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +inline constexpr std::size_t kDerivedRecordSize = 0x14c; +inline constexpr std::size_t kDerivedRecordPayload = 4; +// The console passes the count of records it built: raster, depth-stencil, the tag-5 record and blend can all be +// present, so the count reaches 4 (measured from the title's record writes, see the notes in docs/d3d12_vulkan.md). +inline constexpr unsigned kDerivedMaxRecords = 4; + +// An owned deep copy of one pipeline state stream. The root signature references are held until destruction; shader +// bytecode, stream-output and input-layout arrays and strings, and cached blobs are copied, and their pointers in the +// copy point at the copies. +class PsoStreamRecord { +public: + // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. + using ShaderData = std::shared_ptr>; + static std::unique_ptr capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, + std::span shaders = {}); + static std::unique_ptr derived(const PsoStreamRecord& base, std::vector stream); + ~PsoStreamRecord() = default; + PsoStreamRecord(const PsoStreamRecord&) = delete; + PsoStreamRecord& operator=(const PsoStreamRecord&) = delete; + + // The stream bytes. Its pointers refer to this record's copies, so the record must outlive any use of the desc. + const std::vector& bytes() const { return bytes_; } + // The PC runtime reads the stream and never writes it; the const_cast only meets the desc's void* member. + D3D12_PIPELINE_STATE_STREAM_DESC desc() const { + D3D12_PIPELINE_STATE_STREAM_DESC d{}; + d.SizeInBytes = bytes_.size(); + d.pPipelineStateSubobjectStream = const_cast(bytes_.data()); + return d; + } + +private: + PsoStreamRecord() = default; + bool copy_pointed_data(std::size_t type, std::size_t payload_offset); + + std::vector bytes_; + struct Payloads { + std::vector> blobs; + std::vector shaders; + std::vector roots; + ~Payloads(); + }; + std::shared_ptr payloads_; + +}; + +enum class DeriveStatus { ok, unknown_tag, missing_state, malformed }; + +// Writes the base stream with `count` records applied (count 1..kDerivedMaxRecords; `records` holds count records). +// The result's pointers still refer to the base record's copies. +DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* records, unsigned count, + std::vector& out); + +// Keeps `record` on `object` (lifetime follows the object) and finds it again. attach returns false on failure, and +// then the record is dropped. find returns null when no record was attached to that object. +bool attach_pso_record(ID3D12Object* object, std::unique_ptr record); +bool share_pso_record(ID3D12Object* source, ID3D12Object* target); +const PsoStreamRecord* find_pso_record(ID3D12Object* object); + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp index 81abaea3d..37270beeb 100644 --- a/runtime/shims/dstorage.cpp +++ b/runtime/shims/dstorage.cpp @@ -280,7 +280,9 @@ public: uint32_t capacity() const { return capacity_; } void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); } - void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); } + void complete(uint32_t index, HRESULT hr) { + entries_[index].store(hr,std::memory_order_release); + } std::atomic& refs() { return refs_; } private: @@ -409,6 +411,19 @@ bool guarded_move(void* destination, const void* source, size_t size) { } } +// Reads one byte of every 4 KiB page of the range from user mode. Title memory that xmem maps from physical pages is +// committed by a vectored handler on first touch; a kernel write (ReadFile) raises no user-mode fault and fails with +// ERROR_NOACCESS instead. No C++ objects here: the function has __try. +void touch_pages(void* buffer, size_t size) { + const uintptr_t start = reinterpret_cast(buffer); + for (uintptr_t page = start & ~uintptr_t{0xfff}; page < start + size; page += 0x1000) { + __try { + (void)*reinterpret_cast(page < start ? start : page); + } __except (EXCEPTION_EXECUTE_HANDLER) { + } + } +} + HRESULT read_error(DWORD error) { switch (error) { case ERROR_NOACCESS: @@ -432,7 +447,16 @@ HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint3 at.Offset = static_cast(position); at.OffsetHigh = static_cast(position >> 32); DWORD got = 0; - if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + if (!ReadFile(handle, out + done, size - done, &got, &at)) { + const DWORD error = GetLastError(); + if (error != ERROR_NOACCESS) return read_error(error); + // Destination pages not committed yet (see touch_pages): commit them from user mode and read again once. + touch_pages(out + done, size - done); + at = OVERLAPPED{}; + at.Offset = static_cast(position); + at.OffsetHigh = static_cast(position >> 32); + if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + } if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check done += got; } diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp index 720c106f3..75f5e9810 100644 --- a/runtime/shims/file_system.cpp +++ b/runtime/shims/file_system.cpp @@ -701,6 +701,41 @@ void note_open_failure(const char* api, LPCWSTR name, DWORD error, const void* c rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); } +// Reads one byte of every 4 KiB page of [buffer, buffer + size) from user mode, so that pages committed on first +// touch (xmem's physical-page views: a reserve-only section committed by its vectored handler) are committed before +// the kernel writes into them. A page that is not valid at all is left for the caller's ReadFile to refuse. No C++ +// objects here: the function has __try. +bool touch_pages(void* buffer, DWORD size) { + auto* p = static_cast(buffer); + const uintptr_t first = reinterpret_cast(buffer) & ~uintptr_t{0xfff}; + const uintptr_t end = reinterpret_cast(buffer) + size; + bool all = true; + for (uintptr_t page = first; page < end; page += 0x1000) { + const uintptr_t at = page < reinterpret_cast(p) ? reinterpret_cast(p) : page; + __try { + (void)*reinterpret_cast(at); + } __except (EXCEPTION_EXECUTE_HANDLER) { + all = false; + } + } + return all; +} + +// ReadFile with one retry for a destination the kernel cannot write yet. The retail title reads into title memory +// that xmem maps from physical pages committed on first touch; the kernel's write raises no user-mode fault, so +// ReadFile fails with ERROR_NOACCESS (998), and the title's read loop sleeps 1 ms and retries forever (measured on +// 1.0.2.1, native Windows). Touching the pages from user mode commits them; the read is then retried once. +BOOL WINAPI read_file(HANDLE file, LPVOID buffer, DWORD size, LPDWORD read, LPOVERLAPPED overlapped) { + if (ReadFile(file, buffer, size, read, overlapped)) return TRUE; + if (GetLastError() != ERROR_NOACCESS || !buffer || !size) return FALSE; + static std::atomic logged{false}; + if (!logged.exchange(true)) + std::fprintf(stderr, "[rt] fs: ReadFile into uncommitted title memory (ERROR_NOACCESS): committing the " + "destination pages and retrying (logged once)\n"); + touch_pages(buffer, size); + return ReadFile(file, buffer, size, read, overlapped); +} + HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, DWORD disposition, DWORD flags, HANDLE template_file) { if (!name) { @@ -1405,6 +1440,7 @@ using namespace rt::fs; {dll, "CreateFileA", reinterpret_cast(&create_file_a)}, \ {dll, "CreateFileW", reinterpret_cast(&create_file_w)}, \ {dll, "CreateFile2", reinterpret_cast(&create_file2)}, \ + {dll, "ReadFile", reinterpret_cast(&read_file)}, \ {dll, "FindFirstFileA", reinterpret_cast(&find_first_file_a)}, \ {dll, "FindFirstFileW", reinterpret_cast(&find_first_file_w)}, \ {dll, "FindFirstFileExA", reinterpret_cast(&find_first_file_ex_a)}, \ diff --git a/runtime/shims/present_window.h b/runtime/shims/present_window.h new file mode 100644 index 000000000..1f03f58fc --- /dev/null +++ b/runtime/shims/present_window.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +// The thread that owns an HWND must continue dispatching window messages while another +// thread creates pipelines or waits for the GPU. A stop event also wakes an idle window. +namespace rt::d3d12_xs { +class PresentWindow { +public: + PresentWindow() = default; + PresentWindow(const PresentWindow&) = delete; + PresentWindow& operator=(const PresentWindow&) = delete; + ~PresentWindow() { + if (stop_) SetEvent(stop_); + if (owner_.joinable()) owner_.join(); + if (stop_) CloseHandle(stop_); + } + + HWND create() { + if (stop_) return nullptr; + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_) return nullptr; + try { + std::promise> ready; + auto result = ready.get_future(); + owner_ = std::thread([stop = stop_, ready = std::move(ready)]() mutable { + WNDCLASSW cls{}; + cls.lpfnWndProc = &procedure; + cls.hInstance = GetModuleHandleW(nullptr); + cls.lpszClassName = L"LeonidaPresentX"; + HWND window = nullptr; + if (RegisterClassW(&cls) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) + window = CreateWindowExW(0, cls.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + nullptr, nullptr, cls.hInstance, nullptr); + ready.set_value({window, window ? ERROR_SUCCESS : GetLastError()}); + if (!window) return; + while (MsgWaitForMultipleObjectsEx(1, &stop, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE) == + WAIT_OBJECT_0 + 1) { + MSG msg; + while (WaitForSingleObject(stop, 0) == WAIT_TIMEOUT && PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + if (msg.message == WM_QUIT) return; + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + if (IsWindow(window)) DestroyWindow(window); + }); + const auto [window, error] = result.get(); + if (!window) SetLastError(error); + return window; + } catch (const std::exception&) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return nullptr; + } + } + +private: + static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_DESTROY) { + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); + } + HANDLE stop_ = nullptr; + std::thread owner_; +}; +} // namespace rt::d3d12_xs diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index b45fbf689..751305c85 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,4 +1,6 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. +// xg_xs.dll: the console's texture layout library. Titles ask it which swizzle mode a texture should use, how large it +// is, where each mip and slice lies, and to copy linear data into tiled memory and back. The game executable +// (1.0.2.1) imports two functions from it. // // Measured from the call sites in the executable, read statically (shapes and checks only): // HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) @@ -7,86 +9,498 @@ // known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. // HRESULT XGCreateTextureComputer(const desc*, computer** out) // 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. +// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites), slot 2 with +// one out pointer to a large stack structure (2 sites), slot 8 with six arguments in a loop over subresources +// (1 site) and slot 10 with seven arguments (1 site). // -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). +// The computer's methods, their arguments and the layout structure slot 2 fills are taken from Marvisak/VIctory +// (GPL-3.0), crates/victory-hle/src/modules/xg.rs at commit d2a4bae1f, which serves the same title: 0 AddRef, +// 1 Release, 2 the layout, 6 an element's byte offset, 8 a copy into and 9 a copy out of a subresource, 10 the 64 KiB +// tiling. They match the slots measured above. The layouts come from runtime/src/console_texture_layout.h, ported +// from the same project. +// +// Kept from the measured callers: a description this shim cannot lay out still gets a computer in *out (with a +// negative HRESULT), because two callers use *out without checking the HRESULT. That computer answers every slot +// with E_NOTIMPL and writes nothing. COM says *out is null on failure; this breaks that on purpose. +// +// Not modelled: compression metadata planes (HTILE, CMASK, FMASK, DCC), addressing and copies for the pipe/bank XOR +// modes (_X, _T) and MSAA (they need the GPU's pipe configuration; the host renders those targets), and the slots no +// caller reaches (size, alignment, mip offset, element coordinate, view descriptor), which log once and return +// E_NOTIMPL. #include #include +#include #include #include +#include #include #include +#include +#include +#include +#include #include +#include "../src/console_texture_layout.h" #include "shims.h" namespace { +namespace ct = leonida::console_texture; + constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); +constexpr HRESULT kInvalidArg = static_cast(0x80070057u); +constexpr HRESULT kFail = static_cast(0x80004005u); constexpr size_t kSlots = 32; -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { +// D3D12_RESOURCE_DESC, whose layout field carries 0x100 | swizzle mode on the console (1 row major, 0 "pick one"). +struct ResourceDesc { + uint32_t dimension; + uint64_t alignment; + uint64_t width; + uint32_t height; + uint16_t depth_or_array; + uint16_t mips; + uint32_t format; + uint32_t samples; + uint32_t quality; + uint32_t layout; + uint32_t flags; +}; +static_assert(sizeof(ResourceDesc) == 0x38); + +constexpr uint32_t kSwizzled = 0x100; +constexpr uint32_t kRowMajor = 1; +constexpr uint32_t kAllowRenderTarget = 1; +constexpr uint32_t kAllowDepthStencil = 2; +constexpr uint32_t kTexture1d = 2, kTexture2d = 3, kTexture3d = 4; + +// The layout structure slot 2 fills. Offsets 0x00, 0x08, 0x10 and 0x1c of a mip are the ones the title reads; the +// rest follow the library's older public shape (VIctory's reading). +constexpr size_t kMips = 15; +struct MipOut { + uint64_t size; + uint64_t offset; + uint64_t slice_size; + uint32_t pitch_texels; + uint32_t pitch_bytes; + uint32_t alignment; + uint32_t padded[3]; // width, height in elements, depth or array size + uint32_t elements[2]; + uint32_t texels[2]; + uint32_t depth_or_array; + uint32_t samples; + uint32_t swizzle; + uint64_t bank_rotation[2]; + uint32_t slice_depth; + uint32_t in_tail; + uint32_t tail_position; // where a tail mip starts in elements: x bits 0-10, y 11-21 +}; +struct PlaneOut { + uint32_t usage; // 1 data, 7 depth, 8 stencil (metadata planes are not made) + uint64_t size; + uint64_t slice_size; + uint64_t offset; + uint64_t alignment; + uint32_t element_bytes; + uint32_t standard_mips; + uint32_t tail_mips; + MipOut mips[kMips]; +}; +struct LayoutOut { + uint64_t size; + uint64_t alignment; + uint32_t mips; + uint32_t planes; + PlaneOut plane[4]; + uint32_t dimension; +}; +static_assert(sizeof(MipOut) == 0x70); +static_assert(sizeof(PlaneOut) == 0x6c8); +static_assert(sizeof(LayoutOut) == 0x1b40); + +struct PackedMips { + uint8_t standard; + uint8_t packed; + uint32_t tiles; + uint32_t start; +}; +struct SubresourceTiling { + uint32_t width; + uint16_t height; + uint16_t depth; + uint32_t start; +}; +constexpr uint64_t kTile = 64u << 10; + +// Prints once per call site kind; `slot` is the vtable index for a computer method, or -1 for an export. +void warn_once(std::atomic& warned, const char* what, int slot, const void* caller, const char* why) { if (warned.exchange(true, std::memory_order_relaxed)) return; char name[64]; if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); else std::snprintf(name, sizeof(name), "%s%d", what, slot); - std::fprintf(stderr, "[rt] xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); + std::fprintf(stderr, "[rt] xg_xs: %s: %s (caller %s, logged once)\n", name, why, + rt::shims::module_offset(reinterpret_cast(caller)).c_str()); +} + +// The mode the console's library picks for a description: linear for 1D, the XOR render and depth modes for targets, +// else 4 KiB standard. VIctory's reading of the library's older optimal-mode function (any size, 2D, 3D and cubes +// alike); revisit if streamed textures come out scrambled. +uint32_t suggested(const ResourceDesc& d) { + if (d.dimension == kTexture1d) return ct::kLinear; + if (d.flags & kAllowDepthStencil) return ct::kSw64kbZX; + if (d.flags & kAllowRenderTarget) return ct::kSw64kbRX; + return ct::kSw4kbS; } -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } +std::optional texture_of(const ResourceDesc& d) { + ct::TextureDesc t; + switch (d.dimension) { + case kTexture1d: t.dimension = ct::Dimension::tex1d; break; + case kTexture2d: t.dimension = ct::Dimension::tex2d; break; + case kTexture3d: t.dimension = ct::Dimension::tex3d; break; + default: return std::nullopt; + } + if (d.layout == 0) t.swizzle = suggested(d); + else if (d.layout == kRowMajor) t.swizzle = ct::kLinear; + else if ((d.layout & ~0xffu) == kSwizzled) t.swizzle = d.layout & 0xffu; + else return std::nullopt; + if (d.width > std::numeric_limits::max()) return std::nullopt; + t.width = static_cast(d.width); + t.height = d.height; + t.depth_or_array = d.depth_or_array; + t.mips = d.mips; + t.format = d.format; + t.samples = d.samples ? d.samples : 1; + auto texture = ct::Texture::make(t); + // The layout structure has room for 15 mips. + if (!texture || texture->planes[0].layout.mips.size() > kMips) return std::nullopt; + return texture; +} + +// ---- The computer that cannot lay its description out: every slot E_NOTIMPL, nothing written. ---- + +ULONG __stdcall stub_add_ref(void*) { return 1; } +ULONG __stdcall stub_release(void*) { return 1; } template -HRESULT __stdcall computer_slot(void*) { +HRESULT __stdcall stub_slot(void*) { static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "no layout for this description; E_NOTIMPL"); return kNotImpl; } template -constexpr auto make_vtable(std::index_sequence) { +constexpr auto make_stub_vtable(std::index_sequence) { return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; + (Slot == 0 ? reinterpret_cast(&stub_add_ref) + : Slot == 1 ? reinterpret_cast(&stub_release) + : reinterpret_cast(&stub_slot))...}; } +const auto kStubVtable = make_stub_vtable(std::make_index_sequence{}); +struct StubComputer { + const void* const* vtable; +}; +StubComputer g_stub{kStubVtable.data()}; + +// ---- The computer with a layout. ---- -const auto kVtable = make_vtable(std::make_index_sequence{}); struct Computer { const void* const* vtable; + std::atomic refs{1}; + ResourceDesc desc{}; + uint32_t mips = 0; + ct::Texture texture; }; -Computer g_computer{kVtable.data()}; -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; +ULONG __stdcall add_ref(Computer* c) { return c->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +ULONG __stdcall release(Computer* c) { + const ULONG left = c->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) delete c; + return left; +} + +// The mode a tail mip is reported in: the 256-byte one of its kind (3 for the render kind, which GFX10 lacks), the +// depth mode itself. +uint32_t tail_swizzle(uint32_t s) { + switch (s) { + case 2: case 6: case 10: case 18: case 22: case 26: return ct::kSw256bD; + case 23: case 27: return 3; + case 24: return s; + default: return ct::kSw256bS; + } +} + +MipOut mip_out(const ResourceDesc& desc, const ct::Layout& l, size_t i) { + const ct::Mip& m = l.mips[i]; + const uint64_t bpe = l.desc.element_bytes; + const uint32_t block = l.desc.block; + const bool three_d = desc.dimension == kTexture3d; + const uint32_t array = desc.depth_or_array ? desc.depth_or_array : 1u; + MipOut out{}; + out.pitch_texels = m.pitch * block; + out.pitch_bytes = m.pitch * l.desc.element_bytes; + out.padded[0] = m.pitch; + out.padded[1] = m.rows; + out.padded[2] = three_d ? m.depth_pitch : array; + out.elements[0] = m.width; + out.elements[1] = m.height; + const uint64_t w = desc.width >> i; + out.texels[0] = w ? static_cast(w) : 1u; + out.texels[1] = (desc.height >> i) ? (desc.height >> i) : 1u; + out.depth_or_array = three_d ? m.depth : array; + out.samples = l.desc.samples; + out.slice_depth = l.block[2]; + const uint64_t slice = uint64_t{m.pitch} * m.rows * bpe; + const uint64_t depth = three_d ? m.depth_pitch : 1u; + if (!m.tail) { + out.offset = m.offset; + out.slice_size = slice * l.desc.samples; + out.size = out.slice_size * depth; + out.alignment = static_cast(l.alignment); + out.swizzle = l.desc.swizzle; + } else { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if (l.thick) { // a 3D tail mip is placed by position, not by offset + out.slice_size = l.alignment / l.block[2]; + out.tail_position = m.tail->x | (m.tail->y << 11); + } else { + out.offset = m.tail->offset; + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + return out; } -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { +HRESULT __stdcall layout(Computer* c, LayoutOut* out) { + if (!out) return kInvalidArg; + std::memset(out, 0, sizeof(*out)); + out->size = c->texture.size; + out->alignment = c->texture.alignment; + out->mips = c->mips; + out->planes = static_cast(c->texture.planes.size()); + out->dimension = c->desc.dimension; + // The library calls a depth plane "depth" only beside stencil or without mips. + const bool depth = (c->desc.flags & kAllowDepthStencil) && (c->texture.planes.size() > 1 || c->mips == 1); + for (size_t p = 0; p < c->texture.planes.size() && p < 4; ++p) { + const ct::Plane& src = c->texture.planes[p]; + const ct::Layout& l = src.layout; + PlaneOut& plane = out->plane[p]; + plane.usage = src.stencil ? 8u : depth ? 7u : 1u; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = src.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c->mips - l.first_tail_mip; + for (size_t i = 0; i < l.mips.size() && i < kMips; ++i) plane.mips[i] = mip_out(c->desc, l, i); + } + return S_OK; +} + +// The plane, its mip and array slice for a subresource index, and the tiled bytes and the linear bytes a copy touches. +struct CopyArgs { + const ct::Plane* plane; + uint32_t mip, slice; + size_t tiled, linear; +}; + +std::optional copy_args(const Computer* c, uint32_t plane, uint32_t subresource, uint32_t row, + uint32_t depth) { + if (plane >= c->texture.planes.size() || c->mips == 0) return std::nullopt; + const ct::Plane& p = c->texture.planes[plane]; + const ct::Layout& l = p.layout; + const uint32_t mip = subresource % c->mips, slice = subresource / c->mips; + if (mip >= l.mips.size()) return std::nullopt; + const ct::Mip& m = l.mips[mip]; + const uint64_t bytes = uint64_t{m.width} * l.desc.element_bytes; + const uint64_t depths = l.subresource_depth(mip); + // Every factor is at most 2^32, so each product fits in 64 bits; the sum is checked against size_t below. + const uint64_t linear = (depths - 1) * depth + uint64_t{m.height - 1} * row + bytes; + const uint64_t tiled = p.offset + l.size; + if (linear > std::numeric_limits::max() || tiled > std::numeric_limits::max()) + return std::nullopt; + return CopyArgs{&p, mip, slice, static_cast(tiled), static_cast(linear)}; +} + +HRESULT result(ct::Error e) { + switch (e) { + case ct::Error::ok: return S_OK; + case ct::Error::unsupported: return kNotImpl; + default: return kInvalidArg; + } +} + +void warn_copy(const Computer* c, const char* what, uint32_t subresource, ct::Error e) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) >= 8) return; + std::fprintf(stderr, + "[rt] xg_xs: %s subresource %u failed (%s): dim=%u %llux%u depth/array=%u mips=%u format=%u " + "layout=0x%x\n", + what, subresource, + e == ct::Error::unsupported ? "addressing not modelled" : e == ct::Error::too_small ? "too small" + : "invalid", + c->desc.dimension, static_cast(c->desc.width), c->desc.height, + c->desc.depth_or_array, c->desc.mips, c->desc.format, c->desc.layout); +} + +// (tiled base, plane, subresource, linear, row pitch, depth pitch). +HRESULT __stdcall copy_into(Computer* c, uint8_t* tiled, uint32_t plane, uint32_t subresource, const uint8_t* linear, + uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.tile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy into", subresource, e); + return result(e); +} + +// (linear, plane, subresource, sample, tiled base, row pitch, depth pitch). +HRESULT __stdcall copy_from(Computer* c, uint8_t* linear, uint32_t plane, uint32_t subresource, uint32_t /*sample*/, + const uint8_t* tiled, uint32_t row, uint32_t depth) { + const auto a = copy_args(c, plane, subresource, row, depth); + if (!a || !tiled || !linear) return kInvalidArg; + const size_t offset = static_cast(a->plane->offset); + const ct::Error e = a->plane->layout.detile(tiled + offset, a->tiled - offset, a->mip, a->slice, linear, a->linear, + row, depth); + if (e != ct::Error::ok) warn_copy(c, "copy out of", subresource, e); + return result(e); +} + +// (total tiles, packed mips, tile shape in texels, in: room / out: count, first, subresource tilings), in 64 KiB +// tiles of plane 0, for 2D 64 KiB modes only (others fail, as on the console). The mip tail is the packed part, tile 0 +// of each slice; tilings list the standard mips of every slice in turn. With a tail the console's library lists two +// slices at most and zeroes all but the first (VIctory's reading; the title reads slice 0 only). +HRESULT __stdcall tiling(Computer* c, uint32_t* tiles, PackedMips* packed, uint32_t* shape, uint32_t* count, + uint32_t first, SubresourceTiling* out) { + const ct::Layout& l = c->texture.planes[0].layout; + if (l.alignment != kTile) return kFail; + if (l.thick) return kNotImpl; + const uint32_t standard = l.first_tail_mip; + const bool tail = standard < c->mips; + const uint64_t tail_tiles = standard == 0 ? l.slice_size / kTile + : tail ? l.mips[standard - 1].offset / kTile + : 0; + const uint32_t block = l.desc.block; + if (tiles) *tiles = static_cast(l.size / kTile); + if (packed) { + packed->standard = static_cast(standard); + packed->packed = static_cast(c->mips - standard); + packed->tiles = static_cast(tail_tiles); + packed->start = 0; + } + if (shape) { + shape[0] = l.block[0] * block; + shape[1] = l.block[1] * block; + shape[2] = l.block[2]; + } + if (count) { + const uint32_t slices = tail ? std::min(l.slices, 2u) : l.slices; + const uint64_t total = uint64_t{standard} * slices; + const uint32_t wanted = + static_cast(std::min(total > first ? total - first : 0, *count)); + for (uint32_t i = 0; i < wanted && out; ++i) { + const uint32_t slice = (first + i) / standard, mip = (first + i) % standard; + const ct::Mip& m = l.mips[mip]; + SubresourceTiling entry{}; + if (!(tail && slice > 0)) { + entry.width = m.pitch / l.block[0]; + entry.height = static_cast(m.rows / l.block[1]); + entry.depth = 1; + entry.start = static_cast((uint64_t{slice} * l.slice_size + m.offset) / kTile); + } + out[i] = entry; + } + *count = out ? wanted : 0; + } + return S_OK; +} + +// (plane, mip, x, y, z or slice, sample, bit position): an element's byte offset from the texture's start, 0 if +// outside. VIctory measured the title reading texels of a 128x4 4KB_S texture on the CPU through it. +uint64_t __stdcall element_offset(Computer* c, uint32_t plane, uint32_t mip, uint64_t x, uint32_t y, uint32_t z, + uint32_t /*sample*/, uint32_t* bit) { + if (bit) *bit = 0; + if (plane >= c->texture.planes.size()) return 0; + const ct::Plane& p = c->texture.planes[plane]; + const uint32_t x32 = x > std::numeric_limits::max() ? std::numeric_limits::max() + : static_cast(x); + uint64_t at = 0; + if (p.layout.offset(mip, x32, y, z, at) != ct::Error::ok) return 0; + return p.offset + at; +} + +template +HRESULT __stdcall unused_slot(Computer*) { static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); + warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress(), + "method not implemented; E_NOTIMPL"); return kNotImpl; } +template +constexpr auto make_vtable(std::index_sequence) { + return std::array{ + (Slot == 0 ? reinterpret_cast(&add_ref) + : Slot == 1 ? reinterpret_cast(&release) + : Slot == 2 ? reinterpret_cast(&layout) + : Slot == 6 ? reinterpret_cast(&element_offset) + : Slot == 8 ? reinterpret_cast(©_into) + : Slot == 9 ? reinterpret_cast(©_from) + : Slot == 10 ? reinterpret_cast(&tiling) + : reinterpret_cast(&unused_slot))...}; +} +const auto kVtable = make_vtable(std::make_index_sequence{}); + +HRESULT __stdcall XGCreateTextureComputer(const ResourceDesc* desc, void** out) { + if (!out) return E_POINTER; + std::optional texture; + if (desc) texture = texture_of(*desc); + if (!texture) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) < 8) { + if (desc) + std::fprintf(stderr, + "[rt] xg_xs: XGCreateTextureComputer: no layout for dim=%u %llux%u depth/array=%u " + "mips=%u format=%u samples=%u layout=0x%x flags=0x%x (caller %s)\n", + desc->dimension, static_cast(desc->width), desc->height, + desc->depth_or_array, desc->mips, desc->format, desc->samples, desc->layout, + desc->flags, + rt::shims::module_offset(reinterpret_cast(_ReturnAddress())).c_str()); + else + std::fprintf(stderr, "[rt] xg_xs: XGCreateTextureComputer: null description\n"); + } + *out = &g_stub; // see the top of the file: two measured callers use *out without checking the HRESULT + return kInvalidArg; + } + auto* c = new (std::nothrow) Computer; + if (!c) { + *out = &g_stub; + return E_OUTOFMEMORY; + } + c->vtable = kVtable.data(); + c->desc = *desc; + c->mips = static_cast(texture->planes[0].layout.mips.size()); + c->texture = std::move(*texture); + *out = c; + return S_OK; +} + +// (desc, flags, out layout); the title passes flags 0 and puts the result in the description's layout field. +HRESULT __stdcall XGSuggestSwizzleMode(const ResourceDesc* desc, uint32_t /*flags*/, uint32_t* mode) { + if (!desc || !mode) return kInvalidArg; + *mode = kSwizzled | suggested(*desc); + return S_OK; +} + } // namespace SHIM_TABLE(xg_xs, diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index cc7a91d21..7aa100035 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -27,6 +27,7 @@ // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. #include +#include #include #include @@ -593,6 +594,36 @@ const GUID kAccessibilityInterfaces[] = { {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}, // IXAccessibilityImpl2 }; +// Forward the speech family to the +// operating system's installed runtime. Other offline services keep their existing providers. +struct HostSpeechProvider { + HMODULE module=nullptr; + IUnknown* base=nullptr; + IUnknown* extended=nullptr; + HostSpeechProvider() { + char enabled[4]{}; + if(GetEnvironmentVariableA("LEONIDA_LOCAL_SPEECH",enabled,sizeof(enabled))!=1 || enabled[0]!='1') return; + module=LoadLibraryExW(L"xgameruntime.dll",nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32); + if(!module)return; + using Query=HRESULT (WINAPI*)(const GUID*,REFIID,void**); + auto query=reinterpret_cast(GetProcAddress(module,"QueryApiImpl")); + if(!query)return; + (void)query(&kAccessibilityClass,kAccessibilityInterfaces[0],reinterpret_cast(&base)); + (void)query(&kAccessibilityClass,kAccessibilityInterfaces[1],reinterpret_cast(&extended)); + } + ~HostSpeechProvider(){if(extended)extended->Release();if(base)base->Release();if(module)FreeLibrary(module);} +}; +HostSpeechProvider& host_speech_provider(){static HostSpeechProvider host;return host;} +template +bool call_host_speech(HRESULT& result,Args... args) { + auto& host=host_speech_provider(); + auto* obj=Slot==21?host.extended:host.base; + if(!obj)return false; + using Method=HRESULT (STDMETHODCALLTYPE*)(IUnknown*,Args...); + auto fn=reinterpret_cast((*reinterpret_cast(obj))[Slot]); + result=fn(obj,args...); + return true; +} // 5: HRESULT XHighContrastGetMode(XHighContrastMode* mode): Off, the first enumerator. ASSUMPTION: the signature and // that Off is 0 (GDK reference, not re-checked for this file). HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) { @@ -606,34 +637,48 @@ HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { retu // 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the // callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. -HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { +HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void* context) { + HRESULT hr; if(callback && call_host_speech<8>(hr,callback,context))return hr; return callback ? S_OK : E_INVALIDARG; } // 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { + if(!handle)return E_POINTER; *handle=nullptr; + HRESULT hr; if(call_host_speech<9>(hr,handle))return hr; if (handle) *handle = nullptr; return offline_failure(self); } // 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. -HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } +template HRESULT STDMETHODCALLTYPE speech_handle_call(void*,void* handle) { + if(!handle)return E_INVALIDARG; + HRESULT hr;return call_host_speech(hr,handle)?hr:E_INVALIDARG; +} +HRESULT STDMETHODCALLTYPE speech_custom_voice(void*,void* handle,const char* voice) { + if(!handle||!voice)return E_INVALIDARG; + HRESULT hr;return call_host_speech<12>(hr,handle,voice)?hr:E_INVALIDARG; +} // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, // XSpeechSynthesizerStreamHandle* stream) -HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { +template HRESULT STDMETHODCALLTYPE speech_create_stream(void*,void* handle,const char* text,void** stream) { + if(stream)*stream=nullptr; + HRESULT hr;if(handle && text && stream && call_host_speech(hr,handle,text,stream))return hr; if (stream) *stream = nullptr; return E_INVALIDARG; } // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) -HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { +HRESULT STDMETHODCALLTYPE speech_stream_size(void*,void* stream,size_t* size) { + HRESULT hr;if(stream && size && call_host_speech<15>(hr,stream,size))return hr; if (size) *size = 0; return E_INVALIDARG; } // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) -HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { +HRESULT STDMETHODCALLTYPE speech_stream_data(void*,void* stream,size_t capacity,void* buffer,size_t* used) { + HRESULT hr;if(stream && buffer && used && call_host_speech<16>(hr,stream,capacity,buffer,used))return hr; if (used) *used = 0; return E_INVALIDARG; } @@ -654,18 +699,18 @@ const void* const kAccessibilityVtable[] = { FN(accessibility_offline<7>), // 7 XSpeechToTextSendString FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices FN(speech_create), // 9 XSpeechSynthesizerCreate - FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle - FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice - FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice - FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText - FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle + FN(speech_handle_call<10>), // 10 XSpeechSynthesizerCloseHandle + FN(speech_handle_call<11>), // 11 XSpeechSynthesizerSetDefaultVoice + FN(speech_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice + FN(speech_create_stream<13>), // 13 XSpeechSynthesizerCreateStreamFromText + FN(speech_handle_call<14>), // 14 XSpeechSynthesizerCloseStreamHandle FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString FN(accessibility_offline<18>), // 18 XSpeechToTextUpdateHypothesisString FN(accessibility_offline<19>), // 19 XSpeechToTextFinalizeHypothesisString FN(accessibility_offline<20>), // 20 XSpeechToTextCancelHypothesisString - FN(speech_create_stream), // 21 XSpeechSynthesizerCreateStreamFromSsml + FN(speech_create_stream<21>), // 21 XSpeechSynthesizerCreateStreamFromSsml }; static_assert(std::size(kAccessibilityVtable) == 22, "IUnknown + IXAccessibilityImpl's 19 methods"); ClassObject g_accessibility_object{kAccessibilityVtable}; diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index e8988c046..52368c2d8 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -14,11 +14,12 @@ // locally at a title's call sites (each function says which). The page functions are built on the Windows placeholder // APIs (VirtualAlloc2, MapViewOfFile3), whose flags the title's own XMemVirtualAlloc calls already use. #include +#include +#include #include #include #include -#include #include #include #include @@ -36,8 +37,9 @@ #include "shims.h" #include "startup_trace.h" -#include "../src/title_va_alias.h" #include "xmem.h" +#include "../src/gpu_label_memory.h" +#include "../src/title_va_alias.h" namespace { @@ -71,13 +73,21 @@ void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAli // Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader // address into it can be given a GPU copy, and an address anywhere else cannot. +void track_label_data(void* p,std::size_t bytes,bool heap) { + if(!p)return; MEMORY_BASIC_INFORMATION info{}; + if(VirtualQuery(p,&info,sizeof(info)) && info.Type==MEM_PRIVATE) + leonida::label::memory().track(reinterpret_cast(p),bytes,reinterpret_cast(info.AllocationBase),heap); +} + void* title_block(size_t size) { void* p = allocate_block(size); leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + track_label_data(p,size?size:1,true); return p; } void free_title_block(void* p) { + if(p)leonida::label::memory().release_heap(reinterpret_cast(p)); if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); _aligned_free(p); } @@ -252,12 +262,45 @@ struct Window { DWORD protect; }; +// A sparse temporary file gives large physical pools real shared pages without reserving their +// total size against the process's pagefile commitment. Views retain the section until the last alias dies. +HANDLE file_backed_section(std::uint64_t bytes) { + wchar_t dir[32768]{}; + const auto len = GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", dir, DWORD(std::size(dir))); + if (!len || len >= std::size(dir)) return nullptr; + const std::filesystem::path parent(dir); + if (!parent.is_absolute()) return nullptr; + static std::atomic sequence{}; + const auto name = L"physical-" + std::to_wstring(GetCurrentProcessId()) + L"-" + + std::to_wstring(GetTickCount64()) + L"-" + std::to_wstring(++sequence) + L".tmp"; + const HANDLE file = CreateFileW((parent / name).c_str(), GENERIC_READ | GENERIC_WRITE | DELETE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, + FILE_FLAG_DELETE_ON_CLOSE, nullptr); + if (file == INVALID_HANDLE_VALUE) { + return nullptr; + } + DWORD ignored{}; + LARGE_INTEGER size{}; + size.QuadPart = static_cast(bytes); + HANDLE section = nullptr; + if (DeviceIoControl(file, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &ignored, nullptr) && + SetFilePointerEx(file, size, nullptr, FILE_BEGIN) && SetEndOfFile(file)) + section = CreateFileMappingW(file, nullptr, PAGE_READWRITE, size.HighPart, size.LowPart, nullptr); + CloseHandle(file); + return section; +} + struct Section { HANDLE handle; - explicit Section(HANDLE h) : handle(h) {} + void* scratch; + bool file_backed; + Section(HANDLE h, bool use_file) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)), file_backed(use_file) {} Section(const Section&) = delete; Section& operator=(const Section&) = delete; - ~Section() { CloseHandle(handle); } + ~Section() { + if (scratch) UnmapViewOfFile(scratch); + CloseHandle(handle); + } }; struct PhysicalPage { @@ -277,16 +320,28 @@ std::map g_windows; // base -> window std::unordered_map g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; -// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run -// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the -// number of views, and the retail title maps about 100,000 pages in one call. -struct View { - uint64_t count; - std::shared_ptr
section; // kept for remapping part of the run after its pages are freed - uint64_t offset; // section offset of the first page - DWORD protect; +struct MappedPage { + uint64_t page; + std::shared_ptr
section; + uint64_t offset; +}; + +std::unordered_map g_mapped; +SRWLOCK g_fault_lock = SRWLOCK_INIT; + +struct FaultLockExclusive { + FaultLockExclusive() { AcquireSRWLockExclusive(&g_fault_lock); } + ~FaultLockExclusive() { ReleaseSRWLockExclusive(&g_fault_lock); } + FaultLockExclusive(const FaultLockExclusive&) = delete; + FaultLockExclusive& operator=(const FaultLockExclusive&) = delete; +}; + +struct FaultLockShared { + FaultLockShared() { AcquireSRWLockShared(&g_fault_lock); } + ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } + FaultLockShared(const FaultLockShared&) = delete; + FaultLockShared& operator=(const FaultLockShared&) = delete; }; -std::map g_views; // view base -> view // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. @@ -353,6 +408,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which // the copy also checks. if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + if(result)track_label_data(result,size,false); return result; } @@ -460,74 +516,19 @@ void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULON return VirtualAlloc(address, size, host_type, host_prot); } -// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER -// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one -// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a -// page inside a long run only remaps the rest of one capped view, not the whole run. -constexpr uint64_t kMaxViewPages = 1024; // 64 MiB - -bool map_view(uintptr_t address, const View& view) { - for (uint64_t mapped = 0; mapped < view.count;) { - const uintptr_t base = address + mapped * kPhysicalPageSize; - void* const target = reinterpret_cast(base); - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE || - info.RegionSize < kPhysicalPageSize) { - SetLastError(ERROR_INVALID_ADDRESS); - return false; - } - const uint64_t available = info.RegionSize / kPhysicalPageSize; - const uint64_t remaining = view.count - mapped; - const uint64_t count = (std::min)({available, remaining, kMaxViewPages}); - const SIZE_T size = static_cast(count * kPhysicalPageSize); - const uint64_t offset = view.offset + mapped * kPhysicalPageSize; - if (!isolate_placeholder(target, size)) return false; - if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size, - MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) { - return false; - } - g_views.emplace(base, View{count, view.section, offset, view.protect}); - mapped += count; - } - return true; -} - -// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that -// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep -// their pages. -bool unmap_range(uintptr_t start, uintptr_t end) { - auto it = g_views.upper_bound(start); - if (it != g_views.begin()) { - const auto prev = std::prev(it); - if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev; - } - while (it != g_views.end() && it->first < end) { - const uintptr_t base = it->first; - const View view = it->second; - const uintptr_t view_end = base + view.count * kPhysicalPageSize; - if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(base), - MEM_PRESERVE_PLACEHOLDER)) { - return false; - } - it = g_views.erase(it); - if (base < start) { - View left = view; - left.count = (start - base) / kPhysicalPageSize; - if (!map_view(base, left)) return false; - } - if (view_end > end) { - const uint64_t skipped = (end - base) / kPhysicalPageSize; - View right = view; - right.count = view.count - skipped; - right.offset += skipped * kPhysicalPageSize; - return map_view(end, right); // the last view the range touches - } +// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. +bool unmap_page(uintptr_t address) { + const FaultLockExclusive lock; + const auto it = g_mapped.find(address); + if (it == g_mapped.end()) return true; + if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), + MEM_PRESERVE_PLACEHOLDER)) { + return false; } + g_mapped.erase(it); return true; } -bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } - // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was // mapped there. The caller has found the window. bool map_page(uintptr_t address, uint64_t page, DWORD protect) { @@ -538,7 +539,81 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - return map_view(address, View{1, it->second.section, it->second.offset, protect}); + void* const target = reinterpret_cast(address); + if (!isolate_placeholder(target, kPhysicalPageSize)) return false; + const FaultLockExclusive lock; + void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, + it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, + protect, nullptr, 0); + if (!view) return false; + g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; + return true; +} + +enum class PageCommit { not_ours, committed_before, committed_now, failed }; + +PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { + const auto it = g_mapped.find(address); + if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { + return PageCommit::not_ours; + } + if (info.State == MEM_COMMIT) { + protect = info.Protect; + return PageCommit::committed_before; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now + : PageCommit::failed; +} + +bool access_allowed(DWORD protect, ULONG_PTR access) { + if (protect & PAGE_GUARD) return false; + switch (protect & 0xff) { + case PAGE_EXECUTE_READWRITE: + case PAGE_EXECUTE_WRITECOPY: + return true; + case PAGE_READWRITE: + case PAGE_WRITECOPY: + return access != 8; + case PAGE_EXECUTE_READ: + return access != 1; + case PAGE_READONLY: + return access == 0; + case PAGE_EXECUTE: + return access == 8; + default: + return false; + } +} + +LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { + thread_local bool busy = false; + const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; + if (busy || !record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) { + return EXCEPTION_CONTINUE_SEARCH; + } + busy = true; + const uintptr_t accessed = static_cast(record->ExceptionInformation[1]); + const uintptr_t address = accessed & ~static_cast(kPhysicalPageSize - 1); + DWORD protect = 0; + PageCommit result; + { + const FaultLockShared lock; + result = commit_mapped_page(address, accessed, protect); + } + busy = false; + if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; + if (result == PageCommit::committed_before && access_allowed(protect, record->ExceptionInformation[0])) { + return EXCEPTION_CONTINUE_EXECUTION; + } + return EXCEPTION_CONTINUE_SEARCH; +} + +bool install_physical_page_fault_handler() { + static const bool installed = AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; + return installed; } // Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still @@ -576,7 +651,7 @@ void note_physical_attributes(uint64_t attributes, uint64_t count, const void* c // a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they // differ, so the count is in/out. // -// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical +// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) on touch, given physical // memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can // be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded; // every page is 64 KiB, which all four callers' arithmetic agrees with. @@ -595,14 +670,25 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } + if (!install_physical_page_fault_handler()) { + *page_count = 0; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 - const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT, + HANDLE handle = file_backed_section(bytes); + const bool use_file = handle != nullptr; + if (!handle) handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, static_cast(bytes >> 32), static_cast(bytes), nullptr); if (!handle) { *page_count = 0; return FALSE; } - const auto section = std::make_shared
(handle); + const auto section = std::make_shared
(handle, use_file); + if (!section->scratch) { + *page_count = 0; + return FALSE; + } for (uint64_t i = 0; i < count; ++i) { uint64_t slot; if (!g_free_slots.empty()) { @@ -645,9 +731,8 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on // success. A page number of 0 in the array unmaps that one page. // -// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a -// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a -// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. +// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later +// without touching its neighbours. A failure part-way leaves the pages before it mapped. void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { const uintptr_t start = reinterpret_cast(address); if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || @@ -660,36 +745,20 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint return nullptr; } const std::lock_guard lock(g_phys_mutex); - const uintptr_t end = start + page_count * kPhysicalPageSize; - if (!page_array) return unmap_range(start, end) ? address : nullptr; + if (!page_array) { + for (uint64_t i = 0; i < page_count; ++i) { + if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; + } + return address; + } const Window* const window = find_window(start, page_count * kPhysicalPageSize); if (!window) { SetLastError(ERROR_INVALID_ADDRESS); return nullptr; } const DWORD protect = view_protect(*window); - if (!unmap_range(start, end)) return nullptr; - for (uint64_t i = 0; i < page_count;) { - if (page_array[i] == 0) { - ++i; - continue; - } - const auto it = g_pages.find(page_array[i]); - if (it == g_pages.end()) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - View view{1, it->second.section, it->second.offset, protect}; - while (i + view.count < page_count) { - const auto next = g_pages.find(page_array[i + view.count]); - if (next == g_pages.end() || next->second.section != view.section || - next->second.offset != view.offset + view.count * kPhysicalPageSize) { - break; - } - ++view.count; - } - if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; - i += view.count; + for (uint64_t i = 0; i < page_count; ++i) { + if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; } return address; } @@ -794,9 +863,26 @@ BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; +BOOL WINAPI TitleVirtualFree(LPVOID address,SIZE_T size,DWORD flags) { + DWORD saved=0; + const bool ok=leonida::label::memory().release_pages(reinterpret_cast(address),size,(flags&MEM_RELEASE)!=0,[&]{ + const BOOL r=::VirtualFree(address,size,flags);saved=GetLastError();return !!r; + }); + SetLastError(saved);return ok?TRUE:FALSE; +} +BOOL WINAPI TitleVirtualFreeEx(HANDLE process,LPVOID address,SIZE_T size,DWORD flags) { + if(GetProcessId(process)!=GetCurrentProcessId())return ::VirtualFreeEx(process,address,size,flags); + DWORD saved=0; + const bool ok=leonida::label::memory().release_pages(reinterpret_cast(address),size,(flags&MEM_RELEASE)!=0,[&]{ + const BOOL r=::VirtualFreeEx(process,address,size,flags);saved=GetLastError();return !!r; + }); + SetLastError(saved);return ok?TRUE:FALSE; +} + LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + if(result)track_label_data(result,size,false); return result; } @@ -804,35 +890,85 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty namespace rt::xmem { -// main's xmem commits physical pages on first touch and exposes these two for code that must see them committed -// (slot 133's import, d3d12_xmem_placed_test). Here a physical page is committed when it is allocated, so there is -// nothing to do: the range only has to be mapped, readable memory, and the page array non-null. -bool commit_physical_range(const void* address, std::size_t size) { +bool commit_physical_range(const void* address, size_t size) { if (size == 0) return true; - const auto* at = static_cast(address); - const auto* const end = at + size; - while (at < end) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(at, &info, sizeof(info)) || info.State != MEM_COMMIT) { - SetLastError(ERROR_INVALID_ADDRESS); - return false; - } - at = static_cast(info.BaseAddress) + info.RegionSize; + const uintptr_t start = reinterpret_cast(address); + if (start > (std::numeric_limits::max)() - (size - 1)) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + const uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); + const uintptr_t first = start & mask; + const uintptr_t pages = (((start + (size - 1)) & mask) - first) / kPhysicalPageSize + 1; + const FaultLockShared lock; + for (uintptr_t i = 0; i < pages; ++i) { + DWORD protect = 0; + const uintptr_t page = first + i * kPhysicalPageSize; + if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; } return true; } -bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count) { - if (count && !page_array) { +std::shared_ptr pin_mapped_data(const void* address, std::size_t size) { + const auto start = reinterpret_cast(address); + if (!size || !start || size > UINTPTR_MAX - start) return {}; + const auto end = start + size; + const auto first = start & ~std::uintptr_t(kPhysicalPageSize - 1); + const FaultLockShared lock; + const auto base = g_mapped.find(first); + if (base == g_mapped.end() || !base->second.section || !base->second.section->scratch) return {}; + const auto section = base->second.section; + const auto offset = base->second.offset; + for (auto page=first; pagesecond.section != section || it->second.offset != offset+page-first) return {}; + DWORD previous{}; + const auto ready = commit_mapped_page(page, std::max(page,start), previous); + if (ready!=PageCommit::committed_before && ready!=PageCommit::committed_now) return {}; + } + for (auto at=start; at(at), &info, sizeof(info)) || + info.Type!=MEM_MAPPED || info.State!=MEM_COMMIT || (info.Protect & (PAGE_NOACCESS|PAGE_GUARD)) || + ((info.Protect & 255)!=PAGE_READWRITE && (info.Protect & 255)!=PAGE_WRITECOPY)) return {}; + at=reinterpret_cast(info.BaseAddress)+info.RegionSize; + } + return {section,static_cast(section->scratch)+offset+(start-first)}; +} + +bool commit_physical_pages(const uint64_t* page_array, size_t count) { + if (count == 0) return true; + if (!page_array) { SetLastError(ERROR_INVALID_PARAMETER); return false; } + const std::lock_guard lock(g_phys_mutex); + size_t first = 0; + while (first < count) { + const auto it = g_pages.find(page_array[first]); + if (it == g_pages.end() || !it->second.section->scratch) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + size_t last = first + 1; + while (last < count) { + const auto next = g_pages.find(page_array[last]); + if (next == g_pages.end() || next->second.section != it->second.section || + next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { + break; + } + ++last; + } + void* const backing = static_cast(it->second.section->scratch) + it->second.offset; + if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; + first = last; + } return true; } -} // namespace rt::xmem +} -#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} +#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)}, {dll,"VirtualFree",reinterpret_cast(&TitleVirtualFree)}, {dll,"VirtualFreeEx",reinterpret_cast(&TitleVirtualFreeEx)} // The classic libraries and the memory api sets a title's imports name. SHIM_TABLE(title_memory, diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index beef935e6..45c422841 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -2,10 +2,13 @@ #include #include +#include namespace rt::xmem { bool commit_physical_range(const void* address, std::size_t size); +// A lifetime-pinned alias of a contiguous range of the title's writable mapped physical pages. +std::shared_ptr pin_mapped_data(const void* address, std::size_t size); bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); } diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 595110f36..3e89e1cff 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -1,4 +1,5 @@ #pragma once +#include "gpu_label_memory.h" // The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until // ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and @@ -517,6 +518,7 @@ struct UavView { std::uint32_t mip; // texture std::uint32_t first_layer; std::uint32_t layer_count; + bool exact_clear_format = false; // newly exposed 1D/3D UAVs: do not clear via a different backing format }; // ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are @@ -657,7 +659,7 @@ struct AccelerationStructurePostbuild { using Command = std::variant; @@ -786,6 +788,11 @@ public: } // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes. + bool write_gpu_label(const label::Write& write) { + if(write.target.owner.expired() || write.clock>2) return false; + return append(write); + } + bool write_immediate(const WriteImmediate& write) { if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false; return append(write); diff --git a/runtime/src/console_texture_layout.h b/runtime/src/console_texture_layout.h new file mode 100644 index 000000000..782d8584a --- /dev/null +++ b/runtime/src/console_texture_layout.h @@ -0,0 +1,610 @@ +// Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and alignment, where each mip and array slice +// starts, the address of each element, and copies between tiled memory and linear rows. Used by the xg_xs.dll shim +// (runtime/shims/xg_xs.cpp), whose texture computer answers the title's layout and copy calls from it. +// +// Ported from Marvisak/VIctory (GPL-3.0), crates/victory-formats/src/texture.rs at commit d2a4bae1f, which follows +// AMD's address library (addrlib) as shipped in Mesa under src/amd/addrlib: block dimensions, mip placement and mip +// tails from gfx10addrlib.cpp and addrlib2.cpp (ComputeSurfaceInfoMacroTiled, ComputeThinBlockDimension, +// GetMipTailDim, GetMaxNumMipsInTail, HwlComputeSurfaceInfoLinear, ComputeSurfaceAddrFromCoordMacroTiled), and the +// 256-byte micro tile patterns in kMicro from gfx10SwizzlePattern.h (the RB+ tables, as on RDNA2). addrlib carries +// this notice: +// +// Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +// SPDX-License-Identifier: MIT +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +// documentation files (the "Software"), to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and +// to permit persons to whom the Software is furnished to do so, subject to the following conditions: the above +// copyright notice and this permission notice shall be included in all copies or substantial portions of the +// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. +// +// Units: an element is a texel, or a 4x4 block of a block-compressed format. Mips of one array slice (or one depth +// slab of a thick 3D texture) are stored together, smallest first: the mip tail (the small mips sharing one block) +// at offset 0, mip 0 last. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::console_texture { + +// A swizzle mode, by its hardware number (addrlib's ADDR_SW_* order). +enum : uint32_t { + kLinear = 0, + kSw256bS = 1, + kSw256bD = 2, + kSw4kbS = 5, + kSw4kbD = 6, + kSw64kbS = 9, + kSw64kbD = 10, + kSw64kbST = 17, + kSw64kbDT = 18, + kSw4kbSX = 21, + kSw4kbDX = 22, + kSw4kbRX = 23, + kSw64kbZX = 24, + kSw64kbSX = 25, + kSw64kbDX = 26, + kSw64kbRX = 27, +}; + +// log2 of the block size in bytes (0 for linear); nullopt for modes GFX10 does not have. +inline std::optional block_log2(uint32_t swizzle) { + switch (swizzle) { + case 0: return 0; + case 1: case 2: return 8; + case 5: case 6: case 21: case 22: case 23: return 12; + case 9: case 10: case 17: case 18: case 24: case 25: case 26: case 27: return 16; + default: return std::nullopt; + } +} +inline bool is_standard(uint32_t s) { return s == 1 || s == 5 || s == 9 || s == 17 || s == 21 || s == 25; } +inline bool is_display(uint32_t s) { return s == 2 || s == 6 || s == 10 || s == 18 || s == 22 || s == 26; } +inline bool is_z_order(uint32_t s) { return s == 24; } +// Pipe and bank XOR modes (_T, _X): their addresses depend on the GPU's pipe configuration. +inline bool is_xor(uint32_t s) { return s >= 16; } + +enum class Dimension { tex1d, tex2d, tex3d }; + +enum class Error { + ok, + invalid, // the description makes no texture, or a coordinate or subresource lies outside it + unsupported, // a valid layout whose addressing is not implemented here + too_small, // a buffer is smaller than the layout or the rows need +}; + +// One plane of a texture. +struct Desc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; + uint32_t element_bytes = 4; // 1, 2, 4, 8 or 16 + uint32_t block = 1; // texels per element side: 1, or 4 for block compression + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Tail { + uint32_t offset = 0; // byte offset inside the tail block + uint32_t x = 0, y = 0; // element position the mip starts at +}; + +// Where one mip lives inside a slice. +struct Mip { + uint32_t width = 0, height = 0, depth = 0; // size in elements (depth 1 unless the texture is 3D) + uint32_t pitch = 0, rows = 0, depth_pitch = 0; // padded size in elements: whole blocks, or the tail's share + uint64_t offset = 0; // byte offset of its first block in the slice (0 in the tail) + std::optional tail; +}; + +namespace detail { + +constexpr uint32_t div_ceil(uint32_t a, uint32_t b) { return (a + b - 1) / b; } +constexpr uint32_t round_up(uint32_t a, uint32_t b) { return div_ceil(a, b) * b; } + +// Elements along one side of mip `mip`, as data and copies see it: texels halve rounding down (to at least 1), then +// round up to whole elements. +constexpr uint32_t dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(std::max(texels >> mip, 1u), block); +} +// Elements along one side of mip `mip` for placement (padding, tail, offsets): addrlib halves mip 0's elements +// rounding up, which can be one more than dim() for odd sizes. +constexpr uint32_t padded_dim(uint32_t texels, uint32_t mip, uint32_t block) { + return div_ceil(div_ceil(std::max(texels, 1u), block), 1u << mip); +} + +// Micro tile (256 bytes) patterns by log2 of the element size: for each address bit, the element coordinate bit it +// takes (x0, y1, z0...), "--" for the bits inside an element. Thin S, thin D, thick S (also the D 3D modes). From +// addrlib's GFX10_SW_256_S_RBPLUS, GFX10_SW_256_D_RBPLUS and GFX10_SW_4K_S3_RBPLUS patterns; the larger blocks add +// bits Y, X (thin) or Y, X, Z (thick) in turn. +inline constexpr const char* kMicro[3][5] = { + {"x0x1x2x3y0y1y2y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1y2x2", "------x0y0y1x1x2", "--------y0y1x0x1"}, + {"x0x1x2y1y0y2x3y3", "--x0x1x2y0y1y2x3", "----x0x1y0y1x2y2", "------x0y0x1x2y1", "--------x0y0x1y1"}, + {"x0x1z0y0z1y1x2z2", "--x0z0y0z1y1x1z2", "----x0y0z0y1x1z1", "------x0z0y0x1z1", "--------z0y0x0z1"}, +}; + +// For each axis, the address bit each coordinate bit lands on. +inline std::array, 3> pattern(int kind, uint32_t element_log2, uint32_t block_log2) { + std::array, 3> axes; + const char* micro = kMicro[kind][element_log2]; + for (uint32_t bit = 0; bit < 8; ++bit) { + const char a = micro[2 * bit]; + const int axis = a == 'x' ? 0 : a == 'y' ? 1 : a == 'z' ? 2 : -1; + if (axis < 0) continue; + const size_t index = static_cast(micro[2 * bit + 1] - '0'); + auto& to = axes[static_cast(axis)]; + if (to.size() <= index) to.resize(index + 1, 0); + to[index] = bit; + } + static constexpr int kThin[2] = {1, 0}; + static constexpr int kThick[3] = {1, 0, 2}; + const int* order = kind == 2 ? kThick : kThin; + const uint32_t n = kind == 2 ? 3u : 2u; + for (uint32_t bit = 8, i = 0; bit < block_log2; ++bit, ++i) axes[static_cast(order[i % n])].push_back(bit); + return axes; +} + +// Byte offsets inside a block for coordinates 0..2^bits of one axis. +inline std::vector spread(const std::vector& bits) { + std::vector out(size_t{1} << bits.size()); + for (uint32_t c = 0; c < out.size(); ++c) { + uint32_t v = 0; + for (size_t i = 0; i < bits.size(); ++i) v |= ((c >> i) & 1u) << bits[i]; + out[c] = v; + } + return out; +} + +} // namespace detail + +constexpr uint32_t kMaxMips = 16; +// The largest width, height and depth (or array size) accepted, in texels. GFX10's image descriptors hold at most +// 16384 texels per side, so no texture the GPU can use is refused. The bound also keeps every size computed below +// within uint64_t (and its uint32_t steps), which unchecked values from a title would otherwise overflow. +constexpr uint32_t kMaxExtent = 1u << 14; + +// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +inline constexpr uint32_t kBlock256_2d[5][2] = {{16, 16}, {16, 8}, {8, 8}, {8, 4}, {4, 4}}; +inline constexpr uint32_t kBlock256_3d[5][3] = {{8, 4, 8}, {4, 4, 8}, {4, 4, 4}, {4, 2, 4}, {2, 2, 4}}; +inline constexpr uint32_t kBlock1k_3d[5][3] = {{16, 8, 8}, {8, 8, 8}, {8, 8, 4}, {8, 4, 4}, {4, 4, 4}}; + +class Layout { +public: + Desc desc; + std::array block{}; // block dimensions in elements (linear: the pitch alignment, 1, 1) + bool thick = false; // 3D blocks span block[2] depth slices (GFX10 3D S and D modes) + // Array slices, depth slabs of block[2] slices (thick), or depth slices (thin and linear 3D). + uint32_t slices = 0; + uint64_t slice_size = 0; // bytes of one slice: its whole mip chain + uint64_t size = 0; + uint64_t alignment = 0; + uint32_t first_tail_mip = 0; // the first mip in the tail; mips.size() without one + std::vector mips; + + static std::optional make(const Desc& d) { + const auto log2 = block_log2(d.swizzle); + if (!log2) return std::nullopt; + const auto in = [](uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; }; + const bool valid = + in(d.width, 1, kMaxExtent) && in(d.height, 1, kMaxExtent) && in(d.depth, 1, kMaxExtent) && + in(d.mips, 1, kMaxMips) && std::has_single_bit(d.element_bytes) && d.element_bytes <= 16 && + (d.block == 1 || d.block == 4) && std::has_single_bit(d.samples) && d.samples <= 8 && + (d.samples == 1 || (d.dimension == Dimension::tex2d && d.mips == 1)) && + (d.dimension != Dimension::tex1d || d.height == 1) && + (d.dimension != Dimension::tex3d || d.swizzle == 0 || d.swizzle == 5 || d.swizzle == 9 || + d.swizzle == 17 || d.swizzle == 21 || (d.swizzle >= 24 && d.swizzle <= 27)); + if (!valid) return std::nullopt; + return *log2 == 0 ? linear(d) : tiled(d, *log2); + } + + // Whether offset() and the copies work for this layout: linear and the modes without pipe or bank XOR, + // single-sampled. The XOR modes (_X, _T) and MSAA need the GPU's pipe and bank configuration (Series X and S + // differ); titles use them for render targets and depth, which the host renders. + bool addressable() const { return desc.swizzle == kLinear || !pattern_[0].empty(); } + + // Depth slices a subresource of mip `mip` covers: the mip's depth for 3D textures, else 1 (one array slice). + uint32_t subresource_depth(uint32_t mip) const { return mip < mips.size() ? mips[mip].depth : 0; } + + // Byte offset of element (x, y) of mip `mip` in array slice or depth slice `z`. Coordinates must lie inside. + Error offset(uint32_t mip, uint32_t x, uint32_t y, uint32_t z, uint64_t& out) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = desc.dimension == Dimension::tex3d ? m.depth : slices; + const bool inside = x < m.width && y < m.height && z < depth; + if (!inside) return Error::invalid; + if (!addressable()) return Error::unsupported; + const auto [slice, inner] = split(z); + const uint64_t base = uint64_t{slice} * slice_size + m.offset; + if (desc.swizzle == kLinear) { + out = base + (uint64_t{y} * m.pitch + x) * desc.element_bytes; + return Error::ok; + } + out = base + row(m, y, inner) + column(m, x); + return Error::ok; + } + + // Copies one subresource out of tiled memory (the whole texture, `size` bytes) into linear rows: mip `mip` of + // array slice `slice` (3D: every depth slice of the mip, slice 0). Rows are row_pitch bytes apart, depth slices + // depth_pitch. + Error detile(const uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(linear + l, tiled + t, n); + }); + } + // The reverse of detile(): linear rows into tiled memory. + Error tile(uint8_t* tiled, size_t tiled_len, uint32_t mip, uint32_t slice, const uint8_t* linear, + size_t linear_len, size_t row_pitch, size_t depth_pitch) const { + return walk(tiled_len, mip, slice, linear_len, row_pitch, depth_pitch, [&](size_t t, size_t l, size_t n) { + std::memcpy(tiled + t, linear + l, n); + }); + } + + // Byte offsets inside a block of each element coordinate bit, per axis; empty for linear and XOR/MSAA modes. + const std::array, 3>& pattern() const { return pattern_; } + +private: + std::array, 3> pattern_; + + // HwlComputeSurfaceInfoLinear: rows aligned to 256 bytes, mips packed smallest first, a 3D texture's depth slices + // each hold the chain. + static Layout linear(const Desc& d) { + using namespace detail; + Layout l; + l.desc = d; + const uint64_t bpe = d.element_bytes; + const uint32_t align = 256 / d.element_bytes; + const bool three_d = d.dimension == Dimension::tex3d; + uint64_t offset = 0; + for (uint32_t i = d.mips; i-- > 0;) { + const uint32_t h = padded_dim(d.height, i, d.block); + const uint32_t pitch = round_up(padded_dim(d.width, i, d.block), align); + Mip m; + m.width = dim(d.width, i, d.block); + m.height = dim(d.height, i, d.block); + m.depth = three_d ? dim(d.depth, i, 1) : 1; + m.pitch = pitch; + m.rows = h; + m.depth_pitch = three_d ? d.depth : 1; + m.offset = offset; + l.mips.push_back(m); + offset += uint64_t{pitch} * h * bpe; + } + std::reverse(l.mips.begin(), l.mips.end()); + l.block = {align, 1, 1}; + l.slices = d.depth; + l.slice_size = offset; + l.size = offset * d.depth; + l.alignment = 256; + l.first_tail_mip = d.mips; + return l; + } + + static Layout tiled(const Desc& d, uint32_t block_log2) { + using namespace detail; + Layout l; + l.desc = d; + const uint32_t element_log2 = static_cast(std::countr_zero(d.element_bytes)); + const uint64_t bpe = d.element_bytes; + const uint64_t block_bytes = uint64_t{1} << block_log2; + const bool thick = d.dimension == Dimension::tex3d && (is_standard(d.swizzle) || is_display(d.swizzle)); + std::array block{}; + if (thick) { // ComputeThickBlockDimension + const uint32_t amp = (block_log2 - 10) / 3, rest = (block_log2 - 10) % 3; + const auto* b = kBlock1k_3d[element_log2]; + block = {b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + (rest != 0 ? 1u : 0u))}; + } else { // ComputeThinBlockDimension + const uint32_t samples_log2 = static_cast(std::countr_zero(d.samples)); + const uint32_t elements_log2 = block_log2 - element_log2 - samples_log2; + const bool wide = (samples_log2 & 1) == 0 || (block_log2 & 1) != 0; + const uint32_t w = (elements_log2 + (wide ? 1u : 0u)) / 2; + block = {1u << w, 1u << (elements_log2 - w), 1}; + } + uint32_t slices = round_up(d.depth, block[2]); + const bool three_d = d.dimension == Dimension::tex3d; + // Mip depths placed by a thick layout (thin ones store depth as slices). + const auto mip_depth = [&](uint32_t i) { return thick ? padded_dim(d.depth, i, 1) : 1u; }; + const auto depth_of = [&](uint32_t i) { return three_d ? dim(d.depth, i, 1) : 1u; }; + const auto width = [&](uint32_t i) { return dim(d.width, i, d.block); }; + const auto height = [&](uint32_t i) { return dim(d.height, i, d.block); }; + uint32_t first_tail_mip = d.mips; + uint64_t slice_size = 0; + if (d.mips == 1) { + Mip m; + m.width = width(0); + m.height = height(0); + m.depth = depth_of(0); + m.pitch = round_up(width(0), block[0]); + m.rows = round_up(height(0), block[1]); + m.depth_pitch = three_d ? slices : 1; + l.mips.push_back(m); + slice_size = uint64_t{m.pitch} * m.rows * bpe * d.samples; + } else { + // GetMipTailDim: the largest mip the tail takes. + std::array tail_max = block; + if (thick) { + switch (block_log2 % 3) { + case 0: tail_max[1] >>= 1; break; + case 1: tail_max[0] >>= 1; break; + default: tail_max[2] >>= 1; break; + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail (ComputeSurfaceInfoMicroTiled). + const uint32_t effective = thick ? block_log2 - (block_log2 - 8) / 3 : block_log2; + const uint32_t max_in_tail = effective == 8 ? 0 + : (effective >= 9 && effective <= 11) ? 1 + (1u << (effective - 9)) + : effective - 4; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + std::array fixed = tail_max; + if (is_z_order(d.swizzle) && element_log2 <= 1) { + const auto* b = kBlock256_2d[element_log2]; + fixed[0] /= b[0] / kBlock256_2d[2][0]; + fixed[1] /= b[1] / kBlock256_2d[2][1]; + } + std::vector sizes; + for (uint32_t i = 0; i < d.mips; ++i) { + const uint32_t w = padded_dim(d.width, i, d.block), h = padded_dim(d.height, i, d.block); + if (w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail) { + first_tail_mip = i; + slice_size += block_bytes / block[2]; + break; + } + const uint32_t pitch = round_up(w, block[0]), rows = round_up(h, block[1]); + const uint32_t depth = round_up(mip_depth(i), block[2]); + const uint64_t one = uint64_t{pitch} * rows * bpe; + slice_size += one; + sizes.push_back(one * block[2]); + Mip m; + m.width = width(i); + m.height = height(i); + m.depth = depth_of(i); + m.pitch = pitch; + m.rows = rows; + m.depth_pitch = three_d ? depth : 1; + l.mips.push_back(m); + } + // Standard mips from the smallest up, after the tail block. + uint64_t offset = first_tail_mip < d.mips ? block_bytes : 0; + for (uint32_t i = first_tail_mip; i-- > 0;) { + l.mips[i].offset = offset; + offset += sizes[i]; + } + uint32_t micro[2]; + if (thick) { + micro[0] = kBlock256_3d[element_log2][0]; + micro[1] = kBlock256_3d[element_log2][1]; + } else { + micro[0] = kBlock256_2d[element_log2][0]; + micro[1] = kBlock256_2d[element_log2][1]; + } + uint32_t pitch = tail_max[0], rows = tail_max[1]; + for (uint32_t i = first_tail_mip; i < d.mips; ++i) { + const uint32_t m = max_in_tail - 1 - (i - first_tail_mip); + const uint32_t offset_in_tail = m > 6 ? 16u << m : m << 8; + // Address bits 8.. of the offset, odd ones x, even ones y. + const auto bits = [&](uint32_t from) { + uint32_t v = 0; + for (uint32_t b = 0; b < 6; ++b) v |= ((offset_in_tail >> (from + 2 * b)) & 1u) << b; + return v; + }; + uint32_t x = bits(9), y = bits(8); + if ((block_log2 & 1) != 0) { + std::swap(x, y); + if ((element_log2 & 1) != 0) { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + Mip t; + t.width = width(i); + t.height = height(i); + t.depth = depth_of(i); + t.pitch = pitch; + t.rows = rows; + t.depth_pitch = thick ? round_up(mip_depth(i), kBlock256_3d[element_log2][2]) : 1; + t.offset = 0; + t.tail = Tail{offset_in_tail, x * micro[0], y * micro[1]}; + l.mips.push_back(t); + pitch = std::max(pitch >> 1, micro[0]); + rows = std::max(rows >> 1, micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + const uint64_t slab = thick ? block[2] : 1; + slice_size *= slab; + slices /= block[2]; + if (!is_xor(d.swizzle) && d.samples == 1) { + const int kind = thick ? 2 : (is_display(d.swizzle) ? 1 : 0); + const auto bits = detail::pattern(kind, element_log2, block_log2); + for (size_t a = 0; a < 3; ++a) l.pattern_[a] = detail::spread(bits[a]); + } + l.block = block; + l.thick = thick; + l.slices = slices; + l.slice_size = slice_size; + l.size = slice_size * slices; + l.alignment = block_bytes; + l.first_tail_mip = first_tail_mip; + return l; + } + + // The slice and the depth inside it for z (an array slice or a 3D depth slice). + std::pair split(uint32_t z) const { + return thick ? std::pair{z / block[2], z % block[2]} : std::pair{z, 0u}; + } + + // The part of an address that depends on the row (and depth in a thick block). + uint64_t row(const Mip& m, uint32_t y, uint32_t z) const { + const uint32_t bw = block[0], bh = block[1]; + const int log2 = std::countr_zero(alignment); + // In the tail the pattern of the shifted position gives the mip's offset inside the tail block. + y += m.tail ? m.tail->y : 0; + const uint64_t blocks = uint64_t{y / bh} * (m.pitch / bw); + return (blocks << log2) + (pattern_[1][y % bh] | pattern_[2][z]); + } + + // The part of an address that depends on the column. + uint64_t column(const Mip& m, uint32_t x) const { + const uint32_t bw = block[0]; + x += m.tail ? m.tail->x : 0; + return (uint64_t{x / bw} << std::countr_zero(alignment)) + pattern_[0][x % bw]; + } + + // Visits contiguous runs as (tiled byte offset, linear byte offset, length). + template + Error walk(size_t tiled_len, uint32_t mip, uint32_t slice, size_t linear_len, size_t row_pitch, + size_t depth_pitch, Copy&& copy) const { + if (mip >= mips.size()) return Error::invalid; + const Mip& m = mips[mip]; + const uint32_t depth = m.depth; + uint32_t first = slice; + if (desc.dimension == Dimension::tex3d) { + if (slice != 0) return Error::invalid; + first = 0; + } + if (first >= slices) return Error::invalid; + if (!addressable()) return Error::unsupported; + const size_t n = desc.element_bytes; + const size_t bytes = size_t{m.width} * n; + // need = (depth - 1) * depth_pitch + (height - 1) * row_pitch + bytes, refused on overflow. + const size_t dz = depth - 1u, dy = m.height - 1u; + if ((dz && depth_pitch > SIZE_MAX / dz) || (dy && row_pitch > SIZE_MAX / dy)) return Error::too_small; + const size_t depth_offset = dz * depth_pitch, row_offset = dy * row_pitch; + if (depth_offset > SIZE_MAX - row_offset || depth_offset + row_offset > SIZE_MAX - bytes) + return Error::too_small; + const size_t need = depth_offset + row_offset + bytes; + if (tiled_len < size || linear_len < need || row_pitch < bytes) return Error::too_small; + const bool is_linear = desc.swizzle == kLinear; + // The row and depth contribute one common base to every column, so the same contiguous runs repeat on + // every row, including mip tails. + struct Run { + size_t tiled, linear, len; + }; + std::vector runs; + if (!is_linear) { + size_t first_linear = 0, first_tiled = static_cast(column(m, 0)); + for (uint32_t x = 1; x < m.width; ++x) { + const size_t off = static_cast(column(m, x)); + const size_t at = x * n; + if (off != first_tiled + (at - first_linear)) { + runs.push_back({first_tiled, first_linear, at - first_linear}); + first_tiled = off; + first_linear = at; + } + } + runs.push_back({first_tiled, first_linear, bytes - first_linear}); + } + for (uint32_t z = 0; z < depth; ++z) { + const auto [s, inner] = split(first + z); + const uint64_t base = uint64_t{s} * slice_size + m.offset; + for (uint32_t y = 0; y < m.height; ++y) { + const size_t linear_row = z * depth_pitch + y * row_pitch; + if (is_linear) { + copy(static_cast(base + uint64_t{y} * m.pitch * n), linear_row, bytes); + } else { + const size_t tiled_row = static_cast(base + row(m, y, inner)); + for (const Run& r : runs) copy(tiled_row + r.tiled, linear_row + r.linear, r.len); + } + } + } + return Error::ok; + } +}; + +// What a DXGI format stores per element: bytes, texels per element side (4 for block compression), and whether its +// stencil is a second plane (the GPU keeps depth and stencil apart). nullopt for 96-bit, 1-bit, packed 4:2:2 and +// video formats, which have no layout here. +struct Format { + uint32_t bytes, block; + bool stencil; +}; +inline std::optional format(uint32_t dxgi) { + const auto in = [&](uint32_t lo, uint32_t hi) { return dxgi >= lo && dxgi <= hi; }; + if (in(1, 4)) return Format{16, 1, false}; + if (in(9, 18)) return Format{8, 1, false}; + if (in(19, 22) || in(44, 47)) return Format{4, 1, true}; + if (in(23, 43) || dxgi == 67 || in(87, 93) || dxgi == 116 || dxgi == 117) return Format{4, 1, false}; + if (in(48, 59) || dxgi == 85 || dxgi == 86 || dxgi == 115) return Format{2, 1, false}; + if (in(118, 120)) return Format{2, 1, true}; + if (in(60, 65)) return Format{1, 1, false}; + if (in(70, 72) || in(79, 81)) return Format{8, 4, false}; + if (in(73, 78) || in(82, 84) || in(94, 99)) return Format{16, 4, false}; + return std::nullopt; +} + +// A texture as the console allocates it: a D3D12-style description with a swizzle mode. +struct TextureDesc { + Dimension dimension = Dimension::tex2d; + uint32_t width = 1, height = 1; // in texels + uint32_t depth_or_array = 1; // depth of a 3D texture, else the array size + uint32_t mips = 1; // 0: the full chain + uint32_t format = 0; // DXGI format number + uint32_t samples = 1; + uint32_t swizzle = kLinear; +}; + +struct Plane { + uint64_t offset = 0; // from the start of the texture + bool stencil = false; + Layout layout; +}; + +// Every data plane of a texture (depth, then stencil), placed one after the other. No compression metadata planes +// (HTILE, CMASK, FMASK, DCC): the console adds them to render targets and depth buffers unless the description +// denies them, so those are smaller here than on the console; the host GPU renders them, so nothing reads that +// memory. +struct Texture { + std::vector planes; + uint64_t size = 0; + uint64_t alignment = 0; + + static std::optional make(const TextureDesc& desc) { + const auto f = format(desc.format); + if (!f) return std::nullopt; + const uint32_t depth3d = desc.dimension == Dimension::tex3d ? desc.depth_or_array : 1; + const uint32_t mips = + desc.mips ? desc.mips + : 32u - static_cast(std::countl_zero( + std::max({desc.width, desc.height, depth3d, 1u}))); + const auto plane = [&](uint32_t bytes) { + Desc d; + d.dimension = desc.dimension; + d.width = desc.width; + d.height = desc.height; + d.depth = desc.depth_or_array; + d.mips = mips; + d.element_bytes = bytes; + d.block = f->block; + d.samples = std::max(desc.samples, 1u); + d.swizzle = desc.swizzle; + return d; + }; + Texture t; + auto main = Layout::make(plane(f->bytes)); + if (!main) return std::nullopt; + t.planes.push_back({0, false, std::move(*main)}); + if (f->stencil) { + auto s = Layout::make(plane(1)); + if (!s) return std::nullopt; + const uint64_t a = s->alignment; + const uint64_t offset = (t.planes[0].layout.size + a - 1) / a * a; + t.planes.push_back({offset, true, std::move(*s)}); + } + const Plane& last = t.planes.back(); + t.size = last.offset + last.layout.size; + for (const Plane& p : t.planes) t.alignment = std::max(t.alignment, p.layout.alignment); + return t; + } +}; + +} // namespace leonida::console_texture diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h index 10f0dada8..d32f975b2 100644 --- a/runtime/src/depth24_fragment.h +++ b/runtime/src/depth24_fragment.h @@ -37,12 +37,13 @@ struct Depth24Bias { int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias float slope = 0.0f; // SlopeScaledDepthBias float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it + float levels = 16777215.0f; bool any() const { return constant != 0 || slope != 0.0f; } }; // D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). -inline float depth24_bias_constant(int bias) { - return float(bias) * float(1.0 / 16777215.0); +inline float depth24_bias_constant(int bias, float levels=16777215.0f) { + return float(bias) * float(1.0 / double(levels)); } namespace spirv24 { @@ -141,7 +142,7 @@ private: // The edit, on a parsed module. Globals are collected first and spliced in at their section's end. class Patch { public: - Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { + Patch(Module& m, std::uint32_t entry, float levels) : m_(m), entry_(entry), levels_(levels) { // Copies: apply() moves the module's instructions while the code at returns still looks types up. for (const Inst& i : m.insts()) { if (opcode(i) == op_function) break; @@ -185,7 +186,7 @@ public: void prime_quantise() { t_bool(); glsl(); - for (float f : {16777215.0f, 0.0f}) f32(f); + for (float f : {levels_, 0.0f}) f32(f); for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); } std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } @@ -248,11 +249,11 @@ public: std::uint32_t quantise(std::vector& code, std::uint32_t z) { const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); const std::uint32_t b = emit(code, op_bitcast, tu, {z}); - const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); + const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(levels_)}); const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), - f32(16777215.0f)}); + f32(levels_)}); const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); @@ -327,6 +328,7 @@ public: } private: + float levels_; Module& m_; std::uint32_t entry_; std::vector existing_; @@ -369,7 +371,7 @@ inline std::vector depth24_patch_fragment(const std::vector depth24_patch_fragment(const std::vector 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); z = p.emit(entry_code, op_f_add, tf, {z, amount}); diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index 5de8e9b79..6e14c60d5 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -106,6 +106,8 @@ private: // Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. inline constexpr std::uint32_t frame_event_origin = 0; +// WaitFrameEventX flag 2 with timeout 0 is the retail title's poll for the current token, which it asserts succeeds. +inline constexpr std::uint32_t wait_flag_current_token = 0x2; // Statistics types (bit mask). Interval and render entries are never produced here. inline constexpr std::uint32_t stat_frame_interval = 0x01; inline constexpr std::uint32_t stat_frame_event = 0x02; @@ -216,9 +218,9 @@ public: // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, std::uint64_t* token) { - (void)flags; if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; std::unique_lock lock(mutex_); + if (flags & wait_flag_current_token) return current_token_locked(token); ++waiters_; const std::int32_t result = wait_locked(lock, timeout_ms, token); if (--waiters_ == 0) cv_.notify_all(); @@ -412,6 +414,25 @@ private: } } + // Never blocks: a fresh token for the newest passed origin, with no wait for the next origin or the latency. + std::int32_t current_token_locked(std::uint64_t* token) { + if (shutdown_ || suspended_) return pacer_hr::invalid_state; + *token = tokens_->issue(); + if (!interval_set_ || !armed_) return pacer_hr::ok; + const std::uint64_t now = clock_.now_us(); + retire_locked(now); + const std::uint64_t first = epoch_us_ + offset_us_; + const std::int64_t newest = now >= first ? std::int64_t((now - first) / period_us_) : 0; + last_origin_ = std::max(last_origin_, newest); + Record record; + record.token = *token; + record.origin_us = first + std::uint64_t(last_origin_) * period_us_; + record.due_us = record.origin_us - offset_us_ + period_us_; + records_.push_back(record); + if (records_.size() > 64) records_.pop_front(); + return pacer_hr::ok; + } + std::int32_t wait_locked(std::unique_lock& lock, std::uint32_t timeout_ms, std::uint64_t* token) { const std::uint64_t start = clock_.now_us(); const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index e6fc4df6d..85ea2edfc 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -146,6 +146,26 @@ inline ImageWords encode(const Image& image) { // TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } +// Synthetic volume UAV metadata distinguishes the storage view from SRVs of the same mip, and distinct W +// ranges from one another. Sampled fetches use it because Vulkan only applies slicing to storage views. +// WORD4[31] is reserved on GFX10/GFX103; hardware uses WORD7 for metadata addresses. DEPTH and BASE_ARRAY +// stay unchanged. D3D12 depth is at most 2048, so count - 1 and offset fit 11 bits. +inline constexpr std::uint32_t volume_uav_flag = 0x80000000; +inline constexpr std::uint32_t volume_uav_tag = 0xD7800000; +inline constexpr std::uint32_t volume_uav_tag_mask = 0xff800000; +// RGB9E5 emulation uses R32_UINT storage, not the logical float format in T# word 1. The same tag marks packed +// 1D-family UAVs (without a W range). No ordinary SRV or raw hardware T# has this synthetic metadata. +inline constexpr std::uint32_t packed_uav_flag = 0x00400000; +inline constexpr std::uint32_t volume_uav_word(std::uint32_t offset, std::uint32_t count) { + return volume_uav_tag | ((count - 1) << 11) | offset; +} +inline constexpr bool partial_volume_uav(const ImageWords& words, const Image& image) { + const auto mip_depth = image.depth >> image.first_mip; + return image.type == ImageType::image_3d && (words[4] & volume_uav_flag) && + (words[7] & volume_uav_tag_mask) == volume_uav_tag && + (words[7] & ~packed_uav_flag) != volume_uav_word(0, mip_depth ? mip_depth : 1u); +} + inline constexpr float image_min_lod(const ImageWords& words) { return float(detail::get(words[1], 8, 12)) / 256.0f; } diff --git a/runtime/src/gpu_label_memory.h b/runtime/src/gpu_label_memory.h new file mode 100644 index 000000000..890aadf7e --- /dev/null +++ b/runtime/src/gpu_label_memory.h @@ -0,0 +1,77 @@ +#pragma once +#include +#include +#include +#include +#include + +namespace leonida::label { +struct Region { + std::uintptr_t begin, end, allocation_base; + bool heap; + std::uint64_t generation=1; +}; +struct Target { + std::weak_ptr owner; + std::uintptr_t address = 0; + unsigned bytes = 0; + std::uint64_t generation=0; +}; +struct Write { + Target target; + std::uint64_t value{}; + unsigned clock{}; // 0: supplied value; 1: GPU timestamp; 2: system timestamp +}; +class Memory { + std::mutex mutex_; + std::map> regions_; +public: + void track(std::uintptr_t base,std::uintptr_t bytes,std::uintptr_t allocation_base,bool heap) { + if (!base || !bytes || !allocation_base || bytes>std::numeric_limits::max()-base) return; + const auto end=base+bytes; + std::lock_guard lock(mutex_); + auto previous=regions_.upper_bound(base); + if (!heap && previous!=regions_.begin()) { + --previous; + const auto& r=*previous->second; + if (!r.heap && r.allocation_base==allocation_base && base>=r.begin && end<=r.end) return; + } + regions_[base]=std::make_shared(Region{base,end,allocation_base,heap}); + } + void release_heap(std::uintptr_t base) { + std::lock_guard lock(mutex_);regions_.erase(base); + } + template bool release_pages(std::uintptr_t base,std::uintptr_t bytes,bool entire,Release&& release) { + std::lock_guard lock(mutex_); + if(!release()) return false; + for(auto i=regions_.begin();i!=regions_.end();) { + const auto& r=*i->second; + if(r.heap || (entire ? r.allocation_base!=base : + (!bytes ? r.allocation_base!=base : (base>=r.end || (base=bytes))))) { ++i; continue; } + if(entire || i->second->generation==std::numeric_limits::max()) i=regions_.erase(i); + else { ++i->second->generation; ++i; } + } + return true; + } + Target capture(std::uintptr_t address,unsigned bytes) { + if((bytes!=4 && bytes!=8) || (address&(bytes-1)))return {}; + std::lock_guard lock(mutex_); + auto it=regions_.upper_bound(address); + while(it!=regions_.begin()) { + --it;const auto& r=*it->second; + if(address=bytes) return {it->second,address,bytes,r.generation}; + } + return {}; + } + template bool publish(const Target& target,Store&& store) { + std::lock_guard lock(mutex_); + const auto region=target.owner.lock(); + if(!region || target.generation!=region->generation || (target.bytes!=4 && target.bytes!=8) || (target.address&(target.bytes-1)) || + target.addressbegin || target.address>=region->end || region->end-target.addressbegin); + if(it==regions_.end() || it->second!=region) return false; + return store(target.address,target.bytes,region->allocation_base); + } +}; +inline Memory& memory(){static Memory m;return m;} +} // namespace leonida::label diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 63bd016e8..8ea202fa0 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -62,10 +62,40 @@ extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_t reserve_tls_index0_at_start; #pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0") +// Select the settings used to display the offline first-run UI. Keep explicit caller settings. +bool configure_first_run_ui(const std::filesystem::path& package, std::filesystem::path& overlay) { + const auto set_default = [](const wchar_t* name, const wchar_t* value) { + return GetEnvironmentVariableW(name, nullptr, 0) != 0 || _wputenv_s(name, value) == 0; + }; + const struct { const wchar_t* name; const wchar_t* value; } settings[] = { + {L"LEONIDA_D3D12", L"vulkan"}, {L"LEONIDA_ARENA_MB", L"2048"}, + {L"LEONIDA_GRAPHICS_STAGE_LAYOUT", L"1"}, {L"LEONIDA_PIPELINE_COMPILE", L"on-demand"}, + {L"LEONIDA_GPU_LABELS", L"1"}, {L"LEONIDA_FRAME_PACING", L"1"}, + {L"LEONIDA_LOCAL_SPEECH", L"1"}, {L"LEONIDA_KEYBOARD_PAD", L"always"}, + }; + for (const auto& setting : settings) { + if (!set_default(setting.name, setting.value)) return false; + } + std::wstring executable(32768, L'\0'); + const DWORD length = GetModuleFileNameW(nullptr, executable.data(), static_cast(executable.size())); + if (!length || length >= executable.size()) return false; + executable.resize(length); + const auto state = std::filesystem::path(executable).parent_path() / L"first-run-ui"; + if (overlay.empty()) overlay = state / L"overlay"; + if (!GetEnvironmentVariableW(L"LEONIDA_XMEM_BACKING_DIR", nullptr, 0)) { + std::error_code error; + const auto backing = state / L"xmem"; + std::filesystem::create_directories(backing, error); + if (error || !set_default(L"LEONIDA_XMEM_BACKING_DIR", backing.c_str())) return false; + } + return SetCurrentDirectoryW(package.c_str()) != FALSE; +} + int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" + " gta6rt --first-run-ui [--game-dir DIR] [--overlay DIR] [--trace FILE]\n" " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); return 2; } @@ -77,7 +107,7 @@ int wmain(int argc, wchar_t** argv) { uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash int archetype_lookup_arg = 0; uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context - bool dry_run = false, init = false, run = false, trace_d3d12 = false; + bool dry_run = false, init = false, run = false, trace_d3d12 = false, first_run_ui = false; std::vector game_args; // wide: path::string() throws on a character the code page lacks (RT-84) std::wstring trace_file; for (int i = 1; i < argc; ++i) { @@ -88,6 +118,7 @@ int wmain(int argc, wchar_t** argv) { } if (a == L"--dry-run") dry_run = true; else if (a == L"--init") init = true; + else if (a == L"--first-run-ui") first_run_ui = true; else if (a == L"--run") run = true; else if (a == L"--trace-d3d12") trace_d3d12 = true; else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; @@ -114,7 +145,8 @@ int wmain(int argc, wchar_t** argv) { } if (image.empty()) return usage(); // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. - if (dry_run + init + run != 1) return usage(); + if (dry_run + init + run + first_run_ui != 1) return usage(); + run = run || first_run_ui; // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). if ((init || run) && !rt::host_cpu::check_skipped()) if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { @@ -129,6 +161,11 @@ int wmain(int argc, wchar_t** argv) { std::filesystem::path a = std::filesystem::absolute(p, ec); return ec ? p : a; }; + if (first_run_ui) { + image = absolute_or_same(image); + if (!mods_dir.empty()) mods_dir = absolute_or_same(mods_dir); + if (!trace_file.empty()) trace_file = absolute_or_same(trace_file).wstring(); + } game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); // LEONIDA_SHADERS too: the D3D12 device reads it at the title's first pipeline state, after it may have moved. @@ -145,6 +182,10 @@ int wmain(int argc, wchar_t** argv) { if (!rt::base_reservation::inherited()) if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. + if (first_run_ui && !configure_first_run_ui(game_dir, overlay_dir)) { + std::fprintf(stderr, "cannot initialize the first-run UI paths or graphics settings\n"); + return 1; + } if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; rt::fs::configure(game_dir, overlay_dir); // Mods (docs/modding.md): \mods unless --mods names another. Loaded and reported here; @@ -178,6 +219,7 @@ int wmain(int argc, wchar_t** argv) { rt::d3d12_trace::set_enabled(trace_d3d12); // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); + rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" : "error: cannot create the trace file\n"); diff --git a/runtime/src/native_pso.h b/runtime/src/native_pso.h new file mode 100644 index 000000000..88a260ca8 --- /dev/null +++ b/runtime/src/native_pso.h @@ -0,0 +1,332 @@ +#pragma once + +// The description Xbox device slot 57 receives (native graphics pipelines) and how its stages find the game's own +// shader containers. Standard library only, so the parsing is tested on every platform. +// +// Layout measured by LooperSalty on 1.0.2.1 and implemented by enx in 5c175db90: 0x108 bytes, the root +// signature at +0x00, pairs at +0x08 and +0x18, then seven blocks {code, size, records, size} at +0x28 + k * 0x20. +// Measured by KkelebekK: pair 0 is state blob A (380-388 bytes: blend, raster, +// depth, not decoded), pair 1 is state blob B (80-188 bytes: formats and input layout, decode_state_b), and each +// stage's records blob carries the source container's HASH digest after its 0x43 word (docs/fspx.md, kind 7). +// The block index is not trusted as the stage: the stage comes from the translator's index entry of the container. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::native_pso { + +struct Pair { + const void* data; + std::uint64_t size; +}; + +struct StageBlock { + Pair code; // +0x00: the stage's native program + Pair records; // +0x10: kind-7 style records holding the container's HASH digest +}; + +inline constexpr std::size_t kStageBlocks = 7; + +struct GraphicsDesc { + const void* root_signature; // +0x00 + Pair state_a; // +0x08 + Pair state_b; // +0x18 + StageBlock stages[kStageBlocks]; // +0x28 +}; + +static_assert(sizeof(Pair) == 0x10 && sizeof(StageBlock) == 0x20, "pairs are {pointer, u64 size}"); +static_assert(offsetof(GraphicsDesc, state_a) == 0x08 && offsetof(GraphicsDesc, state_b) == 0x18); +static_assert(offsetof(GraphicsDesc, stages) == 0x28 && sizeof(GraphicsDesc) == 0x108, + "the slot-57 description has a 0x108-byte prefix"); + +// Far above the largest blob measured (a few KiB), and small enough for 32-bit offsets inside one. +inline constexpr std::uint64_t kPairLimit = 16u << 20; + +// The size, not the pointer, determines whether a pair is absent. +enum class PairState { absent, present, malformed }; + +// A table entry with size 0 is absent whatever its pointer (the title passes base + offset, measured on 1.0.2.1). +inline PairState pair_state(const Pair& p) { + if (!p.size) return PairState::absent; + if (!p.data || p.size > kPairLimit) return PairState::malformed; + return PairState::present; +} + +inline std::span bytes(const Pair& p) { + if (pair_state(p) != PairState::present) return {}; + return {static_cast(p.data), static_cast(p.size)}; +} + +inline std::uint32_t read_u32(std::span b, std::size_t at) { + std::uint32_t v = 0; + if (at + 4 <= b.size()) std::memcpy(&v, b.data() + at, 4); + return v; +} + +struct InputElement { + std::string name; + std::uint32_t semantic_index = 0; + std::uint32_t format = 0; + std::uint32_t input_slot = 0; + std::uint32_t aligned_byte_offset = 0; + std::uint32_t classification = 0; + std::uint32_t step_rate = 0; +}; + +// State blob B. The u32 field widths after each name are a hypothesis that fits the +// measured sizes: 0x50 bytes with no element, and 188 bytes with POSITION, COLOR and TEXCOORD. +struct FixedState { + std::array rtv_formats{}; // +0x10, DXGI_FORMAT values + std::uint32_t sample_mask = 0; // +0x1c + std::uint8_t dsv_format = 0; // +0x24 + std::uint8_t rt_count = 0; // +0x25 + std::uint8_t topology_type = 0; // +0x26, low nibble + std::uint8_t sample_count = 1; // +0x28 + std::vector elements; // count at +0x4c, packed from +0x50 +}; + +inline constexpr std::size_t kStateBHeader = 0x50; +inline constexpr std::uint32_t kMaxInputElements = 32; // D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT +inline constexpr std::uint32_t kMaxSemanticName = 256; + +// Empty for a blob that is too short, names more than 8 targets, a topology type past PATCH (4), or an element +// list that runs past the blob or has a malformed name. Bytes after the last element are allowed. +inline std::optional decode_state_b(std::span b, const char** why = nullptr) { + const auto fail = [&](const char* reason) { + if (why) *why = reason; + return std::nullopt; + }; + if (b.size() < kStateBHeader) return fail("blob B shorter than its header"); + FixedState s; + std::memcpy(s.rtv_formats.data(), b.data() + 0x10, 8); + s.sample_mask = read_u32(b, 0x1c); + s.dsv_format = b[0x24]; + s.rt_count = b[0x25]; + s.topology_type = b[0x26] & 0x0f; + s.sample_count = b[0x28] ? b[0x28] : 1; + if (s.rt_count > 8) return fail("blob B render target count over 8"); + if (s.topology_type > 4) return fail("blob B topology type over 4"); + const std::uint32_t count = read_u32(b, 0x4c); + if (count > kMaxInputElements) return fail("blob B input element count over 32"); + std::size_t at = kStateBHeader; + for (std::uint32_t i = 0; i < count; ++i) { + if (at + 4 > b.size()) return fail("blob B input element past the end"); + const std::uint32_t length = read_u32(b, at); + at += 4; + if (length < 2 || length > kMaxSemanticName || at + length + 24 > b.size()) + return fail("blob B semantic name length out of range"); + const auto* name = reinterpret_cast(b.data() + at); + if (name[length - 1] != '\0' || std::memchr(name, '\0', length - 1)) + return fail("blob B semantic name not one NUL-terminated string"); + InputElement e; + e.name.assign(name, length - 1); + at += length; + e.semantic_index = read_u32(b, at); + e.format = read_u32(b, at + 4); + e.input_slot = read_u32(b, at + 8); + e.aligned_byte_offset = read_u32(b, at + 12); + e.classification = read_u32(b, at + 16); + e.step_rate = read_u32(b, at + 20); + at += 24; + s.elements.push_back(std::move(e)); + } + return s; +} + +using Digest = std::array; + +// Every 16 bytes that follow a 4-aligned 0x43 word, without duplicates. A register number can also read 0x43, so +// all candidates are returned and the map decides which one names a container. +inline std::vector record_digests(std::span records) { + std::vector out; + std::set seen; + for (std::size_t at = 0; at + 4 + 16 <= records.size(); at += 4) { + if (read_u32(records, at) != 0x43) continue; + Digest d; + std::memcpy(d.data(), records.data() + at + 4, 16); + if (seen.insert(d).second) out.push_back(d); + } + return out; +} + +inline std::string hex(const Digest& d) { + static constexpr char kHex[] = "0123456789abcdef"; + std::string s; + for (const std::uint8_t b : d) { + s += kHex[b >> 4]; + s += kHex[b & 15]; + } + return s; +} + +inline std::optional parse_digest(std::string_view text) { + if (text.size() != 32) return std::nullopt; + Digest d{}; + for (std::size_t i = 0; i < 32; ++i) { + const char c = text[i]; + int v = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 : -1; + if (v < 0) return std::nullopt; + d[i / 2] = static_cast(d[i / 2] << 4 | v); + } + return d; +} + +struct ShaderRef { + Digest digest; + std::string stage; // the translator's stage: "vs", "ps", "gs", "ms", "cs" + std::string path; // the container, relative to the map file's folder, '/' separated +}; + +// native_hashes.txt, written by tools/native_pso_hashes.py next to the translator's index.json: a first line +// "# native_pso_hashes 1", then one "<32 hex digest>\t\t" line per digest. +class HashMap { +public: + static constexpr std::string_view kHeader = "# native_pso_hashes 1"; + + bool parse(std::string_view text, std::string* error = nullptr) { + const auto fail = [&](std::string why) { + if (error) *error = std::move(why); + map_.clear(); + return false; + }; + map_.clear(); + std::size_t line_no = 0; + bool header = false; + while (!text.empty()) { + const std::size_t end = text.find('\n'); + std::string_view line = text.substr(0, end); + text = end == std::string_view::npos ? std::string_view{} : text.substr(end + 1); + ++line_no; + if (!line.empty() && line.back() == '\r') line.remove_suffix(1); + if (line_no == 1) { + if (line != kHeader) return fail("native_hashes.txt: unknown header"); + header = true; + continue; + } + if (line.empty() || line.front() == '#') continue; + const std::size_t t1 = line.find('\t'); + const std::size_t t2 = t1 == std::string_view::npos ? t1 : line.find('\t', t1 + 1); + if (t2 == std::string_view::npos || t2 + 1 >= line.size()) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": expected three fields"); + const auto digest = parse_digest(line.substr(0, t1)); + const std::string_view stage = line.substr(t1 + 1, t2 - t1 - 1); + if (!digest || stage.empty()) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": bad digest or stage"); + const std::string_view path = line.substr(t2 + 1); + const auto [it, inserted] = map_.try_emplace(*digest, ShaderRef{*digest, std::string(stage), std::string(path)}); + if (!inserted && (it->second.stage != stage || it->second.path != path)) + return fail("native_hashes.txt line " + std::to_string(line_no) + ": conflicting digest"); + } + if (!header) return fail("native_hashes.txt is empty"); + return true; + } + + const ShaderRef* find(const Digest& d) const { + const auto it = map_.find(d); + return it == map_.end() ? nullptr : &it->second; + } + + std::size_t size() const { return map_.size(); } + +private: + std::map map_; +}; + +struct PlannedStage { + std::size_t block = 0; + const ShaderRef* shader = nullptr; +}; + +enum class PlanStatus { + ok, + malformed, // a pair is malformed or blob B does not decode + missing, // a stage has no records, or its digest names no translated container + ambiguous, // a stage's records name two different containers + unsupported, // a stage kind this path does not build (hs, ds, cs), two of one kind, or no VS/MS +}; + +struct Plan { + PlanStatus status = PlanStatus::malformed; + FixedState state; + std::vector stages; // in block order + std::size_t failed_block = 0; // for missing/ambiguous/unsupported/malformed blocks + const char* reason = ""; // why a description is malformed + bool mesh = false; // an MS stage: the pipeline goes through a pipeline state stream + + const ShaderRef* stage(std::string_view name) const { + for (const PlannedStage& s : stages) + if (s.shader->stage == name) return s.shader; + return nullptr; + } +}; + +inline Plan plan(const GraphicsDesc& desc, const HashMap& map) { + Plan p; + if (pair_state(desc.state_a) == PairState::malformed) { + p.reason = "blob A pair malformed"; + return p; + } + if (pair_state(desc.state_b) != PairState::present) { + p.reason = "blob B pair absent or malformed"; + return p; + } + auto state = decode_state_b(bytes(desc.state_b), &p.reason); + if (!state) return p; + p.state = std::move(*state); + for (std::size_t k = 0; k < kStageBlocks; ++k) { + const StageBlock& block = desc.stages[k]; + const PairState code = pair_state(block.code), records = pair_state(block.records); + p.failed_block = k; + if (code == PairState::malformed || records == PairState::malformed) { + p.reason = "a stage pair malformed"; + return p; + } + if (code == PairState::absent && records == PairState::absent) continue; + if (records != PairState::present) { // code without records: nothing names its container + p.status = PlanStatus::missing; + return p; + } + const ShaderRef* found = nullptr; + for (const Digest& d : record_digests(bytes(block.records))) { + const ShaderRef* ref = map.find(d); + if (!ref) continue; + if (found && found != ref) { + p.status = PlanStatus::ambiguous; + p.failed_block = k; + return p; + } + found = ref; + } + p.failed_block = k; + if (!found) { + p.status = PlanStatus::missing; + return p; + } + const std::string& s = found->stage; + if (!(s == "vs" || s == "ps" || s == "gs" || s == "ms") || p.stage(s)) { + p.status = PlanStatus::unsupported; + return p; + } + p.stages.push_back({k, found}); + } + const bool vs = p.stage("vs"), ms = p.stage("ms"); + if (vs == ms || (ms && p.stage("gs"))) { + p.status = PlanStatus::unsupported; + return p; + } + p.mesh = ms; + p.status = PlanStatus::ok; + return p; +} + +} // namespace leonida::native_pso diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index 3148d0ad1..51a8c40c1 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h @@ -12,6 +12,16 @@ namespace leonida { +// The device's distinct family indices. An object used on more than one family keeps its contents +// across fenced D3D12 queue handoffs without explicit Vulkan ownership transfers. +template +void share_across_queue_families(CreateInfo& create, std::span families) { + if (families.size() < 2) return; + create.sharingMode = VK_SHARING_MODE_CONCURRENT; + create.queueFamilyIndexCount = static_cast(families.size()); + create.pQueueFamilyIndices = families.data(); +} + // Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no // graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable // family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h index 0049394cf..e90173095 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -2,8 +2,10 @@ // Console rectangle lists on Vulkan, which has no such primitive. // -// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for -// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// A rectangle is three corners and the hardware makes the fourth, a + b - p (p the right-angle corner, a and b its +// neighbours), for the position and for every interpolant, after the vertex stage. Which vertex is p is not fixed: +// the retail boot's full-screen rectangle has it at the second vertex. The stage picks the vertex opposite the longest +// screen-space edge, and the first vertex on a tie. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline // whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in // its backlog); no code is taken from it. // @@ -11,11 +13,15 @@ // the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and // the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a // small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) -// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of -// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// the list draws and emits the parallelogram as the two triangles (p, a, f) and (p, f, b), with the winding of +// (v1, v2, v3). Both start at p, so a flat input (taken from a triangle's first vertex) is p's over the whole // rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), // and so is the stage's Position; the generated stage reads and writes exactly those. // +// The edges are measured in normalized device coordinates, not pixels (the stage does not know the viewport). For the +// usual axis-aligned rectangle that is exact; a rotated rectangle drawn into a very non-square viewport can pick a +// different corner than the pixel-space right angle. +// // Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or // ViewportIndex, or a Location output that is not a vec4 float. // @@ -24,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -45,7 +50,9 @@ inline std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector rect_list_geometry(const std::vector corners; + std::vector> loaded; const std::uint32_t cs[3] = {c0, c1, c2}; for (const Var& v : vars) { - Corners c{}; + std::array three{}; for (int k = 0; k < 3; ++k) { const std::uint32_t ptr = id(); - c.v[k] = id(); + three[k] = id(); emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); - emit(body, op_load, {t_v4, c.v[k], ptr}); + emit(body, op_load, {t_v4, three[k], ptr}); } + loaded.push_back(three); + } + // Which vertex is the right angle: the one opposite the longest edge, measured on screen (position.xy / position.w; + // a right triangle's longest edge is its hypotenuse). Ties go to the first vertex, which keeps the plain + // "v1 is the corner" order for every rectangle whose right angle is there. A triangle that is not a right + // triangle gets the same rule, so the choice is at least consistent. + std::uint32_t screen[3][2]; + for (int k = 0; k < 3; ++k) { + const std::uint32_t x = id(), y = id(), w = id(); + emit(body, op_composite_extract, {t_float, x, loaded[0][k], 0}); + emit(body, op_composite_extract, {t_float, y, loaded[0][k], 1}); + emit(body, op_composite_extract, {t_float, w, loaded[0][k], 3}); + screen[k][0] = id(); + screen[k][1] = id(); + emit(body, op_fdiv, {t_float, screen[k][0], x, w}); + emit(body, op_fdiv, {t_float, screen[k][1], y, w}); + } + const auto squared_edge = [&](int a, int b) { + const std::uint32_t dx = id(), dy = id(), xx = id(), yy = id(), sum = id(); + emit(body, op_fsub, {t_float, dx, screen[a][0], screen[b][0]}); + emit(body, op_fsub, {t_float, dy, screen[a][1], screen[b][1]}); + emit(body, op_fmul, {t_float, xx, dx, dx}); + emit(body, op_fmul, {t_float, yy, dy, dy}); + emit(body, op_fadd, {t_float, sum, xx, yy}); + return sum; + }; + const std::uint32_t e01 = squared_edge(0, 1), e02 = squared_edge(0, 2), e12 = squared_edge(1, 2); + const std::uint32_t g12_01 = id(), g12_02 = id(), at_first = id(), g02_01 = id(), not_first = id(), at_second = id(); + emit(body, op_ford_greater_equal, {t_bool, g12_01, e12, e01}); + emit(body, op_ford_greater_equal, {t_bool, g12_02, e12, e02}); + emit(body, op_logical_and, {t_bool, at_first, g12_01, g12_02}); // the edge opposite v1 is longest: v1 is the corner + emit(body, op_ford_greater_equal, {t_bool, g02_01, e02, e01}); + emit(body, op_logical_not, {t_bool, not_first, at_first}); + emit(body, op_logical_and, {t_bool, at_second, not_first, g02_01}); // else the edge opposite v2: v2; else v3 + const std::uint32_t first4 = id(), second4 = id(); + emit(body, op_composite_construct, {t_bool4, first4, at_first, at_first, at_first, at_first}); + emit(body, op_composite_construct, {t_bool4, second4, at_second, at_second, at_second, at_second}); + // The corner p, its neighbours a = next and b = the one after (the same cyclic order as v1 v2 v3, so the winding + // is the drawn triangle's), and the fourth corner a + b - p, for the position and for every interpolant alike. + for (const auto& three : loaded) { + Corners c{}; + const auto pick = [&](std::uint32_t first, std::uint32_t second, std::uint32_t third) { + const std::uint32_t inner = id(), outer = id(); + emit(body, op_select, {t_v4, inner, second4, second, third}); + emit(body, op_select, {t_v4, outer, first4, first, inner}); + return outer; + }; + c.v[0] = pick(three[0], three[1], three[2]); + c.v[1] = pick(three[1], three[2], three[0]); + c.v[2] = pick(three[2], three[0], three[1]); const std::uint32_t sum = id(), diff = id(); - // The fourth corner is v2 + v3 - v1, the rule d3d12_rect_list tests. OPEN QUESTION, opt-in with - // LEONIDA_RECT_FOURTH=v1v3: the retail title's full-screen rectangle draws were measured with corners - // top-left, bottom-left, bottom-right, where only v1 + v3 - v2 covers the target (see the pull request). - static const bool local_old_rule = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); - if (local_old_rule) { - emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); - emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); - } else { - emit(body, op_fadd, {t_v4, sum, c.v[0], c.v[2]}); - emit(body, op_fsub, {t_v4, diff, sum, c.v[1]}); - } + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); c.v[3] = diff; corners.push_back(c); } - // Two triangles, (v1, v2, v4) and (v1, v4, v3): the diagonal is v1 to v4, so both start at v1 and a flat input - // (which Vulkan takes from a triangle's first vertex) is v1's over the whole rectangle. The attributes are + // Two triangles, (p, a, f) and (p, f, b): the diagonal is p to f, so both start at p and a flat input + // (which Vulkan takes from a triangle's first vertex) is p's over the whole rectangle. The attributes are // affine over the parallelogram, so the split does not change any interpolated value. - static const bool local_old_split = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); - const int triangles_old[2][3] = {{0, 1, 3}, {0, 3, 2}}; - const int triangles_new[2][3] = {{0, 1, 2}, {0, 2, 3}}; // diagonal v1 to v3, both start at v1 - const auto& triangles = local_old_split ? triangles_old : triangles_new; + const int triangles[2][3] = {{0, 1, 3}, {0, 3, 2}}; for (const auto& triangle : triangles) { for (int k : triangle) { for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); diff --git a/runtime/src/rgba4_fragment.h b/runtime/src/rgba4_fragment.h new file mode 100644 index 000000000..b62162848 --- /dev/null +++ b/runtime/src/rgba4_fragment.h @@ -0,0 +1,81 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +namespace leonida::rgba4 { +using Inst=std::vector; +inline Inst instruction(std::uint32_t op,std::initializer_list args) { + Inst w{(std::uint32_t(args.size()+1)<<16)|op};w.insert(w.end(),args);return w; +} +// Quantize only written color outputs at the requested locations. For a wider fallback attachment +// this reproduces four-bit UNORM writes for pipelines whose affected attachments use no blending. +inline bool quantize(Inst& words,unsigned mask) { + if(!mask)return true; + if(words.size()<5 || words[0]!=0x07230203)return false; + std::vector code,declarations; + std::map locations, pointer_type, width, scalar, variables; + unsigned import_id=0,next=words[3],float_type=0; + for(std::size_t at=5;at>16,op=words[at]&65535u; + if(!n || n>words.size()-at)return false; + Inst i(words.begin()+at,words.begin()+at+n);at+=n; + if(op==11 && n>=3) { + const char* s=reinterpret_cast(i.data()+2);const auto bytes=(n-2)*4; + if(bytes>=13 && std::memcmp(s,"GLSL.std.450",13)==0)import_id=i[1]; + } else if(op==71 && n==4 && i[2]==30)locations[i[1]]=i[3]; + else if(op==22 && n==3 && i[2]==32){float_type=i[1];width[i[1]]=1;scalar[i[1]]=i[1];} + else if(op==23 && n==4){width[i[1]]=i[3];scalar[i[1]]=i[2];} + else if(op==32 && n==4 && i[2]==3)pointer_type[i[1]]=i[3]; + else if(op==59 && n>=4 && i[3]==3)variables[i[2]]=i[1]; + code.push_back(std::move(i)); + } + if(!float_type)return false; + std::map outputs; + for(auto [id,ptr]:variables)if(locations.count(id)&&locations[id]<8&&(mask&(1u<> constants; + auto components=[&](unsigned type) -> const std::array& { + auto [it,inserted]=constants.try_emplace(type); + if(!inserted)return it->second; + constexpr std::array vals{0.f,1.f,15.f,1.f/15.f}; + std::array base{}; + for(unsigned j=0;j<4;++j){base[j]=next++;declarations.push_back(instruction(43,{scalar[type],base[j],std::bit_cast(vals[j])}));} + if(width[type]==1){it->second=base;return it->second;} + for(unsigned j=0;j<4;++j){const auto id=next++;Inst c=instruction(44,{type,id});c.resize(3+width[type],base[j]);c[0]=(unsigned(c.size())<<16)|44u;declarations.push_back(std::move(c));it->second[j]=id;} + return it->second; + }; + std::vector rewritten;bool changed=false; + for(auto& i:code) { + const auto op=i[0]&65535u; + if((op==65||op==66||op==83) && i.size()>=4 && outputs.count(i[3]) && pointer_type.count(i[1])) + outputs[i[2]]=pointer_type[i[1]]; + if(op==63 && i.size()>=3 && outputs.count(i[1]))return false; + if(op==62 && i.size()>=3 && outputs.count(i[1])) { + const auto type=outputs[i[1]]; + if(!width.count(type)||width[type]<1||width[type]>4||scalar[type]!=float_type)return false; + const auto& c=components(type); + const auto clamped=next++,scaled=next++,rounded=next++,value=next++; + rewritten.push_back(instruction(12,{type,clamped,import_id,43,i[2],c[0],c[1]})); // GLSL FClamp + rewritten.push_back(instruction(133,{type,scaled,clamped,c[2]})); + rewritten.push_back(instruction(12,{type,rounded,import_id,2,scaled})); // GLSL RoundEven + rewritten.push_back(instruction(133,{type,value,rounded,c[3]}));i[2]=value;changed=true; + } + rewritten.push_back(std::move(i)); + } + if(!changed)return false; + Inst result(words.begin(),words.begin()+5);result[3]=next;bool declared=false; + for(const auto& i:rewritten) { + const auto op=i[0]&65535u; + if(op==14 && add_import){Inst imp=instruction(11,{import_id,0,0,0,0});std::memcpy(imp.data()+2,"GLSL.std.450",13);result.insert(result.end(),imp.begin(),imp.end());} + if(op==54&&!declared){for(const auto& dec:declarations)result.insert(result.end(),dec.begin(),dec.end());declared=true;} + result.insert(result.end(),i.begin(),i.end()); + } + if(!declared)return false;words=std::move(result);return true; +} +} diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h index 829c1d874..ac1871e17 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -12,10 +12,9 @@ // submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 // buffer). Addresses that are not in the title's memory are passed through unchanged. // -// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver -// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the -// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was -// added to it, so it is tested without a GPU (title_va_alias_test). +// The table is process-wide, like the title's address space. A resolver makes a GPU copy for an address in the +// title's memory that has none yet. Without it the table only translates previously added ranges. +#include #include #include #include @@ -37,7 +36,6 @@ public: // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); - using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. @@ -109,19 +107,6 @@ public: if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); } - // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares - // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). - void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { - TableScanner scanner; - void* context; - { - std::lock_guard lock(hook_mutex_); - scanner = scanner_; - context = hook_context_; - } - if (scanner) scanner(context, table_va, descriptors); - } - // The scan's cost, per ExecuteCommandLists that had tables to scan. void note_scan(std::uint64_t nanoseconds) { scans_.fetch_add(1, std::memory_order_relaxed); @@ -189,20 +174,18 @@ public: } std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } - // The first device to register keeps the hooks until it clears them. - void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + // The first device to register keeps the resolver until it clears it. + void set_resolver(void* context, Resolver resolver) { std::lock_guard lock(hook_mutex_); if (hook_context_) return; hook_context_ = context; resolver_ = resolver; - scanner_ = scanner; } - void clear_hooks(void* context) { + void clear_resolver(void* context) { std::lock_guard lock(hook_mutex_); if (hook_context_ != context) return; hook_context_ = nullptr; resolver_ = nullptr; - scanner_ = nullptr; } std::size_t size() const { return count_.load(std::memory_order_acquire); } @@ -230,7 +213,6 @@ private: std::mutex hook_mutex_; void* hook_context_ = nullptr; Resolver resolver_ = nullptr; - TableScanner scanner_ = nullptr; void* source_context_ = nullptr; DescriptorSource source_ = nullptr; std::atomic pulled_{0}; diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h index ea65caa2d..8f2dd61f8 100644 --- a/runtime/src/vulkan13_features.h +++ b/runtime/src/vulkan13_features.h @@ -32,6 +32,8 @@ public: Vulkan13Features& operator=(const Vulkan13Features&) = delete; bool core = false; // a Vulkan 1.3 device: the features are core + bool pipeline_cache_control = false; + bool enable_pipeline_cache_control = false; bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device. @@ -45,6 +47,7 @@ public: void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { core = api_version >= VK_API_VERSION_1_3; + pipeline_cache_control=false;enable_pipeline_cache_control=false; dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; extended_dynamic_state = false; if (!features2) return; @@ -53,6 +56,7 @@ public: VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; features2(physical, &query); dynamic_rendering = f13.dynamicRendering == VK_TRUE; + pipeline_cache_control = f13.pipelineCreationCacheControl == VK_TRUE; synchronization2 = f13.synchronization2 == VK_TRUE; subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; @@ -98,6 +102,7 @@ public: // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). void choose(const Vulkan13Features& from) { core = from.core; + pipeline_cache_control=from.pipeline_cache_control;enable_pipeline_cache_control=false; dynamic_rendering = from.dynamic_rendering; synchronization2 = from.synchronization2; subgroup_size_control = from.subgroup_size_control; @@ -111,6 +116,7 @@ public: if (core) { enable13_.pNext = chain; enable13_.dynamicRendering = VK_TRUE; + enable13_.pipelineCreationCacheControl = pipeline_cache_control && enable_pipeline_cache_control ? VK_TRUE : VK_FALSE; enable13_.synchronization2 = VK_TRUE; enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 4bb6b53e3..566b7ccd4 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1,4 +1,5 @@ #pragma once +#include "vulkan_gpu_labels.h" // The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, // image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in @@ -85,7 +86,7 @@ struct VulkanDeviceFunctions { X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \ X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ - X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ + X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) X(vkCmdBlitImage) \ X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \ X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \ X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \ @@ -941,6 +942,7 @@ public: replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage; replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; replay_.copy_image = vk.vkCmdCopyImage; + replay_.blit_image = vk.vkCmdBlitImage; replay_.resolve_image = vk.vkCmdResolveImage; replay_.fill_buffer = vk.vkCmdFillBuffer; replay_.update_buffer = vk.vkCmdUpdateBuffer; @@ -1202,6 +1204,7 @@ public: } { std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled + storage_pending_.erase(id); std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); } if (img) { @@ -1274,6 +1277,18 @@ public: replay_.zero_size = size; } + struct GeometryUpload { + std::uint64_t source{}, size{}; + VkBuffer buffer{}; + VkDeviceSize offset{}; + std::shared_ptr owner; + }; + using GeometryProvider = std::function; + void set_geometry_provider(GeometryProvider provider) { + std::unique_lock lock(resource_mutex_); + geometry_provider_=std::move(provider); + } + // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). void set_title_memory(std::function copy) { std::unique_lock lock(resource_mutex_); @@ -1419,12 +1434,29 @@ public: // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + void set_graphics_family(std::uint32_t family) { graphics_family_ = family; } + void set_compute_copy_aspects(std::function check) { + replay_.compute_copy_aspects = std::move(check); + } // `before` is called at the start of every submission of command lists (a held batch: when it is released), // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. // Set once, before the first queue exists. void set_before_execute(std::function before) { before_execute_ = std::move(before); } + // Table VAs are offsets in this device's arena. Install its scanner before creating any queues. + using TableScanner = std::function; + void set_table_scanner(TableScanner scan) { table_scanner_ = std::move(scan); } + void set_cpu_texture_publisher(std::function f) { cpu_texture_publisher_ = std::move(f); } + bool publish_cpu_textures() const { return !cpu_texture_publisher_ || cpu_texture_publisher_(); } + void set_sample_table_resolver(std::function f) { sample_table_resolver_ = std::move(f); } + bool prepare_sample_table(std::uint64_t address, std::uint32_t count) const { + return !sample_table_resolver_ || sample_table_resolver_(address,count); + } + void scan_table(std::uint64_t va, std::uint32_t descriptors) const { + if (table_scanner_) table_scanner_(va, descriptors); + } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1448,9 +1480,10 @@ public: // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + std::vector families = {}) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); + scratch_ = std::make_unique(get, device_, std::move(allocate), std::move(families)); if (!scratch_->loaded()) scratch_.reset(); } @@ -1611,7 +1644,11 @@ private: const ResourceBinding* resolve(ResourceId id) const { const auto it = resources_.find(id); - return it == resources_.end() ? nullptr : &it->second; + if (it == resources_.end()) return nullptr; + const auto& binding = it->second; + // The caller holds resource_mutex_, so the registered owner's lifetime includes this bind. + if (binding.ensure_residency && !binding.ensure_residency(binding.residency_owner)) return nullptr; + return &binding; } // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. @@ -1739,6 +1776,10 @@ private: resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; std::function before_execute_; + TableScanner table_scanner_; + GeometryProvider geometry_provider_; + std::function sample_table_resolver_; + std::function cpu_texture_publisher_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -1760,6 +1801,7 @@ private: std::unique_ptr counted_dispatch_; std::uint32_t predicate_family_ = UINT32_MAX; std::uint32_t transfer_only_family_ = UINT32_MAX; + std::uint32_t graphics_family_ = UINT32_MAX; DebugLabelFunctions labels_; }; #ifdef _MSC_VER @@ -2345,6 +2387,23 @@ private: // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. if (prepared.size() < lists.size()) prepared.resize(lists.size()); ReplayFunctions replay = context_.replay_; + std::vector geometry; + if (context_.geometry_provider_) { + replay.title_memory = [&](std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { + if (!va || !bytes || bytes>UINT64_MAX-va) return false; + for (const auto& upload : geometry) { + if (va < upload.source || va-upload.source > upload.size || bytes > upload.size-(va-upload.source)) continue; + buffer=upload.buffer; offset=upload.offset+(va-upload.source); + return true; + } + VulkanContext::GeometryUpload upload; + if (!context_.geometry_provider_(va,bytes,upload)) return false; + buffer=upload.buffer;offset=upload.offset; + geometry.push_back(std::move(upload)); + return true; + }; + } + replay.graphics_family = family_ == context_.graphics_family_; replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy : kind_ == QueueKind::compute ? detail::queue_stages_compute : 0; @@ -2555,6 +2614,7 @@ private: }; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + label::completions().begin_record(command_buffer); if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { discard(); return ReplayResult::unsupported; @@ -2598,8 +2658,7 @@ private: storage_init_seen_ = context_.storage_init_version_; } // The set this submission binds may be a new generation whose table another queue's submission uploads: - // wait for that one, as for the storage images (the table's buffers are used by one queue family only: - // every D3D12 queue of the device is made in info.queue_family). + // wait for that one, as for the storage images. The table and fallback images share the device's families. if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && context_.bindless_upload_version_ != bindless_upload_seen_) { waits_.push_back(context_.bindless_upload_semaphore_); @@ -2706,6 +2765,7 @@ private: slot->counted_dispatch = std::move(counted_batch); queries.commit(); slot->segments = std::move(queries.retained); + slot->geometry = std::move(geometry); } else { discard(); } @@ -2940,6 +3000,7 @@ private: std::unique_ptr predicate; // retained until this slot completes std::vector khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime std::vector khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime + std::vector geometry; }; struct PendingBindings { @@ -2962,6 +3023,7 @@ private: auto& vk = context_.vk; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + label::completions().begin_record(command_buffer); if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { slot->ticket = 0; return false; @@ -3100,6 +3162,7 @@ private: for (auto& slot : buffers_) { if (slot.ticket > done) continue; slot.segments.clear(); + slot.geometry.clear(); recycle_khr_stages(slot.khr_instances); recycle_khr_as_queries(slot.khr_as_queries); for (VkEvent event : slot.events) @@ -3236,7 +3299,9 @@ private: submit.pCommandBuffers = &command_buffer; submit.signalSemaphoreCount = signal_count; submit.pSignalSemaphores = signals; - res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); + const auto label_fence=label::completions().submit_fence(command_buffer); + res = context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence); + label::completions().submitted(command_buffer,res==VK_SUCCESS); if (res == VK_SUCCESS) { context_.record_submit_locked(progress_, ticket); if (signals_fence) context_.holds().signaled(fence, value); diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h index cb5b61f65..1477a9924 100644 --- a/runtime/src/vulkan_bindless.h +++ b/runtime/src/vulkan_bindless.h @@ -8,9 +8,10 @@ // 2 the descriptor hash table 1 7 3D r32ui storage images 256 // 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: // 4 2D r32ui storage images 1024 storage images by component class -// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. +// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the first four STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. // bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). // bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. +// bindings 26-28: storage-only 1D-array images by component class, 256 each (STORE_DIMS index 4). // These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays // from the device's limits instead; the shaders declare runtime arrays, so any count works for them. // @@ -43,6 +44,7 @@ #define VK_NO_PROTOTYPES #endif #include "descriptor_table.h" +#include "queue_families.h" #include @@ -52,12 +54,13 @@ #include #include #include +#include #include namespace leonida { -// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. -enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; +// The first five dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. +enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_1d_array, dim_2d_ms, dim_2d_ms_array }; // Storage views of one image by the component type a shader reads or writes it with (the translator picks by the // T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). @@ -70,7 +73,7 @@ struct StorageViews { }; namespace bindless { -inline constexpr std::uint32_t binding_count = 26; +inline constexpr std::uint32_t binding_count = 29; constexpr std::array default_counts(); } // namespace bindless @@ -94,10 +97,12 @@ struct Binding { inline constexpr std::uint32_t table_binding = 2; inline constexpr std::uint32_t sampler_binding = 1; inline constexpr std::uint32_t first_ms_binding = 20; +inline constexpr std::uint32_t ms_binding_count = 6; +inline constexpr std::uint32_t first_1d_array_storage_binding = first_ms_binding + ms_binding_count; inline constexpr std::uint32_t no_binding = 0xffffffffu; -// Indexed by binding number. -inline constexpr std::array bindings = {{ +// Indexed by binding number. Keep the literal extent for tools/spirv_metal_set0.py. +inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, @@ -111,6 +116,8 @@ inline constexpr std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, + {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, }}; static_assert(bindings.size() == binding_count); @@ -121,8 +128,12 @@ constexpr std::array default_counts() { return counts; } +constexpr bool ms_binding(std::uint32_t binding) { + return binding >= first_ms_binding && binding < first_ms_binding + ms_binding_count; +} + constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { - return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; + return !ms_binding(binding) || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; } // Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose @@ -131,7 +142,8 @@ constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampl std::uint32_t resource_limit) { const auto& counts = features.counts; std::uint32_t sampled = 0, total = 0; - for (std::uint32_t b = 0; b < first_ms_binding; ++b) { + for (std::uint32_t b = 0; b < binding_count; ++b) { + if (ms_binding(b)) continue; if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; } @@ -153,12 +165,13 @@ constexpr bool multisampled(ImageDimension dimension) { } constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { - constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; + constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, no_binding, first_ms_binding, first_ms_binding + 1}; return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); } // component_class: 0 = float, 1 = uint, 2 = sint. constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { + if (dimension == ImageDimension::dim_1d_array) return first_1d_array_storage_binding + component_class; return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; } @@ -196,8 +209,9 @@ struct SetLayout { }; // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 3-6 MiB (93793 descriptors on an RTX 5070). +// roughly 4-8 MiB with 119137 descriptors when all MS classes and array bindings reach their limits. inline constexpr std::uint32_t max_2d_images = 65536; +inline constexpr std::uint32_t max_2d_array_images = 16384; inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images // A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can // create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. @@ -214,8 +228,9 @@ inline constexpr std::uint32_t growth_headroom = 64; // 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). // 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says // what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. -// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a -// storage view an index past the sampled array. The other bindings keep their default counts. +// A storage array holds the smaller of the storage count and its dimension's sampled count: add_image never +// gives a storage view an index past the sampled array. The storage-only 1D array is capped at its default of 256. +// The other bindings keep their default counts. // layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: // step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports // 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. @@ -243,15 +258,20 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi auto& counts = features.counts; counts = default_counts(); std::uint32_t images = 1, samplers = 1, storage = 1; + std::uint32_t array_images = bindings[sampled_binding(ImageDimension::dim_2d_array)].count; // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only // take descriptors away. const auto apply = [&](bool final) { counts[sampled_binding(ImageDimension::dim_2d)] = images; + counts[sampled_binding(ImageDimension::dim_2d_array)] = array_images; counts[sampler_binding] = samplers; - for (std::uint32_t d = 0; d < 4; ++d) { + for (std::uint32_t d = 0; d <= std::uint32_t(ImageDimension::dim_1d_array); ++d) { const auto dimension = ImageDimension(d); + const auto sampled_at = sampled_binding(dimension); + const auto capacity = sampled_at == no_binding ? bindings[storage_binding(dimension, 0)].count + : counts[sampled_at]; const bool capped = final || dimension != ImageDimension::dim_2d; - const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; + const std::uint32_t held = capped ? std::min(storage, capacity) : storage; for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; } @@ -305,6 +325,9 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); + // A material can keep many array-layer and cube views alive at once. Grow them only out of + // the remaining set budget, including any storage bindings that share their index range. + grow(array_images, max_2d_array_images, growth_headroom, set_limit); apply(true); return full; } @@ -314,8 +337,8 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi class BindlessSet { public: BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}) - : device_(device), memory_(memory), features_(features) { + BindlessFeatures features = {}, std::vector families = {}) + : device_(device), memory_(memory), features_(features), families_(std::move(families)) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); } @@ -342,7 +365,8 @@ public: // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. std::uint32_t image_capacity(ImageDimension dimension) const { - return features_.counts[bindless::sampled_binding(dimension)]; + const auto binding = bindless::sampled_binding(dimension); + return binding == bindless::no_binding ? storage_capacity(dimension) : features_.counts[binding]; } std::uint32_t storage_capacity(ImageDimension dimension) const { return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; @@ -401,6 +425,7 @@ public: std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; + if (!stores && bindless::sampled_binding(dimension) == bindless::no_binding) return 0; if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; auto& used = image_used_[std::uint32_t(dimension)]; const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); @@ -597,7 +622,7 @@ private: VkDescriptorImageInfo info; }; - static constexpr std::uint32_t dimensions = 6, classes = 3; + static constexpr std::uint32_t dimensions = 7, classes = 3; // The first free index in [begin, end), marked used; 0 when there is none. static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { @@ -695,10 +720,11 @@ private: constexpr std::uint32_t ms_type = 3; constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; // dimension -> (index into types, view type) - constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; + constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, 2, ms_type, ms_type}; constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; + VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, + VK_IMAGE_VIEW_TYPE_1D_ARRAY, + VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; for (std::uint32_t t = 0; t < std::size(types); ++t) { for (std::uint32_t c = 0; c < classes; ++c) { if (t == ms_type && !supports_ms_class(c)) continue; @@ -713,6 +739,7 @@ private: if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; FallbackImage& image = fallback_images_[t * classes + c]; + share_across_queue_families(info, families_); if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); @@ -737,8 +764,9 @@ private: VkImageView view = VK_NULL_HANDLE; if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; fallback_views_.push_back(view); - if (c == 0 || bindless::multisampled(dimension)) - fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; + const auto sampled_at = bindless::sampled_binding(dimension, c); + if (sampled_at != bindless::no_binding && (c == 0 || bindless::multisampled(dimension))) + fallback_by_binding_[sampled_at] = view; const auto storage_at = bindless::storage_binding(dimension, c); if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; const auto r32ui_at = bindless::r32ui_binding(dimension); @@ -760,6 +788,7 @@ private: (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); TableBuffer made; made.size = bytes; + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); @@ -998,8 +1027,9 @@ private: return; } const std::uint32_t sampled_at = bindless::sampled_binding(dimension); - queue(sampled_at, index, - sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); + if (sampled_at != bindless::no_binding) + queue(sampled_at, index, + sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); const auto store = [&](std::uint32_t binding, VkImageView view) { if (binding == bindless::no_binding || index >= features_.counts[binding]) return; queue(binding, index, @@ -1014,6 +1044,7 @@ private: VkDevice device_; VkPhysicalDeviceMemoryProperties memory_; BindlessFeatures features_; + std::vector families_; Functions vk_; bool ok_ = false; VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; diff --git a/runtime/src/vulkan_gpu_labels.h b/runtime/src/vulkan_gpu_labels.h new file mode 100644 index 000000000..d507fb171 --- /dev/null +++ b/runtime/src/vulkan_gpu_labels.h @@ -0,0 +1,156 @@ +#pragma once +#include "gpu_label_memory.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif + +namespace leonida::label { +inline bool enabled() { + static const bool active=[] {const char* v=std::getenv("LEONIDA_GPU_LABELS");return v && v[0]=='1';}(); + return active; +} +// Each submitted Vulkan command buffer owns a fence and its query slots until the GPU finishes it. +// The CPU destination is a generation-checked title data allocation. No guest pointer is a GPU command destination. +class Completions { + static constexpr unsigned per_pool=64; + struct Batch { + VkFence fence{}; + std::vector pools; + std::vector labels; + }; + std::mutex mutex_; std::condition_variable changed_; bool closing_=false; + std::thread worker_; bool process_shutdown_=false; VkDevice device_{}; + std::unordered_map> recording_; + std::vector> pending_; + std::vector idle_pools_; std::vector idle_fences_; + PFN_vkCreateQueryPool create_pool_{}; PFN_vkDestroyQueryPool destroy_pool_{}; + PFN_vkCmdResetQueryPool reset_query_{}; PFN_vkCmdWriteTimestamp timestamp_{}; PFN_vkGetQueryPoolResults results_{}; + PFN_vkCreateFence create_fence_{}; PFN_vkDestroyFence destroy_fence_{}; PFN_vkGetFenceStatus fence_status_{}; + PFN_vkResetFences reset_fences_{}; PFN_vkDeviceWaitIdle device_idle_{}; + std::uint64_t published_[3]{},lost_{},errors_{}; + VkQueryPool pool() { + if(!idle_pools_.empty()){auto h=idle_pools_.back();idle_pools_.pop_back();return h;} + VkQueryPoolCreateInfo c{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};c.queryType=VK_QUERY_TYPE_TIMESTAMP;c.queryCount=per_pool; + VkQueryPool p{};return create_pool_(device_,&c,nullptr,&p)==VK_SUCCESS?p:VK_NULL_HANDLE; + } + VkFence fence() { + if(!idle_fences_.empty()){auto f=idle_fences_.back();idle_fences_.pop_back();if(reset_fences_(device_,1,&f)==VK_SUCCESS)return f;destroy_fence_(device_,f,nullptr);} + VkFenceCreateInfo c{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};VkFence f{};return create_fence_(device_,&c,nullptr,&f)==VK_SUCCESS?f:VK_NULL_HANDLE; + } + void recycle(Batch& b) {for(auto p:b.pools)idle_pools_.push_back(p);if(b.fence)idle_fences_.push_back(b.fence);} + static bool store(const Target& target,std::uint64_t value) { +#ifdef _WIN32 + return memory().publish(target,[&](std::uintptr_t address,unsigned width,std::uintptr_t allocation_base){ + MEMORY_BASIC_INFORMATION mbi{}; + if(!VirtualQuery(reinterpret_cast(address),&mbi,sizeof(mbi)) || mbi.State!=MEM_COMMIT || + mbi.Type!=MEM_PRIVATE || reinterpret_cast(mbi.AllocationBase)!=allocation_base || + (mbi.Protect&PAGE_GUARD) || ((mbi.Protect&0xff)!=PAGE_READWRITE && (mbi.Protect&0xff)!=PAGE_WRITECOPY)) return false; + const auto begin=reinterpret_cast(mbi.BaseAddress); + if(addressmbi.RegionSize || mbi.RegionSize-(address-begin)(address),static_cast(value)); + else InterlockedExchange64(reinterpret_cast(address),static_cast(value)); + return true; + }); +#else + (void)target;(void)value;return false; +#endif + } + void publish(const Batch& batch) { + for(std::size_t i=0;i(i%per_pool),1,sizeof(value),&value, + sizeof(value),VK_QUERY_RESULT_64_BIT)!=VK_SUCCESS){++errors_;continue;} + } else if(op.clock==2) { +#ifdef _WIN32 + LARGE_INTEGER qpc{}; if(!QueryPerformanceCounter(&qpc)){++errors_;continue;} + value=static_cast(qpc.QuadPart); +#else + ++errors_;continue; +#endif + } + if(store(op.target,value))++published_[op.clock];else ++lost_; + } + } + void run() { + std::unique_lock lock(mutex_); + for(;;) { + if(pending_.empty() && !closing_) changed_.wait(lock,[&]{return closing_ || !pending_.empty();}); + if(process_shutdown_)return; + for(auto i=pending_.begin();i!=pending_.end();) { + auto& b=**i;const auto status=fence_status_(device_,b.fence); + if(status==VK_NOT_READY && !closing_){++i;continue;} + if(status==VK_SUCCESS)publish(b);else ++errors_; + recycle(b);i=pending_.erase(i); + } + if(closing_)return; + if(!pending_.empty())changed_.wait_for(lock,std::chrono::milliseconds(1)); + } + } +public: + ~Completions() { + if(!worker_.joinable())return; + {std::lock_guard lock(mutex_);process_shutdown_=true;closing_=true;changed_.notify_all();} + worker_.join(); + } + void initialize(VkDevice dev,PFN_vkGetDeviceProcAddr get) { + if(!enabled() || !dev || !get)return; + std::lock_guard lock(mutex_);if(device_)return; +#define LABEL_FN(name) reinterpret_cast(get(dev,#name)) + create_pool_=LABEL_FN(vkCreateQueryPool);destroy_pool_=LABEL_FN(vkDestroyQueryPool); + reset_query_=LABEL_FN(vkCmdResetQueryPool);timestamp_=LABEL_FN(vkCmdWriteTimestamp);results_=LABEL_FN(vkGetQueryPoolResults); + create_fence_=LABEL_FN(vkCreateFence);destroy_fence_=LABEL_FN(vkDestroyFence);fence_status_=LABEL_FN(vkGetFenceStatus); + reset_fences_=LABEL_FN(vkResetFences);device_idle_=LABEL_FN(vkDeviceWaitIdle); +#undef LABEL_FN + if(!create_pool_||!destroy_pool_||!reset_query_||!timestamp_||!results_||!create_fence_||!destroy_fence_||!fence_status_||!reset_fences_||!device_idle_)return; + device_=dev;closing_=false;worker_=std::thread([this]{run();}); + } + void begin_record(VkCommandBuffer cb) { + if(!enabled())return;std::lock_guard lock(mutex_);auto i=recording_.find(cb); + if(i!=recording_.end()){recycle(*i->second);recording_.erase(i);} + } + void record(VkCommandBuffer cb,const Write& op) { + if(!enabled())return;std::lock_guard lock(mutex_);if(!device_||closing_){++errors_;return;} + auto& slot=recording_[cb]; + if(!slot){slot=std::make_unique();slot->fence=fence();} + if(!slot->fence){++errors_;return;} + const auto i=slot->labels.size();const auto j=static_cast(i%per_pool); + if(!j){auto p=pool();if(!p){++errors_;return;}slot->pools.push_back(p);} + auto p=slot->pools[i/per_pool];reset_query_(cb,p,j,1);timestamp_(cb,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,p,j); + slot->labels.push_back(op); + } + VkFence submit_fence(VkCommandBuffer cb) { + if(!enabled()||!cb)return VK_NULL_HANDLE;std::lock_guard lock(mutex_);auto i=recording_.find(cb); + return i==recording_.end()?VK_NULL_HANDLE:i->second->fence; + } + void submitted(VkCommandBuffer cb,bool ok) { + if(!enabled()||!cb)return;std::lock_guard lock(mutex_);auto i=recording_.find(cb);if(i==recording_.end())return; + if(ok && i->second->fence){pending_.push_back(std::move(i->second));changed_.notify_one();}else recycle(*i->second); + recording_.erase(i); + } + void stop(VkDevice dev) { + {std::lock_guard lock(mutex_);if(!dev||device_!=dev)return;} + device_idle_(dev); + {std::lock_guard lock(mutex_);closing_=true;changed_.notify_all();} + if(worker_.joinable())worker_.join();std::lock_guard lock(mutex_); + for(auto& pair:recording_)recycle(*pair.second);recording_.clear(); + for(auto f:idle_fences_)destroy_fence_(dev,f,nullptr);idle_fences_.clear(); + for(auto p:idle_pools_)destroy_pool_(dev,p,nullptr);idle_pools_.clear(); + device_=VK_NULL_HANDLE; + } +}; +inline Completions& completions(){static Completions engine;return engine;} +} // namespace leonida::label diff --git a/runtime/src/vulkan_graphics_shader_modules.h b/runtime/src/vulkan_graphics_shader_modules.h new file mode 100644 index 000000000..5c2b1bd71 --- /dev/null +++ b/runtime/src/vulkan_graphics_shader_modules.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { +class GraphicsShaderModules { +public: + struct Module { + VkDevice device; + PFN_vkDestroyShaderModule destroy; + std::vector words; + VkShaderModule handle = VK_NULL_HANDLE; + Module(VkDevice d, PFN_vkDestroyShaderModule fn, std::span input) + : device(d), destroy(fn), words(input.begin(), input.end()) {} + ~Module() { if (handle) destroy(device, handle, nullptr); } + }; + using Reference = std::shared_ptr; + Reference acquire(VkDevice device, PFN_vkCreateShaderModule create, PFN_vkDestroyShaderModule destroy, + std::span words, bool reuse = true) { + if (words.empty()) return {}; + std::uint64_t hash = 14695981039346656037ull; + if (reuse) { + for (std::uint32_t word : words) hash = (hash ^ word) * 1099511628211ull; + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) { ++hits_; return found; } + } + auto result = std::make_shared(device, destroy, words); + VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + info.pCode = words.data(); info.codeSize = words.size_bytes(); + if (create(device, &info, nullptr, &result->handle) != VK_SUCCESS) { result->handle=VK_NULL_HANDLE; return {}; } + if (!reuse) return result; + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) { ++hits_; return found; } + if ((++created_ % 1024) == 0) + std::erase_if(modules_, [](const auto& entry) { return entry.second.expired(); }); + modules_.emplace(hash,result); + return result; + } + std::pair counts() { + std::lock_guard lock(mutex_); return {created_,hits_}; + } +private: + Reference find_locked(std::uint64_t hash, std::span words) { + const auto [first,last] = modules_.equal_range(hash); + for (auto i=first; i!=last; ++i) + if (auto live=i->second.lock(); live && std::equal(words.begin(),words.end(),live->words.begin(),live->words.end())) + return live; + return {}; + } + std::mutex mutex_; + std::unordered_multimap> modules_; + std::uint64_t created_=0,hits_=0; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index cdc6b5bfe..54dd7c926 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,5 +1,7 @@ #include #pragma once +#include +#include "vulkan_gpu_labels.h" #include "resource_tiling.h" @@ -100,6 +102,13 @@ struct ResourceBinding { bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush bool sparse_buffer = false; + bool xbox_depth16_stencil8=false; + bool rgba4_render_fallback=false; + // The two independently addressable storage images of an Xbox depth/stencil UAV. + ResourceId depth_uav = 0, stencil_uav = 0; + void* residency_owner = nullptr; + bool (*ensure_residency)(void*) = nullptr; + ResourceId depth_conversion = 0; // R32_FLOAT transfer image for a widened Xbox D16+S8 attachment }; struct VulkanAccess { @@ -465,6 +474,7 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) { case VK_FORMAT_R16_SINT: case VK_FORMAT_A4R4G4B4_UNORM_PACK16: case VK_FORMAT_R4G4B4A4_UNORM_PACK16: + case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D16_UNORM: return {2, 1}; case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: @@ -759,6 +769,7 @@ struct ComputePipeline { VkPipelineLayout layout = VK_NULL_HANDLE; std::uint64_t code_base = 0; VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none + std::function materialize; }; // A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it @@ -780,8 +791,11 @@ struct GraphicsPipeline { // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth // and stencil. Null when it cannot be built. static constexpr std::uint32_t unbound_depth = 1u << 8; + static constexpr std::uint32_t rectangle_stage = 1u << 9; + bool base_rectangle_stage = false; std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count + bool pending_base_compile = false; }; // The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. @@ -819,6 +833,9 @@ struct ReplayFunctions { // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers VkPipelineStageFlags2 queue_stages = 0; + bool graphics_family = true; + // Aspects with maintenance10 depth/stencil transfer support on a dedicated compute family. + std::function compute_copy_aspects; PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears PFN_vkCmdEndRendering end_rendering = nullptr; PFN_vkCmdClearAttachments clear_attachments = nullptr; @@ -826,6 +843,7 @@ struct ReplayFunctions { PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr; PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; PFN_vkCmdCopyImage copy_image = nullptr; + PFN_vkCmdBlitImage blit_image = nullptr; PFN_vkCmdResolveImage resolve_image = nullptr; // resolves PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears @@ -1039,6 +1057,7 @@ struct Prepared { // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. VkBuffer staged = VK_NULL_HANDLE; std::vector staged_reads, staged_writes; + VkDeviceSize clear_pattern_bytes = 0; // rectangular UAV clear on a compute-only queue std::vector discards; // DiscardResource: the subresources to discard VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands VkDeviceSize write_offset = 0; @@ -1050,6 +1069,8 @@ struct Prepared { QueryPool* queries = nullptr; // query commands: the heap ComputePipeline pipeline; // dispatches std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws + std::uint32_t depth_uav_copy = UINT32_MAX; + bool order_depth_uav = false; VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write @@ -1057,6 +1078,26 @@ struct Prepared { std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR }; +struct DepthUavCopy { + std::array storage; + ResourceBinding conversion{}; + VkBuffer scratch; + VkDeviceSize offset; + bool to_storage; +}; + +inline bool texture_uav_layout(std::uint32_t layout) { + return layout == d3d12_layout::unordered_access || layout == d3d12_layout::direct_queue_unordered_access || + layout == d3d12_layout::compute_queue_unordered_access; +} + +inline bool unsupported_depth_uav_access(std::uint32_t layout, std::uint32_t access) { + // A queue-specific COMMON layout permits implicit storage writes. Generic COMMON permits only + // sampling and copies, even when the access scope is COMMON (zero). + return layout == d3d12_layout::direct_queue_common || layout == d3d12_layout::compute_queue_common || + (layout == d3d12_layout::common && (access & d3d12_access::unordered_access)); +} + inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT // What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every @@ -1371,14 +1412,12 @@ inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const V return out; } -// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page -// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids -// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set -// (D3D-220). -inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, - const ResourceBinding& resource, const VkImageSubresourceRange& range, - VkImageLayout dst_layout) { - const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); +// Copies zeroes from the device's zero page or transfer scratch. A buffer can initialize block-compressed +// images and, with maintenance10, a depth or stencil aspect on a compute-only queue where a clear is illegal. +inline bool zero_image_aspect(const ReplayFunctions& vk, VkCommandBuffer command_buffer, + const ResourceBinding& resource, const VkImageSubresourceRange& range, + VkImageAspectFlags aspect, VkImageLayout dst_layout) { + const BlockFormat fmt = block_format(resource.format, aspect); if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; const std::uint32_t mip_begin = range.baseMipLevel; const std::uint32_t mip_end = @@ -1412,7 +1451,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com VkDeviceSize zero_off = 0; VkDeviceSize zero_cap = 0; if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { - const VkDeviceSize align = fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; if (vk.zero_size >= pad + fmt.bytes) { zero_buf = vk.zero_buffer; @@ -1421,12 +1460,11 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com } } if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { - // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). - const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; + const VkDeviceSize align = std::max(4, fmt.bytes); + const VkDeviceSize fill_bytes = ((needed + align - 1) / align) * align; VkBuffer scratch = VK_NULL_HANDLE; VkDeviceSize offset = 0; if (vk.copy_scratch(fill_bytes, scratch, offset)) { - const VkDeviceSize align = fmt.bytes; const VkDeviceSize pad = (align - (offset % align)) % align; if (fill_bytes >= pad + fmt.bytes) { vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); @@ -1451,7 +1489,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com layer_count <= zero_cap / (slice_bytes * mip_d)) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; + r.imageSubresource = {aspect, mip, layer_begin, layer_count}; r.imageExtent = {ext.width, ext.height, mip_d}; regions.push_back(r); continue; @@ -1464,7 +1502,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, 0, std::int32_t(z)}; r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; regions.push_back(r); @@ -1478,7 +1516,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com const std::uint32_t eh = std::min(rows_per_copy * fmt.block, ext.height - oy); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ext.width, eh, 1}; regions.push_back(r); @@ -1497,7 +1535,7 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com std::min(cols_per_copy * fmt.block, ext.width - ox); VkBufferImageCopy r{}; r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; + r.imageSubresource = {aspect, mip, layer, 1}; r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; r.imageExtent = {ew, eh, 1}; regions.push_back(r); @@ -1524,12 +1562,15 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; - const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); - const bool compressed = fmt.block > 1 || (!can_clear && color); - if (resource.not_zeroed || (!can_clear && !color)) { + const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color) || + (resource.depth_uav && vk.graphics_family); + const bool compute_depth = !color && resource.depth_uav && !vk.graphics_family && + (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && vk.compute_copy_aspects && + (vk.compute_copy_aspects(resource.format) & piece.range.aspectMask) == piece.range.aspectMask; + if (resource.not_zeroed || (!can_clear && !color && !compute_depth)) { image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (compressed) { + } else if (fmt.block > 1 || !can_clear) { const bool can_zero = vk.copy_buffer_to_image && ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); @@ -1538,7 +1579,10 @@ inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); + bool zeroed = true; + for (auto aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) + if (piece.range.aspectMask & aspect) + zeroed &= zero_image_aspect(vk, command_buffer, resource, piece.range, aspect, dst); image_barrier(vk, command_buffer, resource, piece.range, dst, layout, zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, @@ -2102,6 +2146,77 @@ void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const } } +// Vulkan cannot copy a depth or stencil image aspect directly to or from a color image. The transfer +// buffer preserves the native D16, D32 or S8 bits. Only the requested layers and planes are copied, even when the device +// requires both parent aspects to transition layouts together. A storage descriptor always names GENERAL. +inline void copy_depth_uav(const ReplayFunctions& vk, VkCommandBuffer cb, const Prepared& p, const DepthUavCopy& copy, + VkImageLayout parent_layout, LayoutTracker* tracker) { + constexpr auto all = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; + constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; + constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; + const auto parent_access = copy.to_storage ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_TRANSFER_WRITE_BIT; + const auto child_access = copy.to_storage ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT; + const auto parent_range = planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts); + image_barrier(vk, cb, p.binding, parent_range, parent_layout, VK_IMAGE_LAYOUT_GENERAL, + any, all, parent_access, transfer); + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + for (unsigned plane = 0; plane < copy.storage.size(); ++plane) { + const ResourceBinding& child = copy.storage[plane]; + if (!child.image) continue; + const ResourceId child_id = plane ? p.binding.stencil_uav : p.binding.depth_uav; + auto pieces = current(tracker, child_id, color, VK_IMAGE_LAYOUT_GENERAL); + if (!copy.to_storage) initialize(vk, cb, child, child_id, pieces, VK_IMAGE_LAYOUT_GENERAL, tracker); + for (const auto& piece : pieces) + image_barrier(vk, cb, child, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, child_access, transfer); + if (tracker) tracker->set(child_id, color, VK_IMAGE_LAYOUT_GENERAL); + VkBufferImageCopy parent_region{}; + parent_region.bufferOffset = copy.offset; + const VkImageAspectFlags aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + parent_region.imageSubresource = {aspect, p.range.baseMipLevel, p.range.baseArrayLayer, p.range.layerCount}; + parent_region.imageExtent = {p.binding.width, p.binding.height, 1}; + VkBufferImageCopy child_region = parent_region; + child_region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + // Last use of this staging range was a read by CopyBufferToImage, possibly on the previous barrier. + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_READ_BIT, transfer, VK_ACCESS_TRANSFER_WRITE_BIT, transfer); + // A D32 depth aspect and R32_FLOAT colour carry the same bits through transfer scratch. The + // intermediate colour image permits a real normalized blit between R32_FLOAT and R16_UNORM; + // shaders see the latter's exact bits through an R16_UINT view. + const bool convert = plane == 0 && copy.conversion.image; + const VkImage colour = convert ? copy.conversion.image : child.image; + VkImageBlit blit{}; + if (convert) { + const auto id = p.binding.depth_conversion; + const auto previous = current(tracker, id, color, VK_IMAGE_LAYOUT_UNDEFINED); + for (const auto& piece : previous) + image_barrier(vk, cb, copy.conversion, piece.range, piece.layout, VK_IMAGE_LAYOUT_GENERAL, + piece.layout == VK_IMAGE_LAYOUT_UNDEFINED ? 0 : any, all, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, transfer); + if (tracker) tracker->set(id, color, VK_IMAGE_LAYOUT_GENERAL); + blit.srcSubresource = blit.dstSubresource = child_region.imageSubresource; + blit.srcOffsets[1] = blit.dstOffsets[1] = {int32_t(p.binding.width), int32_t(p.binding.height), 1}; + if (!copy.to_storage) { + vk.blit_image(cb, child.image, VK_IMAGE_LAYOUT_GENERAL, colour, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST); + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + } + } + vk.copy_image_to_buffer(cb, copy.to_storage ? p.binding.image : colour, VK_IMAGE_LAYOUT_GENERAL, + copy.scratch, 1, copy.to_storage ? &parent_region : &child_region); + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + vk.copy_buffer_to_image(cb, copy.scratch, copy.to_storage ? colour : p.binding.image, VK_IMAGE_LAYOUT_GENERAL, + 1, copy.to_storage ? &child_region : &parent_region); + if (convert && copy.to_storage) { + memory_barrier(vk, cb, VK_ACCESS_TRANSFER_WRITE_BIT, transfer, VK_ACCESS_TRANSFER_READ_BIT, transfer); + vk.blit_image(cb, colour, VK_IMAGE_LAYOUT_GENERAL, child.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_NEAREST); + } + image_barrier(vk, cb, child, color, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, + child_access, transfer, any, all); + } + image_barrier(vk, cb, p.binding, parent_range, VK_IMAGE_LAYOUT_GENERAL, parent_layout, + parent_access, transfer, any, all); +} + } // namespace detail namespace detail { @@ -2117,7 +2232,7 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) return ReplayResult::unsupported; const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->pending_base_compile)) return ReplayResult::unresolved_resource; if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; @@ -2180,7 +2295,9 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct for (std::size_t slot = 0; slot < p.colors.size(); ++slot) if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; - if (unbound) { + if (!draw.mesh && draw.topology == topology_rect_list && !pipeline->base_rectangle_stage) + unbound |= GraphicsPipeline::rectangle_stage; + if (unbound || (!p.pipeline && pipeline->pending_base_compile)) { p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; if (!p.pipeline) return ReplayResult::unsupported; } @@ -2314,6 +2431,7 @@ public: // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. std::vector draws; + std::vector depth_uav_copies; std::size_t draw_count = 0; std::vector queries; VkQueryPool segment_pool = VK_NULL_HANDLE; @@ -2574,6 +2692,13 @@ inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFun }, command); if (missing(id, p.binding, p.range)) return true; + if (p.depth_uav_copy != UINT32_MAX) { + const auto& copy = prepared.depth_uav_copies[p.depth_uav_copy]; + auto color = p.range; + color.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + if (!copy.to_storage && (missing(p.binding.depth_uav, copy.storage[0], color) || + missing(p.binding.stencil_uav, copy.storage[1], color))) return true; + } } return false; } @@ -2591,6 +2716,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.list = &list; out.commands.assign(commands.size(), {}); out.draw_count = 0; + out.depth_uav_copies.clear(); out.queries.clear(); out.segment_pool = VK_NULL_HANDLE; out.segment_base = out.segment_count = 0; @@ -2621,6 +2747,60 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun out.wrote_readback = false; out.readback_src_stages = 0; + // Successive plane transfers use the same transient range and order their buffer accesses in emit(). + VkBuffer plane_scratch = VK_NULL_HANDLE; + VkDeviceSize plane_capacity = 0, plane_offset = 0; + const auto prepare_depth_uav = [&](detail::Prepared& p, bool before, bool after) { + if (!p.binding.depth_uav && !p.binding.stencil_uav) return ReplayResult::success; + if (before == after) { + p.order_depth_uav = after; + return ReplayResult::success; + } + if (!vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch) + return ReplayResult::unsupported; + if (!vk.graphics_family) { + // Coupled layouts can also need to zero-initialize the sibling plane on first use. + const auto aspects = detail::planes_for_layout(p.binding, p.range, vk.separate_depth_stencil_layouts).aspectMask; + if (!(vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) || !vk.compute_copy_aspects || + (vk.compute_copy_aspects(p.binding.format) & aspects) != aspects) + return ReplayResult::unsupported; + } + if (p.range.baseMipLevel || p.range.levelCount != 1) return ReplayResult::unsupported; + detail::DepthUavCopy copy{}; + if (p.binding.depth_conversion && (p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT)) { + if (!vk.graphics_family || !vk.blit_image) return ReplayResult::unsupported; + const auto* middle = resolve(p.binding.depth_conversion); + if (!middle || !middle->image) return ReplayResult::unresolved_resource; + copy.conversion = *middle; + } + const ResourceId ids[] = {p.binding.depth_uav, p.binding.stencil_uav}; + for (unsigned plane = 0; plane < 2; ++plane) { + const auto aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; + if (!(p.range.aspectMask & aspect)) continue; + const auto* child = resolve(ids[plane]); + if (!child || !child->image) return ReplayResult::unresolved_resource; + copy.storage[plane] = *child; + } + const VkDeviceSize texels = VkDeviceSize(p.binding.width) * p.binding.height; + const auto largest_aspect = p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT ? VK_IMAGE_ASPECT_DEPTH_BIT : + VK_IMAGE_ASPECT_STENCIL_BIT; + const VkDeviceSize bytes_per_texel = block_format(p.binding.format, largest_aspect).bytes; + if (!texels || !bytes_per_texel || texels > UINT64_MAX / bytes_per_texel / p.range.layerCount) + return ReplayResult::unsupported; + const VkDeviceSize bytes = texels * bytes_per_texel * p.range.layerCount; + if (bytes > plane_capacity) { + if (!vk.copy_scratch(bytes, plane_scratch, plane_offset) || !plane_scratch || plane_offset % 4) + return ReplayResult::unsupported; + plane_capacity = bytes; + } + copy.scratch = plane_scratch; + copy.offset = plane_offset; + copy.to_storage = after; + p.depth_uav_copy = static_cast(out.depth_uav_copies.size()); + out.depth_uav_copies.push_back(copy); + return ReplayResult::success; + }; + for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; auto& p = out.commands[i]; @@ -2658,6 +2838,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun } else if (!image_range(p.binding, transition->subresource, p.range)) { return ReplayResult::invalid_subresource; } + const auto result = prepare_depth_uav(p, transition->before & d3d12_state::unordered_access, + transition->after & d3d12_state::unordered_access); + if (result != ReplayResult::success) return result; } else if (std::holds_alternative(command) || std::holds_alternative(command)) { if (!vk.pipeline_barrier2) return ReplayResult::unsupported; if (const auto* buffer_barrier = std::get_if(&command)) @@ -2667,6 +2850,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!bind(texture->resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) return ReplayResult::invalid_subresource; + // In a queue-specific COMMON layout shaders can write a UAV then read the SRV or copy the + // parent after only a global barrier. Bindless shaders need no per-resource bind command, so + // there is no observable ownership transition at which to synchronize the two images. + if (p.binding.depth_uav && + (detail::unsupported_depth_uav_access(texture->layout_before, texture->access_before) || + detail::unsupported_depth_uav_access(texture->layout_after, texture->access_after))) + return ReplayResult::unsupported; + if (!(texture->flags & texture_barrier_discard) && texture->layout_before != d3d12_layout::undefined) { + const auto result = prepare_depth_uav(p, detail::texture_uav_layout(texture->layout_before), + detail::texture_uav_layout(texture->layout_after)); + if (result != ReplayResult::success) return result; + } } else if (const auto* color_clear = std::get_if(&command)) { if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; @@ -2739,20 +2934,55 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the // bit-exact R32_UINT backing path. const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; + const bool packed_rgb9e5 = view_format == VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 && + p.binding.format == VK_FORMAT_R32_UINT; if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) return ReplayResult::unsupported; const auto* image_layout = uav_clear::layout(p.binding.format); if (!image_layout || image_layout->bytes != p.element.size) return ReplayResult::unsupported; - const bool attachment = p.binding.color_attachment && !p.binding.volume; + // The UAV attachment path supports 1D-array and 2D-array views. Keep 3D clears on the transfer + // path and retain the exact-format restriction for 1D/3D UAVs below. + const bool attachment = p.binding.color_attachment && !p.binding.volume && + (!view.exact_clear_format || p.binding.line); const bool view_attachable = vk.color_attachment_format ? vk.color_attachment_format(view_format) : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; + const bool reinterpret = view_format != p.binding.format && attachment && view_attachable && !packed_rgb9e5; + if (view.exact_clear_format && view_format != p.binding.format && !packed_rgb9e5) + return ReplayResult::unsupported; const VkFormat clear_format = reinterpret ? view_format : p.binding.format; if (!uav_clear::decode(clear_format, p.element, p.clear_color)) return ReplayResult::unsupported; if (reinterpret) p.clear_format = view_format; + // Compute list barriers have no attachment stages, and a dedicated compute queue cannot render. + // Copy the encoded texel bits from a filled buffer. Transfers cannot implement a predicated clear. + if ((vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) && + (!uav->rects.empty() || reinterpret || predicated)) { + if (predicated || p.binding.volume || !vk.copy_scratch || !vk.fill_buffer || !vk.copy_buffer_to_image || + (p.element.size != 1 && p.element.size != 2 && p.element.size != 4)) + return ReplayResult::unsupported; + const auto rects = uav->rects.empty() ? std::span(&whole_view, 1) : + std::span(uav->rects); + detail::clip(rects, detail::mip_extent(p.binding, view.mip), view.layer_count, p.rects); + if (p.rects.empty()) { p.skip = true; continue; } + for (const auto& rect : p.rects) { + VkBufferImageCopy region{}; + region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, view.mip, view.first_layer, view.layer_count}; + region.imageOffset = {rect.rect.offset.x, rect.rect.offset.y, 0}; + region.imageExtent = {rect.rect.extent.width, rect.rect.extent.height, 1}; + const VkDeviceSize pixels = VkDeviceSize(region.imageExtent.width) * region.imageExtent.height; + const VkDeviceSize stride = VkDeviceSize(view.layer_count) * p.element.size; + if (pixels > (UINT64_MAX - 3) / stride) return ReplayResult::unsupported; + p.clear_pattern_bytes = std::max(p.clear_pattern_bytes, (pixels * stride + 3) & ~VkDeviceSize(3)); + p.staged_writes.push_back(region); + } + VkDeviceSize offset = 0; + if (!vk.copy_scratch(p.clear_pattern_bytes, p.staged, offset) || !p.staged || offset % 4) + return ReplayResult::unsupported; + for (auto& region : p.staged_writes) region.bufferOffset = offset; + continue; + } if (!uav->rects.empty() && !attachment) return ReplayResult::unsupported; // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as @@ -2818,6 +3048,9 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) return ReplayResult::unsupported; + if(result==ReplayResult::success && image.rgba4_render_fallback) return ReplayResult::unsupported; + if(result==ReplayResult::success && image.xbox_depth16_stencil8 && image.format!=VK_FORMAT_D16_UNORM_S8_UINT && + !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask==VK_IMAGE_ASPECT_DEPTH_BIT) return ReplayResult::unsupported; const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && !p.buffer_image_copies.empty() && p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; @@ -2950,6 +3183,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!discard->partial) p.discards.push_back(range); } } + } else if (std::holds_alternative(command)) { + // No GPU destination pointer is expected: the batch publishes only a registered title allocation. } else if (const auto* write = std::get_if(&command)) { if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; std::uint64_t bytes = 4; @@ -3082,9 +3317,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline) { + p.pipeline.pipeline=pipeline->materialize(); + if (!p.pipeline.pipeline) return ReplayResult::unsupported; + } } } else if (const auto* build = std::get_if(&command)) { p.khr_instances = 0; @@ -3170,9 +3409,13 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) return ReplayResult::unsupported; const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; + if (!pipeline || (!pipeline->pipeline && !pipeline->materialize)) return ReplayResult::unresolved_resource; if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; p.pipeline = *pipeline; + if (!p.pipeline.pipeline) { + p.pipeline.pipeline=pipeline->materialize(); + if (!p.pipeline.pipeline) return ReplayResult::unsupported; + } } else if (const auto* draw = std::get_if(&command)) { if (out.draw_count == out.draws.size()) out.draws.emplace_back(); auto& prepared_draw = out.draws[out.draw_count]; @@ -3456,6 +3699,15 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c vk.depth24_run(command_buffer, job); if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); }; + const auto finish_depth_uav_barrier = [&](const detail::Prepared& p, VkImageLayout layout) { + if (p.depth_uav_copy != UINT32_MAX) { + detail::copy_depth_uav(vk, command_buffer, p, prepared.depth_uav_copies[p.depth_uav_copy], layout, tracker); + } else if (p.order_depth_uav) { + // A UAV-to-UAV texture barrier names the parent, but the actual shader accesses target its children. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); + } + }; for (std::size_t i = 0; i < commands.size(); ++i) { const auto& command = commands[i]; @@ -3523,6 +3775,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, from.access, from.stages, to.access, to.stages); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (std::holds_alternative(command)) { const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; @@ -3539,7 +3792,10 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (std::holds_alternative(command) || std::holds_alternative(command)) { + } else if (const auto* texture_memory = std::get_if(&command); + std::holds_alternative(command) || std::holds_alternative(command) || + (texture_memory && p.binding.depth_uav && texture_memory->layout_before == d3d12_layout::undefined && + texture_memory->layout_after == d3d12_layout::undefined)) { const auto [sync_before, sync_after, access_before, access_after] = std::visit( [](const auto& c) -> std::array { if constexpr (requires { c.sync_before; }) @@ -3568,10 +3824,13 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout new_layout = image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); LayoutPieces pieces; - if (discard) + // With coupled layouts, discarding a single plane must preserve the other plane's data. + const bool keep_sibling = p.binding.depth_uav && range.aspectMask != p.range.aspectMask; + if (discard && !keep_sibling) pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); else { const VkImageLayout before = + texture->layout_before == d3d12_layout::undefined ? VK_IMAGE_LAYOUT_GENERAL : image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); pieces = detail::current(tracker, id, range, before); detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); @@ -3605,12 +3864,16 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c dependency.pImageMemoryBarriers = barriers; vk.pipeline_barrier2(command_buffer, &dependency); if (tracker) tracker->set(id, range, new_layout); + finish_depth_uav_barrier(p, new_layout); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); + auto clear_value=color_clear->color; + if(p.binding.rgba4_render_fallback)for(auto& channel:clear_value) + channel=std::nearbyint(std::clamp(channel,0.0f,1.0f)*15.0f)/15.0f; + const VkClearColorValue color=detail::render_target_clear_color(p.clear_format,clear_value); if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), state, transfer_dst.access, transfer_dst.stages, [&] { @@ -3645,7 +3908,7 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h + const float depth = p.binding.xbox_depth16_stencil8 ? std::round(std::clamp(depth_clear->depth,0.0f,1.0f)*65535.0f)/65535.0f : p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h : p.binding.format == VK_FORMAT_D16_UNORM ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm : depth_clear->depth; @@ -3703,6 +3966,21 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c const VkImageLayout layout = image_layout(p.binding, state.layout); auto pieces = detail::current(tracker, id, p.range, layout); detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); + if (p.clear_pattern_bytes) { + detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { + detail::emit_buffer_fill(vk, command_buffer, p.staged, p.element, p.staged_writes.front().bufferOffset, + p.clear_pattern_bytes); + for (const auto& region : p.staged_writes) { + // The fill must be visible, and two clear rectangles may overlap. + detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT); + vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, 1, ®ion); + } + }); + continue; + } if (p.rects.empty()) { detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { @@ -3974,6 +4252,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); } + } else if (const auto* label_write=std::get_if(&command)) { + label::completions().record(command_buffer,*label_write); } else if (const auto* write = std::get_if(&command)) { // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 4a8a59ddd..48bfa5048 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -9,6 +9,7 @@ #define VK_NO_PROTOTYPES #endif #include +#include "queue_families.h" #include #include @@ -23,8 +24,9 @@ public: // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, + std::vector families = {}) + : device_(device), allocate_(std::move(allocate)), families_(std::move(families)) { loaded_ = vk_.load(get, device); } @@ -149,6 +151,8 @@ private: VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + // A retired chunk can be reused by a submission on a different queue family. + share_across_queue_families(info, families_); if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; VkMemoryRequirements requirements{}; vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); @@ -172,6 +176,7 @@ private: VkDevice device_; Allocate allocate_; + std::vector families_; Functions vk_; bool loaded_ = false; Batch current_; // handed out, not yet submitted diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp index 4553f25b6..3a4ddb7ba 100644 --- a/runtime/test/bindless_sizing_test.cpp +++ b/runtime/test/bindless_sizing_test.cpp @@ -84,6 +84,13 @@ bool storage_consistent(const BindlessFeatures& f) { f.counts[bindless::r32ui_binding(dimension)] != held) return false; } + // 1D arrays have no sampled capacity, but all three storage classes are always present. + const auto array = ImageDimension::dim_1d_array; + const auto held = storage(f, array); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto binding = bindless::storage_binding(array, c); + if (!held || !bindless::binding_enabled(binding, f) || f.counts[binding] != held) return false; + } return true; } @@ -93,6 +100,33 @@ int main() { using D = ImageDimension; constexpr auto defaults = bindless::default_counts(); static_assert(defaults[0] == 4096 && defaults[bindless::sampler_binding] == 1024 && defaults[8] == 256); + static_assert(bindless::sampled_binding(D::dim_1d_array) == bindless::no_binding); + static_assert(bindless::storage_binding(D::dim_1d_array, 0) == 26 && + bindless::storage_binding(D::dim_1d_array, 1) == 27 && + bindless::storage_binding(D::dim_1d_array, 2) == 28); + static_assert(bindless::sampled_binding(D::dim_2d_ms, 0) == 20 && + bindless::sampled_binding(D::dim_2d_ms_array, 0) == 21 && + bindless::sampled_binding(D::dim_2d_ms, 1) == 22 && + bindless::sampled_binding(D::dim_2d_ms_array, 1) == 23 && + bindless::sampled_binding(D::dim_2d_ms, 2) == 24 && + bindless::sampled_binding(D::dim_2d_ms_array, 2) == 25); + + // SetLayout compacts disabled MS pairs without renumbering either the enabled pair or the storage-only tail. + { + BindlessFeatures f{}; + f.update_after_bind = f.partially_bound = true; + f.ms_samples[1] = VK_SAMPLE_COUNT_4_BIT; + const bindless::SetLayout layout(f); + EXPECT(layout.info.bindingCount == 25 && layout.flags_info.bindingCount == 25); + EXPECT(layout.entries[20].binding == 22 && layout.entries[21].binding == 23); + for (std::uint32_t c = 0; c < 3; ++c) { + const auto& entry = layout.entries[22 + c]; + EXPECT(entry.binding == 26 + c && entry.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && + entry.descriptorCount == 256); + EXPECT(layout.flags[22 + c] == + (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT)); + } + } // An RTX 5070 (driver 621.24): 1048576 of each descriptor type, update-after-bind or not, 4000 samplers. for (const bool update_after_bind : {true, false}) { @@ -103,8 +137,9 @@ int main() { EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); - EXPECT(storage(f, D::dim_2d_array) == 1024 && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); - EXPECT(count(f, D::dim_2d_array) == 1024 && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); + EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); + EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 119137); + EXPECT(count(f, D::dim_2d_array) == bindless::max_2d_array_images && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); EXPECT(storage_consistent(f)); if (update_after_bind) @@ -112,12 +147,12 @@ int main() { count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); } - // At today's sizes exactly (5632 sampled images, 1024 samplers, 3584 storage images): today's set, no MS pairs. + // At today's sizes exactly (5632 sampled images, 1024 samplers, 4352 storage images): no MS pairs. { Device d = uniform(1048576, 1048576); d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages = 5632; d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = 1024; - d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 3584; + d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 4352; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && @@ -125,6 +160,7 @@ int main() { for (std::uint32_t b = 0; b < bindless::first_ms_binding; ++b) if (bindless::bindings[b].type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) EXPECT(f.counts[b] == defaults[b]); EXPECT(f.ms_samples == (std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT})); + EXPECT(totals(f).storage == 4352 && storage(f, D::dim_1d_array) == 256); EXPECT(storage_consistent(f)); } @@ -178,15 +214,19 @@ int main() { Device d = uniform(1048576, 1048576); d.v11.maxPerSetDescriptors = 6159; d.limits.maxSamplerAllocationCount = 4000; - unsigned asked = 0, asked_within = 0; + unsigned asked = 0, asked_within = 0, missing_storage = 0; const auto all_supported = [&](const BindlessFeatures& candidate) { ++asked; asked_within += totals(candidate).all <= 6159; + const bindless::SetLayout layout(candidate); + const auto& last = layout.entries[layout.info.bindingCount - 1]; + missing_storage += last.binding != 28 || last.descriptorType != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE || + last.descriptorCount != storage(candidate, D::dim_1d_array); return true; }; BindlessFeatures f = with_ms(true); EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); - EXPECT(asked > 0 && asked_within == 0); + EXPECT(asked > 0 && asked_within == 0 && missing_storage == 0); EXPECT(count(f, D::dim_2d) == bindless::max_2d_images && f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp index 115a7d96f..b7db73925 100644 --- a/runtime/test/d3d12_bundle_test.cpp +++ b/runtime/test/d3d12_bundle_test.cpp @@ -24,6 +24,7 @@ #include #include +#include #include #include #include @@ -751,7 +752,77 @@ bool layer_checks(ID3D12Device* device, const std::vector& vs, con return true; } -int main() { +// Check the user data captured by DrawInstanced without submitting the synthetic table address to the GPU. +bool root_layout_case(Rig& rig, UINT table_count, UINT constants, bool expect_graphics, bool compact) { + std::vector ranges(table_count); + std::vector params(table_count + (constants != 0)); + for (UINT i = 0; i < table_count; ++i) { + ranges[i] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, i, 0, 0}; + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[i].DescriptorTable = {1, &ranges[i]}; + } + if (constants) { + params.back().ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params.back().Constants = {0, 0, constants}; + } + D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; + desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + desc.Desc_1_0 = {UINT(params.size()), params.data(), 0, nullptr, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + const auto blob = serialize_root_signature(desc); + CHECK(!blob.empty()); + Ref root; + CHECK(rig.device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)) == S_OK); + Ref alloc; + Ref list; + CHECK(rig.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)) == S_OK); + CHECK(rig.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)) == S_OK); + // These signatures fit the compute layout, including the graphics spill case. + list->SetComputeRootSignature(root.p); + CHECK(list->Close() == S_OK); + CHECK(list->Reset(alloc.p, nullptr) == S_OK); + list->SetGraphicsRootSignature(root.p); + if (!expect_graphics) { + CHECK(list->Close() == E_INVALIDARG); + return true; + } + + Ref pso; + CHECK(rig.make_pso(root.p, D3D12_COLOR_WRITE_ENABLE_ALL, pso)); + list->SetPipelineState(pso.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; + list->RSSetViewports(1, &viewport); + constexpr UINT sentinel = 0xabcdef01; + if (constants) list->SetGraphicsRoot32BitConstant(table_count, sentinel, 0); + std::array expected{}; + UINT offset = compact ? 8 : 0; + for (UINT i = 0; i < table_count; ++i) { + const UINT64 handle = 0x1122334455667788ull + i; + list->SetGraphicsRootDescriptorTable(i, {handle}); + expected[offset++] = UINT(handle); + if (!compact) expected[offset++] = UINT(handle >> 32); + } + if (constants) expected[offset] = sentinel; + list->DrawInstanced(3, 1, 0, 0); + CHECK(list->Close() == S_OK); + std::vector commands; + CHECK(rt::d3d12::recorded_commands(list.p, commands)); + CHECK(commands.size() == 1); + const auto* draw = std::get_if(&commands.front()); + CHECK(draw); + for (std::size_t i = 0; i < expected.size(); ++i) { + if (draw->user_data[i] != expected[i]) { + std::fprintf(stderr, "%u tables and %u constants: s%zu = %08x, expected %08x\n", + table_count, constants, i, draw->user_data[i], expected[i]); + return false; + } + } + return true; +} + +int main(int argc, char** argv) { std::setvbuf(stdout, nullptr, _IONBF, 0); vktest::Device vk; const auto device_status = vk.initialize(); @@ -796,6 +867,22 @@ int main() { info.shader_dir = library.string(); Ref ours; REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); + if (argc == 2) { + const bool stage = std::strcmp(argv[1], "--compact") == 0; + REQUIRE(stage || std::strcmp(argv[1], "--legacy") == 0); + Rig rig; + rig.device = ours.p; + rig.vs_code = vs_container; + rig.ps_code = ps_container; + const bool fallback = root_layout_case(rig, 1, 24, true, false); + const bool ordinary = root_layout_case(rig, 1, 1, true, stage); + const bool wide = root_layout_case(rig, 17, 0, stage, stage); + const bool last_register = root_layout_case(rig, 24, 0, stage, stage); + const bool spill = root_layout_case(rig, 25, 0, false, false); + REQUIRE(fallback && ordinary && wide && last_register && spill); + REQUIRE(vk.validation_errors() == errors_before); + return 0; + } REQUIRE(run_all(ours.p, false, nullptr, vs_container, ps_container, list, layer_grids, layer_closes)); REQUIRE(layer_checks(ours.p, vs_container, ps_container, library)); } diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index b4ed0fafe..bea51a617 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -308,6 +308,8 @@ int main() { srv_struct_b(elements), srv_typed(elements), srv_null(elements); { rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -691,11 +693,11 @@ int main() { leonida::gfx10::Buffer decoded{}; EXPECT(leonida::gfx10::decode(raw, decoded)); EXPECT(decoded.address == expected_va); - EXPECT(decoded.stride == 0); - EXPECT(decoded.num_records == 256); + EXPECT(decoded.stride == 16); + EXPECT(decoded.num_records == 16); EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT)); EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle); - EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw); + EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::structured_with_offset); EXPECT(std::memcmp(reinterpret_cast(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0); } diff --git a/runtime/test/d3d12_depth_stencil_uav_test.cpp b/runtime/test/d3d12_depth_stencil_uav_test.cpp new file mode 100644 index 000000000..d88abfc63 --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -0,0 +1,556 @@ +// Xbox depth/stencil creation, shader read-modify-write and exhaustive readback across queue submissions. +// A synthetic compute shader looks up the T#s that the device writes. No game data. +#include "d3d12_copy_compare.h" +#include "d3d12_depth_stencil_uav_views.h" +#include "d3d12_placed_depth_test.h" +#include "d3d12_test_shaders.h" +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" + +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) + +namespace { +using d3d12test::Ref; + +void enhanced_transition(ID3D12GraphicsCommandList7* list, ID3D12Resource* texture, + D3D12_BARRIER_SYNC before_sync, D3D12_BARRIER_ACCESS before_access, + D3D12_BARRIER_LAYOUT before_layout, D3D12_BARRIER_SYNC after_sync, + D3D12_BARRIER_ACCESS after_access, D3D12_BARRIER_LAYOUT after_layout) { + D3D12_TEXTURE_BARRIER barrier{}; + barrier.SyncBefore = before_sync; + barrier.AccessBefore = before_access; + barrier.LayoutBefore = before_layout; + barrier.SyncAfter = after_sync; + barrier.AccessAfter = after_access; + barrier.LayoutAfter = after_layout; + barrier.Subresources = {D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 0, 0, 0, 0, 0}; + barrier.pResource = texture; + D3D12_BARRIER_GROUP group{}; + group.Type = D3D12_BARRIER_TYPE_TEXTURE; + group.NumBarriers = 1; + group.pTextureBarriers = &barrier; + list->Barrier(1, &group); +} + +enum class Handoff { direct, graphics_transitions, compute_transitions }; + +struct Batch { + Ref allocator; + Ref list; + bool open(ID3D12Device* device, D3D12_COMMAND_LIST_TYPE type) { + return SUCCEEDED(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, type, allocator.p, nullptr, IID_PPV_ARGS(&list.p))); + } + bool submit(ID3D12CommandQueue* queue, ID3D12Fence* done, UINT64 value) { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + return rt::d3d12::last_execute_result(queue) == leonida::ReplayResult::success && + SUCCEEDED(queue->Signal(done, value)); + } +}; + +bool compute_transfers(const vktest::Device& vk, VkFormat format, bool stencil) { + if (vk.compute_family == vk.family) return true; +#ifdef VK_KHR_maintenance10 + if (!vk.maintenance10) return false; + VkFormatProperties3 flags{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; + VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &flags}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties2")( + vk.physical, format, &properties); + const VkFormatFeatureFlags2 required = VK_FORMAT_FEATURE_2_DEPTH_COPY_ON_COMPUTE_QUEUE_BIT_KHR | + (stencil ? VK_FORMAT_FEATURE_2_STENCIL_COPY_ON_COMPUTE_QUEUE_BIT_KHR : 0); + return (flags.optimalTilingFeatures & required) == required; +#else + return false; +#endif +} + +struct GuestAllocation { + void* address = nullptr; + ~GuestAllocation() { if (address) VirtualFree(address, 0, MEM_RELEASE); } +}; + +enum class Texture { committed, committed3, placed }; + +// The boot stack's Xbox slot 127 forwards this call to the real device's CreateCommittedResource3. +// Test the actual thunk when present, or the same normalized input at its destination on a standalone build. +HRESULT create_committed3(ID3D12Device* device, ID3D12Device* xbox, const D3D12_HEAP_PROPERTIES& heap, + const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT initial, + const D3D12_CLEAR_VALUE& clear, ID3D12Resource** out, + UINT castable_count = 0, const DXGI_FORMAT* castable = nullptr) { + D3D12_RESOURCE_DESC1 input{desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, + desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags, {}}; + if (xbox && rt::d3d12_xs::device_slot_overridden(127)) { + using Slot127 = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC1*, D3D12_BARRIER_LAYOUT, const D3D12_CLEAR_VALUE*, + ID3D12ProtectedResourceSession*, UINT, const DXGI_FORMAT*, REFIID, void**); + const auto create = reinterpret_cast(d3d12test::slot(xbox, 127)); + return create(xbox, &heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); + } + Ref device10; + const HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device10.p)); + if (FAILED(hr)) return hr; + input.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + return device10->CreateCommittedResource3(&heap, D3D12_HEAP_FLAG_NONE, &input, initial, &clear, nullptr, + castable_count, castable, IID_PPV_ARGS(out)); +} + +int run(vktest::Device& vk, UINT width, UINT height, bool enhanced, Texture kind, UINT16 layers, + DXGI_FORMAT format, Handoff handoff) { + const bool array = layers > 1; + // Array views cover the last two layers so the shader reaches slice 5 in the six-layer case. + const UINT first_slice = array ? layers - 2u : 0; + const bool placed = kind == Texture::placed; + const bool modern = kind == Texture::committed3; + const bool depth16 = format == DXGI_FORMAT_R16_TYPELESS; + const UINT planes = depth16 ? 1 : 2; + const UINT subresources = planes * layers; + const char* fixture = array ? LEONIDA_DEPTH_STENCIL_ARRAY_SPV : LEONIDA_DEPTH_STENCIL_2D_SPV; + const char* bindings = array ? "2,11,12" : "2,8,9"; + if (depth16) { + fixture = array ? LEONIDA_DEPTH16_ARRAY_SPV : LEONIDA_DEPTH16_2D_SPV; + bindings = array ? "2,12" : "2,9"; + } + const auto program = d3d12test::fssm_program({0x44535541, 0xbf810000}); + const auto shader = d3d12test::shader_container(program); + const testfiles::ScratchDir library("leonida_depth_stencil_uav"); + CHECK(testfiles::copy_file(vktest::shader_fixture_path(fixture), library.path() / "write.spv")); + { + std::ofstream index(library.path() / "index.json", std::ios::binary); + index << "{\"write\":{\"stage\":\"cs\",\"fssm_sha256\":\"" << leonida::sha256_hex(program) + << "\",\"bindings\":[" << bindings << "],\"push_constant_bytes\":80,\"local_size\":[1,1,1],\"wave64\":false}}"; + CHECK(index.good()); + } + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.compute_family = vk.compute_family; + info.compute_queues = {vk.compute_queue}; + info.maintenance10 = vk.maintenance10; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.buffer_device_address = vk.buffer_device_address; + info.shader_dir = library.path().string(); + ID3D12Device* device = nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + Ref xbox; + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(device, IID_PPV_ARGS(&xbox.p)))); // takes ownership + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.DepthOrArraySize = layers; + desc.SampleDesc.Count = 1; + desc.Format = format; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + desc.Layout = static_cast(0x101); + D3D12_HEAP_PROPERTIES props{}; + props.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil.Depth = 1.0f; + auto normalized = desc; + normalized.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + if (modern) { + // The standalone PC Device10 retains its ordinary rejection of the combined creation flags. + Ref refused; + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + } + rt::d3d12::set_device_outer(device, xbox.p); + if (!enhanced && !array && !depth16) CHECK(placeddepthtest::check_alias_lifetime(device, xbox.p) && placeddepthtest::check_alias_lifetime(device, xbox.p, true)); + using CreateFn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES, const D3D12_CLEAR_VALUE*, + REFIID, void**); + // The baseline uses PC sizing. In builds with the Xbox slot-25 dependency, size the placement through + // the console's return-buffer-first ABI; keep native footprints for the host pixel readback. + auto native_depth = normalized; + native_depth.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + auto size = device->GetResourceAllocationInfo(0, 1, &native_depth); + CHECK(size.SizeInBytes > 0 && size.SizeInBytes != UINT64_MAX); + if (modern) { + const auto logical = device->GetResourceAllocationInfo(0, 1, &normalized); + CHECK(logical.SizeInBytes == size.SizeInBytes && logical.Alignment == size.Alignment); + } + if (rt::d3d12_xs::device_slot_overridden(25)) { + using SizeFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, + UINT, UINT, const D3D12_RESOURCE_DESC*); + D3D12_RESOURCE_ALLOCATION_INFO xbox_size{}; + const auto get_size = reinterpret_cast(d3d12test::slot(xbox.p, 25)); + CHECK(get_size(&xbox_size, xbox.p, 0, 1, &desc) == &xbox_size); + CHECK(xbox_size.SizeInBytes >= size.SizeInBytes && xbox_size.SizeInBytes != UINT64_MAX && + xbox_size.Alignment >= size.Alignment); + size = xbox_size; + } + GuestAllocation guest; + Ref texture, alias; + const auto create_texture = reinterpret_cast(d3d12test::slot(xbox.p, 76)); + if (placed) { + using PlaceFn = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, D3D12_BARRIER_LAYOUT, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto place = reinterpret_cast(d3d12test::slot(xbox.p, 133)); + guest.address = VirtualAlloc(nullptr, SIZE_T(size.SizeInBytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + CHECK(guest.address); + const auto va = reinterpret_cast(guest.address); + const auto layout = enhanced ? D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS : D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE; + CHECK(SUCCEEDED(place(xbox.p, va, &desc, layout, nullptr, + IID_PPV_ARGS(&texture.p)))); + Ref rejected; + CHECK(place(xbox.p, va, &desc, D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&rejected.p)) == E_INVALIDARG && !rejected.p); + CHECK(SUCCEEDED(place(xbox.p, va, &desc, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, nullptr, + IID_PPV_ARGS(&alias.p)))); + CHECK(texture.p != alias.p && texture->GetGPUVirtualAddress() == va && alias->GetGPUVirtualAddress() == va); + } else if (modern) { + // Exercise the exact no-list overload as well as lists naming both the attachment and its writable planes. + const DXGI_FORMAT d16_views[] = {DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT}; + const DXGI_FORMAT d32s8_views[] = {DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8_UINT}; + const UINT count = layers == 3 ? UINT(depth16 ? std::size(d16_views) : std::size(d32s8_views)) : 0; + const DXGI_FORMAT* castable = count ? (depth16 ? d16_views : d32s8_views) : nullptr; + CHECK(SUCCEEDED(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &texture.p, count, castable)) && texture.p); + if (!array) { + Ref refused; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_RENDER_TARGET, + optimized, &refused.p) == E_INVALIDARG && !refused.p); + auto wrong_clear = optimized; + wrong_clear.Format = DXGI_FORMAT_D32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + wrong_clear, &refused.p) == E_INVALIDARG && !refused.p); + const DXGI_FORMAT incompatible = DXGI_FORMAT_R32G32_FLOAT; + CHECK(create_committed3(device, xbox.p, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, &refused.p, 1, &incompatible) == E_INVALIDARG && !refused.p); + // The PC Device10 endpoint returns S_FALSE for a successful validation-only call. + CHECK(create_committed3(device, nullptr, props, desc, D3D12_BARRIER_LAYOUT_COMMON, + optimized, nullptr) == S_FALSE); + } + } else { + const auto heap_flags = !enhanced && !array && !depth16 + ? D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS : D3D12_HEAP_FLAG_NONE; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, heap_flags, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&texture.p)))); + D3D12_HEAP_FLAGS reported{}; + CHECK(SUCCEEDED(texture->GetHeapProperties(nullptr, &reported))); + CHECK((reported & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) == heap_flags); + if (heap_flags) { + Ref depth_only; + CHECK(device->CreateCommittedResource(&props, heap_flags, &native_depth, D3D12_RESOURCE_STATE_DEPTH_WRITE, + nullptr, IID_PPV_ARGS(&depth_only.p)) == E_INVALIDARG && !depth_only.p); + for (auto type : {D3D12_HEAP_TYPE_UPLOAD, D3D12_HEAP_TYPE_READBACK}) { + auto cpu_heap = props; + cpu_heap.Type = type; + Ref invalid; + CHECK(create_texture(xbox.p, &cpu_heap, heap_flags, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&invalid.p)) == E_INVALIDARG && !invalid.p); + } + } + } + CHECK(texture->GetDesc().Flags == desc.Flags); + if (array) CHECK(check_depth_uav_array_views(device, texture.p, depth16)); + + const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + const D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref dsv, views; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv.p)))); + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views.p)))); + D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; + depth_view.Format = depth16 ? DXGI_FORMAT_D16_UNORM : DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth_view.ViewDimension = array ? D3D12_DSV_DIMENSION_TEXTURE2DARRAY : D3D12_DSV_DIMENSION_TEXTURE2D; + const SIZE_T dsv_step = device->GetDescriptorHandleIncrementSize(dsv_desc.Type); + const auto depth_handle = dsv->GetCPUDescriptorHandleForHeapStart(); + for (UINT layer = 0; layer < layers; ++layer) { + if (array) depth_view.Texture2DArray = {0, layer, 1}; + device->CreateDepthStencilView(texture.p, &depth_view, {depth_handle.ptr + dsv_step * layer}); + } + const SIZE_T base = views->GetCPUDescriptorHandleForHeapStart().ptr; + const SIZE_T step = device->GetDescriptorHandleIncrementSize(views_desc.Type); + CHECK(base && step >= 32); + std::uint32_t keys[2][8]{}; + for (UINT plane = 0; plane < planes; ++plane) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : plane == 0 ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R8_UINT; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; + else view.Texture2D.PlaneSlice = plane; + const D3D12_CPU_DESCRIPTOR_HANDLE handle{base + plane * step}; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, handle); + std::memcpy(keys[plane], reinterpret_cast(handle.ptr), sizeof(keys[plane])); + CHECK(rt::d3d12::bindless_hash_lookup(device, keys[plane]) != 0); + } + if (planes == 2) CHECK(std::memcmp(keys[0], keys[1], sizeof(keys[0])) != 0); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D; + if (array) srv.Texture2DArray = {0, 1, first_slice, 2, 0, 0.0f}; + else srv.Texture2D.MipLevels = 1; + const D3D12_CPU_DESCRIPTOR_HANDLE sampled{base + 2 * step}; + device->CreateShaderResourceView(texture.p, &srv, sampled); + std::uint32_t sampled_key[8]{}; + std::memcpy(sampled_key, reinterpret_cast(sampled.ptr), sizeof(sampled_key)); + CHECK(rt::d3d12::bindless_hash_lookup(device, sampled_key) != 0); + CHECK(std::memcmp(sampled_key, keys[0], sizeof(sampled_key)) != 0); + const D3D12_CPU_DESCRIPTOR_HANDLE invalid{base + 3 * step}; + std::uint32_t zero[8]{}; + for (UINT plane = 0; plane < 2; ++plane) { + std::memset(reinterpret_cast(invalid.ptr), 0x55, sizeof(zero)); + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D; + if (array) view.Texture2DArray = {0, first_slice, 2, plane}; + else view.Texture2D.PlaneSlice = plane; + view.Format = plane == 0 ? DXGI_FORMAT_R8_UINT : DXGI_FORMAT_R32_FLOAT; + device->CreateUnorderedAccessView(texture.p, nullptr, &view, invalid); + CHECK(std::memcmp(reinterpret_cast(invalid.ptr), zero, sizeof(zero)) == 0); + } + + // ClearUAV takes matching handles to two copies of the descriptor and the original Xbox resource. + const D3D12_DESCRIPTOR_HEAP_DESC visible_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref visible; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&visible_desc, IID_PPV_ARGS(&visible.p)))); + device->CopyDescriptorsSimple(planes, visible->GetCPUDescriptorHandleForHeapStart(), {base}, visible_desc.Type); + const auto gpu = visible->GetGPUDescriptorHandleForHeapStart(); + const FLOAT depth_clear[] = {0.75f, 0, 0, 0}; + const UINT stencil_clear[] = {0x31, 0, 0, 0}; + if (!array) { + // Both parents have a real R32_FLOAT storage plane, but this T# belongs to the first parent only. + auto other_desc = desc; + other_desc.Width = other_desc.Height = 2; + Ref other; + CHECK(SUCCEEDED(create_texture(xbox.p, &props, D3D12_HEAP_FLAG_NONE, &other_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&other.p)))); + copycmp::Run rejected; + CHECK(rejected.init(device, true)); + rejected.begin(); + rejected.barrier(other.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {visible.p}; + rejected.list->SetDescriptorHeaps(1, heaps); + rejected.list->ClearUnorderedAccessViewFloat(gpu, {base}, other.p, depth_clear, 0, nullptr); + CHECK(rejected.list->Close() == E_INVALIDARG); + } + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants.Num32BitValues = 16; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC rs{}; + rs.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + rs.Desc_1_0 = {1, ¶m, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = d3d12test::serialize_root_signature(rs); + Ref root; + CHECK(!root_blob.empty()); + CHECK(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pipeline_desc{}; + pipeline_desc.pRootSignature = root.p; + pipeline_desc.CS = {shader.data(), shader.size()}; + Ref pipeline; + CHECK(SUCCEEDED(device->CreateComputePipelineState(&pipeline_desc, IID_PPV_ARGS(&pipeline.p)))); + + // Three submissions. Only the final fence is waited on by the CPU. + copycmp::Run graphics; + CHECK(graphics.init(device, true)); + const auto worker_type = handoff == Handoff::direct ? D3D12_COMMAND_LIST_TYPE_DIRECT : D3D12_COMMAND_LIST_TYPE_COMPUTE; + D3D12_COMMAND_QUEUE_DESC worker_desc{}; + worker_desc.Type = worker_type; + Ref worker; + CHECK(SUCCEEDED(device->CreateCommandQueue(&worker_desc, IID_PPV_ARGS(&worker.p)))); + Batch shader_batch, read_batch; + CHECK(shader_batch.open(device, worker_type) && read_batch.open(device, D3D12_COMMAND_LIST_TYPE_DIRECT)); + std::vector layouts(subresources); + std::vector row_bytes(subresources); + UINT64 total = 0; + device->GetCopyableFootprints(&native_depth, 0, subresources, 0, layouts.data(), nullptr, row_bytes.data(), &total); + CHECK(row_bytes[0] == width * (depth16 ? 2 : 4)); + if (planes == 2) CHECK(row_bytes[layers] == width); + copycmp::Ptr readback; + CHECK(graphics.buffer(D3D12_HEAP_TYPE_READBACK, total, D3D12_RESOURCE_STATE_COPY_DEST, readback)); + + const float depth_seed[] = {0.5f, 0.25f, 1.0f}; + const UINT8 stencil_seed[] = {0x5a, 0x37, 0xcb}; + const UINT16 d16_seed[] = {0, 0xffff, 257, 514, 771, 1028}; + const auto flags = depth16 ? D3D12_CLEAR_FLAG_DEPTH : D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL; + if (modern) { + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_ALL, + D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE); + } + for (UINT layer = 0; layer < layers; ++layer) + graphics.list->ClearDepthStencilView({depth_handle.ptr + dsv_step * layer}, flags, + depth16 ? float(d16_seed[layer]) / 65535.0f : depth_seed[layer], depth16 ? 0 : stencil_seed[layer], + 0, nullptr); + + const bool compute_copy = handoff == Handoff::compute_transitions; + // Graphics-side transfers use ordinary cross-queue UAV layout. With maintenance10 the compute family can + // also perform the transfers, with COMMON as the shared handoff layout at both fences. + if (enhanced) { + Ref list; + CHECK(SUCCEEDED(graphics.list->QueryInterface(IID_PPV_ARGS(&list.p)))); + enhanced_transition(list.p, texture.p, D3D12_BARRIER_SYNC_DEPTH_STENCIL, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_SYNC_ALL, compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + } else { + graphics.barrier(texture.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + CHECK(SUCCEEDED(graphics.list->Close())); + ID3D12CommandList* write_lists[] = {graphics.list.p}; + graphics.queue->ExecuteCommandLists(1, write_lists); + CHECK(rt::d3d12::last_execute_result(graphics.queue.p) == leonida::ReplayResult::success); + CHECK(SUCCEEDED(graphics.queue->Signal(graphics.fence.p, 1))); + CHECK(SUCCEEDED(worker->Wait(graphics.fence.p, 1))); + Ref compute_list; + if (compute_copy) { + CHECK(SUCCEEDED(shader_batch.list->QueryInterface(IID_PPV_ARGS(&compute_list.p)))); + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS); + } + const D3D12_RECT depth_rect{1, 3, 2, 4}, stencil_rect{3, 2, 4, 3}; + ID3D12DescriptorHeap* clear_heaps[] = {visible.p}; + auto* list = shader_batch.list.p; + list->SetDescriptorHeaps(1, clear_heaps); + const UINT d16_clear[] = {0x4512, 0, 0, 0}; + if (depth16) list->ClearUnorderedAccessViewUint(gpu, {base}, texture.p, d16_clear, 1, &depth_rect); + else { + list->ClearUnorderedAccessViewFloat(gpu, {base}, texture.p, depth_clear, 1, &depth_rect); + list->ClearUnorderedAccessViewUint({gpu.ptr + step}, {base + step}, texture.p, stencil_clear, 1, &stencil_rect); + } + D3D12_RESOURCE_BARRIER order{}; + order.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + order.UAV.pResource = texture.p; + list->ResourceBarrier(1, &order); + list->SetComputeRootSignature(root.p); + list->SetPipelineState(pipeline.p); + list->SetComputeRoot32BitConstants(0, 16, keys, 0); + list->Dispatch(1, 1, 1); + if (compute_copy) + enhanced_transition(compute_list.p, texture.p, D3D12_BARRIER_SYNC_COMPUTE_SHADING, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_ALL, D3D12_BARRIER_ACCESS_COMMON, D3D12_BARRIER_LAYOUT_COMMON); + CHECK(shader_batch.submit(worker.p, graphics.fence.p, 2)); + CHECK(SUCCEEDED(graphics.queue->Wait(graphics.fence.p, 2))); + + // The second placement reads the first one's writes at the same guest address. + auto* reader = placed ? alias.p : texture.p; + if (placed) { + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {texture.p, reader}; + read_batch.list->ResourceBarrier(1, &activate); + } + if (enhanced) { + Ref read_list; + CHECK(SUCCEEDED(read_batch.list->QueryInterface(IID_PPV_ARGS(&read_list.p)))); + enhanced_transition(read_list.p, reader, D3D12_BARRIER_SYNC_ALL, + compute_copy ? D3D12_BARRIER_ACCESS_COMMON : D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + compute_copy ? D3D12_BARRIER_LAYOUT_COMMON : D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_SOURCE, D3D12_BARRIER_LAYOUT_COPY_SOURCE); + } else { + D3D12_RESOURCE_BARRIER copy{}; + copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + copy.Transition = {reader, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE}; + read_batch.list->ResourceBarrier(1, ©); + } + for (UINT sub = 0; sub < subresources; ++sub) { + const auto src = copycmp::sub_loc(reader, sub); + const auto dst = copycmp::foot_loc(readback.p, layouts[sub]); + read_batch.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + CHECK(read_batch.submit(graphics.queue.p, graphics.fence.p, 3)); + CHECK(SUCCEEDED(graphics.fence->SetEventOnCompletion(3, nullptr))); + CHECK(graphics.fence->GetCompletedValue() >= 3 && SUCCEEDED(device->GetDeviceRemovedReason())); + unsigned char* mapped = nullptr; + CHECK(SUCCEEDED(readback->Map(0, nullptr, reinterpret_cast(&mapped))) && mapped); + for (UINT sub = 0; sub < subresources; ++sub) { + const UINT layer = sub % layers; + const UINT plane = sub / layers; + const UINT bytes = plane ? 1 : depth16 ? 2 : 4; + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const bool in_view = layer >= first_slice; + const bool cleared = in_view && (plane ? x == 3 && y == 2 : x == 1 && y == 3); + UINT32 expected = 0; + if (depth16) { + expected = cleared ? d16_clear[0] : d16_seed[layer]; + if (layer == layers - 1u && x == 2 && y == 1) expected ^= 0x1357u; + } else if (plane == 0) { + float depth = cleared ? depth_clear[0] : depth_seed[layer]; + if (layer == first_slice && x == 2 && y == 1) depth *= 0.25f; + std::memcpy(&expected, &depth, sizeof(depth)); + } else { + expected = cleared ? stencil_clear[0] : stencil_seed[layer]; + if (layer == layers - 1u && x == 5 && y == 3) expected ^= 0xffu; + } + UINT32 actual = 0; + std::memcpy(&actual, mapped + layouts[sub].Offset + y * layouts[sub].Footprint.RowPitch + x * bytes, bytes); + if (actual != expected) { + std::fprintf(stderr, "subresource %u pixel (%u,%u): got %#x, expected %#x\n", sub, x, y, actual, expected); + readback->Unmap(0, nullptr); + return 1; + } + } + } + } + readback->Unmap(0, nullptr); + const char* path = placed ? "slot 133" : "slot 76"; + if (modern) path = rt::d3d12_xs::device_slot_overridden(127) ? "slot 127" : "CreateCommittedResource3"; + std::printf("%s, %ux%u, %u layers, %u planes, %s barriers, graphics family %u, shader family %u, " + "plane transfers on %s: every pixel matched\n", path, width, height, UINT(layers), planes, + enhanced ? "enhanced" : "legacy", vk.family, handoff == Handoff::direct ? vk.family : vk.compute_family, + compute_copy ? "compute" : "graphics"); + return 0; +} +} // namespace + +int main() { + vktest::Device vk; + vk.request_buffer_device_address = true; + vk.all_queue_types = true; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (!vk.bindless || !vk.storage_image_extended_formats) { + std::fprintf(stderr, "SKIP: shader requires bindless images and typed r8ui storage\n"); + return 77; + } + const auto d32s8 = DXGI_FORMAT_R32G8X24_TYPELESS, d16 = DXGI_FORMAT_R16_TYPELESS; + if (run(vk, 9, 7, false, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 2560, 1440, true, Texture::committed, 1, d32s8, Handoff::direct) || + run(vk, 9, 7, true, Texture::placed, 1, d16, Handoff::graphics_transitions)) return 1; + for (const auto format : {d32s8, d16}) { + if (run(vk, 9, 7, false, Texture::committed, 3, format, Handoff::graphics_transitions) || + run(vk, 13, 9, true, Texture::placed, 3, format, Handoff::graphics_transitions)) return 1; + const auto vk_format = format == d16 ? VK_FORMAT_D16_UNORM : VK_FORMAT_D32_SFLOAT_S8_UINT; + if (compute_transfers(vk, vk_format, format != d16)) { + if (run(vk, 9, 7, true, Texture::placed, 3, format, Handoff::compute_transitions)) return 1; + } else { + std::printf("compute-side depth transfers unavailable for VkFormat %u; graphics-side handoff tested\n", + unsigned(vk_format)); + } + } + // Array lengths reported by the Xbox boot trace. The texels are synthetic. + constexpr UINT16 reported_layers[] = {1, 3, 6}; + for (const UINT16 layers : reported_layers) + if (run(vk, 9, 7, true, Texture::committed3, layers, d16, Handoff::graphics_transitions)) return 1; + if (run(vk, 9, 7, true, Texture::committed3, 3, d32s8, Handoff::graphics_transitions)) return 1; + return vk.validation_errors() ? 1 : 0; +} diff --git a/runtime/test/d3d12_depth_stencil_uav_views.h b/runtime/test/d3d12_depth_stencil_uav_views.h new file mode 100644 index 000000000..8800132ad --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_views.h @@ -0,0 +1,79 @@ +#pragma once + +#include "d3d12_test_shaders.h" +#include "../src/gfx10_descriptors.h" + +#include +#include + +// Exercise the descriptors as seen by a console shader, including the array size sentinel and invalid ranges. +inline bool check_depth_uav_array_views(ID3D12Device* device, ID3D12Resource* resource, bool depth16) { + namespace g = leonida::gfx10; + const UINT layers = resource->GetDesc().DepthOrArraySize; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + d3d12test::Ref heap; + if (layers < 2 || FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + const auto read = [&] { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(slot.ptr), sizeof(words)); + return words; + }; + const auto uav = [&](const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read(); + }; + const g::ImageWords empty{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2DArray = {0, 0, 1, 0}; + g::Image first{}, tail{}; + if (!g::decode(uav(&view), first) || first.type != g::ImageType::image_2d_array || + first.first_layer != 0 || first.layer_count != 1) return false; + view.Texture2DArray = {0, 1, UINT_MAX, 0}; + const auto remaining = uav(&view); + view.Texture2DArray.ArraySize = layers - 1; + if (remaining != uav(&view) || !g::decode(remaining, tail) || tail.address != first.address || + tail.first_layer != 1 || tail.layer_count != layers - 1) return false; + + // A depth SRV still names the original image, with the same base layer and count. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + srv.Texture2DArray = {0, 1, 1, layers - 1, 0, 0}; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image attachment{}; + if (!g::decode(read(), attachment) || attachment.type != g::ImageType::image_2d_array || + attachment.address == tail.address || attachment.first_layer != 1 || attachment.layer_count != layers - 1) + return false; + if (!depth16) { + srv.Format = DXGI_FORMAT_X32_TYPELESS_G8X24_UINT; + srv.Texture2DArray.PlaneSlice = 1; + device->CreateShaderResourceView(resource, &srv, slot); + g::Image stencil{}; + if (!g::decode(read(), stencil) || stencil.address != attachment.address || + stencil.format != g::stencil_format || stencil.first_layer != 1 || stencil.layer_count != layers - 1) + return false; + } + for (const D3D12_TEX2D_ARRAY_UAV invalid : { + D3D12_TEX2D_ARRAY_UAV{1, 0, 1, 0}, {0, 0, 0, 0}, {0, layers, UINT_MAX, 0}, + {0, 1, layers, 0}, {0, 0, 1, depth16 ? 1u : 2u}}) { + view.Texture2DArray = invalid; + if (uav(&view) != empty) { + std::fprintf(stderr, "accepted invalid UAV mip %u layers %u+%u plane %u\n", + invalid.MipSlice, invalid.FirstArraySlice, invalid.ArraySize, invalid.PlaneSlice); + return false; + } + } + view.Texture2DArray = {0, 0, 1, 0}; + view.Format = DXGI_FORMAT_R8_UINT; + if (uav(&view) != empty) return false; + view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + view.Format = depth16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_FLOAT; + view.Texture2D = {}; + return uav(&view) == empty && uav(nullptr) == empty; +} diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index b979ea42b..4a70a3b26 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -16,6 +16,7 @@ // or across B8G8R8X8 and B8G8R8A8: the bytes land in the view's order and encoding. // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "../src/title_va_alias.h" #include "shader_fixture_path.h" #include "test_temp_dir.h" #include "vk_test_device.h" @@ -44,6 +45,24 @@ using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: ha namespace { +struct TitleGeometryPages { + static constexpr UINT bytes_per_view = 3 * 1024 * 1024; + static constexpr UINT count = 7; + std::byte* base = nullptr; + ~TitleGeometryPages() { + if (base) { + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(base)); + VirtualFree(base,0,MEM_RELEASE); + } + } + bool allocate() { + base = static_cast(VirtualAlloc(nullptr,SIZE_T(bytes_per_view)*count,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)); + if(!base) return false; + leonida::title_va_aliases().add_title_memory(reinterpret_cast(base),SIZE_T(bytes_per_view)*count); + return true; + } +}; + struct Vertex { float x, y; std::uint8_t r, g, b, a; @@ -381,7 +400,15 @@ int main() { // State for the draws; the pipeline came with CreateCommandList. list->SetGraphicsRootSignature(root.p); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - const D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; + const bool large_batch = std::getenv("LEONIDA_TEST_GEOMETRY_BATCH") != nullptr; + TitleGeometryPages title_vertices; + D3D12_VERTEX_BUFFER_VIEW vbv{vertex_buffer->GetGPUVirtualAddress(), sizeof(vertices), sizeof(Vertex)}; + if (large_batch) { + EXPECT(title_vertices.allocate()); + std::memcpy(title_vertices.base,vertices,sizeof(vertices)); + vbv.BufferLocation=reinterpret_cast(title_vertices.base); + vbv.SizeInBytes=TitleGeometryPages::bytes_per_view; + } list->IASetVertexBuffers(0, 1, &vbv); const D3D12_INDEX_BUFFER_VIEW ibv{upload_va + 256, sizeof(indices), DXGI_FORMAT_R16_UINT}; list->IASetIndexBuffer(&ibv); @@ -426,6 +453,18 @@ int main() { list->SetGraphicsRoot32BitConstants(0, 2, down_right, 0); list->DrawIndexedInstanced(6, 1, 0, 0, 0); + if (large_batch) { + // More live bytes than the old 16 MiB ring. These zero-area triangles genuinely consume + // six separate CPU-backed views without changing the reference image of the five prior draws. + list->SetPipelineState(pso.p); + for (UINT i=1; i(title_vertices.base)+ + UINT64(i)*TitleGeometryPages::bytes_per_view,TitleGeometryPages::bytes_per_view,sizeof(Vertex)}; + list->IASetVertexBuffers(0,1,&extra); + list->DrawInstanced(3,1,0,0); + } + list->IASetVertexBuffers(0,1,&vbv); + } D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); list->ResourceBarrier(1, &to_copy); diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index cd9448c75..04d2e705a 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -25,6 +25,8 @@ // pixels are predicted on the CPU, error 0, and 1536 of them differ from the plain reflection. // The control also keeps one unbounded SRV table bound and selects its two entries by a root constant. // Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). +#include "../src/gfx10_tiling.h" +#include "../src/title_va_alias.h" #include "vk_test_device.h" #include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" @@ -34,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -64,10 +67,26 @@ constexpr UINT target_size = 64; // the target: each texel covers 8x8 pixels constexpr UINT target_pitch = target_size * 4; // 256 // The synthetic gradient: red rises with x, green with y, blue falls along the diagonal. -Texel gradient(UINT x, UINT y) { +struct RawPages { + std::byte* data = nullptr; + ~RawPages() { + if (!data) return; + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(data)); + VirtualFree(data, 0, MEM_RELEASE); + } +}; +bool large_raw_surface() { return std::getenv("LEONIDA_TEST_LARGE_RAW_TEXTURE") != nullptr; } +bool test_raw_surface() { return large_raw_surface() || std::getenv("LEONIDA_TEST_RAW_TEXTURE") != nullptr; } +bool test_packed4444(){return std::getenv("LEONIDA_TEST_FIXED4")!=nullptr;} +Texel raw_gradient(UINT x, UINT y) { return {std::uint8_t(x * 36), std::uint8_t(y * 36), std::uint8_t(255 - (x + y) * 16), 255}; } // The second texture: the first one point-reflected, so no texel of it is in the same place. +Texel gradient(UINT x,UINT y) { + auto value=raw_gradient(x,y); + if(test_packed4444())for(auto& c:value)c=static_cast(std::nearbyint(double(c)*15.0/255.0)*17.0); + return value; +} Texel reflected(UINT x, UINT y) { return gradient(texture_size - 1 - x, texture_size - 1 - y); } Texel linear_clamp(UINT col, UINT row) { @@ -92,7 +111,10 @@ Texel linear_clamp(UINT col, UINT row) { } // namespace -int main() { +int main(int argc, char** argv) { + const bool unbounded = argc == 2 && std::strcmp(argv[1], "--refresh-unbounded-samplers") == 0; + const bool disabled = argc == 2 && std::strcmp(argv[1], "--refresh-samplers-off") == 0; + const bool refresh = unbounded || disabled || (argc == 2 && std::strcmp(argv[1], "--refresh-samplers") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips @@ -127,7 +149,10 @@ int main() { std::vector pixels(std::size_t(target_pitch) * target_size), control_pixels = pixels, linear_pixels = pixels; unsigned image_hits = 0, sampler_hits = 0; { + const bool direct_views = std::getenv("LEONIDA_TEST_VISIBLE_VIEWS") != nullptr; + const bool staged_views = direct_views || std::getenv("LEONIDA_TEST_STAGED_VIEWS") != nullptr; rt::d3d12::VulkanDeviceInfo info{}; + info.prepare_on_bind = staged_views; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -139,6 +164,9 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.shader_dir = (root_dir / "spirv").string(); + RawPages raw_pages[2]; + RawPages placed_pages[4]; + const bool placed = staged_views || std::getenv("LEONIDA_TEST_PLACED_FIRST_USE") != nullptr; ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; @@ -149,7 +177,7 @@ int main() { // Root signature: [0] a table of one SRV (s0:s1), [1] a table of one sampler (s2:s3). D3D12_DESCRIPTOR_RANGE srv_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; + D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, unbounded ? UINT_MAX : 1u, 0, 0, 0}; D3D12_ROOT_PARAMETER params[2] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; params[0].DescriptorTable = {1, &srv_range}; @@ -221,18 +249,45 @@ int main() { texture_desc.Width = texture_desc.Height = texture_size; texture_desc.DepthOrArraySize = 1; texture_desc.MipLevels = 1; - texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + texture_desc.Format = test_packed4444()?static_cast(115):DXGI_FORMAT_R8G8B8A8_UNORM; + if(test_packed4444())texture_desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const auto initial_state=test_packed4444()?D3D12_RESOURCE_STATE_RENDER_TARGET:D3D12_RESOURCE_STATE_COPY_DEST; texture_desc.SampleDesc.Count = 1; + const auto size=device->GetResourceAllocationInfo(0,1,&texture_desc); + EXPECT(size.SizeInBytes && size.SizeInBytes!=~UINT64{0}); Ref textures[2], upload, readback, readback2, target; - for (auto& texture : textures) - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&texture.p)))); + const auto at_address = [&](RawPages& pages, const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout, + ID3D12Resource** result) { + const auto required = inner->GetResourceAllocationInfo(0,1,&desc); + if (!required.SizeInBytes || required.SizeInBytes == UINT64_MAX) return E_FAIL; + pages.data = static_cast(VirtualAlloc(nullptr, SIZE_T(required.SizeInBytes), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)); + if (!pages.data) return E_OUTOFMEMORY; + const auto va = reinterpret_cast(pages.data); + leonida::title_va_aliases().add_title_memory(va, required.SizeInBytes); + using Place = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + return reinterpret_cast(slot(device.p,133))(device.p,va,&desc,UINT(layout),nullptr,&__uuidof(ID3D12Resource), + reinterpret_cast(result)); + }; + for (UINT i=0; i<2; ++i) { + if (placed) { + EXPECT(SUCCEEDED(at_address(placed_pages[i],texture_desc,D3D12_BARRIER_LAYOUT_COPY_DEST,&textures[i].p))); + EXPECT(rt::d3d12::vulkan_memory_flags(textures[i].p) == 0); + } else { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, + initial_state, nullptr, IID_PPV_ARGS(&textures[i].p)))); + } + } auto rt_desc = texture_desc; + rt_desc.Format=DXGI_FORMAT_R8G8B8A8_UNORM; rt_desc.Width = rt_desc.Height = target_size; rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + if (placed) { + EXPECT(SUCCEEDED(at_address(placed_pages[2],rt_desc,D3D12_BARRIER_LAYOUT_COMMON,&target.p))); + EXPECT(rt::d3d12::vulkan_memory_flags(target.p) == 0); + } else { + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + } // The upload buffer: texture A at 0, texture B at 2048 (8 rows of the 256-byte pitch), the indices at 4096. constexpr UINT64 b_offset = 2048, index_offset = 4096; const auto upload_desc = buffer_desc(8192); @@ -261,13 +316,20 @@ int main() { std::memcpy(up + index_offset, indices, sizeof(indices)); // The two heaps; their start handles come back in RAX (heap slots 9 and 10). - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, direct_views ? 5u : 4u, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 3, + const UINT sampler_slots = unbounded ? D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE : 3u; + const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, sampler_slots, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap, sampler_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + if (refresh) { + rt::d3d12_xs::set_descriptor_heap_allocator( + [](std::size_t n, std::uint64_t) -> void* { return std::calloc(1, n); }, + [](void* p, std::uint64_t) { std::free(p); }); + } EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); + if (refresh) rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); const std::uint64_t srv_cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); const std::uint64_t srv_gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); const std::uint64_t sampler_cpu = reinterpret_cast(slot(sampler_heap.p, 9))(sampler_heap.p); @@ -276,14 +338,56 @@ int main() { EXPECT(srv_cpu && sampler_cpu && srv_gpu >= 0x10000 && sampler_gpu >= 0x10000); EXPECT(srv_gpu < (1ull << 32) && sampler_gpu < (1ull << 32) && step >= 32); + Ref staging_heap; + Ref unused_texture; + D3D12_CPU_DESCRIPTOR_HANDLE staging_start{}; + if (staged_views) { + D3D12_DESCRIPTOR_HEAP_DESC staging{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,3,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + EXPECT(SUCCEEDED(inner->CreateDescriptorHeap(&staging,IID_PPV_ARGS(&staging_heap.p)))); + staging_start = staging_heap->GetCPUDescriptorHandleForHeapStart(); + EXPECT(SUCCEEDED(at_address(placed_pages[3],texture_desc,D3D12_BARRIER_LAYOUT_COMMON,&unused_texture.p))); + } // The SRVs go into slots 0 and 1 (offset by the increment size), the POINT sampler into the sampler heap. for (UINT i = 0; i < 2; ++i) { D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.Format = texture_desc.Format; srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srv.Texture2D = {0, 1, 0, 0.0f}; - device->CreateShaderResourceView(textures[i].p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(srv_cpu + i * step)}); + const D3D12_CPU_DESCRIPTOR_HANDLE handle{SIZE_T(srv_cpu + i * step)}; + if (test_raw_surface()) { + const UINT raw_size = large_raw_surface() ? 1024 : texture_size; + leonida::gfx10::TiledSurface2D layout; + EXPECT(leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_4kb_s, 4, raw_size, raw_size, layout)); + raw_pages[i].data = static_cast(VirtualAlloc(nullptr,layout.tiled_size(),MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE)); + EXPECT(raw_pages[i].data); + const auto addr = reinterpret_cast(raw_pages[i].data); + leonida::title_va_aliases().add_title_memory(addr,layout.tiled_size()); + std::vector source(raw_size*raw_size); + for (UINT y=0; y(0x105); + struct Shape { D3D12_SHADER_RESOURCE_VIEW_DESC view; UINT64 va; } shape{srv,addr}; + static_assert(offsetof(Shape,va)==sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)); + using RawView = void(WINAPI*)(void*, const D3D12_RESOURCE_DESC*, const Shape*, D3D12_CPU_DESCRIPTOR_HANDLE); + reinterpret_cast(slot(device.p,70))(device.p,&raw,&shape,handle); + leonida::gfx10::ImageWords words{}; + std::memcpy(words.data(),reinterpret_cast(handle.ptr),sizeof(words)); + EXPECT(leonida::gfx10::is_image(words)); + } else if (direct_views) { + device->CreateShaderResourceView(textures[i].p,&srv,handle); + if (!i) device->CreateShaderResourceView(unused_texture.p,&srv,{SIZE_T(srv_cpu+4*step)}); + } else if (staged_views) { + const D3D12_CPU_DESCRIPTOR_HANDLE cpu{staging_start.ptr + i*step}; + device->CreateShaderResourceView(textures[i].p,&srv,cpu); + if (!i) device->CreateShaderResourceView(unused_texture.p,&srv,{staging_start.ptr + 2*step}); + device->CopyDescriptorsSimple(1,handle,cpu,D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } else { + device->CreateShaderResourceView(textures[i].p, &srv, handle); + } } D3D12_SAMPLER_DESC sampler_desc{}; sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; @@ -302,6 +406,13 @@ int main() { device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu + 2 * sampler_step)}); + // Seed the game backing directly so the submission test is independent of API write-through. + const auto sampler_real = rt::d3d12_xs::translate_cpu_descriptor_handle(device.p, {SIZE_T(sampler_cpu)}); + if (refresh) { + EXPECT(sampler_real.ptr && sampler_real.ptr != sampler_cpu); + std::memcpy(reinterpret_cast(sampler_cpu), reinterpret_cast(sampler_real.ptr), 3 * sampler_step); + } + // The hash table, after the descriptors were created and before anything has run: a T# is 8 dwords of the // heap slot, an S# 4 dwords followed by 0xFFFFFFFF x4. Each of the three has an index, they differ, and // bytes nothing was created for have none. @@ -313,11 +424,13 @@ int main() { for (unsigned i = 0; i < 8; ++i) key_unknown[i] = 0x5a5a0000u + i; EXPECT(std::memcmp(key_a, key_b, 32) != 0); EXPECT(std::any_of(key_a, key_a + 8, [](std::uint32_t w) { return w != 0; })); - const std::uint32_t index_a = rt::d3d12::bindless_hash_lookup(device.p, key_a); - const std::uint32_t index_b = rt::d3d12::bindless_hash_lookup(device.p, key_b); + std::uint32_t index_a = rt::d3d12::bindless_hash_lookup(device.p, key_a); + std::uint32_t index_b = rt::d3d12::bindless_hash_lookup(device.p, key_b); const std::uint32_t index_s = rt::d3d12::bindless_hash_lookup(device.p, key_s); std::fprintf(stderr, "hash table: T# A -> %u, T# B -> %u, S# -> %u\n", index_a, index_b, index_s); - EXPECT(index_a && index_b && index_s && index_a != index_b); + EXPECT(index_s); + if (staged_views) EXPECT(index_a == 0 && index_b == 0); + else EXPECT(index_a && index_b && index_a != index_b); std::uint32_t key_wrap[8]; std::memcpy(key_wrap, reinterpret_cast(sampler_cpu + sampler_step), 16); std::fill(key_wrap + 4, key_wrap + 8, 0xffffffffu); @@ -333,6 +446,10 @@ int main() { const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; device->CreateRenderTargetView(target.p, nullptr, rtv); + if (placed) { + EXPECT(rt::d3d12::vulkan_memory_flags(target.p) == 0); + for (const auto& texture : textures) EXPECT((rt::d3d12::vulkan_memory_flags(texture.p) == 0) == staged_views); + } D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -346,20 +463,38 @@ int main() { EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); // Upload both textures, then make them shader resources and the target a render target. - for (UINT i = 0; i < 2; ++i) { - D3D12_TEXTURE_COPY_LOCATION dst{}; - dst.pResource = textures[i].p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION src{}; - src.pResource = upload.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = footprint; - src.PlacedFootprint.Offset = i ? b_offset : 0; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + Ref packed_rtv; + if(test_packed4444()){ + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,2,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&desc,IID_PPV_ARGS(&packed_rtv.p)))); + const auto first=reinterpret_cast(slot(packed_rtv.p,9))(packed_rtv.p); + const auto stride=device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + for(unsigned i=0;i<2;++i){ + const D3D12_CPU_DESCRIPTOR_HANDLE dest{SIZE_T(first+i*stride)}; + device->CreateRenderTargetView(textures[i].p,nullptr,dest); + for(unsigned y=0;yClearRenderTargetView(dest,channels,1,&area); + } + } + } else { + for (UINT i = 0; i < 2; ++i) { + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = textures[i].p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = upload.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint = footprint; + src.PlacedFootprint.Offset = i ? b_offset : 0; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } } D3D12_RESOURCE_BARRIER barriers[3] = { - transition(textures[0].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), - transition(textures[1].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + transition(textures[0].p, initial_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + transition(textures[1].p, initial_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; list->ResourceBarrier(3, barriers); const FLOAT clear[4] = {1.0f, 0.0f, 1.0f, 1.0f}; // magenta: a pixel the draws missed shows @@ -409,6 +544,7 @@ int main() { EXPECT(list->Close() == S_OK); ID3D12CommandList* lists[] = {list.p}; queue->ExecuteCommandLists(1, lists); + if (staged_views) EXPECT(rt::d3d12::vulkan_memory_flags(unused_texture.p)==0); EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); @@ -460,10 +596,65 @@ int main() { EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped2))); std::memcpy(control_pixels.data(), mapped2, control_pixels.size()); + if (refresh) { + // Only CPU stores reach the game's backing after the control list has closed. Both samplers + // already have hash entries. The offset texture coordinates distinguish their address modes. + auto* title = reinterpret_cast(sampler_cpu); + const auto* mapped_heap = reinterpret_cast(sampler_real.ptr); + const std::vector original(mapped_heap, mapped_heap + 3 * sampler_step); + EXPECT(std::memcmp(original.data(), original.data() + sampler_step, sampler_step) != 0); + readback2->Unmap(0, nullptr); + const SIZE_T last = SIZE_T(sampler_slots - 1) * sampler_step; + bool extent_matches = true; + unsigned matches[2]{}; + for (unsigned pass = 0; pass < 2; ++pass) { + const bool swapped = pass == 0; + for (unsigned slot = 0; slot < 2; ++slot) + std::memcpy(title + slot * sampler_step, original.data() + (swapped ? 1 - slot : slot) * sampler_step, + sampler_step); + // An unbounded table reaches the heap's last slot. For one-slot tables this is a guard slot. + std::memcpy(title + last, original.data() + pass * sampler_step, sampler_step); + queue->ExecuteCommandLists(1, lists2); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 3 + pass))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(3 + pass, nullptr))); + const auto* expected_last = original.data() + (unbounded ? pass : 2u) * sampler_step; + extent_matches &= std::memcmp(mapped_heap + last, expected_last, sampler_step) == 0; + EXPECT(SUCCEEDED(readback2->Map(0, nullptr, &mapped2))); + for (UINT y = 0; y < target_size; ++y) { + for (UINT x = 0; x < target_size; ++x) { + const bool left = x < target_size / 2; + const bool wraps = (swapped && !disabled) ? !left : left; + const UINT tx = wraps ? x * texture_size / target_size : texture_size - 1; + const UINT ty = y * texture_size / target_size; + const Texel want = left ? gradient(tx, ty) : reflected(tx, ty); + const auto* pixel = static_cast(mapped2) + y * target_pitch + 4 * x; + matches[pass] += std::memcmp(pixel, want.data(), 4) == 0; + } + } + readback2->Unmap(0, nullptr); + } + std::printf("resubmitted sampler tables: %u/%u swapped, %u/%u restored\n", matches[0], + target_size * target_size, matches[1], target_size * target_size); + std::printf("sampler slot %u: %s\n", sampler_slots - 1, extent_matches ? "matched" : "mismatch"); + EXPECT(extent_matches && matches[0] == target_size * target_size && matches[1] == target_size * target_size); + } + + if (staged_views) { + index_a = rt::d3d12::bindless_hash_lookup(device.p,key_a); + index_b = rt::d3d12::bindless_hash_lookup(device.p,key_b); + EXPECT(index_a && index_b && index_a!=index_b); + // The control pass declares an unbounded SRV table. Its entire visible heap becomes reachable, + // including the extra slot; the source-only staging heap does not. + EXPECT((rt::d3d12::vulkan_memory_flags(unused_texture.p)!=0) == direct_views); + EXPECT(rt::d3d12::vulkan_memory_flags(textures[0].p)!=0 && rt::d3d12::vulkan_memory_flags(target.p)!=0); + } // The entries are still there after the draws. EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key_a) == index_a); EXPECT(rt::d3d12::bindless_hash_lookup(device.p, key_s) == index_s); + unused_texture.reset(); + staging_heap.reset(); for (auto& texture : textures) texture.reset(); for (auto* r : {&upload, &readback, &readback2, &target}) r->reset(); pso.reset(); @@ -479,6 +670,7 @@ int main() { allocator.reset(); queue.reset(); fence.reset(); + packed_rtv.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } @@ -489,7 +681,7 @@ int main() { const UINT tx = col / (target_size / texture_size), ty = row / (target_size / texture_size); const Texel want = col < target_size / 2 ? gradient(tx, ty) : reflected(tx, ty); const std::uint8_t* got = &pixels[std::size_t(row) * target_pitch + col * 4]; - const Texel filtered = linear_clamp(col, row); + const Texel filtered = large_raw_surface() ? want : linear_clamp(col, row); const auto* linear = &linear_pixels[std::size_t(row) * target_pitch + col * 4]; for (unsigned k = 0; k < filtered.size(); ++k) { const int error = std::abs(int(linear[k]) - filtered[k]); diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 590d3507b..0625a0291 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -131,6 +131,9 @@ int main() { const auto device_info = [&](bool mesh) { rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; + info.cold_graphics_compile=d.cold_graphics_compile; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/d3d12_native_graphics_fixture.h b/runtime/test/d3d12_native_graphics_fixture.h new file mode 100644 index 000000000..4eaac5bd7 --- /dev/null +++ b/runtime/test/d3d12_native_graphics_fixture.h @@ -0,0 +1,55 @@ +#pragma once + +// A native pipeline description and catalog for the vertex and mesh pixel readback tests. The source +// programs are built by the tests. The extra row names a container whose actual HASH does not match. +#include "d3d12_test_shaders.h" +#include "../src/native_pso.h" + +namespace d3d12test { +namespace np = leonida::native_pso; +inline constexpr np::Digest producer_digest{1}, ps_digest{2}, stale_digest{3}; + +inline bool write_native_catalog(const std::filesystem::path& dest, const char* producer_stage, + const std::vector& producer, const std::vector& ps) { + std::error_code ec; + if (!std::filesystem::create_directory(dest / "dxbc", ec)) return false; + std::ofstream index(dest / "spirv" / "native_hashes.txt"); + index << np::HashMap::kHeader << '\n'; + const auto add = [&](const char* stage, const np::Digest& digest, const std::vector& program) { + const std::string name = std::string(stage) + ".dxbc"; + const auto container = shader_container(program, &digest); + std::ofstream file(dest / "dxbc" / name, std::ios::binary); + file.write(reinterpret_cast(container.data()), container.size()); + index << np::hex(digest) << '\t' << stage << "\t../dxbc/" << name << '\n'; + return file.good() && index.good(); + }; + if (!add(producer_stage, producer_digest, producer) || !add("ps", ps_digest, ps)) return false; + index << np::hex(stale_digest) << '\t' << producer_stage << "\t../dxbc/" << producer_stage << ".dxbc\n"; + return index.good(); +} + +inline HRESULT create_native_pso(ID3D12Device* device, ID3D12RootSignature* root, DXGI_FORMAT target, + const np::Digest& producer, ID3D12PipelineState** out) { + std::array state{}; + state[0x10] = static_cast(target); + std::memset(state.data() + 0x1c, 0xff, sizeof(UINT)); + state[0x25] = 1; + state[0x26] = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + state[0x28] = 1; + const auto record = [](const np::Digest& d) { + std::array bytes{0x43}; + std::memcpy(bytes.data() + 4, d.data(), d.size()); + return bytes; + }; + const auto v = record(producer), p = record(ps_digest); + np::GraphicsDesc desc{}; + desc.root_signature = root; + desc.state_b = {state.data(), state.size()}; + desc.stages[5].records = {v.data(), v.size()}; + desc.stages[2].records = {p.data(), p.size()}; + using Create = HRESULT(WINAPI*)(void*, const np::GraphicsDesc*, const IID*, void**); + return reinterpret_cast(slot(device, 57))(device, &desc, &__uuidof(ID3D12PipelineState), + reinterpret_cast(out)); +} + +} // namespace d3d12test diff --git a/runtime/test/d3d12_placed_depth_test.h b/runtime/test/d3d12_placed_depth_test.h new file mode 100644 index 000000000..95d32772b --- /dev/null +++ b/runtime/test/d3d12_placed_depth_test.h @@ -0,0 +1,141 @@ +// Slot-133 aliases share GPU contents and retain individual COM identities. +#pragma once +#include "d3d12_copy_compare.h" + +namespace placeddepthtest { + +inline bool check_alias_lifetime(ID3D12Device* device, ID3D12Device* xbox, bool opaque = false) { + using copycmp::Ptr; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 256; + desc.Height = 128; + desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto allocation = device->GetResourceAllocationInfo(0, 1, &desc); + if (!allocation.Alignment || allocation.SizeInBytes == UINT64_MAX || allocation.SizeInBytes <= allocation.Alignment) + return false; + struct Pages { + void* ptr; + ~Pages() { if (ptr) VirtualFree(ptr, 0, MEM_RELEASE); } + } pages{VirtualAlloc(nullptr, SIZE_T(allocation.SizeInBytes * 2), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)}; + if (!pages.ptr) return false; + const UINT64 address = reinterpret_cast(pages.ptr); + auto xbox_desc = desc; + xbox_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + xbox_desc.Layout = opaque ? D3D12_TEXTURE_LAYOUT_UNKNOWN : static_cast(0x101); + using Create = HRESULT(WINAPI*)(void*, UINT64, const D3D12_RESOURCE_DESC*, UINT, + const D3D12_CLEAR_VALUE*, REFIID, void**); + const auto create = reinterpret_cast((*reinterpret_cast(xbox))[133]); + const auto place = [&](UINT64 va, const D3D12_RESOURCE_DESC& shape, Ptr& result, + const D3D12_CLEAR_VALUE* clear = nullptr) { + return create(xbox, va, &shape, UINT_MAX, clear, IID_PPV_ARGS(&result.p)); + }; + Ptr first, alias, next, invalid; + if (FAILED(place(address, xbox_desc, first)) || FAILED(place(address, xbox_desc, alias)) || + FAILED(place(address + allocation.SizeInBytes, xbox_desc, next))) return false; + if (first.p == alias.p || alias->GetGPUVirtualAddress() != address || + next->GetGPUVirtualAddress() != address + allocation.SizeInBytes) return false; + // Independent COM private data helps catch accidental reuse of the object itself as the alias. + constexpr GUID cookie_key{0x650cf350, 0xa07e, 0x428d, {0xb4, 0x14, 0xdc, 0xaf, 0xc6, 0x97, 0xe8, 0x4b}}; + const UINT cookie = 12; + UINT bytes = 0; + if (FAILED(first->SetPrivateData(cookie_key, sizeof(cookie), &cookie)) || + alias->GetPrivateData(cookie_key, &bytes, nullptr) != DXGI_ERROR_NOT_FOUND) return false; + auto smaller = xbox_desc; + smaller.Width /= 2; + Ptr other_shape; + if (opaque && (FAILED(place(address, smaller, other_shape)) || other_shape->GetDesc().Width != smaller.Width || + other_shape->GetGPUVirtualAddress() != address)) return false; + D3D12_CLEAR_VALUE optimized{}; + optimized.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + optimized.DepthStencil = {1.0f, 0}; + if (place(address, xbox_desc, invalid, &optimized) != E_NOTIMPL || invalid.p) return false; + if ((!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) || + place(address + allocation.Alignment, xbox_desc, invalid) != E_NOTIMPL || invalid.p || + place(address + 1, xbox_desc, invalid) != E_INVALIDARG || invalid.p) return false; + + Ptr heap; + D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2}; + if (FAILED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))) return false; + D3D12_DEPTH_STENCIL_VIEW_DESC dsv{}; + dsv.Format = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + dsv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; + const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateDepthStencilView(first.p, &dsv, handle); + auto other_view = handle; + other_view.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + if (opaque) device->CreateDepthStencilView(other_shape.p, &dsv, other_view); + copycmp::Run commands; + if (!commands.init(device, true)) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT layouts[2]{}; + UINT64 total = 0; + device->GetCopyableFootprints(&desc, 0, 2, 0, layouts, nullptr, nullptr, &total); + Ptr readback; + const UINT64 sample_offset = (total + 511) & ~UINT64(511); + if (!commands.buffer(D3D12_HEAP_TYPE_READBACK, sample_offset + 256, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return false; + commands.begin(); + if (opaque) { + D3D12_RESOURCE_BARRIER use{}; + use.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + use.Aliasing = {nullptr, other_shape.p}; + commands.list->ResourceBarrier(1, &use); + commands.list->ClearDepthStencilView(other_view, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.625f, 0x34, 0, nullptr); + commands.barrier(other_shape.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = other_shape.p; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {sample_offset,{DXGI_FORMAT_R32_TYPELESS,1,1,1,256}}; + const D3D12_BOX pixel{0,0,0,1,1,1}; + commands.list->CopyTextureRegion(&dst,0,0,0,&src,&pixel); + use.Aliasing = {other_shape.p, first.p}; + commands.list->ResourceBarrier(1,&use); + } + commands.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, + 0.375f, 0xb7, 0, nullptr); + D3D12_RESOURCE_BARRIER activate{}; + activate.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + activate.Aliasing = {first.p, alias.p}; + commands.list->ResourceBarrier(1, &activate); + if (!commands.submit().empty()) return false; + first.reset(); + if (!opaque && (place(address, smaller, invalid) != E_NOTIMPL || invalid.p)) return false; + commands.begin(); + commands.barrier(alias.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT plane = 0; plane < 2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; + src.pResource = alias.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + src.SubresourceIndex = plane; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = layouts[plane]; + commands.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + if (!commands.submit().empty()) return false; + unsigned char* mapped = nullptr; + if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&mapped)))) return false; + float earlier = 0; + if (opaque) std::memcpy(&earlier, mapped + sample_offset, sizeof(earlier)); + bool valid = !opaque || earlier == 0.625f; + for (UINT y = 0; y < desc.Height && valid; ++y) { + for (UINT x = 0; x < desc.Width; ++x) { + float depth; + std::memcpy(&depth, mapped + layouts[0].Offset + y * layouts[0].Footprint.RowPitch + x * sizeof(depth), + sizeof(depth)); + if (depth != 0.375f || mapped[layouts[1].Offset + y * layouts[1].Footprint.RowPitch + x] != 0xb7) { + std::fprintf(stderr, "slot-133 alias: wrong readback at (%u, %u)\n", x, y); + valid = false; + break; + } + } + } + readback->Unmap(0, nullptr); + alias.reset(); + return valid && SUCCEEDED(place(address, smaller, invalid)) && invalid->GetGPUVirtualAddress() == address; +} + +} // namespace placeddepthtest diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp index 13b3bace5..0cb85332c 100644 --- a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp +++ b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp @@ -205,14 +205,14 @@ struct ShaderParams { std::uint32_t mode; std::uint32_t width; std::uint32_t height; - std::uint32_t pad; + std::uint32_t slice; }; bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescriptorSetLayout set0_layout, const g::ImageWords& uav_words, const g::ImageWords& srv_words, const g::SamplerWords& sampler_words, bool do_uint_write, const std::array& input_words, - std::array& out_rgba) { + std::array& out_rgba, int z = -1, bool sliced = false) { std::vector code; if (!read_spirv(LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV, code)) return false; @@ -320,7 +320,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams wp{}; std::memcpy(wp.tsharp, uav_words.data(), sizeof(wp.tsharp)); std::memcpy(wp.ssharp, sampler_words.data(), sizeof(wp.ssharp)); - wp.mode = 0; + wp.mode = z < 0 ? 0u : 2u; + wp.slice = sliced ? 1u : 0u; wp.width = 4; wp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(wp), &wp); @@ -336,7 +337,8 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto ShaderParams sp{}; std::memcpy(sp.tsharp, srv_words.data(), sizeof(sp.tsharp)); std::memcpy(sp.ssharp, sampler_words.data(), sizeof(sp.ssharp)); - sp.mode = 1; + sp.mode = z < 0 ? 1u : 3u; + sp.slice = z < 0 ? 0u : UINT(z); sp.width = 4; sp.height = 4; push(cb, pipe_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(sp), &sp); @@ -358,7 +360,7 @@ bool run_bindless_roundtrip(vktest::Device& d, VkDescriptorSet set0, VkDescripto int main() { vktest::Device d; - const auto status = d.initialize(); + const auto status = d.initialize(true, true); // exercise sliced RGB9E5 volumes when the driver supports them if (status == vktest::DeviceStatus::unavailable) return 77; if (status != vktest::DeviceStatus::ready) return 1; @@ -381,6 +383,8 @@ int main() { info.bindless_partially_bound = d.partially_bound; info.image_view_min_lod = d.image_view_min_lod; info.host_image_copy = d.host_image_copy; + info.robust_image_access = d.robust_image_access; + info.sliced_3d_uav = d.sliced_3d_uav; Ref device; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); @@ -441,7 +445,7 @@ int main() { D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&tex_1d.p)))); - const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 2, + const auto desc_3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 8, 2, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); Ref tex_3d; EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &desc_3d, @@ -785,27 +789,77 @@ int main() { std::array sampled{}; EXPECT(run_bindless_roundtrip(d, set0, set0_layout, rt_uav_words, rt_srv_words, smp_words, !native_storage, input_words, sampled)); - for (UINT i = 0; i < 16; ++i) { - const std::uint32_t want_word = native_storage ? 0x94010040u : input_words[i]; - leonida::uav_clear::Element elem{}; - elem.size = 4; - std::memcpy(elem.bytes.data(), &want_word, 4); - VkClearColorValue want{}; - EXPECT(leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)); - for (UINT c = 0; c < 4; ++c) { - const float got = sampled[i * 4 + c]; - const float exp_v = want.float32[c]; - const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); - if (std::fabs(got - exp_v) > tol) { - std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", - i, c, got, exp_v, want_word); - return 1; + const auto check_samples = [&](bool seed_only) { + for (UINT i = 0; i < 16; ++i) { + const std::uint32_t want_word = seed_only ? 0x94010040u : input_words[i]; + leonida::uav_clear::Element elem{}; + elem.size = 4; + std::memcpy(elem.bytes.data(), &want_word, 4); + VkClearColorValue want{}; + if (!leonida::uav_clear::decode(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, elem, want)) return false; + for (UINT c = 0; c < 4; ++c) { + const float got = sampled[i * 4 + c]; + const float exp_v = want.float32[c]; + const float tol = std::max(1e-6f, std::fabs(exp_v) * 1e-5f); + if (!(std::fabs(got - exp_v) <= tol)) { + std::fprintf(stderr, "bindless sample texel %u ch %u: got %g, want %g (word 0x%08x)\n", + i, c, got, exp_v, want_word); + return false; + } } } - } + return true; + }; + EXPECT(check_samples(native_storage)); std::printf("Bindless set-0 GPU round-trip: 16/16 HDR RGB9E5 texels matched (%s)\n", native_storage ? "clear -> sampled E5B9G9R9" : "storage R32_UINT [bindings 9 & 4] -> sampled E5B9G9R9 [binding 0]"); + + if (!native_storage && d.robust_image_access) { + // Mip 1 of tex_3d is 4x4x4. Seed it through the logical RGB9E5 clear, then write packed data + // through R32_UINT. A sliced view selects only absolute Z=1; relative Z=1 must not write Z=2. + D3D12_UNORDERED_ACCESS_VIEW_DESC volume_uav{}; + volume_uav.Format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + volume_uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + volume_uav.Texture3D = {1, 0, ~0u}; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(10)); + const auto whole = words_at(10); + EXPECT(g::decode(whole, decoded) && decoded.first_mip == 1 && decoded.format == 132 && + (whole[7] & g::packed_uav_flag) && !g::partial_volume_uav(whole, decoded)); + volume_uav.Texture3D.FirstWSlice = 1; + volume_uav.Texture3D.WSize = 1; + device->CreateUnorderedAccessView(tex_3d.p, nullptr, &volume_uav, slot(11)); + const auto partial = words_at(11); + if (d.sliced_3d_uav) { + EXPECT(g::decode(partial, decoded) && g::partial_volume_uav(partial, decoded)); + } else { + EXPECT(all_zero(partial.data(), sizeof(partial))); + } + D3D12_SHADER_RESOURCE_VIEW_DESC volume_srv{}; + volume_srv.Format = volume_uav.Format; + volume_srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + volume_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + volume_srv.Texture3D = {1, 1, 0}; + device->CreateShaderResourceView(tex_3d.p, &volume_srv, slot(12)); + const auto volume_sampled = words_at(12); + EXPECT(g::decode(volume_sampled, decoded) && decoded.format == 132 && volume_sampled[7] == 0); + + EXPECT(SUCCEEDED(alloc->Reset()) && SUCCEEDED(list->Reset(alloc.p, nullptr))); + list->ClearUnorderedAccessViewFloat({0}, slot(10), tex_3d.p, seed, 0, nullptr); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); + const auto& write_key = d.sliced_3d_uav ? partial : whole; + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + true, input_words, sampled, d.sliced_3d_uav ? 1 : 0, d.sliced_3d_uav)); + EXPECT(check_samples(false)); + EXPECT(run_bindless_roundtrip(d, set0, set0_layout, write_key, volume_sampled, smp_words, + false, input_words, sampled, 2)); + EXPECT(check_samples(true)); + std::printf("RGB9E5 volume: 16/16 raw-store samples and 16/16 untouched neighbor texels (%s)\n", + d.sliced_3d_uav ? "sliced" : "whole-mip; partial view refused"); + } } #endif } diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp index 05b90a81c..ae1cbc6a8 100644 --- a/runtime/test/d3d12_rect_list_test.cpp +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -7,6 +7,10 @@ // v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth // corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane // through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frames 3 to 5, rectangle lists whose right angle is at the second vertex, at the third vertex, and a triangle with +// no right angle at all. The layer takes the right-angle corner as the vertex opposite the longest screen edge, so +// the first two must cover all 64x64 pixels on the colour plane too (the retail boot's full-screen draw has its +// right angle at the second vertex); the third only has to draw something and not fail. // frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners // in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. // Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 @@ -86,12 +90,21 @@ int main() { // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; - const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + const Vertex vertices[20] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), - vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; - static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2), + // vertices 11..13: right angle at the second vertex; 14..16: at the third; 17..19: none + vertex(-1, 1, ca), vertex(1, 1, cb), vertex(1, -1, cc), + vertex(-1, 1, ca), vertex(1, -1, cb), vertex(-1, -1, cc), + vertex(-1, 1, ca), vertex(0.5f, 0.75f, cb), vertex(-0.25f, -1, cc)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 640); + const Vertex* const corner_cases[2] = {&vertices[11], &vertices[14]}; - std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent), + second_pixels(target_extent * target_extent), third_pixels(target_extent * target_extent), + skew_pixels(target_extent * target_extent); + std::vector dynamic_pixels(rect_pixels.size()), triangle_pixels(rect_pixels.size()), + repeated_pixels(rect_pixels.size()); { rt::d3d12::VulkanDeviceInfo info{}; info.get_instance_proc = d.instance_proc; @@ -172,8 +185,9 @@ int main() { EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); std::memcpy(up, vertices, sizeof(vertices)); - // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. - const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + // V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners, slots 2 to 4 + // the three more rectangles. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 5, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref srv_heap; EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); @@ -183,9 +197,12 @@ int main() { EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); EXPECT(buffer_va >= 0x10000); - const std::array vsharps[2] = {make_vsharp(buffer_va, 3), - make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; - for (unsigned i = 0; i < 2; ++i) + const std::array vsharps[5] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8), + make_vsharp(buffer_va + 11 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 14 * sizeof(Vertex), 3), + make_vsharp(buffer_va + 17 * sizeof(Vertex), 3)}; + for (unsigned i = 0; i < 5; ++i) std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; @@ -263,6 +280,12 @@ int main() { }; EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + EXPECT(render_frame(3, rect_pso.p, rect_list, 2, 3, second_pixels) == 0); + EXPECT(render_frame(4, rect_pso.p, rect_list, 3, 3, third_pixels) == 0); + EXPECT(render_frame(5, rect_pso.p, rect_list, 4, 3, skew_pixels) == 0); + EXPECT(render_frame(6, quad_pso.p, rect_list, 0, 3, dynamic_pixels) == 0); + EXPECT(render_frame(7, quad_pso.p, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, 0, 3, triangle_pixels) == 0); + EXPECT(render_frame(8, quad_pso.p, rect_list, 0, 3, repeated_pixels) == 0); for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); rect_pso.reset(); quad_pso.reset(); @@ -311,6 +334,80 @@ int main() { } } EXPECT(covered == target_extent * target_extent); + // The same triangle-family PSO can select either primitive at draw time. Compare both rectangle draws + // to the verified type-19 reference; exclude only the shared diagonal from the triangle coverage check. + const Pixel clear_value = {0.5f, 0.125f, 0.25f, 0.5f}; + for (UINT y = 0; y < target_extent; ++y) { + for (UINT x = 0; x < target_extent; ++x) { + const auto i = y * target_extent + x; + EXPECT(std::memcmp(&dynamic_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + EXPECT(std::memcmp(&repeated_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + if (x + y + 1 < target_extent) + EXPECT(std::memcmp(&triangle_pixels[i], &rect_pixels[i], sizeof(Pixel)) == 0); + if (x + y + 1 > target_extent) + EXPECT(std::memcmp(&triangle_pixels[i], &clear_value, sizeof(Pixel)) == 0); + } + } + + // Right angle at the second and at the third vertex: the plane through the three drawn corners, everywhere. + const std::vector* const corner_pixels[2] = {&second_pixels, &third_pixels}; + const char* const corner_names[2] = {"second", "third"}; + unsigned corner_covered[2] = {0, 0}; + float corner_worst = 0.0f; + for (int which = 0; which < 2; ++which) { + const Vertex* t = corner_cases[which]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const Pixel& got = (*corner_pixels[which])[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (t[0].color[c] + s * (t[1].color[c] - t[0].color[c]) + + r * (t[2].color[c] - t[0].color[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + corner_worst = std::fmax(corner_worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + corner_covered[which] += pixel_ok; + } + } + if (corner_covered[which] != target_extent * target_extent) { + std::fprintf(stderr, "rect list with the right angle at the %s vertex: %u of %u pixels on the plane\n", + corner_names[which], corner_covered[which], target_extent * target_extent); + return 1; + } + } + // Not a right triangle: any consistent corner is fine, but every corner choice makes a parallelogram that holds the + // drawn triangle, so each pixel well inside the triangle must be drawn (not the clear colour). + const Pixel clear_pixel = {0.5f, 0.125f, 0.25f, 0.5f}; + unsigned skew_drawn = 0, skew_inside = 0, skew_missing = 0; + { + const Vertex* t = &vertices[17]; + const float x0 = t[0].position[0], y0 = t[0].position[1]; + const float ax = t[1].position[0] - x0, ay = t[1].position[1] - y0; + const float bx = t[2].position[0] - x0, by = t[2].position[1] - y0; + const float det = ax * by - ay * bx; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float px = 2.0f * (float(col) + 0.5f) / target_extent - 1.0f - x0; + const float py = 1.0f - 2.0f * (float(row) + 0.5f) / target_extent - y0; + const float s = (px * by - py * bx) / det, r = (ax * py - ay * px) / det; + const bool drawn = std::memcmp(&skew_pixels[row * target_extent + col], &clear_pixel, sizeof(Pixel)) != 0; + skew_drawn += drawn; + if (s > 0.02f && r > 0.02f && s + r < 0.98f) { + ++skew_inside; + skew_missing += !drawn; + } + } + } + } + EXPECT(skew_inside > 1000 && skew_missing == 0); // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; @@ -333,9 +430,11 @@ int main() { std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); return 1; } - std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " - "%u of %u pixels exact\n", - covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, - target_extent * target_extent); + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; right angle at " + "the second vertex %u and at the third %u of %u (worst error %g); no right angle: %u pixels drawn; " + "quad list: %u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), corner_covered[0], corner_covered[1], + target_extent * target_extent, double(corner_worst), skew_drawn, + target_extent * target_extent - quad_wrong, target_extent * target_extent); return 0; } diff --git a/runtime/test/d3d12_test_shaders.h b/runtime/test/d3d12_test_shaders.h index d778d1bc6..c424ef5be 100644 --- a/runtime/test/d3d12_test_shaders.h +++ b/runtime/test/d3d12_test_shaders.h @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -44,7 +45,8 @@ inline std::vector fssm_program(std::initializer_list shader_container(const std::vector& fssm) { +inline std::vector shader_container(const std::vector& fssm, + const std::array* digest = nullptr) { const auto stream = zlib_stored(fssm); std::vector xbch = {'X', 'B', 'C', 'H'}; for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); @@ -59,11 +61,18 @@ inline std::vector shader_container(const std::vector out = {'D', 'X', 'B', 'C'}; out.resize(28, 0); - put32(out, 1); - put32(out, 36); + put32(out, digest ? 2 : 1); + put32(out, digest ? 40 : 36); + if (digest) put32(out, 40 + 8 + std::uint32_t(dxil.size())); out.insert(out.end(), {'D', 'X', 'I', 'L'}); put32(out, std::uint32_t(dxil.size())); out.insert(out.end(), dxil.begin(), dxil.end()); + if (digest) { + out.insert(out.end(), {'H', 'A', 'S', 'H'}); + put32(out, 20); + put32(out, 0); + out.insert(out.end(), digest->begin(), digest->end()); + } return out; } diff --git a/runtime/test/d3d12_texture1d_target_test.cpp b/runtime/test/d3d12_texture1d_target_test.cpp index 4642440fa..4f12801db 100644 --- a/runtime/test/d3d12_texture1d_target_test.cpp +++ b/runtime/test/d3d12_texture1d_target_test.cpp @@ -234,6 +234,7 @@ struct Format { int main() { vktest::Device vk; + vk.request_buffer_device_address = true; const auto device_status = vk.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips if (device_status != vktest::DeviceStatus::ready) return 1; @@ -250,6 +251,9 @@ int main() { info.conditional_rendering = vk.conditional_rendering; info.storage_buffer_8bit = vk.storage_buffer_8bit; info.buffer_device_address = vk.buffer_device_address; + info.robust_image_access = vk.robust_image_access; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; if (hostwine::host_is_wine()) return 77; // every check is a comparison with Windows D3D12 Ref factory; diff --git a/runtime/test/d3d12_texture1d_test.cpp b/runtime/test/d3d12_texture1d_test.cpp index 007c513b4..b32847a90 100644 --- a/runtime/test/d3d12_texture1d_test.cpp +++ b/runtime/test/d3d12_texture1d_test.cpp @@ -116,7 +116,7 @@ int main() { uav1d.Texture1D.MipSlice = 1; dev->CreateUnorderedAccessView(tex1d, nullptr, &uav1d, {cbv_cpu.ptr + cbv_inc * 5}); - // Default (nullptr) SRV and UAV on a 1D array must write a null descriptor (set 0 has no 1D-array binding). + // Set 0 has storage-only 1D-array bindings: a default SRV is null, but a default UAV covers the whole array. std::memset(reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6), 0x77, cbv_inc * 2); dev->CreateShaderResourceView(tex1d, nullptr, {cbv_cpu.ptr + cbv_inc * 6}); dev->CreateUnorderedAccessView(tex1d, nullptr, nullptr, {cbv_cpu.ptr + cbv_inc * 7}); @@ -147,11 +147,12 @@ int main() { if (!decode_and_lookup(5, img) || img.type != g::ImageType::image_1d || img.first_mip != 1 || img.mip_count != 1 || img.layer_count != 1) return fail("explicit 1D UAV on array T# or bindless lookup mismatch"); - for (UINT slot = 6; slot < 8; ++slot) { - const auto* bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * slot); - for (UINT b = 0; b < 32; ++b) - if (bytes[b] != 0) return fail("default 1DArray view should write a null descriptor"); - } + const auto* srv_bytes = reinterpret_cast(cbv_cpu.ptr + cbv_inc * 6); + for (UINT b = 0; b < 32; ++b) + if (srv_bytes[b] != 0) return fail("default 1DArray SRV should write a null descriptor"); + if (!decode_and_lookup(7, img) || img.type != g::ImageType::image_1d_array || img.first_mip != 0 || + img.mip_count != 1 || img.first_layer != 0 || img.layer_count != tex1d_desc.DepthOrArraySize) + return fail("default 1DArray UAV T# or bindless lookup mismatch"); // RTV / DSV 1D bounds validation (out-of-bounds mip/slice must write a null TargetView) D3D12_RENDER_TARGET_VIEW_DESC bad_rtv{}; @@ -267,6 +268,6 @@ int main() { cbv_heap->Release(); dev->Release(); - std::printf("PASS: d3d12_texture1d_test (1D/1DArray SRV, UAV + CopyTextureRegion round-trip)\n"); + std::printf("PASS: d3d12_texture1d_test (1D views, 1DArray UAV + CopyTextureRegion round-trip)\n"); return 0; } diff --git a/runtime/test/d3d12_texture_uav_oracle.h b/runtime/test/d3d12_texture_uav_oracle.h new file mode 100644 index 000000000..d9d9dfaea --- /dev/null +++ b/runtime/test/d3d12_texture_uav_oracle.h @@ -0,0 +1,279 @@ +#pragma once + +// Native Windows D3D12/WARP reference for synthetic texture UAV dispatches. +// Link d3d12 and dxgi; the HLSL compiler is loaded from System32. +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace uav_oracle { +enum class Status { ready, unavailable, failed }; + +namespace detail { +using Microsoft::WRL::ComPtr; + +inline bool fail(const char* message) { + std::fprintf(stderr, "WARP texture UAV: %s\n", message); + return false; +} + +inline bool check(HRESULT hr, const char* action, ID3DBlob* errors = nullptr) { + if (SUCCEEDED(hr)) return true; + std::fprintf(stderr, "WARP texture UAV: %s failed (0x%08lx)\n", action, static_cast(hr)); + if (errors) std::fputs(static_cast(errors->GetBufferPointer()), stderr); + return false; +} + +struct View { + unsigned shader; + UINT mip; +}; + +inline View select_view(const D3D12_RESOURCE_DESC& resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc) { + if (desc) { + switch (desc->ViewDimension) { + case D3D12_UAV_DIMENSION_TEXTURE1D: return {0, desc->Texture1D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: return {1, desc->Texture1DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2D: return {2, desc->Texture2D.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: return {3, desc->Texture2DArray.MipSlice}; + case D3D12_UAV_DIMENSION_TEXTURE3D: return {4, desc->Texture3D.MipSlice}; + default: return {5, 0}; + } + } + switch (resource.Dimension) { + case D3D12_RESOURCE_DIMENSION_TEXTURE1D: return {resource.DepthOrArraySize > 1 ? 1u : 0u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE2D: return {resource.DepthOrArraySize > 1 ? 3u : 2u, 0}; + case D3D12_RESOURCE_DIMENSION_TEXTURE3D: return {4, 0}; + default: return {5, 0}; + } +} + +inline D3D12_HEAP_PROPERTIES heap_properties(D3D12_HEAP_TYPE type) { + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = type; + heap.CreationNodeMask = heap.VisibleNodeMask = 1; + return heap; +} + +struct Context { + ComPtr device; + ComPtr root; + std::array, 5> pipelines; + + Status prepare_device() { + if (device) return Status::ready; + ComPtr factory; + ComPtr warp; + HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(factory.GetAddressOf())); + if (hr == E_NOINTERFACE || hr == DXGI_ERROR_UNSUPPORTED) return Status::unavailable; + if (!check(hr, "CreateDXGIFactory1")) return Status::failed; + hr = factory->EnumWarpAdapter(IID_PPV_ARGS(warp.GetAddressOf())); + if (hr == DXGI_ERROR_NOT_FOUND || hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) + return Status::unavailable; + if (!check(hr, "EnumWarpAdapter")) return Status::failed; + hr = D3D12CreateDevice(warp.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(device.GetAddressOf())); + if (hr == DXGI_ERROR_UNSUPPORTED || hr == E_NOTIMPL) return Status::unavailable; + return check(hr, "D3D12CreateDevice") ? Status::ready : Status::failed; + } + + bool init() { + if (root) return true; + if (prepare_device() != Status::ready) return false; + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_ROOT_SIGNATURE_DESC desc{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + const HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, + blob.GetAddressOf(), errors.GetAddressOf()); + return check(hr, "D3D12SerializeRootSignature", errors.Get()) && + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(root.GetAddressOf())), "CreateRootSignature"); + } + + bool create_pipeline(unsigned index) { + if (pipelines[index]) return true; + static constexpr const char* types[] = { + "RWTexture1D", "RWTexture1DArray", "RWTexture2D", "RWTexture2DArray", "RWTexture3D", + }; + static constexpr const char* coordinates[] = {"id.x", "id.xz", "id.xy", "id.xyz", "id.xyz"}; + static constexpr char source[] = + "UAV_TYPE dst : register(u0);\n" + "[numthreads(1, 1, 1)]\n" + "void main(uint3 id : SV_DispatchThreadID) {\n" + " dst[UAV_COORD] += 1000u + id.x + 16u * id.y + 256u * id.z;\n" + "}\n"; + struct Compiler { + HMODULE module = LoadLibraryExW(L"d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + ~Compiler() { if (module) FreeLibrary(module); } + } compiler; + if (!compiler.module) return check(HRESULT_FROM_WIN32(GetLastError()), "load d3dcompiler_47.dll"); + auto compile = std::bit_cast(GetProcAddress(compiler.module, "D3DCompile")); + if (!compile) return check(HRESULT_FROM_WIN32(GetLastError()), "find D3DCompile"); + const D3D_SHADER_MACRO macros[] = { + {"UAV_TYPE", types[index]}, {"UAV_COORD", coordinates[index]}, {nullptr, nullptr}, + }; + ComPtr blob, errors; + const HRESULT hr = compile(source, sizeof(source) - 1, "texture_uav_oracle.hlsl", macros, nullptr, "main", + "cs_5_1", D3DCOMPILE_ENABLE_STRICTNESS, 0, blob.GetAddressOf(), errors.GetAddressOf()); + if (!check(hr, "D3DCompile", errors.Get())) return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = root.Get(); + desc.CS = {blob->GetBufferPointer(), blob->GetBufferSize()}; + return check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(pipelines[index].GetAddressOf())), + "CreateComputePipelineState"); + } + + HRESULT create_buffer(UINT64 bytes, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { + const auto heap = heap_properties(heap_type); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); + } +}; + +inline Context& context() { + static thread_local Context ctx; + return ctx; +} +} // namespace detail + +inline Status prepare() { + return detail::context().prepare_device(); +} + +// Provide a valid R32_UINT or R32_TYPELESS texture descriptor and a valid UINT UAV view; a null view +// asks D3D12 to create the default view of a typed R32_UINT resource. Both spans cover the entire +// selected mip (x fastest, then y, then array layer or 3D depth). Other mips are neither read nor written. +inline bool run(const D3D12_RESOURCE_DESC& resource_desc, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, + std::span before, std::span after, UINT dispatch_depth = 0) { + using namespace detail; + const View view = select_view(resource_desc, desc); + auto& ctx = context(); + if (view.shader >= ctx.pipelines.size() || + (resource_desc.Format != DXGI_FORMAT_R32_UINT && resource_desc.Format != DXGI_FORMAT_R32_TYPELESS)) + return fail("expected an R32_UINT or R32_TYPELESS texture and a texture UAV"); + if (!ctx.init() || !ctx.create_pipeline(view.shader)) return false; + + ComPtr texture, upload, readback; + const auto heap = heap_properties(D3D12_HEAP_TYPE_DEFAULT); + if (!check(ctx.device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &resource_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(texture.GetAddressOf())), + "CreateCommittedResource (texture)")) return false; + + const auto actual_desc = texture->GetDesc(); // MipLevels = 0 in the input requests the full chain. + if (view.mip >= actual_desc.MipLevels) return fail("UAV mip slice is out of range"); + const bool volume = actual_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const UINT subresources = volume ? 1 : actual_desc.DepthOrArraySize; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + ctx.device->GetCopyableFootprints(&actual_desc, view.mip, 1, 0, &footprint, nullptr, nullptr, &bytes); + if (bytes == (std::numeric_limits::max)()) return fail("GetCopyableFootprints rejected the texture"); + const auto& fp = footprint.Footprint; + const UINT depth = volume ? fp.Depth : subresources; + const std::uint64_t texels = std::uint64_t(fp.Width) * fp.Height * depth; + if (before.size() != texels || after.size() != texels) + return fail("input and output must span the whole selected mip"); + // Array layers are separate subresources; a 3D mip is one subresource with depth slices at rowPitch * height. + constexpr UINT64 alignment = D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT; + const UINT64 layer_pitch = (bytes + alignment - 1) & ~(alignment - 1); + const UINT64 total = bytes + (subresources - 1) * layer_pitch; + if (total > (std::numeric_limits::max)()) return fail("staging buffers exceed the host address space"); + const auto z_pitch = static_cast(volume ? UINT64(fp.RowPitch) * fp.Height : layer_pitch); + const SIZE_T row_bytes = SIZE_T(fp.Width) * sizeof(std::uint32_t); + if (!check(ctx.create_buffer(total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, + upload.GetAddressOf()), "CreateCommittedResource (upload)") || + !check(ctx.create_buffer(total, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, + readback.GetAddressOf()), "CreateCommittedResource (readback)")) return false; + const auto each_row = [&](auto copy) { + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < fp.Height; ++y) + copy((SIZE_T(z) * fp.Height + y) * fp.Width, z * z_pitch + SIZE_T(y) * fp.RowPitch); + }; + const D3D12_RANGE none{}, all{0, static_cast(total)}; + void* mapped = nullptr; + if (!check(upload->Map(0, &none, &mapped), "Map upload")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(static_cast(mapped) + offset, before.data() + word, row_bytes); + }); + upload->Unmap(0, &all); + + ComPtr uavs; + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{ + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0, + }; + if (!check(ctx.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(uavs.GetAddressOf())), "CreateDescriptorHeap")) + return false; + ctx.device->CreateUnorderedAccessView(texture.Get(), nullptr, desc, uavs->GetCPUDescriptorHandleForHeapStart()); + + // Use fresh submission objects per run, so no allocator or descriptor heap is reset while in use. + ComPtr queue; + ComPtr allocator; + ComPtr list; + ComPtr fence; + constexpr auto direct = D3D12_COMMAND_LIST_TYPE_DIRECT; + const D3D12_COMMAND_QUEUE_DESC queue_desc{direct}; + if (!check(ctx.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(queue.GetAddressOf())), "CreateCommandQueue") || + !check(ctx.device->CreateCommandAllocator(direct, IID_PPV_ARGS(allocator.GetAddressOf())), "CreateCommandAllocator") || + !check(ctx.device->CreateCommandList(0, direct, allocator.Get(), ctx.pipelines[view.shader].Get(), + IID_PPV_ARGS(list.GetAddressOf())), "CreateCommandList") || + !check(ctx.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.GetAddressOf())), "CreateFence")) + return false; + const auto copy_mip = [&](ID3D12Resource* buffer, bool to_texture) { + D3D12_TEXTURE_COPY_LOCATION tex{}, staging{}; + tex.pResource = texture.Get(); + tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + staging.pResource = buffer; + staging.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + staging.PlacedFootprint = footprint; + for (UINT layer = 0; layer < subresources; ++layer) { + tex.SubresourceIndex = view.mip + layer * actual_desc.MipLevels; + staging.PlacedFootprint.Offset = layer * layer_pitch; + list->CopyTextureRegion(to_texture ? &tex : &staging, 0, 0, 0, to_texture ? &staging : &tex, nullptr); + } + }; + const auto transition = [&](D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {texture.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); + }; + copy_mip(upload.Get(), true); + transition(D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[] = {uavs.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(ctx.root.Get()); + list->SetComputeRootDescriptorTable(0, uavs->GetGPUDescriptorHandleForHeapStart()); + list->Dispatch(fp.Width, fp.Height, dispatch_depth ? dispatch_depth : depth); + transition(D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_mip(readback.Get(), false); + if (!check(list->Close(), "Close command list")) return false; + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (!check(queue->Signal(fence.Get(), 1), "Signal queue fence") || + !check(fence->SetEventOnCompletion(1, nullptr), "wait for queue fence") || + !check(ctx.device->GetDeviceRemovedReason(), "D3D12 execution")) return false; + if (!check(readback->Map(0, &all, &mapped), "Map readback")) return false; + each_row([&](SIZE_T word, SIZE_T offset) { + std::memcpy(after.data() + word, static_cast(mapped) + offset, row_bytes); + }); + readback->Unmap(0, &none); + return true; +} +} // namespace uav_oracle diff --git a/runtime/test/d3d12_texture_uav_test.cpp b/runtime/test/d3d12_texture_uav_test.cpp new file mode 100644 index 000000000..f8ef5177b --- /dev/null +++ b/runtime/test/d3d12_texture_uav_test.cpp @@ -0,0 +1,629 @@ +// Synthetic texture UAVs through the Vulkan D3D12 device. It has no compute PSOs yet, so dispatch the translated +// cs_texture_uav.asm through its actual Vulkan set 0. Non-atomic UINT cases also compare in-view writes with +// Windows WARP. Build the shader with runtime/test/shaders/build.py and pass the .spv as argv[1]. +// LEONIDA_VK_VALIDATION=1 enables the Khronos validation layer. No game files are used. +#include "vk_test_device.h" +#include "vk_pc_tail.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" +#include "d3d12_texture_uav_oracle.h" + +#include + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ +} while (0) + +namespace { + +using Microsoft::WRL::ComPtr; +namespace g = leonida::gfx10; +constexpr auto uav_heap = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; +constexpr auto formatless_read = VK_FORMAT_FEATURE_2_STORAGE_READ_WITHOUT_FORMAT_BIT; +constexpr auto formatless_write = VK_FORMAT_FEATURE_2_STORAGE_WRITE_WITHOUT_FORMAT_BIT; + +// Only the layer sees the masked capabilities. The real device and validation layer see the unmodified driver. +PFN_vkGetInstanceProcAddr real_instance_proc = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties2 real_format_properties = nullptr; +VkFormatFeatureFlags2 missing_format_features = 0; + +VKAPI_ATTR void VKAPI_CALL masked_format_properties(VkPhysicalDevice physical, VkFormat format, + VkFormatProperties2* properties) { + real_format_properties(physical, format, properties); + if (format != VK_FORMAT_R32_UINT) return; + for (auto* next = static_cast(properties->pNext); next; next = next->pNext) + if (next->sType == VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3) + reinterpret_cast(next)->optimalTilingFeatures &= ~missing_format_features; +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL masked_instance_proc(VkInstance instance, const char* name) { + if (std::strcmp(name, "vkGetPhysicalDeviceFormatProperties2") == 0) + return reinterpret_cast(masked_format_properties); + return real_instance_proc(instance, name); +} + +// Numeric values are also the branches selected by cs_texture_uav.asm. +enum class Kind : UINT { one_d, array, volume, two_d, float_volume, float_array, atomic_volume }; + +D3D12_RESOURCE_DESC texture(Kind kind, UINT layers, DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = kind == one_d || kind == array || kind == float_array ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : + kind == two_d ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; + desc.Width = 8; + desc.Height = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D ? 1 : 4; + desc.DepthOrArraySize = UINT16(layers); + desc.MipLevels = 3; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return desc; +} + +D3D12_UNORDERED_ACCESS_VIEW_DESC uav(Kind kind, UINT mip, UINT first, UINT count, + DXGI_FORMAT format = DXGI_FORMAT_R32_UINT) { + using enum Kind; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.Format = format; + switch (kind) { + case one_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; view.Texture1D = {mip}; break; + case array: + case float_array: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; view.Texture1DArray = {mip, first, count}; break; + case two_d: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; view.Texture2D = {mip, 0}; break; + default: view.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; view.Texture3D = {mip, first, count}; break; + } + return view; +} + +struct Push { + g::ImageWords key; + UINT kind; +}; + +std::uint32_t push_bytes() { + return leonida::vk_test::pc_tail_requested() ? 128u : 144u; +} + +class Compute { +public: + explicit Compute(vktest::Device& vk) : vk_(vk) {} + ~Compute() { + if (pipeline_) vk_.fn("vkDestroyPipeline")(vk_.device, pipeline_, nullptr); + if (layout_) vk_.fn("vkDestroyPipelineLayout")(vk_.device, layout_, nullptr); + if (module_) vk_.fn("vkDestroyShaderModule")(vk_.device, module_, nullptr); + } + + bool create(ID3D12Device* device, const char* path) { + const auto set_layout = rt::d3d12::bindless_set_layout(device); + set_ = rt::d3d12::bindless_set(device); + EXPECT(set_layout && set_); + std::ifstream file(path, std::ios::binary | std::ios::ate); + EXPECT(file && file.tellg() > 0 && file.tellg() % 4 == 0); + std::vector code(std::size_t(file.tellg()) / 4); + file.seekg(0); + EXPECT(file.read(reinterpret_cast(code.data()), std::streamsize(code.size() * 4))); + // This fixture reads only the descriptor and case selector in s0..s8, not the heap/code-base tail. + EXPECT(!leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)); + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = code.size() * 4; + shader.pCode = code.data(); + EXPECT(vk_.fn("vkCreateShaderModule")(vk_.device, &shader, nullptr, &module_) == + VK_SUCCESS); + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes()}; + VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout.setLayoutCount = 1; + layout.pSetLayouts = &set_layout; + layout.pushConstantRangeCount = 1; + layout.pPushConstantRanges = &push; + EXPECT(vk_.fn("vkCreatePipelineLayout")(vk_.device, &layout, nullptr, &layout_) == + VK_SUCCESS); + VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline.stage.module = module_; + pipeline.stage.pName = "main"; + pipeline.layout = layout_; + EXPECT(vk_.fn("vkCreateComputePipelines")( + vk_.device, VK_NULL_HANDLE, 1, &pipeline, nullptr, &pipeline_) == VK_SUCCESS); + return true; + } + + bool run(ID3D12Resource* resource, UINT mip, VkExtent3D extent, const Push& push, + std::span input, std::span output) { + const auto desc = resource->GetDesc(); + const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; + const bool check_base_mip = push.kind == UINT(Kind::float_volume) && mip != 0; + const std::size_t base_texels = check_base_mip ? std::size_t(desc.Width) * desc.Height * desc.DepthOrArraySize : 0; + constexpr std::uint32_t base_marker = std::bit_cast(4096.0f); + const VkDeviceSize bytes = input.size_bytes() + base_texels * sizeof(base_marker); + const VkImage image = rt::d3d12::vulkan_image(resource); + EXPECT(image); + void *src = nullptr, *dst = nullptr; + const VkBuffer upload = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src); + const VkBuffer readback = vk_.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &dst); + EXPECT(upload && readback); + std::memcpy(src, input.data(), input.size_bytes()); + std::fill_n(static_cast(src) + input.size(), base_texels, base_marker); + + EXPECT(vk_.run([&](VkCommandBuffer cb) { + const auto barrier = vk_.fn("vkCmdPipelineBarrier"); + VkImageMemoryBarrier texture_barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + texture_barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcQueueFamilyIndex = texture_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + texture_barrier.image = image; + texture_barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, check_base_mip ? 0u : mip, + check_base_mip ? mip + 1 : 1, 0, volume ? 1 : extent.depth}; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, + 1, &texture_barrier); + VkBufferImageCopy copies[2]{}; + copies[0].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, volume ? 1 : extent.depth}; + copies[0].imageExtent = {extent.width, extent.height, volume ? extent.depth : 1}; + copies[1].bufferOffset = input.size_bytes(); + copies[1].imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + copies[1].imageExtent = {UINT(desc.Width), desc.Height, desc.DepthOrArraySize}; + const UINT copy_count = check_base_mip ? 2 : 1; + vk_.fn("vkCmdCopyBufferToImage")(cb, upload, image, VK_IMAGE_LAYOUT_GENERAL, + copy_count, copies); + texture_barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + texture_barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, + nullptr, 1, &texture_barrier); + vk_.fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + vk_.fn("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, + 0, 1, &set_, 0, nullptr); + std::array sgprs{}; + std::memcpy(sgprs.data(), &push, sizeof(push)); + vk_.fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + push_bytes(), sgprs.data()); + const UINT dispatch_depth = push.kind == UINT(Kind::one_d) ? 1 : extent.depth; + vk_.fn("vkCmdDispatch")(cb, extent.width, extent.height, dispatch_depth); + texture_barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; + texture_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &texture_barrier); + vk_.fn("vkCmdCopyImageToBuffer")(cb, image, VK_IMAGE_LAYOUT_GENERAL, readback, + copy_count, copies); + VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_HOST_READ_BIT}; + barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, + nullptr); + return true; + })); + std::memcpy(output.data(), dst, output.size_bytes()); + const auto* base = static_cast(dst) + output.size(); + EXPECT(std::all_of(base, base + base_texels, [&](std::uint32_t word) { return word == base_marker; })); + return true; + } + +private: + vktest::Device& vk_; + VkShaderModule module_ = VK_NULL_HANDLE; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; + VkDescriptorSet set_ = VK_NULL_HANDLE; +}; + +bool create_texture(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, ID3D12Resource** resource) { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + // The refusal test needs a valid read-only resource; only a UAV-capable resource can start in UAV state. + const auto state = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS + : D3D12_RESOURCE_STATE_COMMON; + return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, + state, nullptr, IID_PPV_ARGS(resource))); +} + +auto read_slot(D3D12_CPU_DESCRIPTOR_HANDLE h) { + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(h.ptr), sizeof(words)); + return words; +} + +bool flush_descriptors(ID3D12Device* device) { + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + // Queue destruction waits for the device-local descriptor upload before the raw Vulkan dispatch. + return rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success; +} + +bool rejects_partial_clear(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE view) { + ComPtr allocator; + ComPtr list; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + const UINT colors[4] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, view, resource, colors, 0, nullptr); + return list->Close() == E_INVALIDARG; +} + +bool check_case(ID3D12Device* device, Compute* compute, Kind kind, const D3D12_RESOURCE_DESC& shape, + D3D12_CPU_DESCRIPTOR_HANDLE source, D3D12_CPU_DESCRIPTOR_HANDLE copy, bool sliced, + UINT mip, UINT first, UINT count, bool use_default = false) { + const bool volume = kind == Kind::volume || kind == Kind::float_volume || kind == Kind::atomic_volume; + const bool floating = kind == Kind::float_volume || kind == Kind::float_array; + const VkExtent3D extent{UINT(shape.Width) >> mip, std::max(1u, shape.Height >> mip), + volume ? std::max(1u, UINT(shape.DepthOrArraySize) >> mip) : shape.DepthOrArraySize}; + const UINT writable = count == ~0u ? extent.depth - first : count; + const auto desc = uav(kind, mip, first, count, floating ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32_UINT); + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + device->CreateUnorderedAccessView(resource.Get(), nullptr, use_default ? nullptr : &desc, source); + const auto key = read_slot(source); + const bool partial = volume && (first || writable != extent.depth); + if (partial && !sliced) { + EXPECT(key == g::ImageWords{}); + return true; + } + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == mip && decoded.mip_count == 1); + EXPECT(bool(key[4] & g::volume_uav_flag) == volume); + EXPECT(key[7] == (volume ? g::volume_uav_word(first, writable) : 0)); + EXPECT(g::partial_volume_uav(key, decoded) == partial); + EXPECT(!volume || (decoded.depth == shape.DepthOrArraySize && decoded.first_layer == 0 && decoded.layer_count == 1)); + EXPECT((kind != Kind::array && kind != Kind::float_array) || + (decoded.first_layer == first && decoded.layer_count == writable)); + device->CopyDescriptorsSimple(1, copy, source, uav_heap); + EXPECT(read_slot(copy) == key); + if (partial) EXPECT(rejects_partial_clear(device, resource.Get(), copy)); + if (partial && first > 0) { + // A second view of the same volume and mip must not collide with the copied T#. + auto other = desc; + other.Texture3D.FirstWSlice = 0; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &other, source); + EXPECT(read_slot(source) != key && g::is_image(read_slot(source))); + } + if (partial && kind == Kind::float_volume && shape.Format == DXGI_FORMAT_R32_FLOAT) { + // The typed SRV of this same mip must remain unsliced and must not replace the live partial UAV. + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = shape.Format; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture3D = {mip, 1, 0.0f}; + device->CreateShaderResourceView(resource.Get(), &srv, source); + const auto srv_key = read_slot(source); + g::Image sampled{}; + EXPECT(g::decode(srv_key, sampled) && sampled.type == g::ImageType::image_3d && + sampled.address == decoded.address && sampled.first_mip == mip && sampled.mip_count == 1 && + sampled.depth == decoded.depth && sampled.first_layer == 0 && sampled.layer_count == 1); + EXPECT(!(srv_key[4] & g::volume_uav_flag) && srv_key[7] == 0 && srv_key != read_slot(copy)); + } + EXPECT(flush_descriptors(device)); + if (!compute) return true; // CTest exercises the complete descriptor setup, without translated SPIR-V. + + std::vector input(extent.width * extent.height * extent.depth); + auto bits = [&](UINT value) { return floating ? std::bit_cast(float(value)) : value; }; + for (UINT i = 0; i < input.size(); ++i) input[i] = bits(17 + i); + std::vector expected = input, output(input.size()), host(input.size()); + for (UINT z = first; z < first + writable; ++z) + for (UINT y = 0; y < extent.height; ++y) + for (UINT x = 0; x < extent.width; ++x) { + const UINT i = (z * extent.height + y) * extent.width + x; + const UINT initial = 17 + i; + const UINT add = 1000 + x + 16 * y + 256 * (z - first); + if (kind == Kind::atomic_volume) + expected[i] = add + (initial << 16) + ((initial + 5) << 8) + 7 + 99; + else + expected[i] = bits(initial + add + (kind == Kind::float_volume && x % 2 == 0 ? initial : 0)); + } + EXPECT(compute->run(resource.Get(), mip, extent, {read_slot(copy), UINT(kind)}, input, output)); + for (UINT i = 0; i < output.size(); ++i) { + if (output[i] == expected[i]) continue; + std::fprintf(stderr, "kind %u mip %u first %u count %u texel %u: got %#x, expected %#x\n", + UINT(kind), mip, first, count, i, output[i], expected[i]); + return false; + } + if (!floating && kind != Kind::atomic_volume) { + // WARP did not clip out-of-range W accesses to WSize in the native probe. Compare documented in-view + // D3D12 accesses and independently require Vulkan to preserve every non-view slice, even under overdispatch. + EXPECT(uav_oracle::run(shape, use_default ? nullptr : &desc, input, host, + volume ? writable : kind == Kind::one_d ? 1 : 0)); + EXPECT(output == host); + } + return true; +} + +bool check_refusals(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + using enum Kind; + const auto bad = [&](ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* view) { + std::memset(reinterpret_cast(slot.ptr), 0x55, sizeof(g::ImageWords)); + device->CreateUnorderedAccessView(resource, nullptr, view, slot); + return read_slot(slot) == g::ImageWords{}; + }; + ComPtr line, layers, depth, typeless, read_only; + EXPECT(create_texture(device, texture(one_d, 1), &line)); + EXPECT(create_texture(device, texture(array, 4), &layers)); + EXPECT(create_texture(device, texture(volume, 8), &depth)); + EXPECT(create_texture(device, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), &typeless)); + auto shape = texture(one_d, 1); + shape.Flags = D3D12_RESOURCE_FLAG_NONE; + EXPECT(create_texture(device, shape, &read_only)); + EXPECT(bad(read_only.Get(), nullptr) && bad(typeless.Get(), nullptr)); + const auto good = uav(one_d, 0, 0, 1); + EXPECT(bad(nullptr, &good) && bad(depth.Get(), &good)); + for (const auto view : {uav(one_d, 3, 0, 1), uav(one_d, 0, 0, 1, DXGI_FORMAT_R16_FLOAT)}) + EXPECT(bad(line.Get(), &view)); + for (const auto view : {uav(array, 0, 4, 1), uav(array, 0, 1, 0), uav(array, 0, 2, 3), uav(array, 3, 0, 1)}) + EXPECT(bad(layers.Get(), &view)); + for (const auto view : {uav(volume, 3, 0, 1), uav(volume, 2, 2, 1), uav(volume, 1, 1, 0), uav(volume, 1, 2, 3)}) + EXPECT(bad(depth.Get(), &view)); + auto rgba = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS); + ComPtr srgb; + EXPECT(create_texture(device, rgba, &srgb)); + const auto srgb_view = uav(volume, 0, 0, ~0u, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + EXPECT(bad(srgb.Get(), &srgb_view)); + ComPtr refused; + const auto typed_srgb = texture(volume, 4, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); + ComPtr typed, warp_typed; + uav_oracle::detail::Context host; + const bool created = create_texture(device, typed_srgb, &typed); + if (host.prepare_device() == uav_oracle::Status::ready) + EXPECT(created == create_texture(host.device.Get(), typed_srgb, &warp_typed)); + if (created) { + EXPECT(bad(typed.Get(), &srgb_view)); + const auto raw_view = uav(volume, 0, 0, ~0u, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(!bad(typed.Get(), &raw_view)); + } + auto invalid_shape = texture(volume, 4); + invalid_shape.MipLevels = 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + invalid_shape = texture(one_d, 1); + invalid_shape.Width = (1ull << 32) + 8; + EXPECT(!create_texture(device, invalid_shape, &refused) && !refused); + return true; +} + +bool check_formatless_features(ID3D12Device* device, D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + using enum Kind; + const auto check = [&](Kind kind, const D3D12_RESOURCE_DESC& shape, UINT first, UINT count) { + ComPtr resource; + EXPECT(create_texture(device, shape, &resource)); + const auto view = uav(kind, 1, first, count); + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + const auto valid = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(valid, decoded) && decoded.first_mip == 1 && decoded.mip_count == 1); + for (const auto missing : {formatless_read, formatless_write, formatless_read | formatless_write}) { + std::memcpy(reinterpret_cast(slot.ptr), valid.data(), sizeof(valid)); + missing_format_features = missing; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + if (read_slot(slot) != g::ImageWords{}) { + std::fprintf(stderr, "kind %u first slice %u: accepted mip 1 UAV without format features %#llx\n", + UINT(kind), first, static_cast(missing)); + return false; + } + } + return true; + }; + EXPECT(check(one_d, texture(one_d, 1), 0, 1)); + EXPECT(check(array, texture(array, 4), 1, 2)); + // The mask applies to the R32_UINT view, not its typeless resource's backing format. + const auto volume_shape = texture(volume, 8, DXGI_FORMAT_R32_TYPELESS); + EXPECT(check(volume, volume_shape, 0, ~0u)); + if (sliced) EXPECT(check(volume, volume_shape, 1, 2)); + return true; +} + +bool check_packed_formatless_exemption(ID3D12Device* device, vktest::Device& vk, + D3D12_CPU_DESCRIPTOR_HANDLE slot, bool sliced) { + VkFormatProperties features{}; + vk.instance_fn("vkGetPhysicalDeviceFormatProperties")( + vk.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &features); + if (features.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) { + std::puts("Packed R32_UINT exemption not exercised: native RGB9E5 storage"); + return true; + } + constexpr auto format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + ComPtr resource; + if (!create_texture(device, texture(Kind::volume, 8, format), &resource)) { + std::puts("Packed R32_UINT exemption not exercised: no emulated RGB9E5 3D storage"); + return true; + } + const UINT first = sliced ? 1 : 0, count = sliced ? 2 : 4; + const auto view = uav(Kind::volume, 1, first, count, format); + missing_format_features = formatless_read | formatless_write; + device->CreateUnorderedAccessView(resource.Get(), nullptr, &view, slot); + missing_format_features = 0; + const auto key = read_slot(slot); + g::Image decoded{}; + EXPECT(g::decode(key, decoded) && decoded.first_mip == 1 && (key[4] & g::volume_uav_flag)); + EXPECT(key[7] == (g::volume_uav_word(first, count) | g::packed_uav_flag)); + return true; +} + +bool check_standalone(bool sliced) { + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))); + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto slot = heap->GetCPUDescriptorHandleForHeapStart(); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(read_slot(slot)[7] == (sliced ? g::volume_uav_word(1, 2) : 0)); + return true; +} + +bool check_cpu_clear(ID3D12Device* device, vktest::Device& vk, D3D12_CPU_DESCRIPTOR_HANDLE slot) { + EXPECT(!rt::d3d12::bindless_set(device)); + ComPtr queue; + ComPtr allocator; + ComPtr list; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))); + ComPtr image; + EXPECT(create_texture(device, texture(Kind::two_d, 1), &image)); + device->CreateUnorderedAccessView(image.Get(), nullptr, nullptr, slot); + EXPECT(g::is_image(read_slot(slot))); + const UINT value[] = {42, 0, 0, 0}; + list->ClearUnorderedAccessViewUint({}, slot, image.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.Get()}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::success); + void* mapped = nullptr; + const VkBuffer output = vk.buffer(32 * sizeof(UINT), VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); + EXPECT(output); + EXPECT(vk.run([&](VkCommandBuffer cb) { + const VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, + VK_ACCESS_TRANSFER_READ_BIT}; + vk.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0, nullptr, 0, nullptr); + vk.read_back(cb, rt::d3d12::vulkan_image(image.Get()), VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT, + 8, 4, 1, output, 0); + return true; + })); + const auto* pixels = static_cast(mapped); + EXPECT(std::all_of(pixels, pixels + 32, [](UINT pixel) { return pixel == 42; })); + + // A typeless backing may reinterpret bits in a transfer clear; an unsupported clear must not be submitted. + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.Get(), nullptr))); + ComPtr volume; + EXPECT(create_texture(device, texture(Kind::volume, 4, DXGI_FORMAT_R32_TYPELESS), &volume)); + const auto view = uav(Kind::volume, 0, 0, ~0u); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, slot); + EXPECT(g::is_image(read_slot(slot))); + list->ClearUnorderedAccessViewUint({}, slot, volume.Get(), value, 0, nullptr); + EXPECT(SUCCEEDED(list->Close())); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.Get()) == leonida::ReplayResult::unsupported); + return true; +} + +bool test(vktest::Device& vk, const char* shader, bool enable_slices) { + rt::d3d12::VulkanDeviceInfo info{}; + real_instance_proc = vk.instance_proc; + real_format_properties = vk.instance_fn( + "vkGetPhysicalDeviceFormatProperties2"); + EXPECT(real_format_properties); + info.get_instance_proc = masked_instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + info.bindless = vk.bindless; + info.bindless_partially_bound = vk.partially_bound; + info.robust_image_access = vk.robust_image_access; + info.sliced_3d_uav = enable_slices && vk.sliced_3d_uav; + ComPtr device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device)))); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{uav_heap, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)))); + const auto source = heap->GetCPUDescriptorHandleForHeapStart(); + const D3D12_CPU_DESCRIPTOR_HANDLE copy{source.ptr + device->GetDescriptorHandleIncrementSize(uav_heap)}; + if (!enable_slices) { + ComPtr volume; + EXPECT(create_texture(device.Get(), texture(Kind::volume, 8), &volume)); + device->CreateUnorderedAccessView(volume.Get(), nullptr, nullptr, source); + EXPECT(g::is_image(read_slot(source))); + const auto view = uav(Kind::volume, 1, 1, 2); + device->CreateUnorderedAccessView(volume.Get(), nullptr, &view, source); + EXPECT(read_slot(source) == g::ImageWords{}); + info.bindless = false; + ComPtr cpu_only; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&cpu_only)))); + ComPtr cpu_heap; + EXPECT(SUCCEEDED(cpu_only->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&cpu_heap)))); + return check_cpu_clear(cpu_only.Get(), vk, cpu_heap->GetCPUDescriptorHandleForHeapStart()); + } + + using enum Kind; + EXPECT(check_refusals(device.Get(), source)); + EXPECT(check_formatless_features(device.Get(), source, info.sliced_3d_uav)); + EXPECT(check_packed_formatless_exemption(device.Get(), vk, source, info.sliced_3d_uav)); + Compute compute(vk); + if (shader) EXPECT(compute.create(device.Get(), shader)); + auto* dispatch = shader ? &compute : nullptr; + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 0, 0, 1, true)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(one_d, 1), source, copy, false, 2, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, one_d, texture(array, 4), source, copy, false, 1, 0, 1)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 0, 0, 4, true)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, array, texture(array, 4), source, copy, false, 1, 1, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_array, texture(float_array, 4, DXGI_FORMAT_R32_FLOAT), + source, copy, false, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 0, 0, 8, true)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8, DXGI_FORMAT_R32_TYPELESS), source, copy, + vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, volume, texture(volume, 8), source, copy, vk.sliced_3d_uav, 1, 2, ~0u)); + EXPECT(check_case(device.Get(), dispatch, float_volume, texture(float_volume, 8, DXGI_FORMAT_R32_FLOAT), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 0, 4)); + EXPECT(check_case(device.Get(), dispatch, atomic_volume, texture(atomic_volume, 8), + source, copy, vk.sliced_3d_uav, 1, 1, 2)); + EXPECT(check_case(device.Get(), dispatch, two_d, texture(two_d, 1), source, copy, false, 1, 0, 1)); + return true; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 2) { + std::fprintf(stderr, "usage: d3d12_texture_uav_test |--descriptors-only\n"); + return 2; + } + vktest::Device vk; + // Exercise Vulkan 1.3 per-format access even on a logical device without the legacy feature bits. + const auto status = vk.initialize(true, false); + if (status == vktest::DeviceStatus::unavailable && !vk.validation_errors()) { + std::printf("SKIP: no Vulkan 1.3 device with a graphics queue\n"); + return 77; + } + if (status != vktest::DeviceStatus::ready) return 1; + const char* shader = std::strcmp(argv[1], "--descriptors-only") == 0 ? nullptr : argv[1]; + VkPhysicalDeviceProperties props{}; + vk.instance_fn("vkGetPhysicalDeviceProperties")(vk.physical, &props); + if (!vk.bindless || !vk.robust_image_access || (shader && props.limits.maxPushConstantsSize < push_bytes())) { + std::printf("SKIP: requires bindless descriptors and robustImageAccess%s\n", + shader ? " and 144 bytes of push constants" : ""); + return vk.validation_errors() ? 1 : 77; + } + if (shader) { + const auto warp = uav_oracle::prepare(); + if (warp == uav_oracle::Status::unavailable) { + std::printf("SKIP: no D3D12 WARP adapter\n"); + return vk.validation_errors() ? 1 : 77; + } + if (warp != uav_oracle::Status::ready) return 1; + } + if (!test(vk, shader, false) || !test(vk, shader, true) || !check_standalone(vk.sliced_3d_uav) || + vk.validation_errors()) + return 1; + if (!shader) { + std::puts("texture UAV descriptors: creation, copy, range/refusal and clear checks passed"); + return 0; + } + if (!vk.sliced_3d_uav) std::printf("SKIP: sliced 3D UAV GPU writes (feature unavailable); rejection verified\n"); + std::printf("texture UAVs: %u GPU cases (%u compared with WARP), format/range/refusal checks passed\n", + vk.sliced_3d_uav ? 14u : 10u, vk.sliced_3d_uav ? 10u : 8u); + return 0; +} diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp index 7be1e880b..75a2c4c71 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include #include @@ -455,9 +456,137 @@ int check_title_memory(Context& c, int& checks) { return 0; } +// Bind the same interior GPU handle first through a short graphics table, then a wide compute table. +// Update its last CBV after Close and again before resubmitting the identical list. +int check_rebound_tables(Context& c, ID3D12RootSignature* narrow, bool mirror, bool api_copy) { + constexpr UINT selected = 64; + const auto alloc_backing = [](std::size_t n, std::uint64_t) -> void* { + return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + }; + const auto free_backing = [](void* p, std::uint64_t) { VirtualFree(p, 0, MEM_RELEASE); }; + Ref heap; + const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, selected + 4, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + rt::d3d12_xs::set_descriptor_heap_allocator(alloc_backing, free_backing); + const HRESULT created = c.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)); + rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); + EXPECT(created == S_OK); + const UINT step = c.device->GetDescriptorHandleIncrementSize(hd.Type); + const auto cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const auto gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const auto real = rt::d3d12_xs::translate_cpu_descriptor_handle(c.device, {SIZE_T(cpu)}); + EXPECT(real.ptr && real.ptr != cpu && gpu && step == 32); + + const D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, up{D3D12_HEAP_TYPE_UPLOAD}, + rb{D3D12_HEAP_TYPE_READBACK}; + Ref upload, source, out, readback; + const auto data_desc = buffer_desc(2 * kBytes); + const auto result_desc = buffer_desc(kBytes); + const auto uav_desc = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(c.device->CreateCommittedResource(&up, {}, &data_desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&upload.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&def, {}, &data_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&source.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&def, {}, &uav_desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + nullptr, IID_PPV_ARGS(&out.p)) == S_OK); + EXPECT(c.device->CreateCommittedResource(&rb, {}, &result_desc, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback.p)) == S_OK); + std::uint32_t* input = nullptr; + EXPECT(upload->Map(0, nullptr, reinterpret_cast(&input)) == S_OK); + for (UINT i = 0; i < 2 * kElements; ++i) input[i] = 0x10500000u + 37 * i; + upload->Unmap(0, nullptr); + Ref alloc; + Ref list; + EXPECT(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)) == S_OK); + EXPECT(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, c.pso, IID_PPV_ARGS(&list.p)) == S_OK); + const auto transition_resource = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); + }; + list->CopyBufferRegion(source.p, 0, upload.p, 0, data_desc.Width); + transition_resource(source.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + const D3D12_GPU_DESCRIPTOR_HANDLE table{gpu + step}; + list->SetGraphicsRootSignature(narrow); + list->SetGraphicsRootDescriptorTable(2, table); + list->SetComputeRootSignature(c.root); + list->SetComputeRootDescriptorTable(2, table); + list->SetGraphicsRootDescriptorTable(2, table); + const UINT args[] = {selected, 0xfffffffcu}; + list->SetComputeRoot32BitConstants(0, 2, args, 0); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); + transition_resource(out.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + transition_resource(out.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_resource(source.p, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + EXPECT(list->Close() == S_OK); + + // Build two real CBVs in a CPU-only staging heap. Only raw CPU writes reach the title-owned slots below. + Ref staging; + const D3D12_DESCRIPTOR_HEAP_DESC staging_desc{hd.Type, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + EXPECT(c.inner->CreateDescriptorHeap(&staging_desc, IID_PPV_ARGS(&staging.p)) == S_OK); + const auto staging_cpu = staging->GetCPUDescriptorHandleForHeapStart(); + unsigned matched[2]{}; + bool api_slots_correct = true; + for (UINT pass = 0; pass < 2; ++pass) { + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{source->GetGPUVirtualAddress() + kBytes * pass, kBytes}; + const D3D12_CPU_DESCRIPTOR_HANDLE src{staging_cpu.ptr + pass * step}; + c.inner->CreateConstantBufferView(&cbv, src); + const void* copy_from = reinterpret_cast(src.ptr); + if (api_copy) { + // Write to a shader-visible slot outside the bound table. The game copies from its CPU backing. + const D3D12_CPU_DESCRIPTOR_HANDLE from{static_cast(cpu + (selected + 3) * step)}; + copy_from = reinterpret_cast(from.ptr); + if (pass == 0) { + DWORD previous = 0; + EXPECT(VirtualProtect(reinterpret_cast(cpu), hd.NumDescriptors * step, PAGE_READONLY, &previous)); + c.device->CreateConstantBufferView(&cbv, from); + EXPECT(vsharp_base(from.ptr) == 0); + EXPECT(VirtualProtect(reinterpret_cast(cpu), hd.NumDescriptors * step, previous, &previous)); + c.device->CreateConstantBufferView(&cbv, from); + } else { + c.device->CopyDescriptorsSimple(1, from, src, hd.Type); + } + const void* reference = reinterpret_cast(src.ptr); + const auto* inner = reinterpret_cast(real.ptr + (selected + 3) * step); + const bool real_match = std::memcmp(inner, reference, step) == 0; + const bool title_match = std::memcmp(copy_from, reference, step) == 0; + std::printf("API slot %u: real matches staging=%d, title matches staging=%d\n", pass, real_match, title_match); + api_slots_correct &= real_match && (mirror ? title_match : vsharp_base(from.ptr) == 0); + } + for (UINT slot_index : {0u, 1 + selected, 2 + selected}) + std::memcpy(reinterpret_cast(cpu + slot_index * step), copy_from, step); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(c.queue->Signal(c.fence, ++c.fence_value) == S_OK); + EXPECT(c.fence->SetEventOnCompletion(c.fence_value, nullptr) == S_OK); + void* mapped = nullptr; + EXPECT(readback->Map(0, nullptr, &mapped) == S_OK); + const auto* got = static_cast(mapped); + for (UINT i = 0; i < kElements; ++i) + matched[pass] += got[i] == (mirror ? 0x10500000u + 37 * (kElements * pass + i) : 0u); + readback->Unmap(0, nullptr); + EXPECT(vsharp_base(real.ptr) == 0 && vsharp_base(real.ptr + (selected + 2) * step) == 0); + } + std::printf("rebound table (%s): %u/%u and %u/%u GPU words matched on consecutive submissions\n", + mirror ? "updated CBV" : "null CBV", matched[0], kElements, matched[1], kElements); + EXPECT(api_slots_correct && matched[0] == kElements && matched[1] == kElements); + return 0; +} + } // namespace -int main() { +int main(int argc, char** argv) { + const bool api_copy_off = argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy-off") == 0; + const bool mirror_off = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--rebound-tables-off") == 0); + const bool second_device = argc == 2 && std::strcmp(argv[1], "--rebound-second-device") == 0; + const bool api_copy = api_copy_off || (argc == 2 && std::strcmp(argv[1], "--api-descriptor-copy") == 0); + const bool rebind = api_copy || mirror_off || second_device || (argc == 2 && std::strcmp(argv[1], "--rebound-tables") == 0); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) { @@ -492,6 +621,9 @@ int main() { info.buffer_device_address = true; info.subgroup = d.subgroup; info.shader_dir = library.string(); + // Keep another compatibility device alive over the same physical GPU. Each owns its own arena. + Ref first; + if (second_device) EXPECT(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&first.p)) == S_OK); ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; @@ -501,7 +633,7 @@ int main() { // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute // layout cs_user_data.comp reads. - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, rebind ? 65u : 1u, 1, 0, 0}; D3D12_ROOT_PARAMETER params[3] = {}; params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; params[0].Constants = {0, 0, 2}; @@ -539,6 +671,16 @@ int main() { c.fence = fence.p; c.arena = rt::d3d12::device_arena_size(device.p); EXPECT(c.arena > 0); + if (rebind) { + range.NumDescriptors = 1; + const auto narrow_blob = serialize(root_desc); + Ref narrow; + EXPECT(!narrow_blob.empty()); + EXPECT(device->CreateRootSignature(0, narrow_blob.data(), narrow_blob.size(), IID_PPV_ARGS(&narrow.p)) == S_OK); + EXPECT(check_rebound_tables(c, narrow.p, !mirror_off, api_copy) == 0); + EXPECT(d.validation_errors() == 0); + return 0; + } if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; if (check_title_memory(c, checks)) return 1; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 87bf185fa..9bc8d7597 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -36,6 +36,9 @@ // build. On success it prints one marker line, after every check. #ifndef LEONIDA_M15_GUEST #include "vk_test_device.h" +#include "test_temp_dir.h" +#include "d3d12_native_graphics_fixture.h" +#include #endif #include "d3d12_test_shaders.h" #ifndef LEONIDA_M15_GUEST @@ -80,6 +83,7 @@ std::vector read_file(const std::filesystem::path& path) { return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; } + // One 32-byte vertex record, as vs_m15.asm reads it: position xyzw, then colour rgba. struct Vertex { float position[4]; @@ -115,7 +119,11 @@ int main(int argc, char** argv) { // The FSSM programs the index entries are keyed by; the shim's device finds the index through LEONIDA_SHADERS. const std::filesystem::path root_dir = argv[1]; #else -int main() { +int main(int argc, char** argv) { + const bool derived_zero = argc == 2 && std::strcmp(argv[1], "--derived-zero") == 0; + const bool derived_restore = argc == 2 && std::strcmp(argv[1], "--derived-restore") == 0; + const bool native = derived_zero || derived_restore || (argc == 2 && std::strcmp(argv[1], "--native-pso") == 0); + EXPECT(argc == 1 || native); vktest::Device d; const auto device_status = d.initialize(); if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips @@ -134,6 +142,13 @@ int main() { EXPECT(library.load((root_dir / "spirv").string())); EXPECT(library.find("vs", leonida::sha256_hex(vs_program)) && library.find("ps", leonida::sha256_hex(ps_program))); EXPECT(library.find("ps", leonida::sha256_hex(ps_program))->uses_code_base); + std::optional scratch; + if (native) { + scratch.emplace("leonida_native_graphics_draw"); + std::error_code ec; + std::filesystem::copy(root_dir / "spirv", scratch->path() / "spirv", std::filesystem::copy_options::recursive, ec); + EXPECT(!ec && write_native_catalog(scratch->path(), "vs", vs_program, ps_program)); + } #endif const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); // A program the index does not know (the VS's bytes with one word changed) must be refused by the PSO. @@ -168,6 +183,9 @@ int main() { } #else rt::d3d12::VulkanDeviceInfo info{}; + info.first_use_backend_pipelines=d.first_use_backend_pipelines; + info.prepare_on_bind=d.prepare_on_bind; + info.cold_graphics_compile=d.cold_graphics_compile; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; @@ -175,12 +193,12 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; - info.shader_dir = (root_dir / "spirv").string(); + info.shader_dir = ((native ? scratch->path() : root_dir) / "spirv").string(); ID3D12Device* inner = nullptr; EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p), /*console_lists=*/false))); + reinterpret_cast(&device.p)))); rt::d3d12::set_device_outer(inner, device.p); #endif @@ -215,7 +233,40 @@ int main() { pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; pso_desc.SampleDesc.Count = 1; Ref pso, unknown; - EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); +#ifndef LEONIDA_M15_GUEST + if (native) { + EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], stale_digest, &unknown.p)) && !unknown.p); + EXPECT(FAILED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], np::Digest{}, &unknown.p)) && !unknown.p); + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &pso.p)) && pso.p); + Ref duplicate; + EXPECT(SUCCEEDED(create_native_pso(device.p, root.p, pso_desc.RTVFormats[0], producer_digest, &duplicate.p))); + EXPECT(duplicate.p && duplicate.p != pso.p); + EXPECT(rt::d3d12::graphics_pipeline_id(pso.p) != 0 && + rt::d3d12::graphics_pipeline_id(duplicate.p) == rt::d3d12::graphics_pipeline_id(pso.p)); + const GUID marker{0xe79d6ba2, 0x2d8c, 0x4344, {0xa4, 0x81, 0x34, 0x19, 0x24, 0x4e, 0x2a, 0x0b}}; + const UINT value = 17; + EXPECT(SUCCEEDED(pso->SetPrivateData(marker, sizeof(value), &value))); + UINT private_size = 0; + EXPECT(duplicate->GetPrivateData(marker, &private_size, nullptr) == DXGI_ERROR_NOT_FOUND); + if (derived_zero || derived_restore) { + using Derive=HRESULT(WINAPI*)(void*,ID3D12PipelineState*,UINT,const unsigned char*,const IID*,void**); + const auto call=reinterpret_cast(slot(device.p,55)); + std::array record{}; + const UINT tag=3; std::memcpy(record.data(),&tag,4); + Ref masked; + EXPECT(SUCCEEDED(call(device.p,pso.p,1,record.data(),&__uuidof(ID3D12PipelineState),reinterpret_cast(&masked.p))) && masked.p); + if (derived_restore) { + const UINT mask=~0u; std::memcpy(record.data()+4,&mask,4); + Ref restored; + EXPECT(SUCCEEDED(call(device.p,masked.p,1,record.data(),&__uuidof(ID3D12PipelineState),reinterpret_cast(&restored.p))) && restored.p); + std::swap(restored.p,pso.p); + } else std::swap(masked.p,pso.p); + } else std::swap(duplicate.p,pso.p); // The draw uses the second view after releasing the first one. + } else +#endif + { + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + } pso_desc.VS = {unknown_container.data(), unknown_container.size()}; EXPECT(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); @@ -387,6 +438,14 @@ int main() { const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; const Pixel top_left = {0.125f, 1.0f, 0.75f, 1.0f}, bottom_right = {0.25f, 1.125f, 0.875f, 1.0f}; const Pixel bottom_left = {0.75f, 0.25f, 0.75f, 1.0f}; +#ifndef LEONIDA_M15_GUEST + if (derived_zero) { + const Pixel background{0.5f,0.125f,0.25f,0.5f}; + for (const auto& pixel:pixels) EXPECT(std::memcmp(&pixel,&background,sizeof(Pixel))==0); + std::printf("derived mask zero: all %zu pixels equal the clear value\n",pixels.size()); + return 0; + } +#endif unsigned mismatches = 0, edge = 0, edge_triangle = 0, edge_clear = 0; for (UINT row = 0; row < target_extent; ++row) { for (UINT col = 0; col < target_extent; ++col) { diff --git a/runtime/test/d3d12_xmem_placed_test.cpp b/runtime/test/d3d12_xmem_placed_test.cpp index 368b32510..19fd57ce1 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -6,6 +6,7 @@ // GPU VA is the window itself and a GPU copy reads what the CPU writes there afterwards. // Needs VK_EXT_external_memory_host (skipped otherwise). No shaders or game data. #include "vk_test_device.h" +#include "d3d12_test_shaders.h" #include "../shims/d3d12_com.h" #include "../shims/d3d12_xs_device.h" #include "../shims/shims.h" @@ -86,7 +87,7 @@ int gpu_reads_cpu_writes(ID3D12Device* real, ID3D12Resource* buffer, const void* return 0; } -int run(ID3D12Device* real, void* device) { +int run(ID3D12Device* real, void* device, bool eager) { const auto virtual_alloc = reinterpret_cast(rt::shims::find("xmem.dll", "XMemVirtualAlloc")); const auto allocate = reinterpret_cast(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")); @@ -103,7 +104,7 @@ int run(ID3D12Device* real, void* device) { std::uint64_t count = kPages; EXPECT(allocate(0x280, &count, pages) == TRUE && count == kPages); EXPECT(map(window, kPages, pages) == window); - EXPECT(state_is(window, MEM_RESERVE)); // mapped, never touched: nothing committed yet + EXPECT(state_is(window, eager ? MEM_COMMIT : MEM_RESERVE)); // verify the selected physical-page mapper D3D12_RESOURCE_DESC desc{}; desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; @@ -118,10 +119,16 @@ int run(ID3D12Device* real, void* device) { { Ref fallback; EXPECT(place(device, window, desc, &fallback.p) == S_OK && fallback.p); - EXPECT(fallback->GetGPUVirtualAddress() != window_va); - EXPECT(state_is(window, MEM_RESERVE)); + if (eager) { + EXPECT(fallback->GetGPUVirtualAddress() == window_va && state_is(window, MEM_COMMIT)); + for (UINT64 i = 0; i < size; ++i) window[i] = static_cast(i * 17u + 29u); + if (gpu_reads_cpu_writes(real, fallback.p, window, size)) return 1; + } else { + EXPECT(fallback->GetGPUVirtualAddress() != window_va); + EXPECT(state_is(window, MEM_RESERVE)); + } } - std::printf("%s: untouched physical pages without the hook: still reserved, fallback buffer\n", who); + std::printf("%s: physical pages without the hook: %s\n", who, eager ? "already committed and GPU-visible" : "still reserved"); // With it the range is committed first and imported. rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); @@ -142,9 +149,96 @@ int run(ID3D12Device* real, void* device) { return 0; } +int linear_texture_mapping(ID3D12Device* dev, ID3D12Device* xbox, bool private_backing) { + const auto reserve = reinterpret_cast(rt::shims::find("xmem.dll","XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(rt::shims::find("xmem.dll","XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(rt::shims::find("xmem.dll","XMemMapPhysicalPages")); + const auto release = reinterpret_cast(rt::shims::find("xmem.dll","XMemFreePhysicalPages")); + EXPECT(reserve && alloc && map && release); + std::uint64_t count=1,page{}; + void* window = private_backing ? VirtualAlloc(nullptr,kPage64k,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE) + : reserve(nullptr,kPage64k,MEM_RESERVE|kXmem64kPages,0x23,PAGE_READWRITE); + EXPECT(window); + if (!private_backing) EXPECT(alloc(0x280,&count,&page) && map(window,1,&page)==window); + rt::d3d12::set_device_outer(dev,xbox); + rt::d3d12_xs::set_texture_page_provider(&rt::xmem::pin_mapped_data); + constexpr UINT w=9,h=8; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width=w;desc.Height=h;desc.MipLevels=desc.DepthOrArraySize=1;desc.SampleDesc.Count=1; + desc.Format=DXGI_FORMAT_R32G32B32A32_FLOAT;desc.Flags=D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + desc.Layout=static_cast(0x100); + Ref tex,rb; + EXPECT(place(xbox,window,desc,&tex.p)==S_OK && tex->GetGPUVirtualAddress()==reinterpret_cast(window)); + constexpr UINT pitch=256; + D3D12_RANGE empty{0,0};void* cpu=nullptr; + EXPECT(tex->Map(0,&empty,&cpu)==S_OK && cpu && ((cpu!=window)==private_backing)); + std::array pixel{}; + for(UINT y=0;y(cpu)+y*pitch+x*16,pixel.data(),16); + } + D3D12_HEAP_PROPERTIES read_heap{D3D12_HEAP_TYPE_READBACK}; + const auto buf=d3d12test::buffer_desc(h*pitch); + EXPECT(SUCCEEDED(dev->CreateCommittedResource(&read_heap,D3D12_HEAP_FLAG_NONE,&buf,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&rb.p)))); + D3D12_COMMAND_QUEUE_DESC q{}; + Ref queue;Ref commands;Ref list;Ref fence; + EXPECT(SUCCEEDED(dev->CreateCommandQueue(&q,IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&commands.p)))); + EXPECT(SUCCEEDED(dev->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,commands.p,nullptr,IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(dev->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + const auto submit=[&](UINT64 value) { + if(FAILED(list->Close())) return false; + ID3D12CommandList* batch[]{list.p};queue->ExecuteCommandLists(1,batch); + if(FAILED(queue->Signal(fence.p,value))) return false; + const auto end=GetTickCount64()+6000; + while(fence->GetCompletedValue()GetCompletedValue()==value; + }; + auto barrier=d3d12test::transition(tex.p,D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1,&barrier); + D3D12_TEXTURE_COPY_LOCATION from{},to{};from.pResource=tex.p;to.pResource=rb.p; + to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint={0,{desc.Format,w,h,1,pitch}}; + list->CopyTextureRegion(&to,0,0,0,&from,nullptr); + EXPECT(submit(1)); + void* bytes=nullptr;EXPECT(SUCCEEDED(rb->Map(0,nullptr,&bytes))); + for(UINT y=0;y(bytes)+y*pitch, + static_cast(cpu)+y*pitch,w*16)==0); + rb->Unmap(0,nullptr); + tex->Unmap(0,&empty); + Ref rt; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,1}; + EXPECT(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&rt.p)))); + const auto handle=rt->GetCPUDescriptorHandleForHeapStart(); + dev->CreateRenderTargetView(tex.p,nullptr,handle); + EXPECT(SUCCEEDED(commands->Reset()) && SUCCEEDED(list->Reset(commands.p,nullptr))); + barrier=d3d12test::transition(tex.p,D3D12_RESOURCE_STATE_COPY_SOURCE,D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1,&barrier); + const float rgba[]{.25f,.5f,.75f,1.0f}; + list->ClearRenderTargetView(handle,rgba,0,nullptr); + EXPECT(submit(2)); + D3D12_RANGE read{0,h*pitch};cpu=nullptr; + EXPECT(tex->Map(0,&read,&cpu)==S_OK && cpu && ((cpu!=window)==private_backing)); + for(UINT y=0;y(cpu)+y*pitch+x*16,rgba,16)==0); + tex->Unmap(0,&empty); + if (!private_backing) { + EXPECT(map(window,1,nullptr)==window && release(1,&page)); + cpu=reinterpret_cast(1); + EXPECT(FAILED(tex->Map(0,&empty,&cpu)) && !cpu); + } else { + const auto* original=static_cast(window); + for(UINT i=0;iRelease(); return 1; } - failures += run(real.p, device.p); + if (argc==2 && (std::strcmp(argv[1],"--linear-map")==0 || std::strcmp(argv[1],"--linear-staging")==0)) + failures+=linear_texture_mapping(real.p,device.p,std::strcmp(argv[1],"--linear-staging")==0); + else failures += run(real.p, device.p, eager); } if (vk.validation_errors()) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index f02d6cd02..08b34d8c9 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -432,6 +432,22 @@ int main(int argc, char** argv) { check(rt::d3d12_xs::device_slot_hits(76) == 2, "slot 76 hit counter is 2"); check(rt::d3d12_xs::device_slot_first_call_seen(76), "slot 76 first-call flag is set"); + // A backend can run out of memory after allocating the native depth image. Slot 76 must propagate that + // failure without handing a depth-only resource to a caller that requested a working UAV. + { + auto ds_uav = xbox_texture; + ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + check(rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), [](ID3D12Resource*, D3D12_HEAP_FLAGS) -> HRESULT { + return E_OUTOFMEMORY; + }), "install a failing Xbox storage-image provider"); + void* result = reinterpret_cast(1); + hr = create_resource(device.Get(), &heap_properties, D3D12_HEAP_FLAG_NONE, &ds_uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, iid_resource, &result); + check(hr == E_OUTOFMEMORY && !result, "slot 76 propagates storage-image allocation failure atomically"); + rt::d3d12_xs::set_depth_stencil_uav_provider(device.Get(), nullptr); + } + // Xbox device slots from the public HLE. On the Vulkan device the PC entries at 78/79 are // CreateReservedResource2/CreateSampler2 and 80 is past the 80-slot table, so success here can only come from // the routes: frame events return S_OK and a fresh token, CreateCommandQueueX returns a queue proxy and diff --git a/runtime/test/file_system_test.cpp b/runtime/test/file_system_test.cpp index 7a5ea6f08..27194f1a4 100644 --- a/runtime/test/file_system_test.cpp +++ b/runtime/test/file_system_test.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -183,6 +184,63 @@ bool host_renames_case(const std::filesystem::path& folder) { void run_checks(const std::filesystem::path& root); +// Title memory committed on first touch, as xmem maps physical pages: a view of a reserve-only pagefile section whose +// pages a vectored handler commits when user-mode code faults on them. The kernel's write in ReadFile raises no such +// fault, so the host ReadFile fails with ERROR_NOACCESS; the shim commits the pages and reads again. +char* g_first_touch = nullptr; +SIZE_T g_first_touch_size = 0; + +LONG CALLBACK commit_on_touch(EXCEPTION_POINTERS* info) { + const EXCEPTION_RECORD* r = info->ExceptionRecord; + if (r->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || r->NumberParameters < 2) return EXCEPTION_CONTINUE_SEARCH; + auto* at = reinterpret_cast(r->ExceptionInformation[1]); + if (at < g_first_touch || at >= g_first_touch + g_first_touch_size) return EXCEPTION_CONTINUE_SEARCH; + auto* page = reinterpret_cast(reinterpret_cast(at) & ~uintptr_t{0xfff}); + return VirtualAlloc(page, 0x1000, MEM_COMMIT, PAGE_READWRITE) ? EXCEPTION_CONTINUE_EXECUTION + : EXCEPTION_CONTINUE_SEARCH; +} + +void check_read_file_first_touch(const std::filesystem::path& root) { + using ReadFileFn = BOOL(WINAPI*)(HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED); + const auto shim_read = reinterpret_cast(rt::shims::find("kernel32.dll", "ReadFile")); + check(shim_read != nullptr, "ReadFile is served by the file shims"); + if (!shim_read) return; + + std::filesystem::create_directories(root); + const std::filesystem::path file = root / "first_touch.bin"; + constexpr DWORD kSize = 3 * 0x10000 + 123; // crosses several pages and ends inside one + std::vector data(kSize); + for (DWORD i = 0; i < kSize; ++i) data[i] = static_cast(i * 7 + 3); + std::ofstream(file, std::ios::binary).write(reinterpret_cast(data.data()), kSize); + + g_first_touch_size = 4 * 0x10000; + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, + static_cast(g_first_touch_size), nullptr); + g_first_touch = section ? static_cast(MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 0)) : nullptr; + check(g_first_touch != nullptr, "a reserve-only section view stands in for first-touch title memory"); + if (!g_first_touch) return; + void* const handler = AddVectoredExceptionHandler(1, &commit_on_touch); + + auto read_into_view = [&](ReadFileFn read) { + HANDLE h = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + DWORD got = 0; + const BOOL ok = read(h, g_first_touch + 0x800, kSize, &got, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + CloseHandle(h); + return std::make_pair(ok ? got : 0, error); + }; + const auto host = read_into_view(&::ReadFile); + check(host.second == ERROR_NOACCESS, "the host ReadFile into uncommitted pages fails with ERROR_NOACCESS"); + const auto shimmed = read_into_view(shim_read); + check(shimmed.second == 0 && shimmed.first == kSize, "the shimmed ReadFile commits the pages and reads it all"); + check(std::memcmp(g_first_touch + 0x800, data.data(), kSize) == 0, "the bytes read are the file's"); + + RemoveVectoredExceptionHandler(handler); + UnmapViewOfFile(g_first_touch); + CloseHandle(section); + g_first_touch = nullptr; +} + } // namespace int main() { @@ -198,6 +256,7 @@ int main() { // An exception from one check (std::filesystem throws on a host error) ends the checks, not the run: it is a // failure, the folder is still removed and the summary is still printed. try { + check_read_file_first_touch(root / "first_touch"); run_checks(root); } catch (const std::exception& e) { check(false, (std::string("the checks run to the end (stopped by: ") + e.what() + ")").c_str()); diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index e86c6f560..7e7fb49a2 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp @@ -155,6 +155,29 @@ int main() { EXPECT(next.get().token == 2); } + // wait_flag_current_token never blocks or times out: a fresh token for the newest passed origin, registered or not. + { + ManualFrameClock clock; + FramePacer pacer(clock); + std::uint64_t token = 0; + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 1); + EXPECT(setup(pacer, 1)); + clock.advance_us(period * 2 + period / 4); + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 2); + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, wait_flag_current_token, &token) == pacer_hr::ok && + token == 3); + std::uint32_t count = 1; + FrameStatistic stat; + EXPECT(pacer.get_frame_statistics(3, stat_frame_event, &count, &stat) == pacer_hr::ok); + EXPECT(stat.time_us == period * 2); + auto next = wait_async(pacer, infinite_timeout_ms); + EXPECT(blocked(next)); + clock.advance_us(period * 3 / 4); + EXPECT(next.get().token == 4); + } + // Timeouts: 0 polls, a finite one counts fake time, the token is left alone, and a later wait still works. { ManualFrameClock clock; diff --git a/runtime/test/glsl/cs_depth_stencil_uav.comp b/runtime/test/glsl/cs_depth_stencil_uav.comp new file mode 100644 index 000000000..277a86df4 --- /dev/null +++ b/runtime/test/glsl/cs_depth_stencil_uav.comp @@ -0,0 +1,55 @@ +#version 460 +#extension GL_EXT_nonuniform_qualifier : require + +// The two T#s are passed as root constants in s4..s19, exactly as written by CreateUnorderedAccessView. +layout(local_size_x = 1) in; +layout(push_constant) uniform UserData { uint s[20]; } pc; +layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { uint words[]; }; +#if defined(DEPTH16_ARRAY) +layout(set = 0, binding = 12, r16ui) uniform uimage2DArray depths[]; +#elif defined(DEPTH16_2D) +layout(set = 0, binding = 9, r16ui) uniform uimage2D depths[]; +#elif defined(DEPTH_STENCIL_ARRAY) +layout(set = 0, binding = 11, r32f) uniform image2DArray depths[]; +layout(set = 0, binding = 12, r8ui) uniform uimage2DArray stencils[]; +#else +layout(set = 0, binding = 8, r32f) uniform image2D depths[]; +layout(set = 0, binding = 9, r8ui) uniform uimage2D stencils[]; +#endif + +uint lookup(uint first) { + uint hash = 2166136261u; + for (uint i = 0; i < 8; ++i) hash = (hash ^ pc.s[first + i]) * 16777619u; + for (uint probe = 0; probe < 8; ++probe) { + uint slot = 1 + ((hash + probe) & words[0]) * 10; + bool equal = true; + for (uint i = 0; i < 8; ++i) equal = equal && words[slot + i] == pc.s[first + i]; + if (equal) return words[slot + 8]; + } + return 0; +} + +void main() { + // Read before writing. A stale copy (or writing back the wrong plane) changes the expected bytes. + uint depth = lookup(4); +#if defined(DEPTH16_2D) || defined(DEPTH16_ARRAY) +#if defined(DEPTH16_2D) + ivec2 pixel = ivec2(2, 1); +#else + ivec3 pixel = ivec3(2, 1, 1); +#endif + uint before = imageLoad(depths[depth], pixel).r; + imageStore(depths[depth], pixel, uvec4(before ^ 0x1357u)); +#else + uint stencil = lookup(12); +#if defined(DEPTH_STENCIL_ARRAY) + ivec3 depth_pixel = ivec3(2, 1, 0), stencil_pixel = ivec3(5, 3, 1); +#else + ivec2 depth_pixel = ivec2(2, 1), stencil_pixel = ivec2(5, 3); +#endif + float before = imageLoad(depths[depth], depth_pixel).r; + uint mask = imageLoad(stencils[stencil], stencil_pixel).r; + imageStore(depths[depth], depth_pixel, vec4(before * 0.25)); + imageStore(stencils[stencil], stencil_pixel, uvec4(mask ^ 0xffu)); +#endif +} diff --git a/runtime/test/glsl/cs_r9g9b9e5_uav.comp b/runtime/test/glsl/cs_r9g9b9e5_uav.comp index c9879064a..41c986a41 100644 --- a/runtime/test/glsl/cs_r9g9b9e5_uav.comp +++ b/runtime/test/glsl/cs_r9g9b9e5_uav.comp @@ -10,10 +10,10 @@ layout(local_size_x = 16) in; layout(push_constant) uniform Params { uint tsharp[8]; uint ssharp[4]; - uint mode; // 0: write via binding 9 (first half) + binding 4 (second half); 1: sample via binding 0 + uint mode; // 0/1: 2D store/sample; 2/3: 3D store/sample uint width; uint height; - uint pad; + uint slice; // sample's absolute Z, or whether to probe relative Z=1 past a one-slice UAV } pc; layout(set = 0, binding = 0) uniform texture2D sampled_images[]; @@ -23,6 +23,9 @@ layout(set = 0, binding = 2, std430) readonly buffer DescriptorMap { }; layout(set = 0, binding = 4, r32ui) uniform writeonly uimage2D storage_r32ui_images[]; layout(set = 0, binding = 9, r32ui) uniform writeonly uimage2D storage_uint_images[]; +layout(set = 0, binding = 6) uniform texture3D sampled_volumes[]; +layout(set = 0, binding = 7, r32ui) uniform writeonly uimage3D storage_r32ui_volumes[]; +layout(set = 0, binding = 15, r32ui) uniform writeonly uimage3D storage_uint_volumes[]; layout(set = 1, binding = 0, std430) readonly buffer InputWords { uint packed_words[]; @@ -59,11 +62,23 @@ void main() { } else { imageStore(storage_r32ui_images[image], xy, uvec4(packed_words[i], 0u, 0u, 0u)); } + } else if (pc.mode == 2u) { + const uvec4 word = uvec4(packed_words[i], 0u, 0u, 0u); + if (i < total / 2u) { + imageStore(storage_uint_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_uint_volumes[image], ivec3(xy, 1), word); + } else { + imageStore(storage_r32ui_volumes[image], ivec3(xy, 0), word); + if (pc.slice != 0u) imageStore(storage_r32ui_volumes[image], ivec3(xy, 1), word); + } } else { uint sampler_key[8]; for (int k = 0; k < 8; ++k) sampler_key[k] = k < 4 ? pc.ssharp[k] : 0xffffffffu; const uint smp = lookup(sampler_key); const vec2 uv = (vec2(xy) + 0.5) / vec2(float(pc.width), float(pc.height)); - out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + if (pc.mode == 1u) + out_values[i] = textureLod(sampler2D(sampled_images[image], samplers[smp]), uv, 0.0); + else + out_values[i] = texelFetch(sampler3D(sampled_volumes[image], samplers[smp]), ivec3(xy, int(pc.slice)), 0); } } diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index 07b4b7e4d..3c08a9597 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -52,12 +52,18 @@ void main() { target.w[i] = result.w[64u + i] + pc.s[4]; return; } - if (pc.s[5] == 0u) { - // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. - const uint num_records = table.w[2]; - const uint byte_off = pc.s[4] + i * 4u; - if (byte_off + 4u <= num_records) { - Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu)); + if (pc.s[5] == 0u || pc.s[5] == 0xFFFFFFFCu) { + // CBV V# mode: accept byte-address views and Xbox views counted in 16-byte constant rows. + // The rebound-table test indexes 32-byte CBV slots with s4. + const bool indexed = pc.s[5] == 0xFFFFFFFCu; + const uint word = indexed ? pc.s[4] * 8u : 0u; + const uint num_records = table.w[word + 2u]; + const uint stride = (table.w[word + 1u] >> 16u) & 0x3fffu; + const uint mode = (table.w[word + 3u] >> 28u) & 3u; + const uint bytes_per_record = mode < 2u ? max(stride, 1u) : 1u; + const uint byte_off = (indexed ? 0u : pc.s[4]) + i * 4u; + if (byte_off <= 0xfffffffcu && (byte_off + 3u) / bytes_per_record < num_records) { + Words cbv = at(uvec2(table.w[word], table.w[word + 1u] & 0xFFFFu)); result.w[i] = cbv.w[byte_off >> 2u]; } else { result.w[i] = 0u; diff --git a/runtime/test/pso_stream_test.cpp b/runtime/test/pso_stream_test.cpp new file mode 100644 index 000000000..07ac13a32 --- /dev/null +++ b/runtime/test/pso_stream_test.cpp @@ -0,0 +1,268 @@ +// Pipeline state stream copies and the derived-state patch (device slot 55) with synthetic streams only: no D3D12 +// device, no game data. The layout rule is the one measured on the console's slot 86 stream (see the offsets check). +#include + +#include +#include +#include + +#include "d3d12_xs_pso_stream.h" + +namespace { + +int g_failures = 0; + +void check(bool ok, const char* what) { + std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_failures; +} + +std::size_t align_up(std::size_t v, std::size_t a) { return (v + a - 1) / a * a; } + +// Builds a stream the way the console lays it out: u32 type, payload at its natural alignment, next entry 8-aligned. +struct StreamBuilder { + std::vector bytes; + void entry(unsigned type, const void* payload, std::size_t size, std::size_t payload_align) { + const std::size_t at = bytes.size(); + bytes.resize(at + 4); + std::memcpy(bytes.data() + at, &type, 4); + const std::size_t pay = align_up(at + 4, payload_align); + bytes.resize(pay, 0); + const auto* p = static_cast(payload); + bytes.insert(bytes.end(), p, p + size); + bytes.resize(align_up(bytes.size(), 8), 0); + } +}; + +// The test's own copy of the layout rule: payload offset of the first subobject of `wanted`, or npos. +std::size_t payload_of_type(const std::vector& s, unsigned wanted) { + std::size_t off = 0; + while (off + 4 <= s.size()) { + unsigned type; + std::memcpy(&type, s.data() + off, 4); + std::size_t size = sizeof(D3D12_SHADER_BYTECODE), align = 8; + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { size = sizeof(D3D12_BLEND_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK) { size = 4; align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER) { size = sizeof(D3D12_RASTERIZER_DESC); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1) { size = sizeof(D3D12_DEPTH_STENCIL_DESC1); align = 4; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) { size = 8; align = 8; } + else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT) { size = sizeof(D3D12_INPUT_LAYOUT_DESC); align = 8; } + const std::size_t pay = align_up(off + 4, align); + if (type == wanted) return pay; + off = align_up(pay + size, 8); + } + return static_cast(-1); +} + +const unsigned char kVsCode[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32}; +const char kSemantic[] = "POSITION"; + +D3D12_INPUT_ELEMENT_DESC make_element(const char* name) { + D3D12_INPUT_ELEMENT_DESC e{}; + e.SemanticName = name; + e.Format = DXGI_FORMAT_R32G32B32_FLOAT; + return e; +} + +// Root signature (null), VS, BLEND, SAMPLE_MASK, RASTERIZER, DEPTH_STENCIL1, INPUT_LAYOUT. +std::vector base_stream(const D3D12_INPUT_ELEMENT_DESC* elements, unsigned element_count) { + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE vs{kVsCode, sizeof(kVsCode)}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs, sizeof(vs), 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + UINT mask = 0xffffffffu; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_SOLID; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &raster, sizeof(raster), 4); + D3D12_DEPTH_STENCIL_DESC1 ds1{}; + ds1.DepthEnable = TRUE; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, &ds1, sizeof(ds1), 4); + D3D12_INPUT_LAYOUT_DESC layout{elements, element_count}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &layout, sizeof(layout), 8); + return s.bytes; +} + +// One derived record: tag at +0, payload at +4. +std::vector record(unsigned tag, const void* payload, std::size_t size) { + std::vector r(rt::d3d12_xs::kDerivedRecordSize, 0); + std::memcpy(r.data(), &tag, 4); + if (size) std::memcpy(r.data() + 4, payload, size); + return r; +} + +void test_layout_matches_console_offsets() { + // Console slot 86 stream: types 0..5 then BLEND at +0x88 (payload +0x8c), SAMPLE_MASK at +0x1d8, RASTERIZER at + // +0x1e0, DEPTH_STENCIL1 at +0x210 (measured in the notes, mesure sur l'exe). + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_SHADER_BYTECODE sb{}; + for (unsigned i = 0; i < 5; ++i) s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS + i, &sb, sizeof(sb), 8); + check(s.bytes.size() == 0x88, "six entries (types 0..5) end at +0x88"); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + check(payload_of_type(s.bytes, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) == 0x8c, + "BLEND payload at +0x8c"); + check(s.bytes.size() == 0x1d8, "BLEND entry ends at +0x1d8"); + UINT mask = 1; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &mask, 4, 4); + check(s.bytes.size() == 0x1e0, "SAMPLE_MASK entry is 8 bytes, next entry at +0x1e0"); +} + +void test_capture_and_deep_copy() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + D3D12_PIPELINE_STATE_STREAM_DESC desc{base.size(), base.data()}; + auto rec = rt::d3d12_xs::PsoStreamRecord::capture(desc); + check(rec != nullptr, "a synthetic base stream is captured"); + if (!rec) return; + check(rec->bytes().size() == base.size(), "the copy has the stream's size"); + + // Scribble over the source and its pointed-to data: the copy must still hold the original content. + std::memset(base.data(), 0xee, base.size()); + elements[0].SemanticName = "XXXXXXXX"; + D3D12_SHADER_BYTECODE vs_copy{}; + std::memcpy(&vs_copy, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS), + sizeof(vs_copy)); + check(vs_copy.pShaderBytecode != kVsCode && vs_copy.BytecodeLength == sizeof(kVsCode) && + std::memcmp(vs_copy.pShaderBytecode, kVsCode, sizeof(kVsCode)) == 0, + "shader bytecode is copied, not referenced"); + D3D12_INPUT_LAYOUT_DESC il{}; + std::memcpy(&il, rec->bytes().data() + payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT), + sizeof(il)); + check(il.NumElements == 1 && std::strcmp(il.pInputElementDescs[0].SemanticName, kSemantic) == 0, + "input layout semantic names are copied"); +} + +void test_derive_single_and_all_tags() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for derive tests"); return; } + + D3D12_BLEND_DESC blend{}; + blend.RenderTarget[0].RenderTargetWriteMask = 0x5; + auto r2 = record(2, &blend, sizeof(blend)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r2.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 2 (blend) derives"); + const std::size_t bp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND); + check(std::memcmp(out.data() + bp, &blend, sizeof(blend)) == 0, "tag 2 payload lands in the BLEND subobject"); + check(out.size() == rec->bytes().size(), "derived stream keeps the base size"); + + D3D12_RASTERIZER_DESC raster{}; + raster.FillMode = D3D12_FILL_MODE_WIREFRAME; + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.DepthEnable = FALSE; + UINT mask = 0x3; + std::vector three; + auto r0 = record(0, &ds, sizeof(ds)); + auto r1 = record(1, &raster, sizeof(raster)); + auto r3 = record(3, &mask, 4); + three.insert(three.end(), r0.begin(), r0.end()); + three.insert(three.end(), r1.begin(), r1.end()); + three.insert(three.end(), r3.begin(), r3.end()); + check(rt::d3d12_xs::derive_stream(*rec, three.data(), 3, out) == rt::d3d12_xs::DeriveStatus::ok, + "three records (tags 0, 1, 3) derive"); + const std::size_t rp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER); + const std::size_t mp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK); + const std::size_t dp = payload_of_type(out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + check(std::memcmp(out.data() + rp, &raster, sizeof(raster)) == 0, "tag 1 payload lands in RASTERIZER"); + check(std::memcmp(out.data() + mp, &mask, 4) == 0, "tag 3 payload lands in SAMPLE_MASK"); + check(std::memcmp(out.data() + dp, &ds, sizeof(ds)) == 0, "tag 0 patches the DS1 prefix"); + const std::size_t tail = dp + sizeof(ds); + check(out[tail] == 0 && out[tail + 1] == 0 && out[tail + 2] == 0 && out[tail + 3] == 0, + "tag 0 keeps the DS1 depth-bounds field of the base"); +} + +void test_stencil_mask_record() { + // Tag 5 carries the two stencil mask bytes at the DEPTH_STENCIL offsets 0x10/0x11 and zeros elsewhere (read from the + // title's writes). It overlays only those two bytes of the base's DEPTH_STENCIL (or DEPTH_STENCIL1) payload. + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for the tag 5 tests"); return; } + const std::size_t dp = payload_of_type(rec->bytes(), D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1); + + unsigned char mask_payload[0x16] = {}; + mask_payload[0x10] = 0x0f; // read mask + mask_payload[0x11] = 0x3c; // write mask + auto r5 = record(5, mask_payload, sizeof(mask_payload)); + std::vector out; + check(rt::d3d12_xs::derive_stream(*rec, r5.data(), 1, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 alone derives on a base with DEPTH_STENCIL1"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 overlays the two stencil mask bytes"); + bool rest_same = true; + for (std::size_t i = 0; i < 0x38; ++i) + if (i != 0x10 && i != 0x11 && out[dp + i] != rec->bytes()[dp + i]) rest_same = false; + check(rest_same, "tag 5 leaves the other DEPTH_STENCIL1 bytes unchanged"); + + // Order: records apply in the order they are given. Tag 0 writes its own masks, tag 5 overrides them. + D3D12_DEPTH_STENCIL_DESC ds{}; + ds.StencilReadMask = 0x01; + ds.StencilWriteMask = 0x02; + auto r0 = record(0, &ds, sizeof(ds)); + std::vector seq; + seq.insert(seq.end(), r0.begin(), r0.end()); + seq.insert(seq.end(), r5.begin(), r5.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 0 then tag 5 derive together"); + check(out[dp + 0x10] == 0x0f && out[dp + 0x11] == 0x3c, "tag 5 after tag 0 wins (record order)"); + + seq.clear(); + seq.insert(seq.end(), r5.begin(), r5.end()); + seq.insert(seq.end(), r0.begin(), r0.end()); + check(rt::d3d12_xs::derive_stream(*rec, seq.data(), 2, out) == rt::d3d12_xs::DeriveStatus::ok, + "tag 5 then tag 0 derive together"); + check(out[dp + 0x10] == 0x01 && out[dp + 0x11] == 0x02, "tag 0 after tag 5 wins (record order)"); +} + +void test_refusals() { + D3D12_INPUT_ELEMENT_DESC elements[1] = {make_element(kSemantic)}; + std::vector base = base_stream(elements, 1); + auto rec = rt::d3d12_xs::PsoStreamRecord::capture({base.size(), base.data()}); + if (!rec) { check(false, "base captured for refusal tests"); return; } + std::vector out; + + auto r6 = record(6, nullptr, 0); + check(rt::d3d12_xs::derive_stream(*rec, r6.data(), 1, out) == rt::d3d12_xs::DeriveStatus::unknown_tag, + "tag 6 is refused (meaning not known)"); + + // A base without a rasterizer subobject cannot take a tag-1 record. + StreamBuilder s; + ID3D12RootSignature* root = nullptr; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &root, 8, 8); + D3D12_BLEND_DESC blend{}; + s.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend, sizeof(blend), 4); + auto norast = rt::d3d12_xs::PsoStreamRecord::capture({s.bytes.size(), s.bytes.data()}); + if (!norast) { check(false, "stream without rasterizer captured"); return; } + D3D12_RASTERIZER_DESC raster{}; + auto r1 = record(1, &raster, sizeof(raster)); + check(rt::d3d12_xs::derive_stream(*norast, r1.data(), 1, out) == rt::d3d12_xs::DeriveStatus::missing_state, + "tag 1 on a base without RASTERIZER is refused"); + + // A subobject type this module does not walk: VIEW_INSTANCING (payload with a pointer, not modelled). + StreamBuilder v; + unsigned char junk[32] = {}; + v.entry(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, junk, sizeof(junk), 8); + check(rt::d3d12_xs::PsoStreamRecord::capture({v.bytes.size(), v.bytes.data()}) == nullptr, + "a stream with an unmodelled subobject type is not captured"); +} + +} // namespace + +int main() { + std::printf("pso_stream_test: derived pipeline state streams\n"); + test_layout_matches_console_offsets(); + test_capture_and_deep_copy(); + test_derive_single_and_all_tags(); + test_stencil_mask_record(); + test_refusals(); + std::printf("%s: %d failure(s)\n", g_failures ? "FAILED" : "OK", g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 66c594779..527c8adec 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -61,9 +61,11 @@ using namespace leonida; // measured emit, so that the record itself does not allocate there. std::vector g_barriers; std::uint32_t g_calls = 0; +std::uint32_t g_memory = 0; void VKAPI_CALL record_barrier2(VkCommandBuffer, const VkDependencyInfo* info) { ++g_calls; + g_memory += info->memoryBarrierCount; for (std::uint32_t i = 0; i < info->imageMemoryBarrierCount; ++i) g_barriers.push_back(info->pImageMemoryBarriers[i]); } @@ -76,6 +78,178 @@ void expect(bool ok, const char* what) { } } +// Run a stencil-only round trip with coupled depth/stencil layouts. Vulkan transitions both aspects +// together on this device, but the data transfer must never read or write the sibling depth plane. +void depth_uav_barriers(VkCommandBuffer cb) { + namespace y = d3d12_sync; + namespace a = d3d12_access; + namespace l = d3d12_layout; + std::array resources{}; + auto& parent = resources[1]; + parent.aspects = depth_stencil_aspects; + parent.format = VK_FORMAT_D32_SFLOAT_S8_UINT; + parent.depth_uav = 2; + parent.stencil_uav = 3; + resources[2].format = VK_FORMAT_R32_SFLOAT; + resources[3].format = VK_FORMAT_R8_UINT; + LayoutTracker tracker; + for (ResourceId i = 1; i <= 3; ++i) { + auto& r = resources[i]; + r.image = reinterpret_cast(std::uintptr_t(i)); + r.width = 5; + r.height = 7; + tracker.track(i, r, VK_IMAGE_LAYOUT_GENERAL); + } + const auto resolve = [&](ResourceId id) -> const ResourceBinding* { + return id && id < resources.size() ? &resources[id] : nullptr; + }; + struct Access { VkImage image; VkImageAspectFlags aspect; bool read; std::uint32_t layer, layers; }; + static std::vector accesses; + accesses.clear(); + ReplayFunctions vk{}; + vk.pipeline_barrier2 = record_barrier2; + vk.pipeline_barrier = [](VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, + std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, + std::uint32_t, const VkImageMemoryBarrier*) {}; + vk.copy_image_to_buffer = [](VkCommandBuffer, VkImage image, VkImageLayout, VkBuffer, std::uint32_t, + const VkBufferImageCopy* region) { + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, true, sub.baseArrayLayer, sub.layerCount}); + }; + vk.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage image, VkImageLayout, std::uint32_t, + const VkBufferImageCopy* region) { + const auto& sub = region->imageSubresource; + accesses.push_back({image, sub.aspectMask, false, sub.baseArrayLayer, sub.layerCount}); + }; + const BarrierSubresourceRange stencil{1, 0, 0, 0, 0, 0}; + const BarrierSubresourceRange all_planes{all_subresources, 0, 0, 0, 0, 0}; + g_barriers.clear(); + g_memory = 0; + CommandList list; + expect(list.barrier(TextureBarrier{y::depth_stencil, y::all, a::depth_stencil_write, a::common, + l::undefined, l::undefined, 1, all_planes, 0}) && + list.barrier(TextureBarrier{y::depth_stencil, y::compute_shading, a::depth_stencil_write, a::unordered_access, + l::depth_stencil_write, l::unordered_access, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::shader_resource, + l::unordered_access, l::generic_read, 1, stencil, 0}) && + list.barrier(TextureBarrier{y::all, y::copy, a::shader_resource, a::copy_source, + l::generic_read, l::common, 1, stencil, 0}) && list.close(), + "record DSV to stencil UAV then copy source"); + std::uint32_t allocations = 0; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& out, VkDeviceSize& offset) { + expect(size == parent.width * parent.height, "stencil scratch holds one byte per texel"); + ++allocations; + out = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + PreparedList prepared; + vk.graphics_family = false; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject depth/stencil transfers on a non-graphics family before scratch allocation"); + vk.graphics_family = true; + // A global memory barrier in a queue-specific COMMON layout can switch accesses from a shader write + // on the child to a copy or sample on the parent without a texture layout transition. + for (const auto layout : {l::direct_queue_common, l::compute_queue_common}) { + CommandList implicit; + expect(implicit.barrier(TextureBarrier{y::copy, y::compute_shading, a::copy_dest, a::unordered_access, + l::copy_dest, layout, 1, all_planes, 0}) && + implicit.barrier(GlobalBarrier{y::compute_shading, y::copy, a::unordered_access, a::copy_source}) && + implicit.close(), "record queue-specific COMMON and a global dependency"); + expect(prepare(implicit, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "reject ambiguous queue-specific COMMON at prepare"); + } + for (bool before : {false, true}) { + CommandList invalid; + expect(invalid.barrier(TextureBarrier{y::all, y::all, + before ? a::unordered_access : a::copy_source, before ? a::copy_source : a::unordered_access, + before ? l::common : l::copy_source, before ? l::copy_source : l::common, + 1, all_planes, 0}) && invalid.close(), "record explicit UAV access in generic COMMON"); + expect(prepare(invalid, resolve, vk, prepared) == ReplayResult::unsupported && !allocations, + "generic COMMON disallows explicit UAV access on either side of a barrier"); + } + if (prepare(list, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare stencil transfers"); + return; + } + emit(prepared, cb, vk, &tracker); + expect(g_memory == 1 && !g_barriers.empty() && g_barriers.front().oldLayout == VK_IMAGE_LAYOUT_GENERAL && + std::none_of(g_barriers.begin(), g_barriers.end(), [](const auto& b) { return b.newLayout == VK_IMAGE_LAYOUT_UNDEFINED; }), + "UNDEFINED to UNDEFINED only orders memory and preserves both data and tracked layouts"); + expect(allocations == 1 && accesses.size() == 4, "reuse one staging range across both stencil transitions"); + if (accesses.size() == 4) { + expect(accesses[0].read && accesses[0].image == parent.image && accesses[0].aspect == VK_IMAGE_ASPECT_STENCIL_BIT && + !accesses[1].read && accesses[1].image == resources[3].image && accesses[1].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + accesses[2].read && accesses[2].image == resources[3].image && accesses[2].aspect == VK_IMAGE_ASPECT_COLOR_BIT && + !accesses[3].read && accesses[3].image == parent.image && accesses[3].aspect == VK_IMAGE_ASPECT_STENCIL_BIT, + "stencil only moves through the R8 storage image in both directions"); + } + expect(tracker.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(1, 1) == VK_IMAGE_LAYOUT_GENERAL && + tracker.layout(3, 0) == VK_IMAGE_LAYOUT_GENERAL, "coupled parent and independently tracked storage layouts"); + vk.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + expect(prepare(list, resolve, vk, prepared) == ReplayResult::unsupported, "scratch failure refuses the list"); + + // Select layers 1 and 2 (out of 4). The depth-only array has no stencil child. Check the staging size, + // image copy ranges, and the independent initial layouts of the two selected storage layers. + parent.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; + parent.format = VK_FORMAT_D16_UNORM; + parent.stencil_uav = 0; + resources[2].format = VK_FORMAT_R16_UINT; + LayoutTracker arrays; + for (ResourceId id : {1u, 2u}) { + resources[id].array_layers = 4; + arrays.track(id, resources[id], VK_IMAGE_LAYOUT_GENERAL); + } + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); + arrays.set(2, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 2, 1}, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); + const BarrierSubresourceRange two_layers{0, 1, 1, 2, 0, 1}; + CommandList compute; + expect(compute.barrier(TextureBarrier{y::all, y::compute_shading, a::common, a::unordered_access, + l::common, l::unordered_access, 1, two_layers, 0}) && + compute.barrier(TextureBarrier{y::compute_shading, y::all, a::unordered_access, a::common, + l::unordered_access, l::common, 1, two_layers, 0}) && compute.close(), + "record D16 array compute handoff"); + vk.graphics_family = false; + vk.queue_stages = detail::queue_stages_compute; + vk.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + expect(size == 2 * 2 * parent.width * parent.height, "D16 scratch holds two bytes per texel and two layers"); + buffer = reinterpret_cast(std::uintptr_t(0x10)); + offset = 0; + return true; + }; + vk.compute_copy_aspects = [](VkFormat) -> VkImageAspectFlags { return VK_IMAGE_ASPECT_STENCIL_BIT; }; + expect(prepare(compute, resolve, vk, prepared) == ReplayResult::unsupported, + "stencil-only compute copy capability does not authorize a depth transfer"); + vk.compute_copy_aspects = [](VkFormat fmt) -> VkImageAspectFlags { + return fmt == VK_FORMAT_D16_UNORM ? VK_IMAGE_ASPECT_DEPTH_BIT : 0; + }; + if (prepare(compute, resolve, vk, prepared) != ReplayResult::success) { + expect(false, "prepare supported D16 compute transfers"); + return; + } + accesses.clear(); + emit(prepared, cb, vk, &arrays); + expect(accesses.size() == 4 && std::all_of(accesses.begin(), accesses.end(), [](const Access& access) { + return access.layer == 1 && access.layers == 2; + }), "both images are read and written only at the requested layers"); + expect(arrays.layout(2, 0) == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && + arrays.layout(2, 1) == VK_IMAGE_LAYOUT_GENERAL && arrays.layout(2, 2) == VK_IMAGE_LAYOUT_GENERAL, + "selected storage layers end in their descriptor layout and the untouched layer keeps its layout"); + // vkCmdClearDepthStencilImage requires graphics even with maintenance10. A committed depth array first + // seen on compute is initialized from the zero page through a buffer-to-image transfer. + vk.zero_buffer = reinterpret_cast(std::uintptr_t(0x11)); + vk.zero_size = 1024; + const VkImageSubresourceRange fresh{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 1, 2}; + arrays.set(1, fresh, VK_IMAGE_LAYOUT_UNDEFINED); + auto pieces = detail::current(&arrays, 1, fresh, VK_IMAGE_LAYOUT_GENERAL); + accesses.clear(); + detail::initialize(vk, cb, parent, 1, pieces, VK_IMAGE_LAYOUT_GENERAL, &arrays); + expect(accesses.size() == 1 && !accesses[0].read && accesses[0].image == parent.image && + accesses[0].aspect == VK_IMAGE_ASPECT_DEPTH_BIT && accesses[0].layer == 1 && accesses[0].layers == 2, + "first use on compute copies zeros into the selected native depth layers"); +} + } // namespace int main() { @@ -170,6 +344,7 @@ int main() { } } + depth_uav_barriers(cb); if (failures) return 1; std::printf("replay_texture_barrier_test: OK\n"); return 0; diff --git a/runtime/test/replay_uav_clear_offset_test.cpp b/runtime/test/replay_uav_clear_offset_test.cpp index 35818fe8e..4f70fc671 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp @@ -210,6 +210,44 @@ int main() { tex.array_layers = 4; tex.color_attachment = true; + // A dedicated compute family has no rendering commands. A rectangular clear fills transfer scratch and + // copies the clipped rectangle to the requested array slices without disturbing adjacent pixels. + { + auto image = tex; + image.format = VK_FORMAT_R8_UINT; + auto compute = tex_vk; + compute.graphics_family = false; + compute.queue_stages = detail::queue_stages_compute; + compute.begin_rendering = nullptr; + compute.image_view = {}; + VkDeviceSize requested_bytes = 0; + compute.copy_scratch = [&](VkDeviceSize size, VkBuffer& buffer, VkDeviceSize& offset) { + requested_bytes = size; + buffer = scratch; + offset = 256; + return true; + }; + static std::vector copies; + compute.copy_buffer_to_image = [](VkCommandBuffer, VkBuffer, VkImage, VkImageLayout layout, + std::uint32_t count, const VkBufferImageCopy* regions) { + expect(layout == VK_IMAGE_LAYOUT_GENERAL && count == 1, "one compute clear transfer in UAV layout"); + copies.push_back(regions[0]); + }; + const std::array rects{{{-1, 2, 3, 4}, {1, 3, 2, 4}}}; + writes.clear(); + expect(run_tex(image, {2, false, VK_FORMAT_R8_UINT, 0, 0, 0, 0, 1, 2}, false, {0x39,0,0,0}, + rects, &compute) == ReplayResult::success, "rectangle UAV clear on compute-only family"); + expect(requested_bytes == 12 && writes.size() == 1 && writes[0].kind == 'f' && writes[0].offset == 256 && + writes[0].size == 12 && copies.size() == 2 && attachment_clears == 0, "one fill and two rectangle copies"); + if (copies.size() == 2) { + const auto& r = copies[0]; + expect(r.bufferOffset == 256 && r.imageOffset.x == 0 && r.imageOffset.y == 2 && + r.imageExtent.width == 3 && r.imageExtent.height == 2 && + r.imageSubresource.baseArrayLayer == 1 && r.imageSubresource.layerCount == 2 && + copies[1].imageOffset.x == 1 && copies[1].imageOffset.y == 3, "clipped pixels and exactly two layers"); + } + } + const auto fbits = [](float f) { return std::bit_cast(f); }; // R16G16_TYPELESS (SFLOAT) cleared as R16G16_UNORM Float(1.0, 1.0): uses R16G16_UNORM view and float32 {1, 1}. expect(run_tex(tex, {2, false, VK_FORMAT_R16G16_UNORM, 0, 0, 0, 0, 1, 2}, true, {fbits(1.0f), fbits(1.0f), 0, 0}) == diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index a677a9de9..f03c15c42 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -1803,6 +1803,29 @@ def clip_test(tools, spirv, name): return "" +def texture_uav_test(tools, spv): + """The Windows D3D12 test compares every texel itself, through both Vulkan and WARP.""" + if os.name != "nt": + return Skip("SKIP (needs the Windows D3D12 runtime)") + exe = os.path.join(tools, "d3d12_texture_uav_test" + EXE) + if not os.path.isfile(exe): + return f"missing {exe}" + code, out = run(exe, spv) + if code == UNSUPPORTED: + reason = next((line for line in out.splitlines() if line.startswith("SKIP:")), "unsupported device") + return Skip(reason) + return "" if code == 0 else failure(code, out, 8) + + +IMAGE_STORE_CASES = { + "cs_imgstore": (), + "cs_imgload": ("load",), + "cs_imgload_d16": ("load-d16",), + "cs_sample_lz_int_d16": ("load-d16",), + "cs_imgload_mip": ("load-mip",), +} + + def main(): if any(arg in ("-h", "--help") for arg in sys.argv[1:]): print(__doc__) @@ -1853,9 +1876,7 @@ def main(): results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) - for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), - ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), - ("cs_sample_lz_int_d16", ["load-d16"])): + for name, args in IMAGE_STORE_CASES.items(): code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) if code == UNSUPPORTED: # vk_store_test: the device lacks a feature this test needs m = re.search(r"unsupported: .*", out) @@ -1863,6 +1884,9 @@ def main(): continue bad = re.findall(r"(\d+) bad", out) results.append((name, "" if code == 0 and len(bad) == 3 and set(bad) == {"0"} else failure(code, out, 3))) + texture_uav_spv = os.path.join(spirv, "cs_texture_uav.spv") + if os.path.isfile(texture_uav_spv): + results.append(("cs_texture_uav", texture_uav_test(tools, texture_uav_spv))) for name in STORE_WORDS: # TEST-184: image atomics and image_get_resinfo results.append((name, store_words_test(tools, spirv, name))) for name in GET_LOD_TESTS: # TEST-184: image_get_lod, 2D and 2D array diff --git a/runtime/test/shaders/cs_cbv_vector_rows.asm b/runtime/test/shaders/cs_cbv_vector_rows.asm new file mode 100644 index 000000000..6dd26a845 --- /dev/null +++ b/runtime/test/shaders/cs_cbv_vector_rows.asm @@ -0,0 +1,42 @@ +; group: 1,1,1 +; Read four 16-byte register rows through the actual Xbox constant-buffer descriptor staged at byte 64. +s_mov_b32 s4, 64 +s_mov_b32 s5, 0 +s_load_dwordx4 s[8:11], s[4:5], 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v20, 0 +v_mov_b32 v0, 0 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:0 +v_mov_b32 v0, 1 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:4 +v_mov_b32 v0, 2 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:8 +v_mov_b32 v0, 3 +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:12 +s_buffer_load_dwordx2 s[12:13], s[8:11], 0x30 +s_waitcnt lgkmcnt(0) +v_mov_b32 v4, s12 +v_mov_b32 v5, s13 +buffer_store_dword v4, v20, s[0:3], 0 offen offset:16 +buffer_store_dword v5, v20, s[0:3], 0 offen offset:20 +v_mov_b32 v0, 16 +buffer_load_dword v4, v0, s[8:11], 0 idxen +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:24 +v_mov_b32 v0, 15 +buffer_load_dword v4, v0, s[8:11], 0 idxen offset:12 +s_waitcnt vmcnt(0) +buffer_store_dword v4, v20, s[0:3], 0 offen offset:28 +s_buffer_load_dword s14, s[8:11], 0x100 +s_waitcnt lgkmcnt(0) +v_mov_b32 v4, s14 +buffer_store_dword v4, v20, s[0:3], 0 offen offset:32 +s_endpgm diff --git a/runtime/test/shaders/cs_imgatomic3d.asm b/runtime/test/shaders/cs_imgatomic3d.asm index 29f4477a4..cd6b6a113 100644 --- a/runtime/test/shaders/cs_imgatomic3d.asm +++ b/runtime/test/shaders/cs_imgatomic3d.asm @@ -18,10 +18,10 @@ s_mov_b32 s16, 0x5000 s_mov_b32 s17, 0x1400000 s_mov_b32 s18, 0x55 s_mov_b32 s19, 0x55 -s_mov_b32 s20, 0x55 +s_mov_b32 s20, 0x80000055 s_mov_b32 s21, 0x55 s_mov_b32 s22, 0x55 -s_mov_b32 s23, 0x55 +s_mov_b32 s23, 0xd7801800 s_mov_b32 s24, 0x3000 s_mov_b32 s25, 0x1500000 s_mov_b32 s26, 0x33 diff --git a/runtime/test/shaders/cs_imgload_mip.asm b/runtime/test/shaders/cs_imgload_mip.asm new file mode 100644 index 000000000..c9d4d3306 --- /dev/null +++ b/runtime/test/shaders/cs_imgload_mip.asm @@ -0,0 +1,44 @@ +; vk_store_test load-mip: x/y are a texel in the 8x8 mip 1. The 16x16 mip 0 has decoy data and receives +; the results. Fetch each mip-1 format twice: full-width and D16 (RG for UNORM, RA for R32 UINT/SINT). +; Store the float RG bits, and check both packed halves (including integer saturation) in the integer outputs. +v_and_b32_e32 v1, 7, v0 +v_lshrrev_b32_e32 v2, 3, v0 +v_mov_b32_e32 v3, 1 +s_mov_b32 s8, 0x1000 +s_mov_b32 s9, 0x3800000 +s_mov_b32 s10, 0x11 +s_mov_b32 s11, 0x11 +s_mov_b32 s12, 0x11 +s_mov_b32 s13, 0x11 +s_mov_b32 s14, 0x11 +s_mov_b32 s15, 0x11 +image_load_mip v[4:5], v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v6, v[1:3], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s16, 0x2000 +s_mov_b32 s17, 0x1400000 +s_mov_b32 s18, 0x22 +s_mov_b32 s19, 0x22 +s_mov_b32 s20, 0x22 +s_mov_b32 s21, 0x22 +s_mov_b32 s22, 0x22 +s_mov_b32 s23, 0x22 +image_load_mip v7, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v8, v[1:3], s[16:23] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_mov_b32 s24, 0x3000 +s_mov_b32 s25, 0x1500000 +s_mov_b32 s26, 0x33 +s_mov_b32 s27, 0x33 +s_mov_b32 s28, 0x33 +s_mov_b32 s29, 0x33 +s_mov_b32 s30, 0x33 +s_mov_b32 s31, 0x33 +image_load_mip v9, v[1:3], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_load_mip v10, v[1:3], s[24:31] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16 +s_waitcnt vmcnt(0) +v_add_nc_u32_e32 v7, v7, v8 +v_add_nc_u32_e32 v7, v7, v6 +v_add_nc_u32_e32 v9, v9, v10 +image_store v[4:5], v[1:2], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm +image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +image_store v9, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm diff --git a/runtime/test/shaders/cs_texture_uav.asm b/runtime/test/shaders/cs_texture_uav.asm new file mode 100644 index 000000000..b5180a881 --- /dev/null +++ b/runtime/test/shaders/cs_texture_uav.asm @@ -0,0 +1,105 @@ +; group: 1,1,1 +; rsrc2: 0x392 +; s[0:7] = UAV T#, s8 = case (0: 1D, 1: 1D array, 2: 3D UINT, 3: 2D, 4: 3D FLOAT, 5: 1D array FLOAT, 6: 3D atomics). +; s[9:11] = workgroup XYZ. Add 1000 + x + 16*y + 256*z to each existing texel (z is the array +; layer for 1D arrays). d3d12_texture_uav_test pushes production heap descriptors and compares +; every texel against the CPU expectation and, for non-atomic UINT, against Windows WARP. +; The float volume adds the texel twice at even x (LOD 0), once at odd x (LOD 1 reads zero). +; The atomic volume stores the coordinate increment + (initial << 16) + ((initial + 5) << 8) + 7 + 99. +v_mov_b32_e32 v0, s9 +v_mov_b32_e32 v1, s10 +v_mov_b32_e32 v2, s11 +v_lshlrev_b32_e32 v3, 8, v2 +v_lshl_add_u32 v3, v1, 4, v3 +v_add_nc_u32_e32 v3, v0, v3 +v_add_nc_u32_e32 v3, 1000, v3 +s_cmp_eq_u32 s8, 0 +s_cbranch_scc0 11 +image_load v4, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +; The sampled and formatless coherent reads must agree; a mismatch changes the result. +image_load v5, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v0, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm +s_endpgm +s_cmp_eq_u32 s8, 1 +s_cbranch_scc0 7 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 2 +s_cbranch_scc0 11 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +; A sliced UAV must see the same texel via the rebased sampled alias and the sliced storage view. +image_load v5, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc dlc +s_waitcnt vmcnt(0) +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v3, v3, v5 +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +s_cmp_eq_u32 s8, 3 +s_cbranch_scc0 6 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +v_add_nc_u32_e32 v3, v3, v4 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm +s_endpgm +s_cmp_eq_u32 s8, 5 +s_cbranch_scc0 13 +v_mov_b32_e32 v1, v2 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Float array view covers two layers. Verify that the next-layer read does not contribute. +v_add_nc_u32_e32 v1, 2, v1 +image_load v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v1, v2 +image_store v3, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_1D_ARRAY unorm +s_endpgm +s_cmp_eq_u32 s8, 6 +s_cbranch_scc0 31 +; Use a separate T# SGPR group so the non-atomic UINT volume case exercises the sampled alias. +s_mov_b64 s[12:13], s[0:1] +s_mov_b64 s[14:15], s[2:3] +s_mov_b64 s[16:17], s[4:5] +s_mov_b64 s[18:19], s[6:7] +; Inactive add and CAS must neither write nor change their glc destinations. The active add returns +; the initial texel, the active CAS returns that texel + 5, and the following load reads 99. +v_mov_b32_e32 v4, 7 +v_mov_b32_e32 v5, 0 +s_mov_b32 exec_lo, 0 +image_atomic_add v4, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +image_atomic_cmpswap v[4:5], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +s_mov_b32 exec_lo, 1 +v_mov_b32_e32 v6, 5 +image_atomic_add v6, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc +v_mov_b32_e32 v8, 99 +v_add_nc_u32_e32 v9, 5, v6 +image_atomic_cmpswap v[8:9], v[0:2], s[12:19] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc +image_load v7, v[0:2], s[12:19] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_lshl_add_u32 v3, v6, 16, v3 +v_lshl_add_u32 v3, v8, 8, v3 +v_add_nc_u32_e32 v3, v4, v3 +v_add_nc_u32_e32 v3, v7, v3 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_cvt_f32_u32_e32 v3, v3 +v_add_f32_e32 v3, v3, v4 +; Relative LOD 0 reuses the physical mip selected by the view; LOD 1 is outside the single-mip view. +v_mov_b32_e32 v6, v3 +v_and_b32_e32 v3, 1, v0 +image_load_mip v5, v[0:3], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v6, v5 +; Float test uses WSize=2: an outside-Z fetch must be zero even if still inside the image. +v_add_nc_u32_e32 v2, 2, v2 +image_load v4, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +v_add_f32_e32 v3, v3, v4 +v_mov_b32_e32 v2, s11 +image_store v3, v[0:2], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm +s_endpgm diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm index b8f888c13..253cd2c9e 100644 --- a/runtime/test/shaders/ps_imgatomic.asm +++ b/runtime/test/shaders/ps_imgatomic.asm @@ -1,8 +1,8 @@ ; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders: ; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0 ; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s: -; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords: -; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), +; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the tagged R32_UINT 3D UAV. +; Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), ; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8 ; images: ; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31), diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index d6276d8ad..194df74a9 100644 --- a/runtime/test/vk_bindless_test.cpp +++ b/runtime/test/vk_bindless_test.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -315,6 +316,7 @@ int main(int argc, char** argv) { LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage); + LD(vkGetDescriptorSetLayoutSupport); VkQueue queue = VK_NULL_HANDLE; vkGetDeviceQueue(dev, qi, 0, &queue); VkPhysicalDeviceMemoryProperties mp; @@ -536,47 +538,60 @@ int main(int argc, char** argv) { } CHECK(submit()); - // An adapter at the original 5632 sampled-image limit must keep the original set. The per-stage - // resource budget can also leave room for just one class (9985 original resources + 512). + constexpr auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { + std::uint32_t count = 0; + for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) + if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) + count += f.counts[b]; + return count; + }; + + // An adapter at the single-sample limit must keep the original set. The stage resource budget + // can also leave room for just one MS class. Include the non-MS bindings after the MS pairs. + constexpr BindlessFeatures defaults{}; + constexpr auto base_sampled = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, defaults); + constexpr auto base_resources = base_sampled + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, defaults) + + descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, defaults); + constexpr auto ms_pair = + defaults.counts[bindless::first_ms_binding] + defaults.counts[bindless::first_ms_binding + 1]; constexpr auto ms_classes = [](std::uint32_t sampled, std::uint32_t total) { BindlessFeatures f{}; f.ms_samples.fill(VK_SAMPLE_COUNT_4_BIT); bindless::limit_ms_bindings(f, sampled, total); return f.ms_samples; }; - static_assert(ms_classes(5632, 20000) == + static_assert(ms_classes(base_sampled, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - static_assert(ms_classes(7168, 10497) == + static_assert(ms_classes(base_sampled + 3 * ms_pair, base_resources + ms_pair) == std::array{VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - // Does a set with these flags fit the device? Every binding is visible to every stage. - const auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { - std::uint32_t count = 0; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) - if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) - count += f.counts[b]; - return count; - }; + // Check the sized layout against the device's limits. Standalone samplers count in the pool, + // but not towards the per-stage resource budget. const auto fits = [&](const BindlessFeatures& f) { const auto sampled_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, f); const auto sampler_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLER, f); const auto storage_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, f); - const auto stage_resources = sampled_total + storage_total + 2; // table buffer and fragment output + const auto buffer_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, f); + const auto stage_resources = sampled_total + storage_total + buffer_total + 1; // fragment output + const auto pool_descriptors = sampled_total + sampler_total + storage_total + buffer_total; const VkPhysicalDeviceLimits& l = props.properties.limits; if (f.update_after_bind) return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && + props12.maxPerStageDescriptorUpdateAfterBindStorageBuffers >= buffer_total && props12.maxPerStageUpdateAfterBindResources >= stage_resources && - props12.maxUpdateAfterBindDescriptorsInAllPools >= sampled_total + sampler_total + storage_total + 1 && + props12.maxUpdateAfterBindDescriptorsInAllPools >= pool_descriptors && props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; + props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total && + props12.maxDescriptorSetUpdateAfterBindStorageBuffers >= buffer_total; return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && l.maxPerStageDescriptorStorageImages >= storage_total && + l.maxPerStageDescriptorStorageBuffers >= buffer_total && l.maxPerStageResources >= stage_resources && l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; + l.maxDescriptorSetStorageImages >= storage_total && l.maxDescriptorSetStorageBuffers >= buffer_total; }; unsigned mismatches = 0, runs = 0, readbacks = 0; @@ -602,11 +617,19 @@ int main(int argc, char** argv) { BindlessFeatures configurations[2] = {device_flags, {}}; const int configuration_count = (device_flags.update_after_bind || device_flags.partially_bound) ? 2 : 1; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const BindlessFeatures& candidate) { + const bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; for (int configuration = 0; configuration < configuration_count; ++configuration) { BindlessFeatures flags = configurations[configuration]; flags.ms_samples[0] = VK_SAMPLE_COUNT_4_BIT; // A device below the default counts gets a smaller set; this test needs at least those. - const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12); + const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12, layout_supported); const char* name = flags.update_after_bind && flags.partially_bound ? "update after bind, partially bound" : flags.update_after_bind ? "update after bind" : flags.partially_bound ? "partially bound" : "no flags"; if (!full || !fits(flags)) { @@ -615,6 +638,8 @@ int main(int argc, char** argv) { } BindlessSet set(vkGetDeviceProcAddr, dev, mp, flags); EXPECT(set.ok() && set.layout() && set.set()); + EXPECT(set.image_capacity(ImageDimension::dim_1d_array) == set.storage_capacity(ImageDimension::dim_1d_array)); + EXPECT(set.add_image(ImageDimension::dim_1d_array, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes}; const VkDescriptorSetLayout set_layout = set.layout(); @@ -746,7 +771,8 @@ int main(int argc, char** argv) { const std::array keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8}, {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8}, {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8}, - {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}}; + {0xd1, 20u << 20, 0xd3, 0xd4, 0x800000d5, 0xd6, 0xd7, + 0xd7801800}}}; for (std::uint32_t k = 0; k < 4; ++k) std::memcpy(static_cast(heap_map) + atomic_va + 32 * k, keys[k].data(), 32); const VkImageUsageFlags atomic_usage = diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index ec9a39519..3a57b1f77 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -1,7 +1,7 @@ // Driver-level check of the translated corpus: vk_pipeline_check [pipeline_cache.bin] // Reads /index.json (written by tools/rdna2spirv.py) and checks module and pipeline creation for compatible // entries with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash -// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants +// table 2; storage images 4, 7 and 8..19 and 26..28; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants // sized from push_constant_bytes, default 144 or 128 with pc_tail): // - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for // descriptor-free shaders with the standard push-constant range @@ -53,6 +53,7 @@ #include "pipeline_summary.h" #include "../src/spirv_words.h" #include "../src/subgroup_size.h" +#include "../src/vulkan_bindless.h" #include #include @@ -69,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -1099,10 +1101,13 @@ int main(int argc, char** argv) { } VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; + VkPhysicalDeviceVulkan11Properties indexing_limits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; + // Vulkan12Properties already includes the float controls (do not chain both promoted structs). + VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; + indexing_limits.pNext = &indexed; + sgProps.pNext = &indexing_limits; props2.pNext = &sgProps; - sgProps.pNext = &fcProps; vkGetPhysicalDeviceProperties2(pd, &props2); std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); @@ -1240,6 +1245,7 @@ int main(int argc, char** argv) { } #define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout); + LOADD(vkGetDescriptorSetLayoutSupport); LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines); LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData); LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR); @@ -1293,15 +1299,16 @@ int main(int argc, char** argv) { // DenormPreserve 16) need a device property, not a feature. for (const auto& fc : meta.float_controls) { if (fc == "shaderSignedZeroInfNanPreserveFloat32") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; + if (!indexed.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; } else if (fc == "shaderSignedZeroInfNanPreserveFloat64") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; + if (!indexed.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; } else if (fc == "shaderDenormPreserveFloat16") { - if (!fcProps.shaderDenormPreserveFloat16) return "no " + fc; + if (!indexed.shaderDenormPreserveFloat16) return "no " + fc; } else { return "unknown float control " + fc; } } + // Per-format read/write support for formatless storage is checked when the runtime binds the actual view. for (const auto& feat : meta.features) { if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader"; @@ -1316,28 +1323,38 @@ int main(int argc, char** argv) { if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod"; - if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) - return "no shaderStorageImageWriteWithoutFormat"; - if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) - return "no shaderStorageImageReadWithoutFormat"; + if (props.apiVersion < VK_API_VERSION_1_3) { + if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) + return "no shaderStorageImageWriteWithoutFormat"; + if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) + return "no shaderStorageImageReadWithoutFormat"; + } } return {}; }; - // Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays. - std::vector b; - auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) { - b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr}); - }; - add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024); - add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024); - add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); - add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data(); + // Use the runtime's set-0 layout and sizing rules. The translator does not declare the runtime-only MS SRVs. + leonida::BindlessFeatures bindless{}; + std::function layout_supported; + if (vkGetDescriptorSetLayoutSupport) + layout_supported = [&](const leonida::BindlessFeatures& candidate) { + const leonida::bindless::SetLayout layout(candidate); + VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; + vkGetDescriptorSetLayoutSupport(dev, &layout.info, &support); + return support.supported == VK_TRUE; + }; + if (!leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported) && + f12.descriptorBindingSampledImageUpdateAfterBind && f12.descriptorBindingStorageImageUpdateAfterBind && + f12.descriptorBindingStorageBufferUpdateAfterBind) { + bindless.update_after_bind = true; + leonida::bindless::size_bindings(bindless, props2.properties.limits, indexing_limits, indexed, layout_supported); + } + const leonida::bindless::SetLayout layout(bindless); VkDescriptorSetLayout dsl; - if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; } + if (VkResult r = vkCreateDescriptorSetLayout(dev, &layout.info, nullptr, &dsl)) { + std::fprintf(stderr, "layout %d\n", r); + return 1; + } // Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base. const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL, nullptr}; diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 5567511d0..59963e884 100644 --- a/runtime/test/vk_store_test.cpp +++ b/runtime/test/vk_store_test.cpp @@ -1,6 +1,6 @@ // Headless Vulkan test for translated typed image stores and loads (runtime/test/shaders/cs_imgstore.asm and -// cs_imgload.asm). -// Usage: vk_store_test cs.spv [load|load-d16|words|signed-zero] +// cs_imgload*.asm). +// Usage: vk_store_test cs.spv [load|load-d16|load-mip|words|signed-zero] // The shader builds three T#s (word1 FORMAT = 56 rgba8 unorm, 20 r32 uint, 21 r32 sint) and stores to three 8x8 // images. The translator picks the float / uint / sint view (set 0, bindings 8 / 9 / 10 for 2D) from the FORMAT // field, and the bindless index from the descriptor hash table (binding 2). As in the runtime, each image has its @@ -9,6 +9,10 @@ // "load" (cs_imgload.asm): the uint and sint images are filled before the dispatch, and the shader loads both // texels with image_load and stores their sum into the sint image. The device is made without // shaderStorageImageReadWithoutFormat, and a module that declares StorageImageReadWithoutFormat fails (SHADER-151). +// "load-d16": check integer narrowing for packed image_load (cs_imgload_d16.asm) or image_sample_lz +// (cs_sample_lz_int_d16.asm), including saturation at the 16-bit boundaries. +// "load-mip": read level 1 through typed, two-level SRVs with both full-width and D16 fetches; write the checked +// results to level 0 through single-level storage views. The two mips start with different data. // "words" (cs_imgatomic.asm, cs_imgatomic3d.asm, cs_resinfo.asm): the uint and sint images are filled as for "load" // and a 4x4x4 r32 uint volume with 200 + i, and nothing is judged here: the 64 words of each are printed after the // dispatch (texel (x, y) at i = 8y + x, (x, y, z) at i = 16z + 4y + x) for check.py to compare. Three things are @@ -60,7 +64,7 @@ static void table_insert(std::vector& t, const uint32_t key[8], uint32 } int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } + if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|load-mip|words|signed-zero]\n"); return 2; } gipa = load_vulkan(); if (!gipa) return 1; #define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) @@ -121,8 +125,9 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; // "load" mode (cs_imgload.asm): the sint image receives the sum of the two texels read back with image_load. + const bool load_mip = argc > 2 && !std::strcmp(argv[2], "load-mip"); const bool packed_load = argc > 2 && !std::strcmp(argv[2], "load-d16"); - const bool load_mode = packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); + const bool load_mode = load_mip || packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); @@ -236,7 +241,8 @@ int main(int argc, char** argv) { // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). const uint32_t VOL = 4; { - uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55}; + // The volume uses the D3D12 layer's whole-mip UAV tag (FirstWSlice=0, WSize=4). + uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x80000055, 0x55, 0x55, 0xd7801800}; table_insert(table, t, 1); } VkBuffer tb; void* tbp; @@ -244,10 +250,12 @@ int main(int argc, char** argv) { std::memcpy(tbp, table.data(), table.size() * 4); const uint32_t W = 8; - VkImage img[3]; VkImageView view[3]; + const uint32_t base_width = load_mip ? 2 * W : W, mip_count = load_mip ? 2 : 1; + VkImage img[3]; VkImageView view[3], sampled[3]; for (int k = 0; k < 3; k++) { VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {base_width, base_width, 1}; + ii.mipLevels = mip_count; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; @@ -261,6 +269,14 @@ int main(int argc, char** argv) { vi.image = img[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[k]; vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); + sampled[k] = view[k]; + if (load_mip) { + VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; + usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + vi.pNext = &usage; + vi.subresourceRange.levelCount = mip_count; + CHECK(vkCreateImageView(dev, &vi, nullptr, &sampled[k])); + } } VkImage wide; VkImageView wide_view; { @@ -328,10 +344,10 @@ int main(int argc, char** argv) { dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[2], VK_IMAGE_LAYOUT_GENERAL}, + VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[0], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[1], VK_IMAGE_LAYOUT_GENERAL}, + {VK_NULL_HANDLE, sampled[2], VK_IMAGE_LAYOUT_GENERAL}, {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; VkDescriptorImageInfo dii[3][N]; @@ -383,7 +399,10 @@ int main(int argc, char** argv) { const uint32_t image_words = W * W * (signed_zero ? 4 : 1); VkBuffer rb[3]; void* rbp[3]; for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); - // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. + // Mip mode seeds level 0 with a decoy and level 1 with the typed inputs. Signed-zero probes + // all four RGBA32 components; the ordinary load and words modes seed integer views only. + const int first_fill = signed_zero || load_mip ? 0 : filled ? 1 : 3; + const uint32_t mip_offset = load_mip ? base_width * base_width : 0; // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. struct PackedLoad { uint32_t u; int32_t s, sum; }; constexpr PackedLoad boundary[] = { @@ -391,18 +410,24 @@ int main(int argc, char** argv) { {0, 32768, 32767}, {0, -32768, -32768}, {0, -32769, -32768}, {65536, -32769, 32767}, }; static_assert(sizeof(boundary) / sizeof(boundary[0]) == W); - // Load/words modes seed the integer images. The signed-zero probe seeds every component of all three images. - const int first_fill = signed_zero ? 0 : filled ? 1 : 3; VkBuffer fill[3]{}; - for (int k = first_fill; k < 3; ++k) { - void* mapped; - CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapped)); - auto* words = static_cast(mapped); - for (uint32_t i = 0; i < image_words; ++i) { - const bool edge = packed_load && i / W == W - 1; - if (signed_zero) words[i] = 0x39000000u + k * image_words + i; - else if (k == 1) words[i] = edge ? boundary[i % W].u : 100 + i; - else words[i] = static_cast(edge ? boundary[i % W].s : -2 * int32_t(i)); + if (first_fill < 3) { + for (int k = first_fill; k < 3; ++k) { + void* mapped; + const uint32_t count = mip_offset + image_words; + CHECK(make_buffer(count * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapped)); + auto* words = static_cast(mapped); + for (uint32_t i = 0; i < mip_offset; ++i) words[i] = 0x12345678u; + for (uint32_t i = 0; i < image_words; ++i) { + const bool edge = packed_load && i / W == W - 1; + if (signed_zero) words[mip_offset + i] = 0x39000000u + k * image_words + i; + else if (k == 0) words[mip_offset + i] = + (i & 1 ? 0xffu : 0u) | (i & W ? 0xff00u : 0u) | 0xff000000u; + else if (k == 1) words[mip_offset + i] = edge ? boundary[i % W].u : + (load_mip ? 0x100000u : 0u) + 100u + i; + else words[mip_offset + i] = static_cast(edge ? boundary[i % W].s : + -2 * int32_t(i) - (load_mip ? 0x10000 : 0)); + } } } // The volume's fill and its read-back, used in words mode. @@ -426,7 +451,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mip_count, 0, 1}; if (k >= first_fill) { // filled by a copy first ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; } @@ -442,6 +467,7 @@ int main(int argc, char** argv) { VkImageMemoryBarrier vol_ib = ib[0]; vol_ib.image = vol; vol_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + vol_ib.subresourceRange.levelCount = 1; const VkImageSubresourceLayers vol_layers{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; if (words_mode) { // filled by a copy first vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vol_ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; @@ -460,10 +486,16 @@ int main(int argc, char** argv) { 0, nullptr, 1, &vol_ib); } if (first_fill < 3) { + VkBufferImageCopy copies[2]{}; + for (uint32_t level = 0; level < mip_count; ++level) { + auto& copy = copies[level]; + copy.bufferOffset = level ? mip_offset * 4 : 0; + copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; + copy.imageExtent = {base_width >> level, base_width >> level, 1}; + } for (int k = first_fill; k < 3; k++) { - VkBufferImageCopy bic{}; - bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; - vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); + vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + mip_count, copies); ib[k].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; @@ -485,6 +517,7 @@ int main(int argc, char** argv) { ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + ib[k].subresourceRange.levelCount = 1; } vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 3, ib); @@ -546,6 +579,18 @@ int main(int argc, char** argv) { for (uint32_t x = 0; x < W; x++) { uint32_t i = y * W + x; const uint8_t* c = static_cast(rbp[0]) + 4 * i; + if (load_mip) { + const bool red = x & 1, green = y & 1; + const uint32_t packed_float = (red ? 0x3c00u : 0) | (green ? 0x3c000000u : 0); + const uint32_t u = 0x100000u + 100 + i, s = uint32_t(-2 * int32_t(i) - 0x10000); + // D16 saturates red to 65535 (UINT) or -32768 (SINT); the high half holds alpha = 1. + const uint32_t want_u = u + 0x0001ffffu + packed_float; + const uint32_t want_s = s + 0x00018000u; + if (c[0] != (red ? 255 : 0) || c[1] != (green ? 255 : 0) || c[2] || c[3]) bad[0]++; + if (static_cast(rbp[1])[i] != want_u) bad[1]++; + if (static_cast(rbp[2])[i] != want_s) bad[2]++; + continue; + } int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - 128) > 1 || c[3] != 255) bad[0]++; const bool edge = packed_load && y == W - 1; diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 0aca46787..ae9ba56f7 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -104,6 +104,8 @@ public: bool sampler_filter_minmax = false; bool vertex_attribute_divisor = false; bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled + bool storage_image_extended_formats = false; // typed r8ui storage images + bool maintenance10 = false; // depth/stencil transfers on non-graphics families, per format bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as @@ -111,11 +113,16 @@ public: bool a8_render_target = false; // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. VkDeviceSize host_pointer_alignment = 0; + bool sliced_3d_uav = false; // imageSlicedViewOf3D and robustImageAccess enabled + bool robust_image_access = false; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; bool shader_fma = false; // VK_KHR_shader_fma and shaderFmaFloat32 enabled (OpFmaKHR, rdna2spirv.py --fma khr) bool occlusion_query_precise = false; // occlusionQueryPrecise enabled + bool prepare_on_bind=false; + bool first_use_backend_pipelines=false; + bool cold_graphics_compile = false; bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported @@ -176,6 +183,17 @@ public: bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } DeviceStatus initialize(bool presentation = false) { + return initialize_device(presentation, false, true); + } + + // Headless UAV tests can request sliced views and opt out of legacy formatless storage image features. + DeviceStatus initialize(bool enable_sliced_3d_uav, bool enable_legacy_formatless_features) { + return initialize_device(false, enable_sliced_3d_uav, enable_legacy_formatless_features); + } + +private: + DeviceStatus initialize_device(bool presentation, bool enable_sliced_3d_uav, + bool enable_legacy_formatless_features) { const auto failure = [](const char* call, VkResult result) { std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast(result)); return DeviceStatus::failed; @@ -335,7 +353,9 @@ public: std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)", validation ? " (validation on)" : ""); - VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; + VkPhysicalDeviceVulkan13Features features13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, + v13_.core ? &features13 : nullptr}; VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; features2_of(physical, &features); @@ -375,8 +395,18 @@ public: subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off"); // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 // (zero-based VS ids) is in; harmless before. + const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); + const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; + v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; + cold_graphics_compile = v13_.enable_pipeline_cache_control; + prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; + first_use_backend_pipelines = prepare_on_bind || (compile_mode && std::strcmp(compile_mode, "first-use") == 0); VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; + if (v13_.core) { + robust_image_access = features13.robustImageAccess == VK_TRUE; + static_cast(enable11.pNext)->robustImageAccess = robust_image_access; + } enable11.shaderDrawParameters = features11.shaderDrawParameters; VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; enable12.timelineSemaphore = VK_TRUE; @@ -430,14 +460,19 @@ public: sharing_.push_back(f); } VkPhysicalDeviceFeatures enable{}; + storage_image_extended_formats = features.features.shaderStorageImageExtendedFormats == VK_TRUE; + enable.shaderStorageImageExtendedFormats = storage_image_extended_formats; enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) bc = features.features.textureCompressionBC == VK_TRUE; enable.shaderSampledImageArrayDynamicIndexing = bindless; enable.shaderStorageImageArrayDynamicIndexing = bindless; + enable.shaderStorageImageReadWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageReadWithoutFormat; + enable.shaderStorageImageWriteWithoutFormat = + enable_legacy_formatless_features && features.features.shaderStorageImageWriteWithoutFormat; enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available - enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. @@ -536,6 +571,22 @@ public: } #endif + const char* sliced_name = VK_EXT_IMAGE_SLICED_VIEW_OF_3D_EXTENSION_NAME; + VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT sliced{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_SLICED_VIEW_OF_3D_FEATURES_EXT}; + if (enable_sliced_3d_uav && robust_image_access && + std::any_of(extensions.begin(), extensions.end(), [&](const auto& e) { + return std::strcmp(e.extensionName, sliced_name) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &sliced}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + sliced_3d_uav = sliced.imageSlicedViewOf3D == VK_TRUE; + if (sliced_3d_uav) { + sliced.pNext = *v13_.next(); + *v13_.next() = &sliced; + } + } + #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. VkPhysicalDeviceShaderFmaFeaturesKHR fma_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; @@ -605,6 +656,22 @@ public: if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); #endif if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); + if (sliced_3d_uav) device_extensions.push_back(sliced_name); +#ifdef VK_KHR_maintenance10 + VkPhysicalDeviceMaintenance10FeaturesKHR maint10{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_10_FEATURES_KHR}; + if (v13_.core && all_queue_types && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_KHR_MAINTENANCE_10_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maint10}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + maintenance10 = maint10.maintenance10 == VK_TRUE; + if (maintenance10) { + maint10.pNext = *v13_.next(); + *v13_.next() = &maint10; + device_extensions.push_back(VK_KHR_MAINTENANCE_10_EXTENSION_NAME); + } + } +#endif const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); #if defined(VK_KHR_swapchain_maintenance1) @@ -655,6 +722,7 @@ public: return result == VK_SUCCESS ? DeviceStatus::ready : failure("vkCreateCommandPool", result); } +public: bool depth_format_usable(VkFormat format) const { VkFormatProperties properties{}; instance_fn("vkGetPhysicalDeviceFormatProperties")(physical, format, diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp index 8ca6a819a..90a3fa0c6 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -37,6 +37,8 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE; + std::vector families; VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -52,6 +54,9 @@ const VkDevice k_device = make_handle(0x100); VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, VkBuffer* out) { ++g_vk->create_buffer_calls; + g_vk->sharing_mode = info->sharingMode; + if (info->queueFamilyIndexCount) + g_vk->families.assign(info->pQueueFamilyIndices, info->pQueueFamilyIndices + info->queueFamilyIndexCount); if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; const std::uintptr_t id = g_vk->next_buffer++; g_vk->live_buffers[id] = info->size; @@ -148,7 +153,7 @@ int main() { g_vk = &vk; constexpr VkDeviceSize k_4mib = 4u << 20; { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, {2, 5}); EXPECT(scratch.loaded()); VkBuffer buf = VK_NULL_HANDLE; @@ -157,6 +162,7 @@ int main() { EXPECT(vk.create_buffer_calls == 0); EXPECT(scratch.get(100, buf, off)); + EXPECT(vk.sharing_mode == VK_SHARING_MODE_CONCURRENT && vk.families == std::vector({2, 5})); const VkBuffer chunk1 = buf; EXPECT(chunk1 != VK_NULL_HANDLE && off == 0); EXPECT(vk.live_buffers[reinterpret_cast(chunk1)] == k_4mib); diff --git a/runtime/test/xbox_cbv_vector_test.cpp b/runtime/test/xbox_cbv_vector_test.cpp new file mode 100644 index 000000000..3a62c2e8d --- /dev/null +++ b/runtime/test/xbox_cbv_vector_test.cpp @@ -0,0 +1,55 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include +#include +using namespace d3d12test; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr,"line %d: %s\n",__LINE__,#x); return 1; } } while(0) +int main(int argc,char** argv) { + vktest::Device vk; + const auto status=vk.initialize(); + if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=vk.instance_proc;info.instance=vk.instance;info.physical=vk.physical; + info.device=vk.device;info.queue=vk.queue;info.queue_family=vk.family;info.buffer_device_address=true; + ID3D12Device* dev=nullptr; + CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&dev)))); + Ref xbox; + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev,__uuidof(ID3D12Device),reinterpret_cast(&xbox.p),true))); + rt::d3d12::set_device_outer(dev,xbox.p); + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + auto desc=buffer_desc(256); + Ref constants; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&desc,D3D12_RESOURCE_STATE_COMMON,nullptr,IID_PPV_ARGS(&constants.p)))); + Ref descriptors; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,2,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&descriptors.p)))); + auto dst=descriptors->GetCPUDescriptorHandleForHeapStart(); + const UINT stride=dev->GetDescriptorHandleIncrementSize(hd.Type); + D3D12_CONSTANT_BUFFER_VIEW_DESC cb{constants->GetGPUVirtualAddress(),256}; + CHECK(cb.BufferLocation && cb.BufferLocation<(8ull<<20)); + xbox->CreateConstantBufferView(&cb,dst); + dev->CreateConstantBufferView(&cb,{dst.ptr+stride}); + for (unsigned variant=0;variant<2;++variant) { + leonida::gfx10::BufferWords words{}; + std::memcpy(words.data(),reinterpret_cast(dst.ptr+variant*stride),sizeof(words)); + leonida::gfx10::Buffer decoded{}; + CHECK(leonida::gfx10::decode(words,decoded) && decoded.address==cb.BufferLocation); + CHECK(decoded.stride==(variant?0u:16u) && decoded.num_records==(variant?256u:16u)); + CHECK(decoded.oob_select==(variant?leonida::gfx10::OobSelect::raw:leonida::gfx10::OobSelect::structured_with_offset)); + if(argc==3) { + std::vector image(static_cast(cb.BufferLocation)+256); + std::memcpy(image.data()+64,words.data(),sizeof(words)); + for(unsigned row=0;row<16;++row)for(unsigned col=0;col<4;++col) { + const std::uint32_t value=100+10*row+col; + std::memcpy(image.data()+cb.BufferLocation+16*row+4*col,&value,4); + } + std::ofstream file(argv[1+variant],std::ios::binary);CHECK(file.write(reinterpret_cast(image.data()),image.size())); + } + } + CHECK(!vk.validation_errors()); + std::puts("Xbox CBV has sixteen complete 16-byte rows; byte-address view retains 256 bytes"); + return 0; +} diff --git a/runtime/test/xbox_d16s8_surface_test.cpp b/runtime/test/xbox_d16s8_surface_test.cpp new file mode 100644 index 000000000..98f33a3c1 --- /dev/null +++ b/runtime/test/xbox_d16s8_surface_test.cpp @@ -0,0 +1,48 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include +#define CHECK(v) do { if(!(v)){std::fprintf(stderr,"line %d: %s\n",__LINE__,#v);return 1;} } while(0) +using namespace d3d12test; +int main() { + vktest::Device gpu;const auto status=gpu.initialize();if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready);rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=gpu.instance_proc;info.instance=gpu.instance;info.physical=gpu.physical;info.device=gpu.device; + info.queue=gpu.queue;info.queue_family=gpu.family;info.buffer_device_address=true; + Ref dev;CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&dev.p)))); + constexpr DXGI_FORMAT format=static_cast(118); constexpr UINT extent=32; + D3D12_RESOURCE_DESC tex{};tex.Dimension=D3D12_RESOURCE_DIMENSION_TEXTURE2D;tex.Width=extent;tex.Height=extent; + tex.DepthOrArraySize=1;tex.MipLevels=1;tex.Format=format;tex.SampleDesc.Count=1;tex.Flags=D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const auto required=dev->GetResourceAllocationInfo(0,1,&tex);CHECK(required.SizeInBytes>0 && required.SizeInBytes!=~UINT64{0} && required.Alignment); + D3D12_FEATURE_DATA_FORMAT_INFO planes{format};CHECK(SUCCEEDED(dev->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO,&planes,sizeof(planes))) && planes.PlaneCount==2); + D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT},rd{D3D12_HEAP_TYPE_READBACK}; + D3D12_CLEAR_VALUE clear{};clear.Format=format;clear.DepthStencil={0.25f,0x3c}; + Ref texture,readback; + CHECK(SUCCEEDED(dev->CreateCommittedResource(&def,D3D12_HEAP_FLAG_NONE,&tex,D3D12_RESOURCE_STATE_DEPTH_WRITE,&clear,IID_PPV_ARGS(&texture.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp[2]{};UINT rows[2]{};UINT64 bytes[2]{},total=0; + dev->GetCopyableFootprints(&tex,0,2,0,fp,rows,bytes,&total); + CHECK(bytes[0]==extent*2 && bytes[1]==extent && rows[0]==extent && rows[1]==extent && total>0); + CHECK(fp[0].Footprint.Format==DXGI_FORMAT_R16_TYPELESS && fp[1].Footprint.Format==DXGI_FORMAT_R8_TYPELESS); + auto b=buffer_desc(total);CHECK(SUCCEEDED(dev->CreateCommittedResource(&rd,D3D12_HEAP_FLAG_NONE,&b,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(&readback.p)))); + Ref dsv;D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV,1,D3D12_DESCRIPTOR_HEAP_FLAG_NONE,0}; + CHECK(SUCCEEDED(dev->CreateDescriptorHeap(&hd,IID_PPV_ARGS(&dsv.p))));const auto handle=dsv->GetCPUDescriptorHandleForHeapStart(); + D3D12_DEPTH_STENCIL_VIEW_DESC view{};view.Format=format;view.ViewDimension=D3D12_DSV_DIMENSION_TEXTURE2D;dev->CreateDepthStencilView(texture.p,&view,handle); + Ref queue;Ref alloc;Ref list;Ref fence; + D3D12_COMMAND_QUEUE_DESC q{};CHECK(SUCCEEDED(dev->CreateCommandQueue(&q,IID_PPV_ARGS(&queue.p)))); + CHECK(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&alloc.p)))); + CHECK(SUCCEEDED(dev->CreateCommandList(0,D3D12_COMMAND_LIST_TYPE_DIRECT,alloc.p,nullptr,IID_PPV_ARGS(&list.p)))); + CHECK(SUCCEEDED(dev->CreateFence(0,D3D12_FENCE_FLAG_NONE,IID_PPV_ARGS(&fence.p)))); + const auto both=D3D12_CLEAR_FLAG_DEPTH|D3D12_CLEAR_FLAG_STENCIL;list->ClearDepthStencilView(handle,both,.25f,0x3c,0,nullptr); + D3D12_RECT rect{8,8,24,24};list->ClearDepthStencilView(handle,both,.75f,0xa5,1,&rect); + auto bar=transition(texture.p,D3D12_RESOURCE_STATE_DEPTH_WRITE,D3D12_RESOURCE_STATE_COPY_SOURCE);list->ResourceBarrier(1,&bar); + D3D12_TEXTURE_COPY_LOCATION from{};from.pResource=texture.p;from.Type=D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;from.SubresourceIndex=1; + D3D12_TEXTURE_COPY_LOCATION to{};to.pResource=readback.p;to.Type=D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;to.PlacedFootprint=fp[1]; + list->CopyTextureRegion(&to,0,0,0,&from,nullptr);CHECK(SUCCEEDED(list->Close())); + ID3D12CommandList* batch[]={list.p};queue->ExecuteCommandLists(1,batch);CHECK(SUCCEEDED(queue->Signal(fence.p,1))); + const auto end=GetTickCount64()+3000;while(fence->GetCompletedValue()<1 && GetTickCount64()GetCompletedValue()>=1); + void* mapped=nullptr;CHECK(SUCCEEDED(readback->Map(0,nullptr,&mapped)));const auto* pixels=static_cast(mapped)+fp[1].Offset; + for(unsigned y=0;y=8&&x<24&&y>=8&&y<24?0xa5:0x3c)); + readback->Unmap(0,nullptr);CHECK(!gpu.validation_errors()); + std::printf("Xbox D16+S8 allocation %llu; both plane footprints and all %u stencil pixels passed\n",(unsigned long long)required.SizeInBytes,extent*extent); + return 0; +} diff --git a/runtime/test/xbox_depth_storage_test.cpp b/runtime/test/xbox_depth_storage_test.cpp new file mode 100644 index 000000000..9f33db608 --- /dev/null +++ b/runtime/test/xbox_depth_storage_test.cpp @@ -0,0 +1,243 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/title_va_alias.h" +#include +#include + +using namespace d3d12test; +#define VERIFY(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0) + +namespace { +void* leased_pages{}; +unsigned released_leases{}; +void* allocate_texture_pages(std::size_t bytes, std::uint64_t) { + leased_pages = VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (leased_pages) leonida::title_va_aliases().add_title_memory(reinterpret_cast(leased_pages), bytes); + return leased_pages; +} +void release_texture_pages(void* p, std::uint64_t) { + leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + VirtualFree(p, 0, MEM_RELEASE); + ++released_leases; +} +int check_lease(ID3D12Device* dev, ID3D12Device* xbox) { + D3D12_RESOURCE_DESC shape{}; + shape.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + shape.Width = shape.Height = 256; + shape.DepthOrArraySize = shape.MipLevels = 1; + shape.Format = DXGI_FORMAT_R32G32_FLOAT; + shape.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + shape.SampleDesc.Count = 1; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Ref pc; + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &shape, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&pc.p)))); + VERIFY(pc->GetGPUVirtualAddress() == 0); + rt::d3d12_xs::set_descriptor_heap_allocator(allocate_texture_pages, release_texture_pages); + using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + const auto create = reinterpret_cast(slot(xbox, 76)); + { + Ref console; + VERIFY(SUCCEEDED(create(xbox, &heap, 0, &shape, 0, nullptr, &__uuidof(ID3D12Resource), + reinterpret_cast(&console.p)))); + VERIFY(leased_pages && console->GetGPUVirtualAddress() == reinterpret_cast(leased_pages)); + VERIFY(released_leases == 0); + auto* words = static_cast(leased_pages); + words[0] = 0x365f; + words[256 * 256 * 2 - 1] = 0x9814; + VERIFY(console->GetGPUVirtualAddress() == reinterpret_cast(leased_pages)); + } + VERIFY(released_leases == 1); + rt::d3d12_xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} +} + +int main() { + vktest::Device gpu; + const auto status = gpu.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + VERIFY(status == vktest::DeviceStatus::ready); + const bool with_stencil = std::getenv("LEONIDA_TEST_D16S8_UAV") != nullptr; + constexpr auto xbox_d16s8 = static_cast(118); + rt::d3d12::VulkanDeviceInfo info{}; + info.bindless = gpu.bindless; + info.bindless_partially_bound = gpu.partially_bound; + info.get_instance_proc = gpu.instance_proc; + info.instance = gpu.instance; + info.physical = gpu.physical; + info.device = gpu.device; + info.queue = gpu.queue; + info.queue_family = gpu.family; + info.buffer_device_address = true; + ID3D12Device* dev{}; + VERIFY(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&dev)))); + constexpr UINT layers = 6, width = 32; + std::array original{0x1095, 0x568c, 0x242a, 0x93db, 0xb832, 0x0e69}; + D3D12_RESOURCE_DESC tex{}; + tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + tex.Width = tex.Height = 768; + tex.DepthOrArraySize = layers; + tex.MipLevels = 1; + tex.SampleDesc.Count = 1; + tex.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_R16_TYPELESS; + tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_CLEAR_VALUE clear{}; + clear.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_D16_UNORM; + clear.DepthStencil.Depth = 1; + Ref depth; + VERIFY(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, IID_PPV_ARGS(&depth.p)) == E_INVALIDARG && !depth.p); + Ref proxy; + VERIFY(SUCCEEDED(rt::d3d12_xs::create_device_proxy(dev, __uuidof(ID3D12Device), + reinterpret_cast(&proxy.p), true))); + rt::d3d12::set_device_outer(dev, proxy.p); + VERIFY(check_lease(dev, proxy.p) == 0); + const auto allocation = dev->GetResourceAllocationInfo(0, 1, &tex); + VERIFY(allocation.SizeInBytes >= 768u * 768 * layers * 2 && allocation.SizeInBytes != UINT64_MAX); + using XboxCreate = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const D3D12_CLEAR_VALUE*, const IID*, void**); + const auto create = reinterpret_cast(slot(proxy.p, 76)); + tex.Width = tex.Height = width; + if (with_stencil) { + VERIFY(SUCCEEDED(create(proxy.p, &heap, 0, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, &clear, + &__uuidof(ID3D12Resource), reinterpret_cast(&depth.p)))); + } else { + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, __uuidof(ID3D12Resource), nullptr))); + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_DEPTH_WRITE, + &clear, IID_PPV_ARGS(&depth.p)))); + } + VERIFY(depth->GetDesc().Flags == tex.Flags); + Ref dsv, uav; + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, layers}; + VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&dsv.p)))); + hd.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + hd.NumDescriptors = layers + 1; + VERIFY(SUCCEEDED(dev->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&uav.p)))); + const auto slot = [&](ID3D12DescriptorHeap* h, D3D12_DESCRIPTOR_HEAP_TYPE t, UINT i) { + auto handle = h->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += i * dev->GetDescriptorHandleIncrementSize(t); + return handle; + }; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + VERIFY(SUCCEEDED(dev->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + VERIFY(SUCCEEDED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + VERIFY(SUCCEEDED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)))); + VERIFY(SUCCEEDED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[2 * layers]{}; + UINT64 total{}; + dev->GetCopyableFootprints(&tex, 0, with_stencil ? 2 * layers : layers, 0, footprints, nullptr, nullptr, &total); + auto buffer = buffer_desc(total); + D3D12_HEAP_PROPERTIES host{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + VERIFY(SUCCEEDED(dev->CreateCommittedResource(&host, D3D12_HEAP_FLAG_NONE, &buffer, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); + for (UINT i = 0; i < layers; ++i) { + const auto d = slot(dsv.p, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, i); + D3D12_DEPTH_STENCIL_VIEW_DESC dv{}; + dv.Format = with_stencil ? xbox_d16s8 : DXGI_FORMAT_D16_UNORM; + dv.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + dv.Texture2DArray.FirstArraySlice = i; + dv.Texture2DArray.ArraySize = 1; + dev->CreateDepthStencilView(depth.p, &dv, d); + const auto flags = with_stencil ? D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL : D3D12_CLEAR_FLAG_DEPTH; + list->ClearDepthStencilView(d, flags, float(original[i]) / 65535.f, UINT8(0x30 + i), 0, nullptr); + D3D12_UNORDERED_ACCESS_VIEW_DESC uv{}; + uv.Format = DXGI_FORMAT_R16_UINT; + uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + uv.Texture2DArray.FirstArraySlice = i; + uv.Texture2DArray.ArraySize = 1; + dev->CreateUnorderedAccessView(depth.p, nullptr, &uv, slot(uav.p, hd.Type, i)); + } + // Mix legacy and enhanced transitions. Leave slice five entirely on the depth image. + D3D12_RECT rect{3, 4, 19, 26}; + for (UINT i = 0; i < layers - 1; ++i) { + D3D12_TEXTURE_BARRIER enhanced{}; + enhanced.SyncBefore = D3D12_BARRIER_SYNC_DEPTH_STENCIL; + enhanced.SyncAfter = D3D12_BARRIER_SYNC_CLEAR_UNORDERED_ACCESS_VIEW; + enhanced.AccessBefore = D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE; + enhanced.AccessAfter = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS; + enhanced.LayoutBefore = D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE; + enhanced.LayoutAfter = D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS; + enhanced.pResource = depth.p; + enhanced.Subresources = {0, 1, i, 1, 0, 1}; + D3D12_BARRIER_GROUP group{D3D12_BARRIER_TYPE_TEXTURE, 1}; + group.pTextureBarriers = &enhanced; + auto legacy = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + legacy.Transition.Subresource = i; + if (i % 2) list->Barrier(1, &group); else list->ResourceBarrier(1, &legacy); + const UINT values[4]{0x8040u + i}; + list->ClearUnorderedAccessViewUint({}, slot(uav.p, hd.Type, i), depth.p, values, 1, &rect); + std::swap(legacy.Transition.StateBefore, legacy.Transition.StateAfter); + std::swap(enhanced.SyncBefore, enhanced.SyncAfter); + std::swap(enhanced.AccessBefore, enhanced.AccessAfter); + std::swap(enhanced.LayoutBefore, enhanced.LayoutAfter); + if (i % 2) list->Barrier(1, &group); else list->ResourceBarrier(1, &legacy); + } + ID3D12Resource *raw_depth = depth.p, *raw_stencil = nullptr; + if (with_stencil) { + D3D12_UNORDERED_ACCESS_VIEW_DESC st{}; + st.Format = DXGI_FORMAT_R8_UINT; + st.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + st.Texture2DArray.ArraySize = layers; + st.Texture2DArray.PlaneSlice = 1; + dev->CreateUnorderedAccessView(depth.p, nullptr, &st, slot(uav.p, hd.Type, layers)); + const auto inspected_plane = [&](UINT index) -> ID3D12Resource* { + leonida::gfx10::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(slot(uav.p,hd.Type,index).ptr), sizeof(words)); + leonida::gfx10::Image image{}; + if (!leonida::gfx10::decode(words,image)) return nullptr; + return reinterpret_cast(rt::d3d12::uav_image_resource(depth.p,image.address)); + }; + raw_depth = inspected_plane(0); + raw_stencil = inspected_plane(layers); + VERIFY(raw_depth && raw_stencil && raw_depth != depth.p && raw_stencil != raw_depth); + } + auto ready = transition(depth.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, + with_stencil ? D3D12_RESOURCE_STATE_UNORDERED_ACCESS : D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &ready); + for (UINT i = 0; i < (with_stencil ? 2 * layers : layers); ++i) { + D3D12_TEXTURE_COPY_LOCATION from{}, to{}; + from.pResource = i < layers ? raw_depth : raw_stencil; from.SubresourceIndex = i % layers; + to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; to.PlacedFootprint = footprints[i]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } + VERIFY(SUCCEEDED(list->Close())); + ID3D12CommandList* batch[]{list.p}; + queue->ExecuteCommandLists(1, batch); + VERIFY(SUCCEEDED(queue->Signal(fence.p, 1))); + const auto end = GetTickCount64() + 5000; + while (fence->GetCompletedValue() < 1 && GetTickCount64() < end) Sleep(1); + VERIFY(fence->GetCompletedValue() == 1); + void* mapped{}; + VERIFY(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + auto* bytes = static_cast(mapped); + for (UINT i = 0; i < layers; ++i) for (int y = 0; y < width; ++y) for (int x = 0; x < width; ++x) { + const auto offset = footprints[i].Offset + y * footprints[i].Footprint.RowPitch + x * 2; + const auto value = *reinterpret_cast(bytes + offset); + const bool changed = i < layers-1 && x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom; + const UINT expected = changed ? 0x8040u+i : original[i]; + if (value != expected) { + std::fprintf(stderr, "slice %u pixel (%d,%d) expected %04x got %04x\n", i, x, y, expected, value); + return 1; + } + } + if (with_stencil) { + for (UINT i=0; iUnmap(0, nullptr); + VERIFY(gpu.validation_errors() == 0); + std::printf("Depth D16 / storage R16_UINT, six layers and %u exact texels\n", width * width * layers); + return 0; +} diff --git a/runtime/test/xbox_gpu_label_test.cpp b/runtime/test/xbox_gpu_label_test.cpp new file mode 100644 index 000000000..bbf5c8f47 --- /dev/null +++ b/runtime/test/xbox_gpu_label_test.cpp @@ -0,0 +1,59 @@ +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gpu_label_memory.h" +#include +#include +#include + +#define CHECK(x) do { if(!(x)){std::fprintf(stderr,"line %d: %s\n",__LINE__,#x);return 1;} } while(0) +using namespace d3d12test; +namespace xs=rt::d3d12_xs; +struct Data { + void* addr=VirtualAlloc(nullptr,4096,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE); + void track() {auto a=reinterpret_cast(addr);leonida::label::memory().track(a,4096,a,true);} + ~Data(){if(addr){leonida::label::memory().release_heap(reinterpret_cast(addr));VirtualFree(addr,0,MEM_RELEASE);}} +}; +using Create=HRESULT(WINAPI*)(void*,const void*,ID3D12CommandAllocator*,ID3D12PipelineState*,const IID*,void**); +using Label=void(WINAPI*)(void*,std::uintptr_t,std::uint64_t,std::uint32_t,std::uint32_t); +int main() { + _putenv_s("LEONIDA_GPU_LABELS","1"); + vktest::Device gpu;auto status=gpu.initialize();if(status==vktest::DeviceStatus::unavailable)return 77; + CHECK(status==vktest::DeviceStatus::ready); + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc=gpu.instance_proc;info.instance=gpu.instance;info.physical=gpu.physical; + info.device=gpu.device;info.queue=gpu.queue;info.queue_family=gpu.family;info.buffer_device_address=true; + ID3D12Device* inner=nullptr;CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&inner)))); + Ref device;CHECK(SUCCEEDED(xs::create_device_proxy(inner,__uuidof(ID3D12Device),reinterpret_cast(&device.p),true))); + rt::d3d12::set_device_outer(inner,device.p); + Ref queue;D3D12_COMMAND_QUEUE_DESC queue_desc{}; + CHECK(SUCCEEDED(inner->CreateCommandQueue(&queue_desc,IID_PPV_ARGS(&queue.p)))); + Ref allocator;CHECK(SUCCEEDED(inner->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT,IID_PPV_ARGS(&allocator.p)))); + std::uint64_t desc[4]{};Ref list; + CHECK(SUCCEEDED(reinterpret_cast(slot(device.p,73))(device.p,desc,allocator.p,nullptr,&__uuidof(ID3D12GraphicsCommandList),reinterpret_cast(&list.p)))); + CHECK(xs::is_list_proxy(list.p));auto* real=xs::list_proxy_real_list(list.p);CHECK(real); + Data live,stale;CHECK(live.addr && stale.addr);live.track();stale.track(); + const auto base=reinterpret_cast(live.addr),old=reinterpret_cast(stale.addr); + auto* values=static_cast(live.addr);auto* retired=static_cast(stale.addr); + const auto write32=reinterpret_cast