diff --git a/README.md b/README.md index 11082be186..9041367d48 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ Original author's Git Mirror: https://git.notrexed.dev/notrexed/Leonida ## Project status +The Windows integration provides a reproducible build and launch procedure for the offline first-run controller prompts. [First-run UI instructions](docs/first_run_ui.md) + **Early. The game does not boot yet.** Everything that can be done without the game's executable is in place, so work on booting can start as soon as one is available to a developer. @@ -301,7 +303,7 @@ The biggest open pieces: [docs/design.md](docs/design.md)); still open are the vertex-shader input layout (`v0` = `VertexIndex` is unverified if the console runs VS as NGG) and wave64 cross-half code in VS/PS/GS on 32-wide subgroups. - **Xbox D3D12 → Vulkan**: mesh-shader draws, indirect draw state and stream output are still open; #313 tracks the - remaining method surface, and nothing has been checked against the real executable yet ([plan and status](docs/d3d12_vulkan.md)). + remaining method surface. The Windows integration exercises the first-run UI. [Plan and status](docs/d3d12_vulkan.md) - **Model recovery**: investigate the 71 unrecovered fragment candidates in [`levels.rpf`](docs/models.md#full-archive-re-count-at-e293917). See [CONTRIBUTING.md](CONTRIBUTING.md). Never attach game files, extracted assets or generated shaders to issues or diff --git a/docs/README.md b/docs/README.md index 13bf783966..6856349124 100644 --- a/docs/README.md +++ b/docs/README.md @@ -67,6 +67,7 @@ method, scope and caveats. No game data is included. |---|---| | [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. | | [mobile.md](mobile.md) | arm64/mobile path: the x86-64 → arm64 static-recompiler groundwork (`tools/x64_recomp.py`), the `.pdata` coverage census (`tools/recomp_census.py`), and what still blocks iOS. | +| [first_run_ui.md](first_run_ui.md) | Build the Windows integration and display the offline first-run controller prompts. | | [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. | | [retail_boot_chain.md](retail_boot_chain.md) | How far `gta6rt --run` gets with the retail executable: the stops in order and what clears each, the physical-page export shapes, and device slots 26, 48 and 73. | | [retail_boot_intel_host.md](retail_boot_intel_host.md) | The retail boot on an Intel host with 16 GB: which stops of the two boot pages hold there with #7111, the commit-limit stop at the 6.1 GiB physical-page request that #7556 clears, the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth (the console mesh-shader subobject among it). | @@ -85,6 +86,7 @@ method, scope and caveats. No game data is included. | [exe_fail_fast.md](exe_fail_fast.md) | Where the retail executable stops itself (`int3`) on an import's result: 78 sites over 27 imports (`tools/import_fail_fast.py`), grouped by how `main` binds each import (all 13 non-host fatal-checked imports now bind to shims; 0 unbound). | | [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | | [directstorage.md](directstorage.md) | Console DirectStorage: the DLL and ABI the title is expected to use (`DStorageGetFactory`, `dstorage_xs`, `XCRDAPI`), how sure that is and the evidence for it, and what `runtime/shims/dstorage.cpp` serves on the PC. The executable's own imports are unmeasured. | +| [cpu_features.md](cpu_features.md) | CPU instructions in the executable a desktop CPU may lack (`tools/cpu_feature_scan.py`): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX sites (AMD only) and 8 CLWB sites (Intel since Ice Lake), all real code; `#UD` on hosts without them. | | [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | | [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | @@ -92,7 +94,6 @@ method, scope and caveats. No game data is included. | [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | | [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. | | [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. | -| [cpu_features.md](cpu_features.md) | CPU instructions in `game_scarlett_master.exe` that a host lacking the feature or privilege level faults on (SSE4a, CLZERO, MONITORX and others): counts per feature and how many sites lie inside `.pdata` function ranges, measured with `tools/cpu_feature_scan.py` on 1.0.2.1. Counts only. | | [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | | [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. | | [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | diff --git a/docs/boot.md b/docs/boot.md index ccd06a03e8..2b7186e302 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -1,13 +1,9 @@ # First boot: the runbook and the two traces -**Status: `--dry-run` and `--init` have been run on the retail executable; `--run` has not.** The package in the -repository's test corpus does not contain `game_scarlett_master.exe` (RT-5); the dry-run on an executable supplied -separately maps it and leaves 30 imports unimplemented, and `--init` runs its TLS callbacks and the package DLLs' -`DllMain`s without an exception -([`runtime_imports.md`](runtime_imports.md#the-retail-executable-rt-5)), so this page is still the procedure and the -trace tool for the first boot. Outbound `ws2_32.dll` and `winhttp.dll` calls are restricted offline by the shims -(`ws2_offline.cpp` permits loopback only; `winhttp_offline.cpp` refuses all requests), though running with the network -off remains good defence in depth. Nothing here quotes game data; a real trace stays on the player's machine. +The Windows integration has a dedicated [offline first-run UI profile](first_run_ui.md). The original dry-run +and initialization measurements used a separately supplied executable and identified 30 unimplemented imports. +The Winsock shim restricts connections to loopback and the WinHTTP shim refuses outbound requests. Keep retail runs +offline and traces on the player's machine. [Original import measurements](runtime_imports.md#the-retail-executable-rt-5) ## 1. What the first boot produces diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index c6803e5d91..223eee0f7b 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -471,7 +471,7 @@ What is implemented (all of it testable without the game): enables BC texture compression, and `D3D12_OPTIONS12` reports `RelaxedFormatCastingSupported = TRUE`, so a committed or placed texture accepts a castable-format list. Other queries (including `OPTIONS6` and `OPTIONS10`) are logged and refused until the trace shows what the game asks (question 11); - - Single-sampled `A8_UNORM` 2D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose + - Single-sampled `A8_UNORM` 1D, 2D and 3D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose (0, 0, 0, A) before applying the caller's component mapping. Format support includes `MIP` when the Vulkan image supports multiple levels. Where the GPU has `VK_FORMAT_A8_UNORM_KHR` (`VK_KHR_maintenance5`) and can sample, copy and blend it as a colour attachment, a texture created with `ALLOW_RENDER_TARGET` is stored in that @@ -626,7 +626,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 @@ -640,7 +641,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. - 2D-array images up to 16384, 3D and 1D images up to 4096 each (the title streams more cube maps, texture arrays and 1D lookups than the defaults hold: each distinct T# of one takes its own index, and a native boot filled the 1024 2D-array and 256 1D indices during the story load). @@ -662,14 +663,16 @@ side inwards: and 4000 samplers) the set has 65536 2D images, 3936 samplers, 16384 2D-array, 4096 3D and 4096 1D images and 4096 storage indices in each dimension: 152929 descriptors, 5-10 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 + - 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 @@ -691,8 +694,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. @@ -708,7 +711,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 @@ -729,7 +732,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 @@ -877,6 +880,10 @@ The compute path, end to end: with `DEPTH_STENCIL2` and different masks per face, front- and back-facing, with one reference or two (`OMSetFrontAndBackStencilRef`): 498 in all, byte-identical on an RTX 5070 Ti (driver 617.42), and 6 of the 16 differ when the back face is given the front face's masks. + - A triangle-family PSO can draw Xbox rectangle lists. When the input assembler selects topology 17, replay + selects a geometry-stage variant that emits the fourth corner after vertex shading. It requires + `geometryShader` and a vertex pipeline without an application geometry stage. A later triangle draw uses the + original PSO. The translated-draw GPU test switches between both primitives on one PSO and checks every pixel. - **Logic ops** come from `RenderTarget[0]`, as in D3D12, and apply to every target (Vulkan has one per pipeline; it skips float formats). **`DepthClipEnable = FALSE`** is depth clamping: D3D12 clamps output depth to the viewport's range anyway. @@ -1376,13 +1383,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 @@ -1824,10 +1837,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. @@ -2294,9 +2328,39 @@ 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). +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; `d3d12_quad_index_test` for indexed quads). - **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. -- **Quad list**: one four-vertex triangle fan per quad (the pattern 0 1 2, 0 2 3). The translated vertex id is `VertexIndex - BaseVertex`, so each fan reads the index values 4q..4q+3: from the application's index buffer when the draw is indexed, else from a shared 0, 1, 2, ... buffer in the arena's reserved pages (16384 quads per draw at most, more are cut off with a log line), with the draw's first vertex as the vertex offset. A quad's instances are drawn together, so several overlapping blended instances rasterize quad by quad rather than instance by instance. The PSO type is the ordinary triangle type. +- **Quad list**: one triangle-list draw whose indices are `i0 i1 i2, i0 i2 i3` for each quad. Both triangles start + at the quad's first vertex, the one Vulkan takes flat inputs from, and one draw keeps D3D12's instance order + (instance by instance, not quad by quad). The PSO type is the ordinary triangle type. + - **Non-indexed**: a shared index buffer in the arena holds the pattern `0 1 2, 0 2 3` for 16384 quads (a draw + with more is cut off there, with a log line). The draw's first vertex becomes the vertex offset. + - **Indexed**: a compute pass (`src/quad_index_expand.comp`, run by `src/quad_index_expand.h`) reads the + application's index buffer on the GPU and writes the six 32-bit indices of each quad into copy scratch + (`src/vulkan_scratch.h`); the draw binds that scratch with the application's instance count, base vertex and + first instance. The host never reads the indices: a copy or a shader earlier in the same list can have written + them. The pass runs before the draw's rendering scope, after a barrier that makes earlier writes visible to it + and before one that makes its indices visible to the draw, and between two segments of an active + pipeline-statistics query so that `CSInvocations` does not count it (as for the other helper dispatches, + D3D-162). + - Index values are copied as they are, a 16-bit one zero-extended, so `VertexIndex - BaseVertex` is still the + application's index in a translated vertex shader. + - The strip-cut values `0xFFFF` and `0xFFFFFFFF` are ordinary indices, as in every list topology: the replay + enables primitive restart for strips only. What the console does with one inside a quad is not measured. + - An index past the end of the index buffer view reads 0, as in D3D12. The pass reads a 16-bit index from its + aligned 32-bit word, so standalone shader-addressable Vulkan buffers round their backing size up to a word. + The D3D buffer size and view bounds are unchanged. A draw's last one to three indices that do not make a quad + are dropped. + - Needs `bufferDeviceAddress` (the pass uses device addresses, no descriptors). Without it, and inside a + statistics query that cannot be split, the list fails as unsupported instead of drawing something else. + - **Why not a triangle fan per quad** (the first version of the indexed path): a fan takes a flat input from + each triangle's own first vertex, the quad's second and third, and a draw per quad runs every instance of one + quad before the next quad. `d3d12_quad_index_test` shows both on an RTX 4070 SUPER: a quad with a red first + vertex came out black and blue (0 of 4096 pixels red), and of two overlapping instances the first one's + second quad ended on top (2048 of 4096 pixels right). With the expansion the seven test frames cover 16-bit and + 32-bit indices, a first index at an address of 2 modulo 4, a base vertex, two instances, and a view that ends + inside the second quad, plus a 16-bit draw that reaches the end of a standalone upload buffer. + - **Not covered**: quad and rectangle lists through `ExecuteIndirect`, whose draws do not record a topology. ## 4. Object model mapping @@ -2380,16 +2444,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. @@ -2455,15 +2516,11 @@ The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiv - `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. -- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for the architecture - `D3D12_FEATURE_ARCHITECTURE` reports. On a discrete GPU (`UMA = FALSE`): `DEFAULT` is `NOT_AVAILABLE`/`L1`, - `UPLOAD` `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`. On an integrated - GPU (`UMA = TRUE`, `CacheCoherentUMA = FALSE`) the same pages, all in `L0`, and a custom heap in `L1` is refused - with `E_INVALIDARG` (`CreateHeap`, `CreateCommittedResource`), as the host runtime does on - a Radeon 780M (AMD 32.0.13030.13001) and on WARP. All answers have type `CUSTOM` and node masks 1. `CUSTOM`, - unknown types and node masks above 1 get an all-zero answer, logged. The test compares `DEFAULT`, `UPLOAD` and - `READBACK` byte for byte with the host runtime's answer when the host adapter has the layer's architecture (RTX - 4090: identical); `d3d12_heap_properties` compares the `L1` heaps with the layer's own adapter. +- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for a NUMA adapter, matching the + `UMA = FALSE` that `D3D12_FEATURE_ARCHITECTURE` reports: `DEFAULT` is `NOT_AVAILABLE`/`L1`, `UPLOAD` + `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`, all with type `CUSTOM` and + node masks 1. `CUSTOM`, unknown types and node masks above 1 get an all-zero answer, logged. The test compares + `DEFAULT`, `UPLOAD` and `READBACK` byte for byte with the host runtime's answer (RTX 4090: identical). The retail executable calls it (device slot 26) with the buffer for the returned struct in RCX and the device in RDX, node mask in R8 and heap type in R9: three calls right after device creation, node mask 1 and types 1, 2 and 3 (measured under `gta6rt --run` with a register probe in the slot's thunk). A PC C++ method has the device @@ -2739,6 +2796,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`; @@ -3197,16 +3272,8 @@ SDL2 `src/render/direct3d12/SDL_render_d3d12_xbox.cpp` (zlib). entries carry a `PlaneIndex`; display entries carry `PercentScanned`. 11. Xbox titles do not handle `DXGI_ERROR_DEVICE_REMOVED`/`RESET`. -*Public corroboration (not measured here).* XCL, a GPL-2.0-only compatibility layer that runs retail Xbox Series -titles, records `PresentX` at queue slot 30 for the older runtime layout (XDefiant, Minecraft, Fortnite) and 32 for -a newer one (Unicorn Overlord), and the four frame calls at device slots 78-81: `SetFrameIntervalX`, -`ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). The Apache-2.0 -ebiten Xbox binding has the same device order, declares `D3D12XBOX_PRESENT_PLANE_PARAMETERS` as a 0x48-byte x64 -struct and `D3D12XBOX_PRESENT_PARAMETERS` as 0x20 bytes, and stores the token in 64 bits. So the plane and -present-parameter layouts and the token width in `runtime/shims/xbox_present.h` are no longer guesses; the enum -values and the `SuspendX`/`ResumeX` slots still are. XCL returns `S_FALSE` from a timed-out `WaitFrameEventX` -where this layer returns `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. The full comparison is in -[d3d12_xs_surface.md §7.1](d3d12_xs_surface.md#71-public-sources-for-the-presentation-and-device-abi). +*Not measured:* vtable slots of all `*X` methods, exact `D3D12XBOX_*` struct layouts and sizes, enum values, and +whether the token is exactly 64 bits in the ABI. The samples give argument counts and field names only. *Hypothesis (the game is not observed):* a GDKX title follows this pattern, so the DXGI swapchain shim (D3D-2) is probably **not** on its boot path. What is on it: `D3D12XboxCreateDevice`, `IDXGIDevice1`/`IDXGIAdapter`/ @@ -3233,11 +3300,10 @@ Layer plan: **What is implemented (the presentation core).** Everything in the plan above that does not need a slot exists as methods of `rt::d3d12::XboxPresentation` (`runtime/shims/xbox_present.h`), on top of the presenter of section 3.2 and -`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The plane and present-parameter -layouts and the 64-bit token are confirmed on x64 by the public code cited above; the constant values and HRESULTs -are **our own provisional definitions**, because the samples give call shapes and field names only and the enum -values are still unmeasured. The class is the surface the proxy will forward to. The queue-side calls ignore which -queue they came on (one `VkQueue` behind all of them). +`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The struct layouts, constant +values, HRESULTs and the 64-bit token are **our own provisional definitions**: the samples give call shapes and field +names only, so the real slots, layouts and enum values are still unmeasured and the class is the surface the proxy +will forward to. The queue-side calls ignore which queue they came on (one `VkQueue` behind all of them). - *Frame pacing* (`FramePacer`, time from an injectable clock; real time is a steady timer, a host vblank source can replace it). `SetFrameIntervalX` takes the interval as a period in microseconds and the latency, and starts @@ -3472,10 +3538,9 @@ queue they came on (one `VkQueue` behind all of them). second (GameDVR) output, resolving multisampled planes, a mutable-format swapchain (an sRGB/UNORM alternation recreates the swapchain; `VK_KHR_swapchain_mutable_format` is not enabled on the device), a host-vblank clock (the timer drifts from the display; with FIFO presents the swapchain holds the queue to the real refresh anyway), render statistics, - `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. The - public slots are the device's `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX`/`GetFrameStatisticsX` - at 78-81 and `PresentX` at queue 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` have no public - slot. Nothing here is wired to those slots yet, and the game's own runtime is not observed. + `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. Slots to measure (all unknown): the device's `SetFrameIntervalX`, + `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` and the queue's `PresentX`, `SuspendX`, `ResumeX` + (the list is in the header). - *Tests*: `frame_pacer_test` (fake clock: interval, offset, late waits, timeouts, latency blocking, tokens, statistics, suspend/resume, a real 10 ms timer; no GPU) and `xbox_present_test` (the Vulkan device, reading the swapchain image back: blank, solid, two colours, source rectangles, RGBA/BGRA/sRGB sources, 2 planes, plane composition @@ -3889,9 +3954,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. | @@ -4248,7 +4313,7 @@ nothing is copied from their trees. | 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | **Measured** from `XboxBvhBuilder.dll`'s reads ([xdxr.md](xdxr.md)): `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) with every field's offset, and the stream records' offsets, types and defaults. Still open: the record names, and the offline statistics layout, which the DLL never writes (it rejects that postbuild type). | | 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. | | 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | -| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (a discrete GPU: non-UMA; an integrated GPU, `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`: UMA, not cache-coherent, as the host runtime answers on a Radeon 780M), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | +| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | | 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | | 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | | 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | diff --git a/docs/design.md b/docs/design.md index 9862911cdc..324fa92e90 100644 --- a/docs/design.md +++ b/docs/design.md @@ -285,7 +285,7 @@ How the generated SPIR-V expects the runtime to work: |---|---| | Heap-relative buffer device addresses | `Gen.host_addr` sign-extends the low 48 bits of the effective VA after adding any byte offset, then adds `%heap_base`. The runtime stores `device_address - heap_base` in a V#'s 48-bit base field. NVIDIA's Windows driver can place an imported buffer below the heap, so that offset is negative. Zero extension made the resulting device address too high by `2^48`. Console user-mode VAs below `2^47` and full-width root descriptor addresses already within the signed 48-bit range retain their values. A 64-bit base-plus-offset sum gives the correct address for effective VAs in that range, including when the sum crosses zero. Each new shader's `index.json` entry carries `"vsharp_base_sign_extended": true`. Check the field on all loaded entries before enabling below-arena imports for a library, because older modules can share an index with newly translated ones. `tests/semantic/test_vsharp_sext48.py` checks the emitted shifts, both reads against synthetic memory, and the metadata field. | | Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | -| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`); **not GPU-verified**. | +| `s_load_dword*` with `vcc` 64-bit base pointer | SMEM `s_load_dword*` accepts `vcc` (`{vcc_lo, vcc_hi}`, hardware `s[106:107]`) as its 64-bit base pointer in `Gen.scalar_load`, loading `%vcc` as the low dword and `%vcc_hi` as the high dword; `s_buffer_load*` still requires a 4-dword V# and rejects 2-dword `vcc`. Source: RDNA2 ISA SMEM `SBASE` encoding (`sbase = 53` -> `s[106:107] = vcc`). Confirmed by corpus count over the 2,684-shader pipeline library compute corpus (79 shaders use `vcc` as the `s_load` base: 72 `s_load_dwordx4 sgpr, vcc`, 6 `s_load_dwordx8 sgpr, vcc`, 1 `s_load_dwordx4 slist, vcc`; all 79 translate and pass `spirv-val` under `--wave64-emulate`) and CPU-checked by `tests/semantic/test_sload_vcc_base.py` (`spirv-as` + `spirv-val`) and `tests/semantic/test_scalar_mem_smem.py` (both halves and the resulting addresses); **not GPU-verified**: the synthetic `runtime/test/shaders/cs_smem_vcc_base.asm` reads back eight seeded words through the pair in the standard GPU runner. | | Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | | DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | | DPP on a VOPC compare | A VOPC compare whose src0 field is a DPP marker (250 for DPP16, 233/234 for DPP8) takes src0 through the DPP lane selection of the row above and writes VCC: a lane's bit is `compare(src0 of the selected lane, its own src1)`, with 0 for src0 when the selected lane is out of its row or inactive (`bound_ctrl` 1, or DPP8 with `fi` 0). The second word has the layout of a VOP2's DPP word. `llvm-mc` has no decoding for it on gfx10 (LLVM 21.1.8 rejects the first word for `gfx1013`; LLVM defines the form from GFX11 on), so `tools/shader_disasm.py` prints it: it decodes the pair with the first word turned into `v_max_f32` into `v0`, which takes the same second word, and gives the line the compare's name, a `vcc_lo` destination and the real encoding back (`with_vopc_dpp`); `tools/rdna2_decode.py` decodes it directly. **Only the forms where every lane writes its bit are translated**: `row_mask` and `bank_mask` 0xF and either `bound_ctrl` 1 or DPP8. Any other form, and `v_cmpx`, is refused (`DPP compare with lanes that keep their mask bit`), because what a lane DPP leaves unwritten does to its VCC bit is not measured. Found in 3 of the 2,684 pipeline-library compute programs of 1.0.2.1: 4 `v_cmp_gt_f32` each, with `quad_perm:[1,0,3,2]`, `quad_perm:[2,3,0,1]`, `row_ror:8` (all `bound_ctrl:1`, masks 0xF) and `dpp8:[4,5,6,7,0,1,2,3]`, beside `v_min/max_f32_dpp` and `v_mov_b32_dpp` on the same lanes. **Not measured on hardware**: the rule follows from the encoding, from LLVM's GFX11 definition of the same form and from the VOP2 DPP rules measured in the row above; the sweep that measured those (`tools/crosslane_fuzz.py --dpp-sweep --oracle hw`) does not cover compares. Lane values are checked in `tests/semantic/test_dpp_compare.py` (the SPIR-V interpreter) and on a GPU with `runtime/test/shaders/cs_dpp_cmp.asm`. | @@ -338,7 +338,7 @@ How the generated SPIR-V expects the runtime to work: | `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | | `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | | POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | -| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10–10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); every other `image_load` keeps the sampled path and needs no storage feature (SHADER-151). `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) is `Unsupported`. A cube has no storage view of its own: it is bound as a six-layer 2D array, so a coherent `image_load` on `dim:SQ_RSRC_IMG_CUBE` is supported (bindings 11/12/13, the third coordinate is the face). Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | +| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10-10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class for those 2D views, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); other loads in the corpus keep the sampled path and need no storage feature (SHADER-151). The D3D-78 row below describes the storage-only and tagged atomic readback exceptions. `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) or on a dimension without storage views (cube) is `Unsupported`. Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | | 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | | 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | | `image_sample_l` / `image_sample_lz` in every dimension | The T# FORMAT rule applies to a 2D-array, 3D, cube and 1D image too: the sample reads the uint/sint alias of that dimension's sampled binding (3, 6 and 5; a cube uses its 6-layer 2D-array view) and keeps the float view for a float format, the same `image_read_typed` dispatch `image_load` uses. Confirmed by `tests/semantic/test_sample_typed_dims.py` (the alias and sampled-image type each dimension emits, that a float format still samples the float view, and `spirv-val --target-env vulkan1.2`) and `runtime/src/vulkan_bindless.h` (`sampled_binding`). The format rule itself is the 2D row above; a GPU readback on a non-2D integer texture is not measured yet. | @@ -445,6 +445,8 @@ How the generated SPIR-V expects the runtime to work: | Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. | | Resident `image_load tfe` | When no lane faults, the status VGPR retains its prior value. The status follows the data VGPRs, with D16 packing two components per data VGPR. `cs_imgload_tfe` and `cs_imgload_d16_tfe` seed both status registers and check that the translated loads preserve them on fully resident images (GPU-checked on RTX 4070 Ti, Windows driver 630.20). The ordinary image-load lowering covers the resident case. Reporting sparse texel faults requires a separate lowering. [AMD RDNA 2 ISA §8.2.1, TFE and D16](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf), [LLVM AMDGPU instruction selection](https://github.com/llvm/llvm-project/blob/llvmorg-16.0.6/llvm/lib/Target/AMDGPU/AMDGPUInstructionSelector.cpp#L1804-L1833) | | Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | +| 1D and 3D texture UAVs (D3D-78) | Storage bindings are 17–19 for 1D and 26–28 for 1D arrays (SPIR-V `1D`, arrayed), leaving multisample SRV bindings 20–25 unchanged. 1D arrays are storage-only: `image_load` and `image_store` use `(x, layer)` relative to the view. Ordinary 1D and 3D loads use sampled aliases; `image_load ... glc` in either dimension, or any `image_load` on a 1D array, reads the Unknown-format storage view. A layer-created 3D UAV sets reserved bit 31 of T# word 4; word 7 tagged with `0xd7800000` (mask `0xff800000`) holds `WSize - 1` in bits [21:11] and `FirstWSlice` in bits [10:0], including for whole-mip UAVs. Vulkan rebases/checks Z for storage operations. The typed sampled aliases below use the tag to rebase Z and return zero outside the range or for nonzero UAV LOD; an untagged SRV keeps its original coordinates and LOD. For non-`glc` `image_load` on a tagged R32_UINT T# whose SGPR group also feeds volume atomics in the shader, the read uses their formatted storage view (binding 7) so it can observe the atomic result in the same dispatch. Other sampled loads retain the visibility rule below. 3D atomics run only in active lanes with a resolved R32_UINT UAV; `glc` returns the old value and inactive lanes keep their destination. `cs_texture_uav.asm` and `d3d12_texture_uav_test` check coherent and sampled reads, dynamic `image_load_mip`, an untouched base mip, and active/inactive add and compare-and-swap with `glc` on an RTX 4090. | +| Packed RGB9E5 UAV backing (#1287 and D3D-78) | Emulated RGB9E5 still encodes the logical shared-exponent FORMAT in the T#. A sampled view reads E5B9G9R9; a raw storage view uses R32_UINT, with any selected W range applied only to that storage view. On 1D-family and 3D UAVs, bit 22 of the synthetic word 7 marks this backing (tag mask `0xff800000`, lower 22 W bits unchanged). The translator does not implement re-packing for generic `image_store` or unpacking for formatless storage loads: these operations respectively suppress writes or take the fallback, not a view of the wrong numeric type. R32_UINT atomics require a logical R32_UINT volume UAV. The packed bit does not affect slicing or untagged SRVs; `d3d12_r9g9b9e5_uav_test` checks raw stores and sampled readback with the real set 0. | | 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | | Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. | | Dynamic sampled descriptor indices | Set 0 bindings 0 (2D), 3 (2D array and cube), 5 (1D) and 6 (3D), including their integer sampled aliases, use runtime T# hash results for sampling, gather, texel fetch and image queries. Binding 1 uses runtime S# hash results for sampling, gather and LOD queries. Explicit-LOD gather emulation takes its sampler state directly from S# words and uses sampled-image fetches. Literal descriptor words and the zero-on-miss fallback still go through the runtime lookup. Emit `SampledImageArrayDynamicIndexing` and record `shaderSampledImageArrayDynamicIndexing` in the shader index whenever such an array is indexed. A storage-only shader can declare sampled arrays without indexing them. The hash table is one storage buffer containing an array of words. T# and S# operands are scalar across an RDNA2 wave (AMD RDNA 2 ISA, MIMG fields SRSRC/SSAMP). The Vulkan contract requires the resulting index to be dynamically uniform in the subgroup or invocation group, and in the invocation group when the effective subgroup size is one. If wave and Vulkan execution mappings break that uniformity, the affected accesses need separate non-uniform indexing support. Confirmed by the synthetic `sampled_dynamic_index.asm` regression (`test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically` and `test_fetch_and_query_paths` in `tests/semantic/test_sampled_dynamic_index.py`), `spirv-val`, and the declaration-only GPU positive control in [#2806](https://github.com/ItsNotRexed/Leonida/pull/2806#issuecomment-7083836498). [Vulkan VUID 10128](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-SampledImageArrayDynamicIndexing-10128) and [runtime VUIDs 10135 and 10142](https://docs.vulkan.org/refpages/latest/refpages/source/RuntimeSpirv.html#VUID-RuntimeSpirv-SampledImageArrayNonUniformIndexing-10135). | @@ -466,9 +468,9 @@ How the generated SPIR-V expects the runtime to work: | `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | | `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. | | `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair normally carries 64-bit data. In wave64, `s_flbit_i32_b64` can also gather both halves of a lane mask or EXEC before scanning it. The other operations require scalar data. `test_library_compute_forms.py` checks an empty mask and set bits in either half on native and emulated waves. `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | +| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair normally carries 64-bit data. In wave64, `s_flbit_i32_b64` can also gather both halves of a lane mask or EXEC before scanning it. The other operations require scalar data. `test_library_compute_forms.py` checks an empty mask and set bits in either half on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` runs EXEC and VCC masks on every lane of a wave64 (the 1.0.2.1 pipeline library reads EXEC this way). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | | `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by `tests/test_int_hw_probe.py` (`ValuBfeMeasuredOnRdna2`). | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. The source must carry scalar data. Bit replication can also write EXEC, or VCC in wave64. Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | +| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. The source must carry scalar data. Bit replication can also write EXEC, or VCC in wave64. Each lane takes source bit `lane // 2`. `test_library_compute_forms.py` checks both halves of VCC and SCC on native and emulated waves; `tests/semantic/test_lane_mask_bitreplicate_flbit.py` checks VCC, which the 1.0.2.1 pipeline library writes from a constant, on every lane of a wave64. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | | 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| | Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | | Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index 4047065a86..6ccdbaf417 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -322,6 +322,14 @@ The step is reused on the same conditions as the builder's (the image, the three translator, llvm-mc, the wave64 mode and the fallback flags) and reports every program left untranslated on every run. Measured on 1.0.2.1: **12/12 translate and pass `spirv-val`** (1 VS, 11 PS, 1,245–4,239 bytes); the VS's SHA-256 is `01ac7810dcabd62afcd904b231e90d9a031a51808a700e3349290bec5f0d426f`. +The count is twelve because `pe_shader_containers.py` extracts the ten plain containers and the two packed pixel +shaders above. A second measurement, made on the tree of the first-run UI integration, whose extractor took the +ten plain containers only (1 VS, 9 PS): the ten translate and pass `spirv-val` natively and with +`--wave64-emulate`, `ShaderLibrary::load` finds all ten by `(stage, fssm_sha256)`, and `vk_pipeline_check` passes +10/10 modules and 10/10 pipelines (0 failed, 0 skipped) on an AMD Radeon RX 9070 XT (RADV GFX1201, Mesa 26.2.6) and +on an AMD Ryzen 7 9800X3D integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.2.6). The two packed pixel shaders were +not part of that run. +`tests/test_exe_shaders_stage.py` covers the step on synthetic VS/PS `PSV0` containers without game data. **That VS is why 14 graphics PSOs failed (measured).** On the base commit, a 100 s boot refused **14** of 50,469 `CreatePipelineState` calls, every one with `no translated vs for FSSM sha256 01ac...`: none of the 26,503 indexed @@ -439,6 +447,6 @@ constructor's pipelines are created, not that a build produces the right tree (s `tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM` blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on -every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the -container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test` +every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` and `exe/` indexes (found +by the container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test` creates a pipeline through slot 62 whose only translation is in `/bvh/index.json`. diff --git a/docs/first_run_ui.md b/docs/first_run_ui.md new file mode 100644 index 0000000000..d7b2fe5e5c --- /dev/null +++ b/docs/first_run_ui.md @@ -0,0 +1,37 @@ +# Offline first-run UI on Windows + +This integration combines the retail frame-loop runtime with the shader and rendering changes needed to display the first-run controller prompts. The visual milestone is a solid background with legible prompts at the lower right. Gameplay and the 3D world are outside the verified result. + +## Build + +Use an x64 Developer PowerShell with MSVC, CMake and Ninja. Install the Vulkan SDK and put the SPIR-V tools and an AMDGPU-capable `llvm-mc` on `PATH`. The shader tool setup is described in [testing.md](testing.md). Supply an extracted Xbox 1.0.2.1 package and its matching executable from your own files. + +Run the commands from the checkout. Set `$game` to the local package and `$scratch` to a writable directory outside both the package and the checkout. These commands support a fresh shader workspace. SDL3 is fetched during configuration if there is no installed static SDL3 package. + +```powershell +$game = Read-Host 'Path to the extracted Xbox 1.0.2.1 package' +$scratch = Read-Host 'Path for the build, shader workspace and port' +$game = (Resolve-Path -LiteralPath $game).Path +$build = Join-Path $scratch 'build' +$work = Join-Path $scratch 'work' +$port = Join-Path $scratch 'port' +cmake -S runtime -B $build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_REQUIRE_VULKAN=ON -DLEONIDA_D3D12_SHIM_TESTS=ON -DLEONIDA_SDL3_FETCH=ON +cmake --build $build --target gta6rt +python -I make_game.py --game $game --work $work --out $port --runtime-build $build --stages check,shaders,runtime +``` + +Keep the generated shader workspace. The port reads the shader directory recorded in `shader_path.txt`. Native graphics pipelines also use the source containers in the sibling `dxbc` directory. The build indexes the base, library, FidelityFX, BVH and executable-embedded programs. + +## Launch + +Run the title offline. The Winsock shim permits loopback and the WinHTTP shim refuses outbound requests. The hardware verification used a Windows AppContainer with zero network capabilities. [Boot runbook](boot.md) + +```powershell +& (Join-Path $port 'gta6rt.exe') --first-run-ui (Join-Path $game 'game_scarlett_master.exe') +``` + +The profile selects Vulkan, a 2 GiB graphics address arena, on-demand pipelines, console root-argument layout, GPU completion labels, frame pacing and the keyboard gamepad. Explicit environment settings take precedence; a variable that is set but empty does not count. Speech synthesis through the host's own runtime is not part of the profile: `LEONIDA_LOCAL_SPEECH=1` turns it on, and without it the silent voice answers. The switches are listed in [`runtime/README.md`](../runtime/README.md). The package directory is the working directory. Guest output goes under `first-run-ui/overlay` beside the runtime, and sparse physical-memory backing uses `first-run-ui/xmem` on that volume. Use `--overlay DIR` or the absolute directory in `LEONIDA_XMEM_BACKING_DIR` to choose other writable locations. + +## Contributions + +The frame-loop stack comes from [#321](https://github.com/ubiquitarianism/leonida/pull/321). The archive and shader catalog, shader translation, depth and texture support, presentation window and rectangle-list changes retain their upstream commits. Native and derived pipeline support incorporates the work of enx, TomBox, LooperSalty and KkelebekK. Four patches of the published [graphics runtime patches](https://github.com/Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches/tree/d9a0bc1b070d8a36c81b182bc67edd7d24b41bf2) (GPL-3.0, author smg, committed as "Codex") are in this integration almost as published, about 390 lines: `graphics-root-layout` (the switch between the two packings of graphics root arguments, `runtime/shims/d3d12_com.h`), `descriptor-table-refresh` (the title's descriptors pulled into a bound table, and the table scan in the submitting device, `runtime/shims/d3d12_xs_device.cpp` and `runtime/src/vulkan_backend.h`), `descriptor-write-through` (descriptors the layer writes also stored at the title's address, `runtime/shims/d3d12_xs_device.cpp` and `.h`) and `sampler-table-refresh` (title-backed sampler tables, `runtime/shims/d3d12_vulkan_device.cpp`), with their tests in `runtime/test/d3d12_title_va_test.cpp` and `runtime/test/d3d12_m2_textured_test.cpp`. Each region names its patch in a comment. diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 8ce85ff025..d5d76cb931 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -447,14 +447,16 @@ The runtime seeds its `VkPipelineCache` from the cache this tool saves, so a pip driver gives it the same cache key in both programs. Measured on Windows with an RX 9070 XT (driver 32.0.32029.2010) and one synthetic compute shader, reading the application-cache-hit bit: -- `robustBufferAccess`, `scalarBlockLayout` and `robustImageAccess` are each part of the key. The runtime's - device enables none of them, so the checker's does not either. Nothing else that differs between the two - devices changed the key on RX 9070 XT: the checker's other features, the runtime's extensions, the application name. +- `robustBufferAccess`, `scalarBlockLayout` and `robustImageAccess` are each part of the key. The first two are + disabled on both devices; the runtime's device enables supported core image robustness for storage views, and so + does the checker. Nothing else that differs between the two devices changed the key on RX 9070 XT: the checker's + other features, the runtime's extensions, the application name. - On Windows 11 with an Intel RaptorLake-S iGPU, clearing those three features alone makes the checker's cache hit on the runtime's device. On an NVIDIA GeForce RTX 5060 Laptop GPU (driver 621.24), NVIDIA also hashes `VK_EXT_mesh_shader` (with `meshShaderQueries` enabled, matching the runtime since `#577`) and `VK_KHR_maintenance8` into the pipeline cache key even for compute shaders, so the checker enables both whenever supported and keeps `meshShaderQueries` on. +- On a Windows RTX 5070 Ti (617.42), a compute-only seed missed with mesh features omitted and hit with the supported mesh and mesh-query features enabled on both devices. The shader, push constants and pipeline layout were identical. Cache-producing runs request this device configuration for every selected shader batch. - The executable's file name is part of the key; its folder is not. A copy of the checker under another name misses the cache the original wrote, and the runtime's device hits the checker's cache only from a program with the checker's file name. So on this driver a cache written by `vk_pipeline_check.exe` does not hit in diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 6ba391e74a..9c1b28c7b5 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -163,17 +163,23 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s | `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit | | `AcpHal.dll` | 9: `AcpHalAllocateShapeContexts`, `AcpHalCreate`, `AcpHalReleaseShapeContexts`, `ApuAlloc`, `ApuCreateHeap`, `ApuFree`, `ApuIsVirtualAddressValid`, `ApuMapApuAddress`, `ApuMapVirtualAddress` | the audio hardware layer | -The game executable imports two functions from `xg_xs.dll`, the console's texture layout library. -`XGSuggestSwizzleMode` writes the Xbox layout encoding `0x100 | mode`, including when its output aliases the -description. `XGCreateTextureComputer` returns a refcounted computer for supported layouts. Slot 2 writes the Series -layout, slot 8 copies linear source rows into a subresource, and slot 10 reports 64 KiB tiled-resource geometry. -Rows and tile extents are computed in storage elements, so block-compressed formats use one 4x4 block as an element. -Packed mips share a block at the start of each slice, followed by the other mips from smallest to largest. -The shim covers single-sample linear textures, 2D 4 KiB standard and 64 KiB standard/display textures, and single-mip -4 KiB standard volumes. Unsupported descriptions return a failure and a fallback object because two measured -callers dereference the output without checking the HRESULT. Set `LEONIDA_XG_TRACE=1` to log the first 1024 calls -per entry point. See [the source notes](../runtime/shims/xg_xs_THIRD_PARTY.md) and `xg_xs_test`. The table above -predates the shim. +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). `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-or-later, `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. +Set `LEONIDA_XG_TRACE=1` to log the first 1024 calls per entry point; the source notes are in +[xg_xs_THIRD_PARTY.md](../runtime/shims/xg_xs_THIRD_PARTY.md). 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`, @@ -186,6 +192,20 @@ The seven `xmem.dll` imports are served now (see the `xmem.dll` notes above), so again at detach (reason 0), and there is no `exception`, `error` or `unimplemented_call` event. So none of the 30 unimplemented imports is reached by the TLS callbacks or the `DllMain`s. +The executable's audio imports `xapu.dll` (`XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, +`XApuEnqueueCommand`, `XApuGetResultCount`) and `chad.dll` (`XDspActivate`, `XDspConnectWithMaximumStreamLimit`, +`XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) are served by `runtime/shims/xapu_chad.cpp`. The shapes were +read statically from the executable's call sites: one each, four for `XApuEnqueueCommand`. Both connects succeed with +a handle; the APU connect also returns a zeroed shared buffer the title writes stream input to and reads output from. +Commands are accepted and not processed, so the audio stays silent. A stream open (type 1) and a stream close +(type 2) each queue one result of the same type and slot, because the title frees a stream id only when the close +result arrives. `XDspActivate` writes its two outputs as pointers to zeroed memory, which the title reads as "command +done" after each `XDspSubmitCommand`. `XApuConnect` leaves its first argument, a global of the title, untouched. The +buffer size (128 stream slots), the two results and the zeroed DSP status are hypotheses, explained in the file. +`xapu_chad_test` calls all ten in those shapes. With `--trace`, the first call of each, and the first command of each type, is an +`audio_queue` event. +The table above was measured before this shim and still lists these ten as unimplemented; they are served now. The call shapes agree with `docs/audio_hal_exe_calls.md`, which was measured with `tools/import_call_sites.py`. + What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be reached on the way to the first frame. A bound import is not a working one (the binding only says a function with that name exists), and an unimplemented import stops the run only if the title calls it @@ -195,6 +215,19 @@ outbound and name-resolution calls among them, loopback only (see the Winsock2 s imports bind to the host's. `winhttp.dll` is served by the offline shim, which opens none. Known gap: `dnsapi.dll` (`DnsQuery*`) is not shimmed, so a title that calls it reaches the host's resolver. +## Audio hardware (`AcpHal.dll`) + +The game executable imports nine functions from `AcpHal.dll`, the console's audio hardware layer. +`runtime/shims/acphal.cpp` serves them; the argument shapes come from a static read of the executable's call sites +(one thunk per import, 16 call sites in all), and the names of the parameters and object slots are hypotheses. +`ApuCreateHeap` reserves one block of ordinary memory for both sizes it is given, `ApuAlloc` and `ApuFree` manage it +first fit, and an APU address is a fixed 32-bit base plus the offset in it, so `ApuMapVirtualAddress` and +`ApuMapApuAddress` are arithmetic and `ApuIsVirtualAddressValid` checks a live block and the alignment. +`AcpHalAllocateShapeContexts` fills zeroed 64-byte contexts per count, and `AcpHalCreate` returns an object whose +calls succeed and do nothing: there is no audio processor, so the game gets no sound from this path. Its boot checks +fail hard, which is why every call succeeds. `acphal_test` covers the call shapes. +The table under [The retail executable](#the-retail-executable-rt-5) was measured before this shim and still lists these nine as unimplemented; they are served now. + ## Console paths and the write overlay A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder. diff --git a/docs/shader_library.md b/docs/shader_library.md index 7dc25302cf..3ef944a528 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -152,9 +152,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv * It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, - every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, - 2,693 records). It also writes `index.json` with each program's stage, and + blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one + (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -168,10 +167,9 @@ The output is game data and must stay in your work folder. `tests/test_shader_li archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest walk. It also checks the `--carve` copy, the translator's reads of the compute sidecar and the compute `.state`. -**In the build.** `make_game.py`'s `shaders` stage runs this for the compute stage after the BVH step -(`library_shaders`): `--stages cs --disasm --carve` into `/shaders/library`, then `translate()` shards -`rdna2spirv.py` across `--jobs` and merges into `/shaders/spirv/library` with the stage's `--wave64-emulate` -and fallback flags. The runtime's shader library +**In the build.** `make_game.py`'s `shaders` stage runs this for the compute stage after the FSPX step +(`library_shaders`): `--stages cs --disasm --carve` into `/shaders/library`, then `rdna2spirv.py` into +`/shaders/spirv/library` with the stage's `--wave64-emulate` and fallback flags. The runtime's shader library reads that index next to `fspx/` and finds its entries by `fspx_code_sha256` and `fspx_state_sha256` ([fspx.md](fspx.md), "Build and run-time lookup"). That is how the executable creates these pipelines: it reads the library through DirectStorage zlib requests and passes each compute record's four parts to Xbox device slot 67, @@ -222,9 +220,11 @@ What stops the rest, by the translator's message: run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952 SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with - `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder - fallback for these encodings would cover most of the remaining programs. The translator already reads - `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*). + `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. The translator + now decodes these words from the blob with `rdna2_decode` (`restore_vcc_tuples`) and reads them as the + `[s100,...,vcc_lo,vcc_hi]` lists it already takes (design.md *Scalar/buffer memory*); synthetic cases are in + `tests/semantic/test_vcc_tuple_fallback.py`. The count above was measured before this change; it has not been + re-run on the real library. * **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`): the existing `check_printed_encodings` refusal. * **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets. diff --git a/docs/testing.md b/docs/testing.md index d4f69026d7..ffe729d24f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -56,9 +56,9 @@ This page collects the setup steps and the problems testers have run into so far ## Build the test programs -On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_m2_textured`, -`d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and `d3d12_buffer_uav` when it finds `llvm-mc`, -`spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. +On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_rect_list`, +`d3d12_quad_index`, `d3d12_m2_textured`, `d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and +`d3d12_buffer_uav` when it finds `llvm-mc`, `spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. Without `glslangValidator`, other tests are also omitted, including `d3d12_compute`, `d3d12_draw`, `d3d12_set0_compute` and `d3d12_mesh`; some registered tests run only part of their checks. These tests can be **absent**, not reported as skipped, when their build prerequisites are missing, so a passing `ctest` percentage @@ -173,6 +173,25 @@ python -I runtime/test/shaders/check.py .json (add --full-check for SHA-256, slow) shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V; then the same for the - compute programs inside amd_fidelityfx_upscaler_xbox.dll and XboxBvhBuilder.dll + programs inside amd_fidelityfx_upscaler_xbox.dll, XboxBvhBuilder.dll and game_scarlett_master.exe assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC; --wav adds PCM WAV) BCPack uses strict decoding by default. For local calibration use /bcpack-calibration.json. runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with @@ -1736,7 +1736,7 @@ def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: return settings = exe_settings(image, mc_signature, emulate, fallbacks) programs = exe_programs(unpacked, spirv) if read_shader_setting(settings_file) == settings else None - if programs: + if programs and len(programs[1]) < len(programs[0]): exe_report(programs) return log(f"shaders: extracting and translating the graphics programs of {EXE_IMAGE}") diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 458bb147c2..652003b199 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1281,6 +1281,13 @@ if(BUILD_TESTING) add_test(NAME startup_trace COMMAND startup_trace_test) endif() + if(WIN32) + add_executable(present_window_test test/present_window_test.cpp) + target_link_libraries(present_window_test PRIVATE user32) + add_test(NAME present_window COMMAND present_window_test) + set_tests_properties(present_window PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 15) + endif() + if(TARGET device_proxy_test) add_test(NAME device_proxy COMMAND device_proxy_test) set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) @@ -1302,6 +1309,8 @@ if(BUILD_TESTING) add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) add_test(NAME xs_proxy_mock_env_slots_70 COMMAND xs_proxy_mock_test --env-slots-70) add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) + # LEONIDA_SLOT133_LAYOUT_WORD=1 (set by the test itself): the slot 133 stand-in reads its fourth word as a layout. + add_test(NAME xs_proxy_mock_slot133_layout COMMAND xs_proxy_mock_test --slot133-layout) endif() # Reads d3d12.h and takes MSVC options, so only where the Windows runtime is built. if(TARGET gta6rt) @@ -1449,6 +1458,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET clzero_patch_test) add_test(NAME clzero_patch COMMAND clzero_patch_test) endif() + if(WIN32 AND TARGET cpu_emulation_test) + add_test(NAME cpu_emulation COMMAND cpu_emulation_test) + endif() if(WIN32 AND TARGET xmem_test) add_test(NAME xmem COMMAND xmem_test) # The same with write watching off: no reservation is write-watched for the shadows. @@ -1465,9 +1477,6 @@ if(BUILD_TESTING) add_test(NAME acphal COMMAND acphal_test) add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only) endif() - if(WIN32 AND TARGET cpu_emulation_test) - add_test(NAME cpu_emulation COMMAND cpu_emulation_test) - endif() if(WIN32 AND TARGET xapu_chad_test) add_test(NAME xapu_chad COMMAND xapu_chad_test) endif() @@ -1633,6 +1642,11 @@ if(BUILD_TESTING) "$" "$") # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the # game's exact exit code comes back through the relaunch. + add_test(NAME run_tiny_first_run_ui COMMAND gta6rt --first-run-ui $ -- hello 42 first-run-ui) + set_tests_properties(run_tiny_first_run_ui PROPERTIES + ENVIRONMENT "LEONIDA_ARENA_MB=768;LEONIDA_D3D12=;LEONIDA_PIPELINE_COMPILE=" + PASS_REGULAR_EXPRESSION "tiny_game: PASS first-run UI caller override" + FAIL_REGULAR_EXPRESSION "tiny_game: FAIL") add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $ -- hello 42) add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test "$" "$") @@ -1999,6 +2013,19 @@ if(TARGET Vulkan::Headers) if(BUILD_TESTING) add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test) endif() + if(WIN32) + # CPU-only: a completed GPU label is stored into a page the D3D12 layer watches (read-only until written) and + # dropped for a page that is read-only by the title's own doing (runtime/src/vulkan_gpu_labels.h). + add_executable(gpu_label_store_test test/gpu_label_store_test.cpp) + target_link_libraries(gpu_label_store_test PRIVATE Vulkan::Headers) + target_compile_definitions(gpu_label_store_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + if(MSVC) + target_compile_options(gpu_label_store_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME gpu_label_store COMMAND gpu_label_store_test) + endif() + endif() if(WIN32 AND BUILD_TESTING) # Whole title-region import capability: one host allocation bound as a BDA buffer. The default case uses the # measured 185 MiB placeholder size. A machine that cannot import (no importable usage/handle, an import-budget @@ -2025,6 +2052,15 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) + set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) + add_executable(vk_present_dump_test test/vk_present_dump_test.cpp + ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) + target_link_libraries(vk_present_dump_test PRIVATE Vulkan::Headers user32 windowscodecs ole32) + target_compile_definitions(vk_present_dump_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME vk_present_dump COMMAND vk_present_dump_test) + add_test(NAME vk_present_dump_default COMMAND vk_present_dump_test --default) + add_test(NAME vk_present_dump_invalid COMMAND vk_present_dump_test --invalid) + set_tests_properties(vk_present_dump vk_present_dump_default vk_present_dump_invalid PROPERTIES SKIP_RETURN_CODE 77) endif() if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") @@ -2427,6 +2463,13 @@ 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) + # Resource::Map asks the linear mapping of a slot 133 texture first only with LEONIDA_LINEAR_MAP_FIRST=1. + set_tests_properties(xbox_linear_gpu_staging PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 + ENVIRONMENT "LEONIDA_LINEAR_MAP_FIRST=1") + set_tests_properties(xbox_linear_texture_map PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30 + ENVIRONMENT "LEONIDA_LINEAR_MAP_FIRST=1") 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. @@ -2560,8 +2603,9 @@ if(TARGET Vulkan::Headers) -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) - add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp - ${_indirect_count_spv}) + add_custom_target(gta6rt_indirect_count_shader DEPENDS ${_indirect_count_spv}) + add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp) + add_dependencies(d3d12_indirect_dispatch_count_test gta6rt_indirect_count_shader) target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi version) target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") @@ -2581,6 +2625,15 @@ if(TARGET Vulkan::Headers) add_test(NAME pipeline_cache_seed COMMAND pipeline_cache_seed_test $) set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_RETURN_CODE 77) + # 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) @@ -2808,6 +2861,35 @@ 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) + # With LEONIDA_CBV_RAW=1 a view made on the device itself keeps the byte-address form. + add_test(NAME xbox_cbv_vectors_raw COMMAND xbox_cbv_vector_test) + set_tests_properties(xbox_cbv_vectors_raw PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 20 ENVIRONMENT "LEONIDA_CBV_RAW=1") + 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) + # The console's D16S8 family keeps its own path where the GPU has no D24S8 attachment, and is the D24S8 family + # where it has one; LEONIDA_CONSOLE_D16S8=native asks for the D16/S8 path on every GPU (pc_format). + set_tests_properties(xbox_d16s8_storage PROPERTIES + ENVIRONMENT "LEONIDA_TEST_D16S8_UAV=1;LEONIDA_CONSOLE_D16S8=native" 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 + ENVIRONMENT "LEONIDA_CONSOLE_D16S8=native") + 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) @@ -2904,13 +2986,17 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m15.asm 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. @@ -2925,6 +3011,33 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # Indexed quad lists (src/quad_index_expand.h): a vertex shader that reads the instance id and a pixel shader + # with a flat colour input, translated like vs_m15 and ps_m15. + set(LEONIDA_QUAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/quad_shaders) + set(LEONIDA_QUAD_FILES ${LEONIDA_QUAD_DIR}/spirv/index.json ${LEONIDA_QUAD_DIR}/fssm/vs_quad_inst.fssm + ${LEONIDA_QUAD_DIR}/fssm/ps_quad_flat.fssm) + add_custom_command( + OUTPUT ${LEONIDA_QUAD_FILES} + COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_QUAD_DIR} + COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" + $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py + ${LEONIDA_QUAD_DIR} vs_quad_inst ps_quad_flat + DEPENDS ${LEONIDA_TRANSLATOR_DEPS} + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_quad_inst.asm + ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_quad_flat.asm + COMMENT "Translating vs_quad_inst and ps_quad_flat for the indexed quad list test" + VERBATIM) + add_executable(d3d12_quad_index_test test/d3d12_quad_index_test.cpp shims/d3d12_xs_device.cpp + ${LEONIDA_QUAD_FILES}) + target_link_libraries(d3d12_quad_index_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_quad_index_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_QUAD_DIR="${LEONIDA_QUAD_DIR}") + target_compile_options(d3d12_quad_index_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_quad_index COMMAND d3d12_quad_index_test) + # vs_quad_inst reads its root arguments in the pack() layout (from s0), which is LEONIDA_GRAPHICS_STAGE_LAYOUT=0. + set_tests_properties(d3d12_quad_index PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "LEONIDA_GRAPHICS_STAGE_LAYOUT=0") + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) @@ -2970,13 +3083,31 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm 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. @@ -2996,7 +3127,7 @@ if(TARGET Vulkan::Headers) ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_array.asm 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 @@ -3106,7 +3237,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) # LEONIDA_VULKAN_DEVICE: slot 14 creates the console heap on the Vulkan device it links, as in gta6rt. target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_VULKAN_DEVICE) @@ -3266,6 +3397,16 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_geometry_views COMMAND d3d12_title_va_test) set_tests_properties(d3d12_geometry_views PROPERTIES ENVIRONMENT "LEONIDA_GEOMETRY_MB=16" SKIP_RETURN_CODE 77) 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 shims/d3d12_xs_pso_stream.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -3304,6 +3445,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) add_test(NAME d3d12_title_index_window COMMAND d3d12_draw_test --title-index-window) add_test(NAME d3d12_title_vertex_window COMMAND d3d12_draw_test --title-vertex-window) # LEONIDA_STUB_PIPELINES: a pipeline with no translated shader is a no-op stub when the switch is on. @@ -3386,7 +3529,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 @@ -3395,7 +3538,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 @@ -3448,7 +3591,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) @@ -3470,7 +3613,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 @@ -3478,9 +3621,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 @@ -3508,6 +3670,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) @@ -3812,6 +3978,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) diff --git a/runtime/README.md b/runtime/README.md index d80e1b84ee..fadaa47ef8 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -345,6 +345,19 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_CAPTURE_SOURCE` | unset | *Diagnostic.* With `LEONIDA_CAPTURE`, `1` also reads back the presented source texture itself (`src/vulkan_present.h`). | | `LEONIDA_XG_TRACE_FORMAT` | unset | *Diagnostic.* A DXGI format number: logs the first 256 XG layout computers of that format, whatever `LEONIDA_XG_TRACE`'s cap (`shims/xg_xs.cpp`). | | `LEONIDA_FSDRAW_POKE_CB` | unset | *Diagnostic, changes what is drawn.* An experiment of the full-screen draw probe (`src/fsdraw_probe.h`): writes a known colour into the constant buffer a bound table names, to prove the path from the table to the render target. | +| `LEONIDA_PIPELINE_COMPILE` | unset | `on-demand` (the `--first-run-ui` profile sets it) prepares pipeline-state streams and sampled views at bind time: a placed 2D texture then waits for its memory until a command or a view first uses it. `cache-only` makes an eager build (`LEONIDA_LAZY_PIPELINES=0`) ask the driver's cache first and leaves what would have to be compiled to the first draw. `first-use` is accepted and means the default. When a pipeline is compiled is `LEONIDA_LAZY_PIPELINES`. | +| `LEONIDA_GRAPHICS_STAGE_LAYOUT` | on | Graphics root arguments are laid out as the console does for the vertex, pixel and geometry stages (from `s8`, a descriptor table in one dword). `0` keeps `rt::rootsig::pack()` (from `s0`, two dwords per address) for every graphics signature. | +| `LEONIDA_FRAME_PACING` | unset | `1` (the `--first-run-ui` profile sets it) hands device slots 78 to 81 (`SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX`) to the device's own presentation once the first `PresentX` has built it, with the title's interval and origin event replayed to its pacer. Unset, the slots answer from the device's token counter with no wait. | +| `LEONIDA_GPU_LABELS` | unset | `1` (the `--first-run-ui` profile sets it) records the labels of console list slots 71 and 72 and stores each into the title's memory when the GPU has finished the command buffer that carries it (`src/vulkan_gpu_labels.h`). Unset, the two slots do nothing. | +| `LEONIDA_LINEAR_MAP_FIRST` | unset | `Map` of a slot 133 texture leased as linear answers with the placement address and the title texture registry fills the image. `1` gives it the linear mapping instead: pinned pages, with a GPU-written texture read back into them, and a refusal when the pages are gone. | +| `LEONIDA_CONSOLE_D16S8` | by GPU | The console's `D16_UNORM_S8_UINT` family (DXGI 118 to 120) is made as the D24S8 family where the GPU has `D24_UNORM_S8_UINT` as a depth-stencil attachment and keeps its own D16/S8 path where it has none (AMD). `native` or `d24` chooses for every GPU. The device logs which it took. | +| `LEONIDA_RGBA4_COPY_REFUSE` | unset | `1` refuses a footprint copy to or from a `B4G4R4A4_UNORM` render target stored as RGBA8 (its texels are four bytes there, not two). Unset, the copy is made. | +| `LEONIDA_SLOT133_LAYOUT_WORD` | unset | The committed stand-in of device slot 133 (where no resource can be made on the title's pages) reads its fourth word as a resource state. `1` reads it as a `D3D12_BARRIER_LAYOUT`, as the placed-at-VA handler does: `CreateCommittedResource3` with that layout on a device that has it, else the legacy state of the layout. | +| `LEONIDA_DESC_MIRROR` | on | Descriptor writes to a title-backed heap whose real start differs from the title's are also stored at the title's address, and list slots 35 and 36 pull the title's descriptors into the bound table. `0` turns both off. | +| `LEONIDA_SLOT70_TITLE` | on | A small raw view of the title's own memory through device slot 70 becomes a raw buffer view of its GPU copy. `0` keeps the null view. | +| `LEONIDA_WINDOW` | unset | `WxH` resizes the title's window when the presenter attaches to it. | +| `LEONIDA_PRESENT_DUMP` | unset | *Diagnostic.* `DIR` or `DIR,N` writes every Nth presented frame (60 by default) as a PNG into `DIR` (`src/present_dump.h`). The files are pictures of the title: keep them out of commits, issues and pull requests. | +| `LEONIDA_LOCAL_SPEECH` | unset | `1` forwards the title's speech-synthesis calls to the host's installed `xgameruntime.dll` where there is one. Unset, and wherever that library is missing, the silent voice answers. No profile sets it. | The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index f84465564d..b6ec111c73 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1,3 +1,4 @@ +#include #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -209,6 +210,15 @@ class GraphicsCommandList final 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_; } @@ -244,6 +254,7 @@ class GraphicsCommandList final 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 @@ -532,19 +543,30 @@ class GraphicsCommandList final 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); } @@ -582,13 +604,25 @@ class GraphicsCommandList final case D3D12_BARRIER_TYPE_TEXTURE: { const auto& b = group[g].pTextureBarriers[i]; const auto& r = b.Subresources; - if (!list_.barrier(leonida::TextureBarrier{ - 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)}) && - reject()) { + 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)}; + 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; + } + if (!list_.barrier(barrier) && reject()) { std::fprintf(stderr, "[rt] d3d12: texture barrier sync 0x%x->0x%x access 0x%x->0x%x layout %u->%u " "mips %u+%u layers %u+%u planes %u+%u flags 0x%x\n", @@ -1067,9 +1101,47 @@ class GraphicsCommandList final 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: @@ -1246,12 +1318,24 @@ class GraphicsCommandList final 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{}; @@ -1301,6 +1385,7 @@ class GraphicsCommandList final 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)) { @@ -1374,9 +1459,12 @@ class GraphicsCommandList final va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); else va = console_descriptor_table_va(va); - if (type != rt::rootsig::ParamType::Descriptor && va && p->table_descriptors && - (tables_.empty() || tables_.back().first != va)) - tables_.push_back({va, p->table_descriptors}); + if (type != rt::rootsig::ParamType::Descriptor && 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 console layouts a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps @@ -1405,6 +1493,7 @@ class GraphicsCommandList final 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_{}; @@ -1999,6 +2088,11 @@ class CommandQueue final 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). { @@ -2034,12 +2128,43 @@ class CommandQueue final } 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) { + // A table VA is an offset in this device's arena, so its own scanner reads it; the process-wide + // hook belongs to the first device that registered and serves a context without a scanner. + if (!context_.scan_table(table, descriptors)) + leonida::title_va_aliases().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) @@ -2338,6 +2463,11 @@ class CommandQueue final } // 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 093582415d..1a0a36c6b2 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -5,16 +5,19 @@ // 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 +#include + #include #include #include #include +#include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" #include "../src/vulkan_backend.h" @@ -33,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 @@ -70,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 { @@ -144,6 +157,8 @@ 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 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 @@ -168,6 +183,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; @@ -178,6 +194,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 @@ -246,6 +266,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. @@ -272,7 +294,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); @@ -432,14 +454,24 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H // pipelines still see their arguments 8 dwords early (D3D-448); // - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). // A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. +// LEONIDA_GRAPHICS_STAGE_LAYOUT=0 keeps rt::rootsig::pack() (from s0, two dwords per address) for every graphics +// signature instead of the console layout of the vertex, pixel and geometry stages described above. +// (The switch between the two packings is from the patch graphics-root-layout of +// Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b, author smg as "Codex", GPL-3.0.) +inline bool local_graphics_stage_layout() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_GRAPHICS_STAGE_LAYOUT"); return !(v && *v == '0'); }(); + return on; +} + struct RootArgumentLayout { struct Parameter { rt::rootsig::ParamType type; 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. + // A table: the slots its ranges declare, for the scan of title-written V#s before a submission + // (src/title_va_alias.h) and the submission-time heap refresh. Views are capped at 1024 slots (an unbounded + // range counts as 1024) and samplers at the shader-visible sampler heap limit. 0: not a table. std::uint32_t table_descriptors = 0; }; std::vector parameters; @@ -513,7 +545,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_com_object.h b/runtime/shims/d3d12_com_object.h index c7d46d775f..f1af871b11 100644 --- a/runtime/shims/d3d12_com_object.h +++ b/runtime/shims/d3d12_com_object.h @@ -25,6 +25,15 @@ template class Object : public Stubs { public: ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + // Adds a reference unless the count already reached zero (the object is being destroyed). For a caller that found + // the object through a registry it does not own a reference to; the registry entry must still be locked then. + bool try_add_ref() { + ULONG count = refs_.load(); + while (count) { + if (refs_.compare_exchange_weak(count, count + 1)) return true; + } + return false; + } ULONG STDMETHODCALLTYPE Release() override { const ULONG left = --refs_; if (!left) delete static_cast(this); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index a1ddc9b0ed..c272e03e97 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -8,6 +8,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_pipeline_compile.h" #include "d3d12_pipeline_checkpoint.h" @@ -23,10 +24,12 @@ #include "d3d12_title_buffer_windows.h" #include "d3d12_geometry_views.h" #include "d3d12_title_image_census.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" @@ -34,10 +37,12 @@ #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #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/dstorage_trace.h" #include "../src/title_page_watch.h" @@ -62,6 +67,7 @@ #endif #include +#include #include #include #include @@ -78,6 +84,7 @@ #include #include #include +#include #include #include #include @@ -95,12 +102,18 @@ constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read -constexpr std::uint32_t kQuadIndexCount = 64 * 1024; // 0, 1, 2, ... that non-indexed quad lists draw with (16384 quads) +constexpr auto kQuadIndicesPerQuad = std::uint32_t(leonida::quad_triangle_indices.size()); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); // pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); +// Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. +UINT64 align_up(UINT64 value, UINT64 to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered // to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this @@ -150,22 +163,6 @@ 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; - 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; - next = start + count; - if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); - } - return std::uint32_t(std::min(end, kUnbounded)); -} - // memcpy that a page fault ends instead of killing the process: the title may decommit a page between the // VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. // `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy @@ -1059,6 +1056,28 @@ ShadowPagesPtr make_shadow_pages(const std::uint8_t* pages, std::uint8_t* shadow return ShadowPagesPtr(tracker); } +// 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. +// The refresh of title-backed sampler tables (this count, the sampler entries of DeviceState::visible_heaps and the +// sampler-heap case of scan_title_table) is adapted from the patch sampler-table-refresh of +// Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b (author smg, as "Codex"), GPL-3.0; the +// descriptor mapping provider registered in set_device_outer is from its patch descriptor-write-through. +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 ? limit : range.num_descriptors; + next = start + count; + end = std::max(end, next); + } + return std::uint32_t(std::min(end, limit)); +} + // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a @@ -1389,23 +1408,30 @@ 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; bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU) bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32 - // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT - // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is - // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. - VkFormat uint_backed = VK_FORMAT_UNDEFINED; // An A8_UNORM render target stored as VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target): its RTVs render // to the alpha channel and its SRVs view it in that format, whose one channel the T# names as X (gfx10's // channels_a). Other A8_UNORM textures are R8_UNORM images. Vulkan puts A8 in a compatibility class of its own, // so one image cannot be viewed both ways. bool a8_as_alpha = false; + // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT + // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is + // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. + 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 @@ -1426,7 +1452,17 @@ constexpr Format rgb96_format(VkFormat wide, bool typeless = false) { // (and asserts when GetResourceAllocationInfo calls the description invalid). No D16S8 on the PC GPUs in reach, and // the PC has no such DXGI format: they are the D24_UNORM_S8_UINT family here, whose planes are viewed the same way // (depth as UNORM in X, stencil as UINT). Every entry point that takes a format from the title goes through this. -constexpr DXGI_FORMAT pc_format(DXGI_FORMAT format) { +// +// That holds where the GPU has D24_UNORM_S8_UINT as a depth-stencil attachment. Where it has none (AMD), the D24S8 +// family would itself be stored as D32_SFLOAT_S8_UINT, a third precision the title did not ask for; there the +// family is kept as it is and takes the D16/S8 path (Format::xbox_depth16_stencil8: D16_UNORM_S8_UINT where the GPU +// has it, else the first usable of D32_SFLOAT_S8_UINT and D24_UNORM_S8_UINT, with clears and stores quantised to +// 16 bits), which is the path an AMD card was measured on past the title's first frames. The device decides when it +// is created; LEONIDA_CONSOLE_D16S8=native or =d24 chooses for every GPU. Process-wide, like the title's one device. +std::atomic g_console_d16s8_native{false}; +inline bool console_d16s8_native() { return g_console_d16s8_native.load(std::memory_order_relaxed); } +inline DXGI_FORMAT pc_format(DXGI_FORMAT format) { + if (console_d16s8_native()) return format; switch (static_cast(format)) { case 118: return DXGI_FORMAT_D24_UNORM_S8_UINT; case 119: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS; @@ -1535,6 +1571,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: @@ -1770,16 +1809,20 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord struct TitleTexture; // a texture the title keeps in its own memory (TitleTexture, after Resource) // 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; // The blocks textures share (allocate_image). Freed after the context, whose deferred queue holds ranges of them. @@ -2140,10 +2183,30 @@ 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 @@ -2151,19 +2214,22 @@ struct DeviceState { void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { probe_table(table_va, descriptors); // LOCAL DIAGNOSTIC 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) rebase_title_vsharp(reinterpret_cast(arena.mapped + at), aliases); } @@ -3051,6 +3117,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); @@ -3085,6 +3154,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); @@ -3158,6 +3233,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. @@ -3311,7 +3394,9 @@ struct DeviceState { if (desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(VK_FORMAT_A4R4G4B4_UNORM_PACK16) && color_attachment_usable(VK_FORMAT_R8G8B8A8_UNORM)) { log_once("B4G4R4A4_UNORM render targets unavailable natively, using RGBA8; format", desc.Format); - return Format{VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; + Format backed{VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; + backed.rgba4_render_fallback = true; // clears are quantised to 4 bits a channel, as its draws are + return backed; } // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090 // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no @@ -3335,6 +3420,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); @@ -3461,17 +3556,43 @@ 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) { - namespace g = leonida::gfx10; std::lock_guard lock(descriptor_mutex); return bind_image_locked(words, image, vk_image, image_format, aspects, storage, allow_channel_cast, uint_backed); @@ -3487,27 +3608,7 @@ struct DeviceState { if (!pending->second.zero) return true; vk_image = pending->second.zero; } - const auto existing = image_entries.find(words); - if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; - - leonida::ImageDimension dimension; - switch (image.type) { - case g::ImageType::image_2d: dimension = leonida::ImageDimension::dim_2d; break; - case g::ImageType::image_2d_array: - 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_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: - log_once("set 0 has no array for this image type:", int(image.type)); - return false; - } 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)); - 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. @@ -3538,28 +3639,80 @@ struct DeviceState { view_format = image_format; channels_format = image_format; } + // A sampled view only samples: a view in a cast format the image's storage usage does not support (an R32 + // target viewed as E5B9G9R9) stays valid (VUID-VkImageViewCreateInfo-usage-02274). + const bool sampled_only = uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED); + return bind_image_views_locked(words, image, vk_image, view_format, channels_format, + uint_backed ? image_format : view_format, aspects, true, storage, {}, + sampled_only); + } + // The same for a view whose formats the caller has worked out: `view_format` of the sampled view (made when + // `sampled`), `channels_format` whose channels the T#'s swizzle selects from, `storage_format` of the storage view. + bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, + VkFormat view_format, VkFormat channels_format, VkFormat storage_format, + VkImageAspectFlags aspects, bool sampled, bool storage, VolumeSlices slices) { + std::lock_guard lock(descriptor_mutex); + return bind_image_views_locked(words, image, vk_image, view_format, channels_format, storage_format, aspects, + sampled, storage, slices, true); + } + bool bind_image_views_locked(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, + VkImage vk_image, VkFormat view_format, VkFormat channels_format, + VkFormat storage_format, VkImageAspectFlags aspects, bool sampled, bool storage, + VolumeSlices slices, bool sampled_only) { + namespace g = leonida::gfx10; + if (!bindless) { + if (storage) log_once("unordered-access view needs the Vulkan bindless set; type", int(image.type)); + return false; + } + if (const auto pending = pending_image_keys.find(vk_image); pending != pending_image_keys.end()) { + pending->second.keys.try_emplace(words, image); + if (!pending->second.zero) return true; + vk_image = pending->second.zero; + } + const auto existing = image_entries.find(words); + if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; + + leonida::ImageDimension dimension; + switch (image.type) { + case g::ImageType::image_2d: dimension = leonida::ImageDimension::dim_2d; break; + case g::ImageType::image_2d_array: + 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: + log_once("set 0 has no array for this image type:", int(image.type)); + return false; + } + 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(view_format)); + return false; + } 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}; + if (sampled_only) 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}; - // A sampled view only samples: a view in a cast format the image's storage usage does not support (an R32 - // target viewed as E5B9G9R9) stays valid (VUID-VkImageViewCreateInfo-usage-02274). - if (uint_backed || (view_format != image_format && view_format != VK_FORMAT_UNDEFINED)) { - 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 || @@ -3589,20 +3742,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); @@ -3631,7 +3795,7 @@ struct DeviceState { int(dimension), bindless->image_capacity(dimension), entries, per_texture.size(), most, replaced); } - 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; } @@ -3859,6 +4023,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; @@ -3875,7 +4044,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); @@ -3885,6 +4054,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]); @@ -3907,6 +4089,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; @@ -3938,6 +4121,7 @@ DXGI_FORMAT format_family(DXGI_FORMAT format) { // included) and nothing else. bool depth_stencil_family(DXGI_FORMAT format) { // The console's own D16S8 family (DXGI 118-120) counts as the D24S8 family it is made of here (pc_format). + if (format_family(format) == xbox_d16s8) return true; const DXGI_FORMAT family = format_family(pc_format(format)); return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; @@ -4105,8 +4289,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; @@ -4216,22 +4401,32 @@ class DescriptorHeap final 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 (console_addressed_) device_.probe_remove(console_address_); // LOCAL DIAGNOSTIC if (shadowed_) device_.remove_console_heap(console_address_); - 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); @@ -4255,6 +4450,11 @@ class DescriptorHeap final 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_; } // Where shaders read the heap: its arena copy for a console heap that has one (SetDescriptorHeaps' base). D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { @@ -4266,6 +4466,7 @@ class DescriptorHeap final 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; @@ -4277,11 +4478,29 @@ class DescriptorHeap final std::uint64_t console_shader_va_ = 0; }; +// 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) @@ -4293,7 +4512,34 @@ class Resource final 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_attachment_) 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 (title_texture_) device_.title_texture_gone(this, reinterpret_cast(title_address_)); if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { @@ -4339,9 +4585,15 @@ class Resource final bool host_initialized_image() const { return host_transfer_; } bool unbound_attachment() const { return deferred_attachment_ && !deferred_attachment_->bound(); } VkDeviceSize image_backing_bytes() const { return unbound_attachment() ? 0 : image_backing_bytes_; } + // A placed image whose memory waits for its first use (create_texture) gets it here. + bool ensure_texture_bound() const { return !deferred_attachment_ || deferred_attachment_->ensure(); } + VkImage bound_image() const { return descriptor_image(); } + // A deferred placed image with no memory yet, other than one that shows the shared zero image meanwhile. + bool deferrable_sample() const { return !shared_zero_ && unbound_attachment(); } 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 { @@ -4362,6 +4614,9 @@ class Resource final 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 unbound_attachment() ? 0 : memory_flags_; } // of its backing bool is_shadow() const { return shadow_ != nullptr; } // create_shadow_buffer: a copy of title pages const DeviceState& device_state() const { return device_; } @@ -4449,7 +4704,9 @@ class Resource final const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = desc_.Width; + // The indexed quad pass loads 16-bit indices from aligned 32-bit words. Keep the final word inside the + // Vulkan buffer while the D3D resource and views still use desc_.Width. + info.size = addressable || need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -4487,7 +4744,7 @@ class Resource final if (host) { if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) return E_OUTOFMEMORY; - std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed + std::memset(mapped_, 0, std::size_t(info.size)); // committed resources and private padding start zeroed } if (need_bda && vk.vkGetBufferDeviceAddress) { VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; @@ -4541,13 +4798,17 @@ class Resource final if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; const auto start = reinterpret_cast(address); if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + // Apply the same backing size rule to imports. The committed-range check and Vulkan bind requirements + // below cover the padding as well. The import never initializes or writes the caller's padding. + const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width; // The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the // title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090, // found in review), which an import of `address` itself would refuse. const std::uintptr_t base = start & ~static_cast(alignment - 1); void* const base_address = reinterpret_cast(base); const VkDeviceSize offset = start - base; - const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); + const VkDeviceSize bytes = align_up(offset + backing_size, alignment); // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback @@ -4576,11 +4837,10 @@ class Resource final at = region_end - base; } if (!importable) return E_NOTIMPL; - const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; - info.size = desc_.Width; + info.size = backing_size; info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | @@ -4598,7 +4858,7 @@ class Resource final return E_NOTIMPL; const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; // An offset off the buffer's own alignment cannot be bound: the fallback answers. - if (!types || (offset % requirements.alignment) || bytes < offset + requirements.size) return E_NOTIMPL; + if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset) return E_NOTIMPL; VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; import.pHostPointer = base_address; @@ -4893,7 +5153,15 @@ class Resource final 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()) { @@ -5021,7 +5289,13 @@ class Resource final const bool deferrable = desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - if (shared_zero_ || (defer_placed && origin == TitleImageOrigin::placed && deferrable && !cpu_visible())) { + // With pipelines and views prepared at bind time, a placed 2D texture that takes no host copies waits for + // its memory too, until a command or a sampled view first uses it. + const bool defer_sampled = device_.info.prepare_on_bind && origin == TitleImageOrigin::placed && + desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + !(desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && !host_transfer_; + if (shared_zero_ || defer_sampled || + (defer_placed && origin == TitleImageOrigin::placed && deferrable && !cpu_visible())) { vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); deferred_bytes_ = requirements.size; deferred_types_ = allowed; @@ -5121,6 +5395,15 @@ class Resource final } } leonida::ResourceBinding binding{}; + if (deferred_attachment_) { + 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; + }; + } 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 @@ -5128,6 +5411,8 @@ class Resource final 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); @@ -5270,10 +5555,65 @@ class Resource final } public: + // 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 @@ -5281,6 +5621,7 @@ class Resource final } 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) { @@ -5318,6 +5659,39 @@ class Resource final image_address_ = va; device_.note_image_address(image_address_, this); } + // 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) { + 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 @@ -5355,6 +5729,19 @@ class Resource final // 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 { + // A texture whose lease says its title memory is linear (title_linear_) and that also has a placement + // address (slot 133; the video planes among them) has two answers. The placement address, with the title + // texture registry filling the image, is the one the retail boot ran through the intro movie and the story + // load on, so it is asked first. LEONIDA_LINEAR_MAP_FIRST=1 gives such a texture the linear mapping instead + // (pinned pages, with a GPU-written texture read back into them), and its refusal when the pages are gone. + static const bool linear_first = [] { + const char* v = std::getenv("LEONIDA_LINEAR_MAP_FIRST"); + return v && *v == '1'; + }(); + if (linear_first && title_linear_ && data && image_) { + *data = nullptr; + return map_title_texture(subresource, read, data); + } if (image_ && title_address_) { // place_at_title_address: the console answers with the texture's memory if (data) *data = title_address_; // From now on the CPU may write its texels whenever it likes (video planes are mapped once): the @@ -5363,6 +5750,10 @@ class Resource final device_.title_texture_mapped(this, reinterpret_cast(title_address_)); return S_OK; } + if (title_linear_ && data && image_) { // a leased linear texture with no placement address + *data = nullptr; + return map_title_texture(subresource, read, data); + } if (image_) { VkImageSubresourceRange range{}; return !data && cpu_visible() && subresource != leonida::all_subresources && @@ -5377,9 +5768,25 @@ class Resource final } // A texture the title placed: Unmap ends its CPU writes (the title's lock passes the range it wrote), so its // image is filled again before the next submission (TitleTexture). - void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE* written) override { + void STDMETHODCALLTYPE Unmap(UINT sub, const D3D12_RANGE* written) override { if (image_ && title_address_ && title_texture_ && (!written || written->End > written->Begin)) device_.title_texture_unmapped(this, reinterpret_cast(title_address_)); + 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 @@ -5394,6 +5801,83 @@ class Resource final } 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; @@ -5619,6 +6103,8 @@ class Resource final DeviceState& device_; D3D12_RESOURCE_DESC desc_; + Resource* storage_ = nullptr; + bool title_image_registered_ = false; D3D12_HEAP_PROPERTIES heap_; D3D12_HEAP_FLAGS heap_flags_; VkImage image_ = VK_NULL_HANDLE; @@ -5652,6 +6138,8 @@ class Resource final 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 VkImage shared_zero_ = VK_NULL_HANDLE; // owned by the device std::unique_ptr deferred_attachment_; std::atomic replay_seen_{false}; @@ -5842,6 +6330,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: @@ -6121,7 +6686,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -6402,7 +6968,7 @@ class PipelineState final 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); } @@ -6431,11 +6997,26 @@ class PipelineState final 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; @@ -6465,9 +7046,25 @@ class PipelineState final 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 @@ -6588,13 +7185,15 @@ class PipelineState final // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of // the application's own. - const bool rect_list = !mesh && desc.PrimitiveTopologyType == leonida::topology_type_rect_list; + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; if (rect_list && (geometry || !device_.info.features.geometryShader)) { log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); return geometry ? E_INVALIDARG : E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -6633,6 +7232,14 @@ class PipelineState final // 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. @@ -6644,7 +7251,9 @@ class PipelineState final 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)); @@ -6652,7 +7261,7 @@ class PipelineState final } 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 const std::span raw_bytes{ @@ -6719,6 +7328,7 @@ class PipelineState final 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; @@ -6754,6 +7364,7 @@ class PipelineState final // again, the same way, and drops them once the pipeline exists. lazy_ = lazy_graphics_pipelines(); depth24_bias_ = depth24_bias; + rgba4_mask_ = packed_color_mask; // A stage that declares a storage image or buffer it may write needs a device feature outside compute // (src/spirv_stores.h). Without it the pipeline would be created all the same and break // VUID-RuntimeSpirv-NonWritable-06340 / -06341, so the PSO is refused here with the stage named. @@ -6770,6 +7381,10 @@ class PipelineState final pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); return stream_unsupported("graphics shader requires an unavailable storesAndAtomics feature"); } + const auto topology_bits = std::bit_cast(desc.PrimitiveTopologyType); + if (!mesh && topology_bits != leonida::topology_type_rect_list) + graphics_.rectangle_variant_topology = leonida::topology_rect_list; + for (Stage& stage : stages) { if (!stage.entry) continue; // After the f16 link above, which can also edit the pixel shader's words. @@ -6794,11 +7409,13 @@ class PipelineState final const bool patched = depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; sources_.push_back({StageSource::library, std::uint8_t(&stage - stages), patched, stage.entry}); } else { - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + 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_capable_ = true; + if (!lazy_) rectangle_vertex_ = modules_.back(); } VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; info.stage = stage.bit; @@ -6820,11 +7437,8 @@ class PipelineState final if (lazy_) { sources_.push_back({StageSource::rect_list}); } else { - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + 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; @@ -6840,11 +7454,8 @@ class PipelineState final if (lazy_) { sources_.push_back({StageSource::depth_only}); } else { - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); + 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; @@ -6911,12 +7522,12 @@ class PipelineState final } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. - switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -6938,7 +7549,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return stream_unsupported("target-independent rasterization; forced sample count", int(r.ForcedSampleCount)); @@ -7071,7 +7682,7 @@ class PipelineState final 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) { @@ -7159,8 +7770,13 @@ class PipelineState final recipe_.blends = std::move(blends); recipe_.blend = blend; if (!lazy_) { - graphics_.pipeline = build(0, "graphics-create"); - if (!graphics_.pipeline) return E_FAIL; + VkResult compile_status = VK_SUCCESS; + const bool cache_only = device_.info.cold_graphics_compile; + graphics_.pipeline = build(0, "graphics-create", + cache_only ? VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT : 0, + &compile_status); + // A cache-only create that the driver would have to compile stays null: the first draw builds it. + if (!graphics_.pipeline && !(cache_only && compile_status == VK_PIPELINE_COMPILE_REQUIRED)) return E_FAIL; } // lazy: graphics_.pipeline stays null and the first draw builds it as variant 0 graphics_.async_build = async_replay_compile(); graphics_.variant = [this](std::uint32_t unbound) { @@ -7330,7 +7946,6 @@ class PipelineState final } else if (!build_compute("compute-create")) { return E_FAIL; } - // 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). if (entry->uses_code_base || !entry->code_base_known) { @@ -7520,7 +8135,8 @@ class PipelineState final }; // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. - VkPipeline build(std::uint32_t unbound, const char* trigger) { + VkPipeline build(std::uint32_t unbound, const char* trigger, VkPipelineCreateFlags flags = 0, + VkResult* status = nullptr) { CompileActivity activity(device_.active_compiles); const Recipe& r = recipe_; std::vector colors = graphics_.color_formats; @@ -7594,8 +8210,8 @@ class PipelineState final const auto drop_modules = [&] { for (VkShaderModule module : made) device_.context->vk.vkDestroyShaderModule(device_.info.device, module, nullptr); }; + std::vector> words; if (lazy_) { - std::vector> words; std::string why; if (!stage_words(words, why) || words.size() != r.stages.size()) { std::fprintf(stderr, "[rt] d3d12: a pipeline built at its first draw lost its SPIR-V: %s\n", @@ -7620,8 +8236,58 @@ class PipelineState final } } VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = lazy_ ? stages.data() : r.stages.data(); + // A triangle-family pipeline drawn as a rectangle list: the same stages plus the generated geometry stage. + std::vector rectangle_stages; + if (unbound & leonida::GraphicsPipeline::rectangle_stage) { + VkShaderModule rectangle = VK_NULL_HANDLE; + if (!rectangle_capable_) { + drop_modules(); + return VK_NULL_HANDLE; + } + if (lazy_) { + std::size_t vs = SIZE_MAX; + for (std::size_t i = 0; i < sources_.size(); ++i) + if (sources_[i].kind == StageSource::library && sources_[i].slot == 0) vs = i; + std::string why; + const std::vector geometry_words = + vs == SIZE_MAX ? std::vector{} : leonida::rect_list_geometry(words[vs], why); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = geometry_words.size() * 4; + module_info.pCode = geometry_words.data(); + if (geometry_words.empty() || + device_.context->vk.vkCreateShaderModule(device_.info.device, &module_info, nullptr, &rectangle) != + VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); + drop_modules(); + return VK_NULL_HANDLE; + } + made.push_back(rectangle); + bytes += module_info.codeSize; + rectangle_stages = stages; + } else { + if (!rectangle_vertex_) return VK_NULL_HANDLE; + if (!rectangle_module_) { + std::string why; + const auto geometry_words = leonida::rect_list_geometry(rectangle_vertex_->words, why); + if (geometry_words.empty()) { + std::fprintf(stderr, "[rt] d3d12: cannot draw rectangle list: %s\n", why.c_str()); + return VK_NULL_HANDLE; + } + rectangle_module_ = shader_module(geometry_words); + if (!rectangle_module_) return VK_NULL_HANDLE; + } + rectangle = rectangle_module_; + rectangle_stages = r.stages; + } + VkPipelineShaderStageCreateInfo geometry{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + geometry.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + geometry.module = rectangle; + geometry.pName = "main"; + rectangle_stages.push_back(geometry); + } + const auto& pipeline_stages = !rectangle_stages.empty() ? rectangle_stages : lazy_ ? stages : r.stages; + info.stageCount = std::uint32_t(pipeline_stages.size()); + info.pStages = pipeline_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; @@ -7630,6 +8296,7 @@ class PipelineState final info.pDepthStencilState = &r.depth; info.pColorBlendState = &blend; info.pDynamicState = &dynamic; + info.flags=flags; info.layout = graphics_.layout; VkPipeline pipeline = VK_NULL_HANDLE; const auto cache = device_.pipeline_cache(); @@ -7646,10 +8313,13 @@ class PipelineState final const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); + if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); - if (result != VK_SUCCESS) + if (result != VK_SUCCESS) { + if (pipeline) device_.context->vk.vkDestroyPipeline(device_.info.device, pipeline, nullptr); pipeline = VK_NULL_HANDLE; + } drop_modules(); if (pipeline) maybe_checkpoint(cache); return pipeline; @@ -7675,6 +8345,10 @@ class PipelineState final why = source.entry->name + ".spv is missing or not SPIR-V"; return false; } + if (source.slot == 2 && rgba4_mask_ && !leonida::rgba4::quantize(words[i], rgba4_mask_)) { + why = source.entry->name + " could not be quantised for a B4G4R4A4 target stored as RGBA8"; + return false; + } if (source.slot == 0) vs = i; if (source.slot == 2) ps = i; } @@ -7736,6 +8410,7 @@ class PipelineState final bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked leonida::Depth24Bias depth24_bias_{}; + unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for std::vector sources_; struct Request { VkPipeline handle{}; unsigned long long skips = 0; }; using Requests = std::map; @@ -7745,12 +8420,28 @@ class PipelineState final std::mutex variants_mutex_; std::map variants_; VkShaderModule module_ = VK_NULL_HANDLE; - std::vector modules_; + std::vector modules_; + leonida::GraphicsShaderModules::Reference rectangle_vertex_; + VkShaderModule rectangle_module_ = VK_NULL_HANDLE; + bool rectangle_capable_ = false; // graphics: a vertex stage the rectangle-list geometry stage can follow + 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_; }; @@ -7778,6 +8469,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; @@ -8397,11 +9113,16 @@ TitleImage bind_title_image(DeviceState& device, const leonida::gfx10::ImageWord return TitleImage::bound; } -bool image_descriptor(const Resource& resource, const TextureView& asked, leonida::gfx10::Image& out) { +bool image_descriptor(const Resource& resource, const TextureView& asked, bool storage, leonida::gfx10::Image& out, + VkFormat& view_format, DeviceState::VolumeSlices& slices) { TextureView view = asked; view.format = pc_format(view.format); // the console's D16S8 plane views as D24S8's 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. @@ -8413,6 +9134,7 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid // 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 && @@ -8421,13 +9143,15 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid 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; } @@ -8451,7 +9175,7 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid // 4_4_4_4 as on the console, and bind_image views the RGBA8 image with the 4444 view's channels. const bool rgba8_4444 = desc.Format == DXGI_FORMAT_B4G4R4A4_UNORM && resource.format() == VK_FORMAT_R8G8B8A8_UNORM; if (rgba8_4444) named = VK_FORMAT_A4R4G4B4_UNORM_PACK16; - 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) @@ -8470,6 +9194,7 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid 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) || @@ -8487,7 +9212,16 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid 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; @@ -8513,8 +9247,8 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid } } // 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; @@ -8523,34 +9257,48 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid 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 || (rgba8_4444 ? named != VK_FORMAT_A4R4G4B4_UNORM_PACK16 : !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 && rgba8_4444) { view_format = resource.format(); } 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; } @@ -8564,8 +9312,13 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid 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; @@ -8583,7 +9336,8 @@ bool image_descriptor(const Resource& resource, const TextureView& asked, leonid // 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; @@ -8778,6 +9532,8 @@ class Device final 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( @@ -8803,6 +9559,23 @@ class Device final state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); state_.bgra8_srgb_uav_emulated = state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); + { + // The console's D16S8 family (pc_format): as D24S8 where the GPU has that format, as itself where not. + const char* asked = std::getenv("LEONIDA_CONSOLE_D16S8"); + const bool d24 = state_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); + const bool native = asked && std::strcmp(asked, "native") == 0 ? true + : asked && std::strcmp(asked, "d24") == 0 ? false + : !d24; + g_console_d16s8_native.store(native, std::memory_order_relaxed); + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12: console D16S8 textures are %s (D24_UNORM_S8_UINT attachments: %s, " + "D16_UNORM_S8_UINT: %s%s)\n", + native ? "kept as D16+S8" : "made as D24S8", d24 ? "yes" : "no", + state_.depth_usable(VK_FORMAT_D16_UNORM_S8_UINT) ? "yes" : "no", + asked ? ", LEONIDA_CONSOLE_D16S8 set" : ""); + } if (console_format_stand_ins()) { state_.r9g9b9e5_target_stand_in = !state_.color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) && state_.color_attachment_usable(VK_FORMAT_B10G11R11_UFLOAT_PACK32) && @@ -8934,6 +9707,39 @@ class Device final free(device, block, nullptr); }); state_.context->mesh_queries = info.mesh_shader_queries; + 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 state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( @@ -9017,16 +9823,23 @@ class Device final if (info.host_pointer_alignment) state_.get_host_pointer_properties = reinterpret_cast( get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); - // 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); - }); + // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. With buffer + // device addresses the same scratch holds the triangle indices of indexed quad lists (quad_index_expand.h): + // a compute pass writes them through the chunk's address and the draw binds the chunk as its index buffer. + const bool index_scratch = info.buffer_device_address; + state_.context->enable_copy_scratch( + get_device, + [this, index_scratch](const VkMemoryRequirements& requirements) { + return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, index_scratch); + }, + index_scratch ? VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0, 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"))) { VkPhysicalDeviceProperties props{}; get_props(info.physical, &props); state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); + state_.context->configure_quad_indices(get_device, props.limits); } } // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of @@ -9210,7 +10023,7 @@ class Device final "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, - descriptor_hash); + descriptor_hash, state_.families); if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { state_.bindless.reset(); return false; @@ -9382,9 +10195,11 @@ class Device final } arena.mapped = static_cast(mapped); std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read - { - auto* iota = reinterpret_cast(arena.mapped + kZeroPage); - for (std::uint32_t i = 0; i < kQuadIndexCount; ++i) iota[i] = i; + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; @@ -9399,10 +10214,41 @@ class Device final leonida::fsdraw::note_arena(arena.mapped, arena.size); // LOCAL DIAGNOSTIC state_.context->set_zero_page(arena.buffer, 0, kZeroPage); state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + // 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 { + raw_images_.clear(); leonida::title_va_aliases().clear_hooks(&state_); { std::lock_guard lock(state_.title_window_mutex); @@ -9463,6 +10309,100 @@ class Device final 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. @@ -9569,7 +10509,7 @@ class Device final v.format = uav.Format; v.first_mip = volume.MipSlice; v.mip_count = 1; - write_image_descriptor(r, v, dest, true); + write_image_descriptor(r, v, dest, ImageViewUse::storage); } else { CreateUnorderedAccessView(&r, nullptr, &uav, dest); } @@ -9957,7 +10897,7 @@ class Device final void* made = nullptr; const HRESULT hr = create_committed(&heap, D3D12_HEAP_FLAG_NONE, &pc, D3D12_RESOURCE_STATE_COMMON, formats.size() > 1 ? UINT32(formats.size()) : 0, formats.data(), - __uuidof(ID3D12Resource), &made, origin); + __uuidof(ID3D12Resource), &made, std::nullopt, origin); Resource* r = SUCCEEDED(hr) && made ? Resource::from(static_cast(made)) : nullptr; if (!r) { if (made) static_cast(made)->Release(); @@ -10257,6 +11197,164 @@ class Device final void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } + // The buffer resource holding console VA `va`, with a reference added for the caller, or null when no resource this + // layer made holds it. `start` and `size` are the resource's first VA and byte size. + // Only this layer's own buffers have a VA in the registry (the swapchain's are images, a copy's staging binding has + // no VA), so an ID found by VA is the ID3D12Resource pointer of a Resource (resource_id). + ID3D12Resource* add_ref_buffer_at(std::uint64_t va, std::uint64_t bytes, std::uint64_t& start, std::uint64_t& size) { + leonida::ResourceId id = 0; + ID3D12Resource* found = nullptr; + const bool ok = state_.context->buffer_resource_at(va, bytes, id, start, size, [&](leonida::ResourceId candidate) { + auto* resource = static_cast(reinterpret_cast(candidate)); + if (!resource->try_add_ref()) return false; + found = resource; + return true; + }); + 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 @@ -10768,9 +11866,12 @@ class Device final // pixel shaders (s8, one dword per table) where it fits without a spill and keeps pack() otherwise, compute // the console layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); - const rt::rootsig::StagePackResult pixel = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Pixel); + // LEONIDA_GRAPHICS_STAGE_LAYOUT=0 keeps pack() for every graphics signature. + const rt::rootsig::StagePackResult pixel = + local_graphics_stage_layout() ? rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Pixel) + : rt::rootsig::StagePackResult{}; const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); - if (!pixel.ok && packed.ok) { + if (!pixel.ok && packed.ok && local_graphics_stage_layout()) { static std::atomic kept{0}; const unsigned n = ++kept; if (n == 1 || (n & (n - 1)) == 0) @@ -10809,7 +11910,7 @@ class Device final } 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( @@ -11047,6 +12148,8 @@ class Device final 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. @@ -11205,6 +12308,10 @@ class Device final // 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; ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateConstantBufferView"}; // LOCAL DIAGNOSTIC @@ -11212,10 +12319,13 @@ class Device final 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); leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); // The console's constant-buffer V# is a table of 16-byte rows: the title's own inline form of this descriptor @@ -11345,7 +12455,9 @@ class Device final log_once("shader-resource view denied by resource flags; format", int(r->desc().Format)); return; } - if (!r->descriptor_image()) { + // A placed texture whose memory waits for its first use is a texture all the same, and asking for its image + // would bind that memory here, before write_image_descriptor can remember the view (prepare_on_bind). + if (!r->deferrable_sample() && !r->descriptor_image()) { if (!desc) { log_once("buffer SRV requires a description; width", int(r->desc().Width)); return; @@ -11431,7 +12543,7 @@ class Device final return; } } - write_image_descriptor(*r, view, destination, false); + write_image_descriptor(*r, view, destination, ImageViewUse::sampled); // LOCAL DIAGNOSTIC: the texture SRVs the title makes, where they go and the T# they get if (leonida::local_diagnostics()) { static std::atomic made{0}; @@ -11560,60 +12672,99 @@ class Device final ProbeApiWrite probe_note{state_, destination.ptr, 1, "CreateUnorderedAccessView"}; // LOCAL DIAGNOSTIC 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()); } @@ -11864,15 +13015,23 @@ class Device final 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. @@ -12068,7 +13227,7 @@ class Device final ID3D12Resource* made = nullptr; const HRESULT hr = create_at_host_address(reinterpret_cast(static_cast(start)), desc, 0xFFFFFFFFu, __uuidof(ID3D12Resource), - reinterpret_cast(&made)); + reinterpret_cast(&made), nullptr); if (FAILED(hr) || !made) { log_once("a buffer over the title's memory for a vertex or index view could not be made; HRESULT", int(hr)); return; @@ -12088,7 +13247,7 @@ class Device final std::uint64_t title_buffer_bytes_ = 0; 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 cannot be placed on the title's pages (the PC GPU does not sample the console layout): it gets @@ -12134,19 +13293,19 @@ class Device final const UINT32 cast_count = r32 && (made.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && made.SampleDesc.Count == 1 ? 2 : 0; HRESULT hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, - cast_count, castable, riid, out, TitleImageOrigin::placed); + cast_count, castable, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && cast_count) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, initial, nullptr, 0, - nullptr, riid, out, TitleImageOrigin::placed); + nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) hr = create_committed_validated(nullptr, heap, D3D12_HEAP_FLAG_NONE, &made, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, TitleImageOrigin::placed); + D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); if (FAILED(hr) && heap != &fallback) { log_once("a title-placed texture the GPU does not write could not be made on a host-copied heap; " "format", made.Format); hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &made, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, TitleImageOrigin::placed); + D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out, std::nullopt, TitleImageOrigin::placed); } if (SUCCEEDED(hr) && out && *out) { // The interface handed out is the Resource itself (hand_out); ask it back and tell it its address. @@ -12160,6 +13319,7 @@ class Device final }(); texture->place_at_title_address(address, distinct && gpu_written); register_title_texture(texture, reinterpret_cast(address)); + texture->set_title_address(reinterpret_cast(address)); } made->Release(); } @@ -12214,7 +13374,8 @@ class Device final 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)); } @@ -12519,7 +13680,7 @@ class Device final : 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, @@ -12895,7 +14056,7 @@ class Device final // 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) && !(rt::d3d12_xs::console_feature_query() && 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) { @@ -12906,14 +14067,15 @@ class Device final // 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{}; @@ -12934,6 +14096,7 @@ class Device final // 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) { @@ -13012,7 +14175,7 @@ class Device final } 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 | @@ -13030,6 +14193,8 @@ class Device final 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; } @@ -13142,7 +14307,7 @@ class Device final // 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 || (rt::d3d12_xs::console_feature_query() && 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); @@ -13319,9 +14484,9 @@ class Device final static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; - // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. - static UINT64 align_up(UINT64 value, UINT64 to) { - 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 @@ -13333,8 +14498,14 @@ class Device final 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)); - if (!failed && one.SizeInBytes == UINT64_MAX) log_refused_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); + if (one.SizeInBytes == UINT64_MAX) log_refused_allocation(get(i)); + } failed = failed || one.SizeInBytes == UINT64_MAX; if (failed) { if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; @@ -13369,6 +14540,12 @@ class Device final } D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& asked) const { + if (xbox_depth_storage_desc(asked) && outer_ && rt::d3d12_xs::is_device_proxy(outer_)) { + const auto depth = allocation(depth_storage_part(asked, false)); + const auto colour = allocation(depth_storage_part(asked, 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)}; + } D3D12_RESOURCE_DESC desc = asked; desc.Format = pc_format(desc.Format); // the console's D16S8 family as D24S8 return allocation_of(desc); @@ -13525,18 +14702,87 @@ class Device final 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.descriptor_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)); resource.note_shader_view(); } @@ -13547,10 +14793,28 @@ class Device final 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, + std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { 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") @@ -13569,7 +14833,8 @@ class Device final int(desc->Dimension)); return finish(E_INVALIDARG); } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, origin)); + return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out, + storage_heap_flags, origin)); } // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list @@ -13579,6 +14844,7 @@ class Device final 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, + std::optional storage_heap_flags = std::nullopt, TitleImageOrigin origin = TitleImageOrigin::ordinary) { if (out) *out = nullptr; if (!heap || !desc) return E_INVALIDARG; @@ -13626,9 +14892,10 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, desc->Format, castable_count, castable, 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, origin); 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)) { @@ -13803,8 +15070,6 @@ class Device final 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 = @@ -13857,7 +15122,18 @@ class Device final 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 @@ -13882,22 +15158,96 @@ 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; + // 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); d->set_outer(outer); - // Second job, for an outer that is the Xbox-ABI proxy: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands + // Another job for an outer that is the Xbox-ABI proxy: its device slot 70 names a buffer by console VA only, and + // this finds the layer's resource for it. + if (rt::d3d12_xs::is_device_proxy(outer)) + rt::d3d12_xs::set_device_resource_provider( + outer, [](ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, std::uint64_t* start, + std::uint64_t* size) -> ID3D12Resource* { + Device* device = Device::from(real); + return device ? device->add_ref_buffer_at(va, bytes, *start, *size) : nullptr; + }); + // And for the same outer: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands // 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)); @@ -13918,13 +15268,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) { @@ -13965,7 +15315,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) { @@ -14024,13 +15374,13 @@ TitleShadowWatch title_shadow_watch(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) { @@ -14690,10 +16040,23 @@ 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"; + 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}; @@ -14862,13 +16225,26 @@ 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; }); }; info.depth_range_unrestricted = has_device_extension(VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME); + 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)) { @@ -14927,6 +16303,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 @@ -14966,16 +16355,17 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin enable.multiViewport = chosen_features.multiViewport; 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; @@ -15076,6 +16466,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); @@ -15087,6 +16478,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 264b32a489..3bad45d284 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -23,11 +23,15 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/title_va_alias.h" #include "d3d12_xs_device.h" #ifdef LEONIDA_VULKAN_DEVICE #include "d3d12_com.h" // rt::d3d12::create_console_descriptor_heap for slot 14 +#include "../src/vulkan_gpu_labels.h" #endif +#include "d3d12_xs_placed_depth.h" #include "d3d12_trace.h" +#include "../src/native_pso.h" #include "xmem.h" // rt::xmem::copy_page_mappings_fn for queue slot 31 #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" @@ -50,6 +54,7 @@ #include #include +#include #include #include #include @@ -85,6 +90,9 @@ std::atomic g_reference_settler{nullptr}; // Commits the title's pages before slot 133 imports them or slot 14 checks them (set_placed_at_va_pages_hook; gta6rt // registers xmem's commit_physical_range, which leaves memory other than mapped physical pages alone). std::atomic g_placed_at_va_pages{nullptr}; +std::atomic g_pin_texture_pages{nullptr}; +// True while this thread forwards a console caller's CheckFeatureSupport (device slot 13). +thread_local bool g_console_feature_query = false; static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, @@ -114,6 +122,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 = nullptr; // slot 70: a buffer by console VA + 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; @@ -122,10 +140,12 @@ 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::shared_ptr frame_tokens = std::make_shared(); // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock). SRWLOCK presentation_lock = SRWLOCK_INIT; PresentationHandler presentation{}; + bool external_presentation_mode = false; // protected by presentation_lock, including after an explicit detach }; // Runs f(handler) with the presentation lock held shared, so a detach cannot destroy the presentation mid-call. f @@ -166,6 +186,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; }; @@ -193,12 +215,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&) { @@ -233,6 +256,122 @@ D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_handle(const DeviceProxy* device, D3D1 return handle; } +// LOCAL (title-backed descriptor heaps): the title copies descriptors between its heaps' backing memory itself, with +// no API call, so (1) every descriptor the layer writes for a title-backed slot is also stored at the title's address, +// and (2) when a table is bound, what the title wrote at that table's address is carried into the real heap. +// LEONIDA_DESC_MIRROR=0 turns both off. +// Adapted from the patches descriptor-write-through (1) and descriptor-table-refresh (2) of +// Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b (author smg, as "Codex"), GPL-3.0: the functions +// from here to local_mirror_table, DescriptorRange's stride and mapped fields and local_real_gpu_start. +constexpr SIZE_T kLocalDescriptorBytes = 32; +constexpr SIZE_T kLocalMirrorSlots = 64; + +bool local_desc_mirror() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_DESC_MIRROR"); return !(v && *v == '0'); }(); + return on; +} + +// Whether [address, address + bytes) is committed memory that can be read (and, with `write`, written). A handle +// that is only a number (a mock's, or a range the title has released) is left alone instead of faulting. +bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { + const std::uint64_t end = address + bytes; + if (!address || end < address) return false; + while (address < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + const DWORD protect = info.Protect & 0xff; + if (info.Protect & PAGE_GUARD) return false; + const bool writable = protect == PAGE_READWRITE || protect == PAGE_WRITECOPY || + protect == PAGE_EXECUTE_READWRITE || protect == PAGE_EXECUTE_WRITECOPY; + const bool readable = writable || protect == PAGE_READONLY || protect == PAGE_EXECUTE_READ; + if (write ? !writable : !readable) return false; + address = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + +void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { + if (!local_desc_mirror() || !custom.ptr || !count) return; + 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; + } +} + +// 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); + +void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { + if (!local_desc_mirror() || !gpu_handle || g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + if ((device && range.device != device) || !range.heap) continue; + const std::uint64_t gpu_start = local_real_gpu_start(range.heap).ptr; + const std::uint64_t bytes = range.custom_end - range.custom_start; + 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); + 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 " + "title's backing memory\n", static_cast(offset), + static_cast(copied), static_cast(slots)); + return; + } +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -303,6 +442,7 @@ const char* slot_name(unsigned slot) { case 50: return "EnqueueMakeResident (proxies unwrapped)"; case 53: return "CreateCommittedResource1 (initial state mapped)"; 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 (a host caller gets PC CreateMetaCommand)"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; @@ -738,6 +878,15 @@ D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { return handle.ptr != kUnset ? handle : returned; } +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap) { + constexpr UINT64 kUnset = ~static_cast(0); + D3D12_GPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = kUnset; + using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); + const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(heap->real_vtable[10])(heap->real, &handle); + return handle.ptr != kUnset ? handle : returned; +} + template std::uint64_t WINAPI heap_slot(HeapProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -784,7 +933,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; @@ -803,7 +952,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; @@ -1440,6 +1589,18 @@ HWND create_fallback_window(bool show) { return thread ? start.window : nullptr; } +// Device slots 78 to 81 answer from the device's token counter, with no wait: that is what the retail boot was +// measured with through the story load. LEONIDA_FRAME_PACING=1 (the --first-run-ui profile sets it) hands them to +// the device's own presentation once the first PresentX has built it, with the title's interval and origin event +// replayed to its pacer; without that replay the next WaitFrameEventX would fail. +bool frame_pacing_enabled() { + static const bool enabled = [] { + const auto* p = std::getenv("LEONIDA_FRAME_PACING"); + return p && *p && *p != '0'; + }(); + return enabled; +} + // 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. // @@ -1471,6 +1632,15 @@ PresentState* present_state_for(DeviceProxy* device, bool splash_only = false) { PresentState* state = pending.get(); if (!splash_only) device->present_state = pending.release(); const bool titles = target != nullptr; + // LOCAL: LEONIDA_WINDOW=WxH resizes the title's window without waiting on its thread (SWP_ASYNCWINDOWPOS). + if (titles) { + if (const char* size = std::getenv("LEONIDA_WINDOW")) { + int w = 0, h = 0; + if (std::sscanf(size, "%dx%d", &w, &h) == 2 && w > 0 && h > 0) + SetWindowPos(target, nullptr, 0, 0, w, h, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_ASYNCWINDOWPOS); + } + } if (!target) { state->window = create_fallback_window(!hidden); target = state->window; @@ -1494,7 +1664,23 @@ PresentState* present_state_for(DeviceProxy* device, bool splash_only = false) { // The title takes its frame tokens from device slot 80 (WaitFrameEventX), which numbers them from the device's // FrameTokenSource. The pacer refuses a token above the ones its source issued, so it must count from the same // source: with a pacer-owned one every PresentX after the first wait is refused with E_INVALIDARG (#7496, #7685). - state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + // With LEONIDA_FRAME_PACING=1 the pacer also answers a zero-timeout origin wait with the newest passed origin + // (current_origin_poll), as the tree that paced these slots was measured; otherwise it is the pacer as it was. + state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens, + frame_pacing_enabled()); + // 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 && frame_pacing_enabled()) { + 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)); + } if (splash_only) device->present_state = pending.release(); std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p: %s, client area %ldx%ld)\n", static_cast(target), @@ -1503,6 +1689,13 @@ PresentState* present_state_for(DeviceProxy* device, bool splash_only = false) { return state; } +rt::d3d12::XboxPresentation* device_presentation(DeviceProxy* device) { + if (!frame_pacing_enabled()) return nullptr; + std::lock_guard lock(device->present_state_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) { PresentState* state = self->device ? present_state_for(self->device) : nullptr; @@ -1789,7 +1982,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ newer && !qroutes.present_x_set ? qroutes.present_x + 2 : qroutes.present_x; if (Slot >= self->slot_count) { HRESULT hr = S_OK; + bool external_queue = false; if (call_presentation(self->device, [&](const PresentationHandler& p) { + external_queue = self->device->external_presentation_mode; if (Slot == present_x_slot && p.present_x) { hr = p.present_x(p.context, static_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3)); @@ -1806,7 +2001,18 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return false; })) return hr_to_u64(hr); - if (Slot == present_x_slot) return queue_present_x(self, a1, a2, a3); + // An explicitly managed queue has no fallback after detachment. An unmapped + // presentation slot cannot silently open a second window or acknowledge a suspend. + if (external_queue && ((Slot >= 30 && Slot <= 32) || Slot == present_x_slot || + Slot == qroutes.suspend_x || Slot == qroutes.resume_x)) + return hr_to_u64(E_NOTIMPL); + if (Slot == present_x_slot) { + const std::uint64_t presented = queue_present_x(self, a1, a2, a3); + // LOCAL: one trace line per present, so a run's presents can be counted. + d3d12_trace::record("XboxID3D12CommandQueue::PresentX", + static_cast(presented) < 0 ? "failed" : "ok"); + return presented; + } } if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { d3d12_trace::record(child_trace_name(Slot), "console-only"); @@ -2307,6 +2513,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 } @@ -2328,6 +2546,8 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto** const real_vtable = *reinterpret_cast(self->real); + // LOCAL: console SetComputeRootDescriptorTable (35) and SetGraphicsRootDescriptorTable (36) + if constexpr (Slot == 35 || Slot == 36) local_mirror_table(self->device, a2); if constexpr (pc == 10) { // Reset(allocator, pso): console slot 10, and slot 139 as the retail title calls it. The title hands // its allocator proxy; the real list takes the real one (and a wrapped pipeline state the same way). @@ -2616,6 +2836,11 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std: return hr; 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; } @@ -2630,7 +2855,13 @@ HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std return true; })) return hr; + 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; } @@ -2648,6 +2879,11 @@ HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::ui })) return hr; if (!token) return E_POINTER; +#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; } @@ -2726,6 +2962,114 @@ struct PlacedViewCounts { }; PlacedViewCounts g_placed_views[2]; // SRV, UAV +// The providers a shader-resource view of slot 70 asks when the placed-memory path below wrote nothing. +// +// The one measured shape (PR 7066, eugen1763, first retail call) is a raw buffer view: texture_words starts with a +// desktop D3D12_RESOURCE_DESC (buffer), view_desc with a desktop D3D12_SHADER_RESOURCE_VIEW_DESC (R32_TYPELESS, +// BUFFER, RAW flag) followed at once by a D3D12_GPU_VIRTUAL_ADDRESS, the console VA slot 133 registered. For that shape +// and a VA inside a buffer the resource provider knows, the destination gets a raw view of that range: FirstElement +// (va - resource start) / 4, NumElements the description's Width / 4, cut to the end of the resource. A 2D texture +// shape goes to the raw texture view provider. Anything else (another dimension or format, no RAW flag, a VA no buffer +// holds, no provider, unreadable words) writes nothing, with one log line saying why. +struct RawSrvShape { + D3D12_RESOURCE_DESC resource; + D3D12_SHADER_RESOURCE_VIEW_DESC view; + D3D12_GPU_VIRTUAL_ADDRESS va; +}; + +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; + if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return false; + const auto end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + return address + bytes <= end; +} + +// Reads the measured shape from the two words into `out`. Returns null when it parsed, else why it is not that shape. +const char* parse_raw_srv(std::uint64_t texture_words, std::uint64_t view_desc, RawSrvShape& out) { + if (!readable(texture_words, sizeof(D3D12_RESOURCE_DESC)) || + !readable(view_desc, sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) + sizeof(D3D12_GPU_VIRTUAL_ADDRESS))) + return "the words are not readable"; + std::memcpy(&out.resource, reinterpret_cast(texture_words), sizeof(out.resource)); + std::memcpy(&out.view, reinterpret_cast(view_desc), sizeof(out.view)); + std::memcpy(&out.va, reinterpret_cast(view_desc) + sizeof(out.view), sizeof(out.va)); + if (out.resource.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return "arg1 is not a buffer description"; + if (out.view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return "arg2 is not a buffer view"; + if (out.view.Format != DXGI_FORMAT_R32_TYPELESS || !(out.view.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW)) + return "arg2 is not a raw R32_TYPELESS view"; + if (!out.resource.Width || !out.va) return "no width or no address"; + return nullptr; +} + +void log_slot70_null_once(const char* why, std::uint64_t texture_words, std::uint64_t view_desc) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 70 writes a null view: %s (args 0x%llx 0x%llx)\n", why, + static_cast(texture_words), static_cast(view_desc)); +} + +// True when a view was written to `destination` (the real heap's handle; `title_slot` is the handle the title gave). +bool create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, std::uint64_t view_desc, + D3D12_CPU_DESCRIPTOR_HANDLE title_slot, SIZE_T destination) { + 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 true; + } + if (why || !self->resource_provider) { + log_slot70_null_once(why ? why : "no resource provider", texture_words, view_desc); + return false; + } + std::uint64_t start = 0, size = 0; + ID3D12Resource* resource = self->resource_provider(self->real, shape.va, shape.resource.Width, &start, &size); + if (!resource || shape.va < start || shape.va - start >= size) { + if (resource) resource->Release(); + // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, + // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. + static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); + std::uint64_t title_lo = 0, title_hi = 0; + if (title_views && shape.resource.Width && shape.resource.Width <= 65536 && + leonida::title_va_aliases().title_memory(shape.va, title_lo, title_hi) && + shape.resource.Width <= title_hi - shape.va) { + D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; + constants.BufferLocation = shape.va; + constants.SizeInBytes = static_cast(shape.resource.Width); + self->real->CreateConstantBufferView(&constants, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: slot 70 view over title memory (%llu bytes) written as a raw " + "buffer V# on its GPU copy\n", static_cast(shape.resource.Width)); + return true; + } + log_slot70_null_once("no buffer holds the address", texture_words, view_desc); + return false; + } + const std::uint64_t offset = shape.va - start; + const std::uint64_t elements = std::min(shape.resource.Width, size - offset) / 4; + if (offset % 4 || !elements || elements > UINT32_MAX) { + resource->Release(); + log_slot70_null_once("address or width is not 4-byte aligned or too large", texture_words, view_desc); + return false; + } + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Shader4ComponentMapping = shape.view.Shader4ComponentMapping; + view.Buffer.FirstElement = offset / 4; + view.Buffer.NumElements = static_cast(elements); + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + self->real->CreateShaderResourceView(resource, &view, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + resource->Release(); + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 70 wrote a raw buffer view (va 0x%llx, first element %llu, %u elements)\n", + static_cast(shape.va), static_cast(view.Buffer.FirstElement), + view.Buffer.NumElements); + return true; +} + void proxy_create_placed_view_x(DeviceProxy* self, bool unordered, std::uint64_t resource_words, std::uint64_t view_words, std::uint64_t destination) { const unsigned slot = unordered ? 71 : 70; @@ -2734,6 +3078,12 @@ void proxy_create_placed_view_x(DeviceProxy* self, bool unordered, std::uint64_t : "CreateShaderResourceView of placed memory", resource_words, view_words, destination, 0, 0); if (!destination) return; + // LOCAL: whatever this call writes to the real slot is stored at the title's address too when it returns. + struct LocalWriteThrough { + DeviceProxy* self; + std::uint64_t custom; + ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } + } local_write_back{self, destination}; const D3D12_CPU_DESCRIPTOR_HANDLE dest = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); PlacedViewCounts& counts = g_placed_views[unordered ? 1 : 0]; const std::uint64_t n = counts.calls.fetch_add(1, std::memory_order_relaxed) + 1; @@ -2779,6 +3129,10 @@ void proxy_create_placed_view_x(DeviceProxy* self, bool unordered, std::uint64_t static_cast(counts.texture_views.load()), static_cast(counts.textures.load())); if (written || texture_written) return; + if (!unordered && + create_srv_from_raw_x(self, resource_words, view_words, + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}, dest.ptr)) + return; if (unordered) { // A null UAV of the view's kind: a buffer, or a 2D texture for anything else. D3D12_UNORDERED_ACCESS_VIEW_DESC null_view{}; @@ -3032,6 +3386,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; { @@ -3051,6 +3406,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; #ifdef LEONIDA_VULKAN_DEVICE // A CPU-only heap of the Vulkan device keeps its descriptors in the backing itself: the title @@ -3084,7 +3440,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); // LOCAL DIAGNOSTIC (fsdraw): which CPU start the title gets for this heap if (leonida::local_diagnostics()) { static std::atomic logged{0}; @@ -3113,19 +3469,24 @@ 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); } void proxy_create_srv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(18); self->real->CreateShaderResourceView(resource, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(19); self->real->CreateUnorderedAccessView(resource, counter, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, @@ -3143,6 +3504,7 @@ void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_D void proxy_create_sampler(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { note_slot(22); self->real->CreateSampler(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); } void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, @@ -3183,6 +3545,8 @@ void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DE return; } self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); + for (UINT i = 0; dest_starts && i < num_dest; ++i) + local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); } void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, @@ -3191,6 +3555,7 @@ void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D1 const D3D12_CPU_DESCRIPTOR_HANDLE dest = translate_cpu_handle(self, dest_start); const D3D12_CPU_DESCRIPTOR_HANDLE src = translate_cpu_handle(self, src_start); self->real->CopyDescriptorsSimple(num_descriptors, dest, src, type); + local_write_through(self, dest_start, num_descriptors); // LOCAL DIAGNOSTIC (fsdraw): where the title copies its descriptors, and what lands there if (leonida::local_diagnostics()) { static std::atomic copies{0}; @@ -3454,7 +3819,7 @@ class TitleMemoryLease final : public IUnknown { // `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; @@ -3478,7 +3843,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); // the resource's reference + 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}; @@ -3528,6 +3895,28 @@ std::uint64_t proxy_create_committed_resource(DeviceProxy* self, std::uint64_t a } } +// Xbox slot 57 through the factory of the device behind the proxy (set_device_native_graphics_factory), which +// takes the whole description. E_NOTIMPL (no factory, or one that cannot build this description) sends the call +// to proxy_create_graphics_pipeline_from_native_code below. +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 (!accessible_range(raw, sizeof(np::GraphicsDesc), false)) 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 && accessible_range(pair.data, static_cast(pair.size), false)); + }; + 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); +} + // Xbox slot 57 (+0x1c8): DeserializeGraphicsPipelineStateX(const XboxNativeGraphicsPipelineStateDesc* desc, // REFIID riid, void** ppPipelineState). struct XboxNativeGraphicsPipelineStateDesc { @@ -3848,6 +4237,53 @@ HRESULT proxy_create_graphics_pipeline_from_native_code(DeviceProxy* self, const return hr; } +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, @@ -3876,10 +4312,21 @@ 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)); } + // With a provider for the unordered-access planes the texture keeps them (two resources behind one). + 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, pc_initial_state(&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, xbox_layout); return hr; } @@ -3906,8 +4353,29 @@ D3D12_HEAP_PROPERTIES* proxy_get_custom_heap_properties(D3D12_HEAP_PROPERTIES* o // description: the PC flags only, slot 76's layout rule, COMMON for a buffer or an all-ones state, and the clear value // only for a render target or depth texture. The resource is not backed by the memory at va: what the title writes // there does not reach it. Backing it needs the physical-page mapper; until then this gets the title past the call. +// +// The fourth word is read as a resource state here, which is what the retail boot ran through the story load with +// wherever this stand-in answered. The placed-at-VA handler reads the same word as a D3D12_BARRIER_LAYOUT (see +// d3d12_xs_device.h: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, all ones UNDEFINED), and as a state 6 is +// INDEX_BUFFER | RENDER_TARGET, which a PC device refuses for a texture. LEONIDA_SLOT133_LAYOUT_WORD=1 reads it as a +// layout here too: through ID3D12Device10::CreateCommittedResource3 with the layout as given (UNDEFINED for a +// buffer), or on an older PC device through CreateCommittedResource with the legacy state of that layout. constexpr std::uint32_t kPcResourceFlags = 0x3FF; // D3D12_RESOURCE_FLAG_* up to USE_TIGHT_ALIGNMENT (0x200) +D3D12_RESOURCE_STATES legacy_state_for_layout(std::uint32_t layout, bool buffer) { + if (buffer) return D3D12_RESOURCE_STATE_COMMON; + switch (layout) { + case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; // D3D12_BARRIER_LAYOUT_RENDER_TARGET + case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; // UNORDERED_ACCESS + case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; // DEPTH_STENCIL_WRITE + case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; // DEPTH_STENCIL_READ + case 6: return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; // SHADER_RESOURCE + case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; // COPY_SOURCE + case 8: return D3D12_RESOURCE_STATE_COPY_DEST; // COPY_DEST + default: return D3D12_RESOURCE_STATE_COMMON; // UNDEFINED, COMMON and the rest + } +} + HRESULT proxy_create_placed_resource_x(DeviceProxy* self, std::uint64_t va, const D3D12_RESOURCE_DESC* xbox_desc, std::uint32_t initial_state, const D3D12_CLEAR_VALUE* clear_value, const IID* riid, void** out) { @@ -3921,8 +4389,13 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, std::uint64_t va, cons pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); const bool buffer = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; pc_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; - const auto state = (buffer || initial_state == 0xFFFFFFFFu) ? D3D12_RESOURCE_STATE_COMMON - : static_cast(initial_state); + static const bool layout_word = [] { + const char* v = std::getenv("LEONIDA_SLOT133_LAYOUT_WORD"); + return v && *v == '1'; + }(); + const auto state = layout_word ? legacy_state_for_layout(initial_state, buffer) + : (buffer || initial_state == 0xFFFFFFFFu) ? D3D12_RESOURCE_STATE_COMMON + : static_cast(initial_state); const bool clearable = !buffer && (pc_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); @@ -3936,8 +4409,26 @@ HRESULT proxy_create_placed_resource_x(DeviceProxy* self, std::uint64_t va, cons (void)va; const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0}; - return self->real->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &pc_desc, state, - clearable ? clear_value : nullptr, *riid, out); + const D3D12_CLEAR_VALUE* const clear = clearable ? clear_value : nullptr; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + constexpr unsigned kDevice10Create = 76; // ID3D12Device10::CreateCommittedResource3 + void* device10 = nullptr; + if (layout_word && self->slot_count > kDevice10Create && + SUCCEEDED(self->real->QueryInterface(__uuidof(ID3D12Device10), &device10)) && device10) { + D3D12_RESOURCE_DESC1 desc1{}; + std::memcpy(&desc1, &pc_desc, sizeof(pc_desc)); // DESC1 is DESC plus SamplerFeedbackMipRegion (zero) + const std::uint32_t layout = buffer ? 0xFFFFFFFFu : initial_state; // a buffer is created UNDEFINED + using Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, const D3D12_RESOURCE_DESC1*, + std::uint32_t, const D3D12_CLEAR_VALUE*, void*, UINT, const DXGI_FORMAT*, + const IID*, void**); + const auto create = reinterpret_cast((*reinterpret_cast(device10))[kDevice10Create]); + const HRESULT hr = create(device10, &heap, D3D12_HEAP_FLAG_NONE, &desc1, layout, clear, nullptr, 0, nullptr, + riid, out); + static_cast(device10)->Release(); + return hr; + } +#endif + return self->real->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &pc_desc, state, clear, *riid, out); } // The Xbox routes at their configured indices. Returns false when `slot` is none of them. The built-in handlers of @@ -3972,6 +4463,13 @@ bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, // (ID3D12Device13::OpenExistingHeapFromAddress1). log_xbox_route_once(slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5); auto* count = reinterpret_cast(a3); +#ifdef LEONIDA_VULKAN_DEVICE + if (auto* presentation = device_presentation(self)) { + result = hr_to_u64(presentation->GetFrameStatisticsX( + a1, static_cast(a2), count, reinterpret_cast(a4))); + return true; + } +#endif if (!count || (*count > 0 && !a4)) { result = hr_to_u64(E_POINTER); } else { @@ -4083,7 +4581,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; } @@ -4097,7 +4595,7 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap std::atomic g_placed_at_va{nullptr}; HRESULT proxy_create_buffer_at_va(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, - std::uint32_t state, const IID* riid, void** out) { + std::uint32_t state, const D3D12_CLEAR_VALUE* clear, const IID* riid, void** out) { 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. @@ -4134,7 +4632,8 @@ HRESULT proxy_create_buffer_at_va(DeviceProxy* self, void* va, const D3D12_RESOU 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, state, *riid, out, clearable ? clear : nullptr); } // Slot 133 with both of its paths. The buffer on the title's own pages (proxy_create_buffer_at_va) is tried first: it @@ -4145,8 +4644,16 @@ HRESULT proxy_create_buffer_at_va(DeviceProxy* self, void* va, const D3D12_RESOU HRESULT proxy_create_placed_resource_slot133(DeviceProxy* self, std::uint64_t va, const D3D12_RESOURCE_DESC* xbox_desc, std::uint32_t state, const D3D12_CLEAR_VALUE* clear_value, const IID* riid, void** out) { + // A depth-stencil texture with unordered access is the depth provider's when one is set. + if (out && xbox_desc && riid && self->depth_stencil_uav_provider && self->validate_depth_placement && + depth_uav_description(*xbox_desc)) { + note_slot(133); + *out = nullptr; + return proxy_create_placed_depth(self, va, *xbox_desc, state, clear_value, *riid, out); + } if (out && xbox_desc && riid) { - const HRESULT hr = proxy_create_buffer_at_va(self, reinterpret_cast(va), xbox_desc, state, riid, out); + const HRESULT hr = proxy_create_buffer_at_va(self, reinterpret_cast(va), xbox_desc, state, clear_value, + riid, out); if (SUCCEEDED(hr)) { note_slot(133); return hr; @@ -4193,8 +4700,10 @@ void keep_pso_stream(IUnknown* pso, const D3D12_PIPELINE_STATE_STREAM_DESC& desc // 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) { + 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)); using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); used_console_stream = false; d3d12_trace::stream_refusal = nullptr; @@ -4239,6 +4748,8 @@ HRESULT proxy_create_derived_pso(DeviceProxy* self, ID3D12PipelineState* base, s if (!out || !riid || !records) return E_POINTER; 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); + if (!count || count > kDerivedMaxRecords) return E_INVALIDARG; + if (!accessible_range(records, std::size_t(count) * kDerivedRecordSize, false)) return E_INVALIDARG; std::vector patched; switch (derive_stream(*base_record, records, count, patched)) { case DeriveStatus::ok: break; @@ -4246,10 +4757,9 @@ HRESULT proxy_create_derived_pso(DeviceProxy* self, ID3D12PipelineState* base, s 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); } - D3D12_PIPELINE_STATE_STREAM_DESC desc{}; - desc.SizeInBytes = patched.size(); - desc.pPipelineStateSubobjectStream = patched.data(); - return create_pso_from_stream(self, &desc, riid, out); + 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, @@ -4371,6 +4881,24 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 } else if constexpr (Slot == 12) { return hr_to_u64(proxy_create_command_list(self, a1, a2, a3, a4, reinterpret_cast(a5), reinterpret_cast(a6))); + } else if constexpr (Slot == 13) { + const bool console = is_console_caller(_ReturnAddress()); + struct RestoreFeatureQuery { + bool previous; + ~RestoreFeatureQuery() { g_console_feature_query = previous; } + } restore{std::exchange(g_console_feature_query, console)}; + const auto feature = static_cast(a1); + if (feature == D3D12_FEATURE_FORMAT_INFO && a3 == sizeof(D3D12_FEATURE_DATA_FORMAT_INFO) && + console && local_accessible(a2, sizeof(D3D12_FEATURE_DATA_FORMAT_INFO), true)) { + auto* info = reinterpret_cast(a2); + const auto format = static_cast(info->Format); + // Xbox D16/S8 and its depth and stencil aliases occupy slots reserved by desktop DXGI. + if (format >= 118 && format <= 120) { + info->PlaneCount = 2; + return hr_to_u64(S_OK); + } + } + return hr_to_u64(self->real->CheckFeatureSupport(feature, reinterpret_cast(a2), static_cast(a3))); } else if constexpr (Slot == 36) { return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -4450,8 +4978,14 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 if (!riid || *riid == __uuidof(ID3D12PipelineState)) { note_slot(57); log_xbox_route_once(57, "DeserializeGraphicsPipelineStateX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_graphics_pipeline_from_native_code( - self, reinterpret_cast(a1), riid, reinterpret_cast(a3))); + HRESULT hr = E_NOTIMPL; + if (riid && self->native_graphics) + hr = proxy_create_native_graphics(self, reinterpret_cast(a1), *riid, + reinterpret_cast(a3)); + if (hr == E_NOTIMPL) + hr = proxy_create_graphics_pipeline_from_native_code( + self, reinterpret_cast(a1), riid, reinterpret_cast(a3)); + return hr_to_u64(d3d12_trace::result("XboxID3D12Device::CreateNativeGraphicsPipelineState", hr)); } note_slot(57); if (57 >= self->slot_count) return hr_to_u64(refuse_beyond_device(57, self->slot_count)); @@ -4488,10 +5022,17 @@ 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_slot133( - self, a1, reinterpret_cast(a2), static_cast(a3), - reinterpret_cast(a4), reinterpret_cast(a5), - reinterpret_cast(a6))); + const auto* desc = reinterpret_cast(a2); + auto** out = reinterpret_cast(a6); + const HRESULT hr = proxy_create_placed_resource_slot133( + self, a1, desc, static_cast(a3), reinterpret_cast(a4), + reinterpret_cast(a5), 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 == 70) { std::uint64_t routed = 0; if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here @@ -4850,6 +5391,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); @@ -4883,6 +5426,45 @@ 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) { + std::fprintf(stderr, "[rt] d3d12_xs: set_device_resource_provider: %p is not a device proxy; no provider set\n", + device); + return false; + } + proxy->resource_provider = 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()); } @@ -4920,6 +5502,14 @@ void set_placed_at_va_handler(PlacedAtVaHandler handler) { g_placed_at_va.store(handler, std::memory_order_release); } +bool console_feature_query() noexcept { return g_console_feature_query; } + +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); } @@ -4941,6 +5531,7 @@ bool set_presentation_handler(void* device, const PresentationHandler* handler) auto* proxy = static_cast(device_proxy_primary(device)); if (!proxy) return false; AcquireSRWLockExclusive(&proxy->presentation_lock); + proxy->external_presentation_mode = true; proxy->presentation = handler ? *handler : PresentationHandler{}; ReleaseSRWLockExclusive(&proxy->presentation_lock); return true; @@ -4952,9 +5543,9 @@ 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 <= 27) || slot == 31 || + if (slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 13 || slot == 14 || (slot >= 17 && slot <= 27) || slot == 31 || slot == 32 || slot == 34 || slot == 35 || slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || - slot == 53 || slot == 55 || slot == 56 || slot == 61 || slot == 62 || slot == 67 || slot == 70 || slot == 74 || slot == 75 || + slot == 53 || slot == 55 || slot == 56 || slot == 57 || slot == 61 || slot == 62 || slot == 67 || slot == 70 || slot == 74 || slot == 75 || slot == 76 || slot == 86 || slot == 101 || slot == 108 || slot == kCreateCommittedResource3X || slot == 133) return true; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index f7ada96647..7e4660953b 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -12,7 +12,10 @@ // D3D12_SAMPLER_DESC prefix is passed. The PC slot 61 is CreateMetaCommand. Measured on the retail title's // boot. Only for a caller in a guest-mapped image (set_console_caller, below); a host caller reaches the // PC CreateMetaCommand. -// slot 57 DeserializeGraphicsPipelineStateX(desc, iid, out): converts the Xbox 0x68-byte native graphics PSO +// slot 57 the native graphics pipeline state (desc, iid, out). The factory of set_device_native_graphics_factory +// (below) is asked first with the whole 0x108-byte description (leonida::native_pso::GraphicsDesc); when +// it answers E_NOTIMPL (none set, no catalogue, or a plan it cannot build) the call goes on as +// DeserializeGraphicsPipelineStateX(desc, iid, out): converts the Xbox 0x68-byte native graphics PSO // description (+0x00 root signature, +0x08/+0x10 state blob, +0x18/+0x20 pipeline input-layout blob, // +0x28/+0x30 and +0x48/+0x50 bare RDNA2 programs, +0x38/+0x40 and +0x58/+0x60 kind-2 stage blobs) to // D3D12_GRAPHICS_PIPELINE_STATE_DESC and forwards to PC CreateGraphicsPipelineState (slot 10). When the @@ -27,6 +30,11 @@ // Layout per VIctory: 14 resource dwords shaped as D3D12_RESOURCE_DESC, 16 view dwords whose first 10 are // the PC view description and 10-11 the memory's address. A buffer view gets its V#; a texture the PC // null view (no texture exists for the title's memory yet). +// A shader-resource view that gets nothing this way asks the providers below before the null view: +// the raw texture view provider for a 2D texture shape, and for the measured raw buffer shape (PR 7066, +// eugen1763: a desktop D3D12_RESOURCE_DESC of a buffer, a desktop D3D12_SHADER_RESOURCE_VIEW_DESC with +// R32_TYPELESS, BUFFER and RAW followed at once by a D3D12_GPU_VIRTUAL_ADDRESS) the device's resource +// provider, which names the buffer a slot-133 call registered for that address. // slot 71 the same for an unordered-access view. The PC slot 71 is CreateSamplerFeedbackUnorderedAccessView. // slot 74 (pointer, u32, pointer): not measured, returns S_OK. The PC slot 74 is ShaderCacheControl(kinds, control), // which reads the first word as flags and returns E_INVALIDARG. Nothing is written, the PC device is not called. @@ -38,7 +46,9 @@ // in RDX (the PC form is `this` in RCX, return buffer in RDX). Slot 25 (GetResourceAllocationInfo, also a // struct wider than 8 bytes) takes the same form by the same rule. Both accept either form. // slot 133 CreatePlacedResourceX(va, desc, state, clear, riid, out) -> a buffer on the title's pages at va, made by -// the handler of set_placed_at_va_handler (below). Where that cannot be made, PC CreateCommittedResource +// the handler of set_placed_at_va_handler (below); a depth-stencil texture with unordered access goes to +// the depth provider (set_depth_stencil_uav_provider) when one is set. Where neither can make it, PC +// CreateCommittedResource // on a DEFAULT heap, with the Xbox flag bits dropped and an all-ones state as COMMON: not backed by the // memory at va. // slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The 32-byte Xbox desc starts with @@ -120,6 +130,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 @@ -159,6 +171,64 @@ D3D_FEATURE_LEVEL max_feature_level(ID3D12Device* 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 +// `va`; `start` and `size` are then unused, otherwise the resource's first VA and size in bytes. +using ResourceByVaProvider = ID3D12Resource* (*)(ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, + std::uint64_t* start, std::uint64_t* size); +// `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither. Without a provider slot +// 70 does not look for a buffer by its address. +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. +// (From the patch descriptor-write-through of Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b, +// GPL-3.0.) +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. @@ -196,10 +266,12 @@ IUnknown* real_object_behind_proxy(const void* object); // 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, a PC device behind the proxy, or a handler // that fails (a texture, a range the import refuses), the slot creates the committed stand-in described at the top. +// A depth-stencil texture with unordered access goes to the proxy's depth provider first when one is set. +// `clear` is the title's clear value for a render target or depth-stencil texture, else null. // `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 @@ -209,6 +281,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 @@ -245,7 +320,8 @@ std::shared_ptr device_frame_tokens(const void* devic // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue // proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the // console's struct-return form), 31/34/35/45/46/50 (proxies unwrapped), -// 32 and 36 (fence proxies), 48/73 and 78/79/80/81 (the Xbox slots above, at their configured indices), 55, 62, 67, 70, +// 32 and 36 (fence proxies), 48/73 and 78/79/80/81 (the Xbox slots above, at their configured indices), 13 (the +// console's format queries), 55, 57, 62, 67, 70, // 74, 76, 86, 101, 108 and 127. Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap // proxy, and device slot 9 is CreateCommandAllocator, which the proxy handles for the allocator proxy. bool device_slot_overridden(unsigned slot); @@ -255,6 +331,9 @@ bool device_slot_overridden(unsigned slot); // installed every caller is a host one. D3D12XboxCreateDevice installs rt::shims::mapped_image_base. using ConsoleCaller = bool (*)(std::uint64_t address); void set_console_caller(ConsoleCaller classify); +// True on the calling thread while the proxy forwards a CheckFeatureSupport (device slot 13) that a console caller +// made, so the device behind it can answer the console's formats. +bool console_feature_query() noexcept; // Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object // (no reference added), or null when the pointer is not such a proxy. diff --git a/runtime/shims/d3d12_xs_native_pso.h b/runtime/shims/d3d12_xs_native_pso.h new file mode 100644 index 0000000000..ba8537c5fc --- /dev/null +++ b/runtime/shims/d3d12_xs_native_pso.h @@ -0,0 +1,243 @@ +#pragma once + +// Source: adapted from enx/leonida, commit 5c175db901f8486bcdefd03746b578b657e3151f on the original author's git +// mirror (https://git.notrexed.dev/enx/leonida), a fork of this project. Licence: GPL-3.0-or-later as a fork of this +// project. That server could not be reached on 2026-11-25, when this file was merged, so the source and its licence +// could not be read there; the maintainer accepted the file because the source is a fork of this same +// GPL-3.0-or-later project (the README links the server as the original author's mirror) and because +// tools/native_pso_hashes.py is adapted from the same commit. Changed, as the pull request that brought it describes +// it (the source could not be compared): the state and stage resolution moved to runtime/src/native_pso.h, and the +// stage bytecode handed on is read from the user's own carved DXBC containers, not from the description. +// +// 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 0000000000..73bc28eb7a --- /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 index 1b59bf3eaf..e2d0cb5b5d 100644 --- a/runtime/shims/d3d12_xs_pso_stream.cpp +++ b/runtime/shims/d3d12_xs_pso_stream.cpp @@ -240,12 +240,17 @@ void audit_pso_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, HRESULT hr, types.c_str(), shaders.c_str(), d3d12_trace::stream_refusal ? d3d12_trace::stream_refusal : "-"); } -PsoStreamRecord::~PsoStreamRecord() { - for (ID3D12RootSignature* root : roots_) +PsoStreamRecord::Payloads::~Payloads() { + for (ID3D12RootSignature* root : roots) if (root) root->Release(); } std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, bool console) { + return capture(desc, std::span{}, console); +} + +std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, + std::span shaders, bool console) { if (!desc.pPipelineStateSubobjectStream || desc.SizeInBytes == 0 || desc.SizeInBytes > kMaxStreamBytes) return nullptr; const auto* source = static_cast(desc.pPipelineStateSubobjectStream); @@ -253,6 +258,8 @@ std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_S if (!walk(source, desc.SizeInBytes, subs, console)) 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 (console) std::memcpy(record->bytes_.data() + sub.tag_offset, &sub.type, sizeof(sub.type)); @@ -261,6 +268,15 @@ std::unique_ptr PsoStreamRecord::capture(const D3D12_PIPELINE_S return record; } +// 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; +} + // Replaces the pointers in one subobject's payload with copies of what they point to. bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_offset) { unsigned char* payload = bytes_.data() + payload_offset; @@ -269,8 +285,8 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of ID3D12RootSignature* root = nullptr; std::memcpy(&root, payload, sizeof(root)); if (root) { + payloads_->roots.push_back(root); root->AddRef(); - roots_.push_back(root); } return true; } @@ -285,7 +301,9 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of D3D12_SHADER_BYTECODE code{}; std::memcpy(&code, payload, sizeof(code)); if (code.pShaderBytecode && code.BytecodeLength) { - code.pShaderBytecode = own_blob(blobs_, 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; @@ -295,10 +313,10 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of std::memcpy(&so, payload, sizeof(so)); if (so.pSODeclaration && so.NumEntries) so.pSODeclaration = reinterpret_cast( - own_blob(blobs_, so.pSODeclaration, so.NumEntries * sizeof(D3D12_SO_DECLARATION_ENTRY))); + own_blob(payloads_->blobs, so.pSODeclaration, so.NumEntries * sizeof(D3D12_SO_DECLARATION_ENTRY))); if (so.pBufferStrides && so.NumStrides) so.pBufferStrides = reinterpret_cast( - own_blob(blobs_, so.pBufferStrides, so.NumStrides * sizeof(UINT))); + own_blob(payloads_->blobs, so.pBufferStrides, so.NumStrides * sizeof(UINT))); std::memcpy(payload, &so, sizeof(so)); return true; } @@ -308,12 +326,12 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of 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(blobs_, layout.pInputElementDescs, bytes))); + 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(blobs_, elements[i].SemanticName, len)); + reinterpret_cast(own_blob(payloads_->blobs, elements[i].SemanticName, len)); } layout.pInputElementDescs = elements; std::memcpy(payload, &layout, sizeof(layout)); @@ -323,7 +341,7 @@ bool PsoStreamRecord::copy_pointed_data(std::size_t type, std::size_t payload_of D3D12_CACHED_PIPELINE_STATE cached{}; std::memcpy(&cached, payload, sizeof(cached)); if (cached.pCachedBlob && cached.CachedBlobSizeInBytes) { - cached.pCachedBlob = own_blob(blobs_, cached.pCachedBlob, cached.CachedBlobSizeInBytes); + cached.pCachedBlob = own_blob(payloads_->blobs, cached.pCachedBlob, cached.CachedBlobSizeInBytes); std::memcpy(payload, &cached, sizeof(cached)); } return true; @@ -369,6 +387,15 @@ bool attach_pso_record(ID3D12Object* object, std::unique_ptr re 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*); diff --git a/runtime/shims/d3d12_xs_pso_stream.h b/runtime/shims/d3d12_xs_pso_stream.h index 4e26932fe0..bfeaf29b31 100644 --- a/runtime/shims/d3d12_xs_pso_stream.h +++ b/runtime/shims/d3d12_xs_pso_stream.h @@ -21,6 +21,7 @@ #include #include #include +#include #include namespace rt::d3d12_xs { @@ -46,7 +47,13 @@ class PsoStreamRecord { public: // Null when the stream is malformed, holds a subobject type this module does not walk, or is too large. static std::unique_ptr capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, bool console = false); - ~PsoStreamRecord(); + // The same, with shader containers the caller already keeps alive: a stage whose bytecode is one of `shaders` is + // referenced through it and not copied. + using ShaderData = std::shared_ptr>; + static std::unique_ptr capture(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, + std::span shaders, bool console = false); + static std::unique_ptr derived(const PsoStreamRecord& base, std::vector stream); + ~PsoStreamRecord() = default; PsoStreamRecord(const PsoStreamRecord&) = delete; PsoStreamRecord& operator=(const PsoStreamRecord&) = delete; @@ -65,8 +72,13 @@ class PsoStreamRecord { bool copy_pointed_data(std::size_t type, std::size_t payload_offset); std::vector bytes_; - std::vector> blobs_; // owned copies; their buffers do not move when this grows - std::vector roots_; // AddRef'd + struct Payloads { + std::vector> blobs; // owned copies; their buffers do not move when this grows + std::vector shaders; + std::vector roots; // AddRef'd + ~Payloads(); + }; + std::shared_ptr payloads_; }; enum class DeriveStatus { ok, unknown_tag, missing_state, malformed }; @@ -79,6 +91,7 @@ DeriveStatus derive_stream(const PsoStreamRecord& base, const unsigned char* rec // 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/present_window.h b/runtime/shims/present_window.h new file mode 100644 index 0000000000..1f03f58fcc --- /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/xbox_present.cpp b/runtime/shims/xbox_present.cpp index 1cc883318d..77c2c9c53e 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -1,3 +1,4 @@ +#include #include "xbox_present.h" #include "d3d12_trace.h" @@ -31,10 +32,10 @@ void log_once(bool& done, const char* text) { } // namespace XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock, - std::shared_ptr tokens) + std::shared_ptr tokens, bool current_origin_poll) : presenter_(std::move(presenter)), own_clock_(clock ? nullptr : std::make_unique()), - pacer_(clock ? *clock : *own_clock_, std::move(tokens)) { + pacer_(clock ? *clock : *own_clock_, std::move(tokens), current_origin_poll) { // A present waiting for a swapchain image gives up once SuspendX has been called. presenter_->set_abort([this] { return pacer_.suspended(); }); // LEONIDA_SDR_EOTF=gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead of piecewise sRGB; "srgb" or diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index 4f56db3d80..86381f2d62 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h @@ -101,7 +101,7 @@ class XboxPresentation { // `clock` null: real time (a steady high-resolution timer). Tests pass a leonida::ManualFrameClock, which must // outlive this object. `presenter` is what create_window_presenter returned. explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr, - std::shared_ptr tokens = nullptr); + std::shared_ptr tokens = nullptr, bool current_origin_poll = false); ~XboxPresentation(); XboxPresentation(const XboxPresentation&) = delete; XboxPresentation& operator=(const XboxPresentation&) = delete; diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp index 8b6b816a7e..7a9066d5d8 100644 --- a/runtime/shims/xg_xs.cpp +++ b/runtime/shims/xg_xs.cpp @@ -1,18 +1,57 @@ -// xg_xs.dll: Xbox Series texture layout and CPU copies. The object has an -// Xbox vtable (AddRef and Release first, with no QueryInterface). +// 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. The object has an Xbox vtable (AddRef and Release first, with no +// QueryInterface). +// +// Measured from the call sites in the executable, read statically (shapes and checks only): +// HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) +// 2 call sites, both in the game's helper that fills a texture description before XGCreateTextureComputer. The +// out pointer is a 32-bit field of that description, which the helper first sets to 0 and, when the mode is +// 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), 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). +// +// Two layout models answer, in this order: +// 1. xg_xs_layout.h (single-plane textures that are not targets, in the linear, 4 KiB and 64 KiB standard and +// 64 KiB display modes). The D3D12 layer lays the title's streamed and placed textures out with the same header, +// so what the title is told here is what the layer reads back. +// 2. runtime/src/console_texture_layout.h, for a description the first cannot lay out (targets, depth with stencil, +// the other swizzle modes, multisampling): namespace `port` below. Its methods, their arguments and the layout +// structure slot 2 fills are taken from Marvisak/VIctory (GPL-3.0-or-later; translated from Rust to C++ and +// changed for Leonida), 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 neither model can 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 (0 for the slots that return a number) and writes nothing. COM says *out is null on failure; this +// breaks that on purpose. +// +// Not modelled by the second model: 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 (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 #include +#include "../src/console_texture_layout.h" #include "shims.h" #include "xg_xs_layout.h" #include "../src/title_page_watch.h" @@ -249,6 +288,439 @@ auto make_vtable(std::index_sequence) { const auto kVtable = make_vtable(std::make_index_sequence{}); Computer unavailable{kVtable.data(), {1}, {}}; +// ---- The second model: runtime/src/console_texture_layout.h. ---- + +namespace port { + +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); + +// 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: %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; +} + +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 with a layout. ---- + +struct Computer { + const void* const* vtable; + std::atomic refs{1}; + ResourceDesc desc{}; + uint32_t mips = 0; + ct::Texture texture; +}; + +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 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); + // The texture's image on the PC GPU is filled from this memory: tell the D3D12 layer it changed. + if (e == ct::Error::ok) leonida::title_texel_writes::note(tiled, a->tiled); + 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; +} + +// 3, 4: the size and the alignment slot 2 reports. +uint64_t __stdcall total_size(Computer* c) { return c->texture.size; } +uint64_t __stdcall total_alignment(Computer* c) { return c->texture.alignment; } + +// 5 (plane, mip): the offset slot 2 reports for the mip, 0 outside. +uint64_t __stdcall mip_offset(Computer* c, uint32_t plane, uint32_t mip) { + if (plane >= c->texture.planes.size() || plane >= 4) return 0; + const ct::Layout& l = c->texture.planes[plane].layout; + if (mip >= l.mips.size() || mip >= kMips) return 0; + return mip_out(c->desc, l, mip).offset; +} + +template +HRESULT __stdcall unused_slot(Computer*) { + static std::atomic warned{false}; + 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 == 3 ? reinterpret_cast(&total_size) + : Slot == 4 ? reinterpret_cast(&total_alignment) + : Slot == 5 ? reinterpret_cast(&mip_offset) + : 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{}); + +// A computer for `desc`; on failure *out is left as it was. +HRESULT create(const ResourceDesc& desc, void** out, const void* caller) { + std::optional texture = texture_of(desc); + if (!texture) { + static std::atomic warned{0}; + if (warned.fetch_add(1, std::memory_order_relaxed) < 8) + 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(caller)).c_str()); + return kNotImpl; + } + auto* c = new (std::nothrow) Computer; + if (!c) 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; +} + +} // namespace port + HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { static std::atomic calls{0}; ResourceDesc d{}; @@ -267,6 +739,11 @@ HRESULT __stdcall XGCreateTextureComputer(const void* desc, void** out) { // How the title lays out a texture of this shape (title_xg_layouts): what its CPU writes use. leonida::title_xg_layouts::note({d.dimension, d.format, d.height, d.depth_or_array, d.mips, d.width}, d.layout); + } else { + // What xg_xs_layout.h cannot lay out, the second model may: targets, depth with stencil, other modes. + port::ResourceDesc p; + std::memcpy(&p, desc, sizeof(p)); + hr = port::create(p, out, _ReturnAddress()); } } trace_desc(calls, "create", _ReturnAddress(), desc ? &d : nullptr, out, 0, hr, t.mode, t.layout.size); diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 741b7d55b7..a145014328 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -660,6 +660,7 @@ HRESULT WINAPI GetApiVersionImpl(uint64_t* first, uint64_t* second) { return S_OK; } + // HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize. HRESULT __stdcall XGameRuntimeInitialize() { if (g_runtime_refs.fetch_add(1) == 0) std::fprintf(stderr, "[rt] xgameruntime: initialized (offline)\n"); diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index eb70bafe13..3a5be55209 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -28,6 +28,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 @@ -595,6 +596,36 @@ const GUID kAccessibilityInterfaces[] = { {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}, // IXAccessibilityImpl2 }; +// LEONIDA_LOCAL_SPEECH=1 forwards speech synthesis to the locally installed Windows gaming runtime (the host's own +// xgameruntime.dll, from System32). Off unless set: no profile sets it, and the silent voice below answers. +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) { @@ -623,6 +654,8 @@ constexpr SpeechVoiceInformation kSilentVoice = {"Leonida silent voice - English // 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(void* context, callback): one voice, the silent one every // synthesizer below speaks with. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* context, InstalledVoicesCallback callback) { + HRESULT host_result; + if (callback && call_host_speech<8>(host_result, context, callback)) return host_result; if (!callback) return E_INVALIDARG; callback(&kSilentVoice, context); return S_OK; @@ -645,6 +678,8 @@ uint8_t g_speech_stream_handle = 0; // 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): silent synthesizer handle. HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) { + HRESULT host_result; + if (handle && call_host_speech<9>(host_result, handle)) return host_result; if (!handle) return E_POINTER; *handle = &g_speech_synth_handle; static std::atomic s_logged{false}; @@ -655,24 +690,33 @@ HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) { // 10: HRESULT XSpeechSynthesizerCloseHandle(XSpeechSynthesizerHandle handle) HRESULT STDMETHODCALLTYPE speech_close_synth(void*, void* handle) { + HRESULT host_result; + if (handle && handle != &g_speech_synth_handle && call_host_speech<10>(host_result, handle)) return host_result; return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; } // 11: HRESULT XSpeechSynthesizerSetDefaultVoice(XSpeechSynthesizerHandle handle) HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) { + HRESULT host_result; + if (handle && handle != &g_speech_synth_handle && call_host_speech<11>(host_result, handle)) return host_result; return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; } // 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId): only the // enumerated voice is installed. HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char* voice_id) { + HRESULT host_result; + if (handle && handle != &g_speech_synth_handle && voice_id && call_host_speech<12>(host_result, handle, voice_id)) return host_result; if (handle != &g_speech_synth_handle || !voice_id) return E_INVALIDARG; return std::strcmp(voice_id, kSilentVoice.voice_id) == 0 ? S_OK : E_INVALIDARG; } // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, // XSpeechSynthesizerStreamHandle* stream) -HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, void** stream) { +template +HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char* text, void** stream) { + HRESULT host_result; + if (synth && synth != &g_speech_synth_handle && text && stream && call_host_speech(host_result, synth, text, stream)) return host_result; if (stream) *stream = nullptr; if (synth != &g_speech_synth_handle) return E_INVALIDARG; if (!stream) return E_POINTER; @@ -682,11 +726,15 @@ HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, // 14: HRESULT XSpeechSynthesizerCloseStreamHandle(XSpeechSynthesizerStreamHandle stream) HRESULT STDMETHODCALLTYPE speech_close_stream(void*, void* stream) { + HRESULT host_result; + if (stream && stream != &g_speech_stream_handle && call_host_speech<14>(host_result, stream)) return host_result; return stream == &g_speech_stream_handle ? S_OK : E_INVALIDARG; } // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) { + HRESULT host_result; + if (stream && stream != &g_speech_stream_handle && size && call_host_speech<15>(host_result, stream, size)) return host_result; if (size) *size = 0; if (stream != &g_speech_stream_handle) return E_INVALIDARG; if (!size) return E_POINTER; @@ -696,6 +744,8 @@ HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void* stream, size_t size, void* buffer, size_t* used) { + HRESULT host_result; + if (stream && stream != &g_speech_stream_handle && buffer && used && call_host_speech<16>(host_result, stream, size, buffer, used)) return host_result; if (used) *used = 0; if (stream != &g_speech_stream_handle) return E_INVALIDARG; if (!buffer || size < sizeof(kSilentWave)) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); @@ -723,7 +773,7 @@ const void* const kAccessibilityVtable[] = { FN(speech_close_synth), // 10 XSpeechSynthesizerCloseHandle FN(speech_set_default_voice), // 11 XSpeechSynthesizerSetDefaultVoice FN(speech_set_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice - FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText + FN(speech_create_stream<13>), // 13 XSpeechSynthesizerCreateStreamFromText FN(speech_close_stream), // 14 XSpeechSynthesizerCloseStreamHandle FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData @@ -731,7 +781,7 @@ const void* const kAccessibilityVtable[] = { 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 c8cbbd8da3..3ccdabfe94 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -14,6 +14,8 @@ // 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 @@ -40,6 +42,7 @@ #include "startup_trace.h" #include "xmem.h" #include "../src/dstorage_trace.h" +#include "../src/gpu_label_memory.h" #include "../src/title_page_watch.h" #include "../src/title_geometry_watch.h" #include "../src/title_va_alias.h" @@ -76,14 +79,22 @@ 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); if (p) leonida::title_memory_map::changed(); 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); if (p) leonida::title_memory_map::changed(); @@ -272,10 +283,39 @@ 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; void* scratch; - explicit Section(HANDLE h) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)) {} + 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() { @@ -492,6 +532,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, std::fprintf(stderr, "[rt] xmem: GPU-only reservation %p (%llu MiB, protect 0x%lx) has no CPU view\n", result, static_cast(size >> 20), static_cast(protect)); } + if(result)track_label_data(result,size,false); return result; } @@ -833,14 +874,16 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, 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_RESERVE, + 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; } // From host_heap: the unmap that drops the last reference frees it under g_fault_lock. - const auto section = std::allocate_shared
(leonida::host_heap::Allocator
{}, handle); + const auto section = std::allocate_shared
(leonida::host_heap::Allocator
{}, handle, use_file); if (!section->scratch) { *page_count = 0; return FALSE; @@ -1131,16 +1174,31 @@ LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_ty leonida::geometry_writes::notify(from, from + size, leonida::geometry_writes::Event::replaced); } } + if(result)track_label_data(result,size,false); return result; } +// The pages are freed with the GPU label regions locked (src/gpu_label_memory.h), so a completed label is never +// stored into pages that are going away. BOOL WINAPI TitleVirtualFree(LPVOID address, SIZE_T size, DWORD free_type) { - const BOOL result = VirtualFree(address, size, free_type); + DWORD saved=0; + const bool result=leonida::label::memory().release_pages(reinterpret_cast(address),size,(free_type&MEM_RELEASE)!=0,[&]{ + const BOOL r=::VirtualFree(address,size,free_type);saved=GetLastError();return !!r; + }); if (result) leonida::title_memory_map::changed(); if (result && (free_type & MEM_DECOMMIT)) note_unwatched_change(address, size, 0, true); if (result && (free_type & MEM_RELEASE) && !(free_type & MEM_PRESERVE_PLACEHOLDER)) leonida::title_write_watch::remove(reinterpret_cast(address)); - return result; + SetLastError(saved); + return result ? 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; } BOOL WINAPI TitleVirtualProtect(LPVOID address, SIZE_T size, DWORD protect, PDWORD old) { @@ -1185,6 +1243,45 @@ bool commit_physical_range(const void* address, size_t size) { return true; } +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; + // The view that holds a page: a run of pages is one view, or several after a partial unmap. + const auto view_of = [](std::uintptr_t page) { + auto it = g_views.upper_bound(page); + if (it == g_views.begin()) return g_views.end(); + --it; + return (page - it->first) / kPhysicalPageSize < it->second.count ? it : g_views.end(); + }; + const auto base = view_of(first); + if (base == g_views.end() || !base->second.section || !base->second.section->scratch) return {}; + const auto section = base->second.section; + const auto offset = base->second.offset + (first - base->first); + // A view the title mapped writable can be read-only for a while: the D3D12 layer guards the pages its shadows + // copy and opens them again at the title's next write. + bool writable = true; + for (auto page=first; pagesecond.section != section || it->second.offset+(page-it->first) != offset+page-first) return {}; + if ((it->second.protect & 255)!=PAGE_READWRITE && (it->second.protect & 255)!=PAGE_WRITECOPY) writable = false; + 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 && + !(writable && (info.Protect & 255)==PAGE_READONLY))) return {}; + at=reinterpret_cast(info.BaseAddress)+info.RegionSize; + } + return {section,static_cast(section->scratch)+offset+(start-first)}; +} + static bool commit_pages_locked(const uint64_t* page_array, size_t count) { if (count == 0) return true; if (!page_array) { @@ -1208,7 +1305,7 @@ static bool commit_pages_locked(const uint64_t* page_array, size_t count) { ++last; } void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; + if (!it->second.section->file_backed && !VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; leonida::title_memory_map::changed(); first = last; } @@ -1258,6 +1355,7 @@ bool transfer_physical(std::span pages, uint16_t offset, std::sp #define TITLE_VIRTUAL_MEMORY(dll) \ {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)}, \ {dll, "VirtualFree", reinterpret_cast(&TitleVirtualFree)}, \ + {dll, "VirtualFreeEx", reinterpret_cast(&TitleVirtualFreeEx)}, \ {dll, "VirtualProtect", reinterpret_cast(&TitleVirtualProtect)} // The classic libraries and the memory api sets a title's imports name. diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h index 22bb365a2e..6352274505 100644 --- a/runtime/shims/xmem.h +++ b/runtime/shims/xmem.h @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -9,6 +10,8 @@ namespace rt::xmem { void geometry_aliases(std::uintptr_t va, std::vector& addresses); 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); // Copy a validated DirectStorage staging buffer through the page table. The page list has diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index c28904efef..010abbbc01 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 @@ -527,6 +528,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 @@ -667,7 +669,7 @@ struct AccelerationStructurePostbuild { using Command = std::variant; @@ -797,6 +799,11 @@ class CommandList { } // 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 0000000000..393e0adee2 --- /dev/null +++ b/runtime/src/console_texture_layout.h @@ -0,0 +1,611 @@ +// 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-or-later; translated from Rust to C++ and changed for Leonida), +// 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 10f0dada87..d32f975b26 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 @@ class Module { // 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 @@ class Patch { 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 @@ class Patch { 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 @@ class Patch { } 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 688ae185a3..2c9f1fd7e4 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -1,4 +1,6 @@ #pragma once +#include +#include // Frame pacing for the Xbox presentation path (docs/d3d12_vulkan.md section 4.5): what SetFrameIntervalX, // ScheduleFrameEventX, WaitFrameEventX and GetFrameStatisticsX do, and the token check and flip bookkeeping that @@ -115,6 +117,7 @@ inline constexpr std::uint32_t frame_event_flip = 2; inline constexpr std::uint32_t frame_event_count = 3; // Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE). inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2; +inline constexpr std::uint32_t wait_flag_current_token = frame_wait_flag_token_on_timeout; // 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; @@ -184,8 +187,10 @@ class FrameTokenSource { class FramePacer { public: - explicit FramePacer(FrameClock& clock, std::shared_ptr tokens = nullptr) - : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared()) { + explicit FramePacer(FrameClock& clock, std::shared_ptr tokens = nullptr, + bool current_origin_poll = false) + : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared()), + current_origin_poll_(current_origin_poll) { clock_.set_wake([this] { { std::lock_guard guard(mutex_); } cv_.notify_all(); @@ -251,6 +256,8 @@ class FramePacer { if (event >= frame_event_count) return pacer_hr::invalid_arg; if (event == frame_event_origin && !token) return pacer_hr::invalid_arg; std::unique_lock lock(mutex_); + if (current_origin_poll_ && event == frame_event_origin && timeout_ms == 0 && (flags & wait_flag_current_token)) + return current_token_locked(token); ++waiters_; const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token); if (--waiters_ == 0) cv_.notify_all(); @@ -513,6 +520,24 @@ class FramePacer { } } + std::int32_t current_token_locked(std::uint64_t* token) { + if (shutdown_ || suspended_) return pacer_hr::invalid_state; + if (!interval_set_ || !event_armed_[frame_event_origin]) { + *token = tokens_->issue(); + return pacer_hr::ok; + } + const auto now = clock_.now_us(); + retire_locked(now); + const auto offset = event_offset_us_[frame_event_origin]; + const auto first = epoch_us_ + offset; + const auto newest = now >= first ? static_cast((now - first) / period_us_) : 0; + auto& tick = last_event_tick_[frame_event_origin]; + tick = std::max(tick, newest); + const auto origin = first + static_cast(tick) * period_us_; + *token = issue_token_locked(origin, origin - offset + period_us_); + return pacer_hr::ok; + } + bool any_armed_locked() const { return event_armed_[0] || event_armed_[1] || event_armed_[2]; } @@ -594,6 +619,7 @@ class FramePacer { std::uint64_t epoch_us_ = 0; std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed std::shared_ptr tokens_; + bool current_origin_poll_ = false; std::uint64_t last_presented_ = 0; std::uint64_t immediate_presents_ = 0; std::uint64_t presents_recorded_ = 0; diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b8d0b9ecf8..9dad4ed7a4 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 0000000000..7446220873 --- /dev/null +++ b/runtime/src/gpu_label_memory.h @@ -0,0 +1,94 @@ +#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 < r.begin && r.begin - 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 < r.end && r.end - 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.address < region->begin || target.address >= region->end || + region->end - target.address < target.bytes) + return false; + const auto it = regions_.find(region->begin); + 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 6357dd0b00..8e37677400 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -161,10 +161,43 @@ 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) { + // A variable that is set but empty is not a setting: Windows cannot hold one, but a caller on Wine can pass one + // (NAME= in the environment), and asking for the size alone reports it as present there. + const auto set_default = [](const wchar_t* name, const wchar_t* value) { + wchar_t first[2]{}; + return GetEnvironmentVariableW(name, first, 2) != 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_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; } @@ -187,7 +220,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) { @@ -198,6 +231,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]; @@ -224,7 +258,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()) { @@ -239,6 +274,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); // An unattended run can select a fresh write root even when its launcher supplies --overlay. if (const DWORD size = GetEnvironmentVariableW(L"LEONIDA_WRITE_DIR", nullptr, 0)) { @@ -264,6 +304,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); #ifdef LEONIDA_VULKAN_DEVICE @@ -312,6 +356,7 @@ int wmain(int argc, wchar_t** argv) { // So do the file shims' reads, whose kernel writes do not fault them in: on ERROR_NOACCESS (title_page_watch.h). leonida::geometry_writes::aliases.store(&rt::xmem::geometry_aliases); leonida::kernel_writes::set_committer(&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 0000000000..8982c701ac --- /dev/null +++ b/runtime/src/native_pso.h @@ -0,0 +1,342 @@ +#pragma once + +// Source: adapted from enx/leonida, commit 5c175db901f8486bcdefd03746b578b657e3151f on the original author's git +// mirror (https://git.notrexed.dev/enx/leonida), a fork of this project. Licence: GPL-3.0-or-later as a fork of this +// project. That server could not be reached on 2026-11-25, when this file was merged, so the source and its licence +// could not be read there; the maintainer accepted the file because the source is a fork of this same +// GPL-3.0-or-later project (the README links the server as the original author's mirror) and because +// tools/native_pso_hashes.py is adapted from the same commit. Changed, as the pull request that brought it describes +// it (the source could not be compared): the parsing is standard-library code of its own, apart from the D3D12 part +// (runtime/shims/d3d12_xs_native_pso.h), and a stage is taken from the translator's index entry of the container +// its records name, not from the position of its block. +// +// 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/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h index 96e16f9ccc..98e5788a84 100644 --- a/runtime/src/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h @@ -1,7 +1,8 @@ // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. // -// Used by vk_pipeline_check for its offline corpus checkpoints. The runtime fills a mapped session staging file -// directly (d3d12_pipeline_checkpoint.h). +// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime, which writes the session cache on device +// teardown (pipeline_cache_store.h; a reader of the old file keeps it open until its rename completes) and fills a +// mapped session staging file directly (d3d12_pipeline_checkpoint.h). #pragma once #include diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h new file mode 100644 index 0000000000..2e594fcb50 --- /dev/null +++ b/runtime/src/present_dump.h @@ -0,0 +1,256 @@ +#pragma once + +// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::present_dump { + +inline unsigned texel_size(VkFormat format) { + switch (format) { + case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: + case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 8; + case VK_FORMAT_R32G32B32A32_SFLOAT: return 16; + default: return 0; + } +} + +inline std::uint8_t unorm8(float v) { + return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0; +} + +inline std::uint8_t half_unorm8(std::uint16_t bits) { + const int exponent = bits >> 10; + const int fraction = bits & 1023; + if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0; + return unorm8(std::ldexp(float(1024 + fraction), exponent - 25)); +} + +inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) { + if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) { + std::memcpy(dst, src, size_t(width) * 4); + return; + } + const unsigned stride = texel_size(format); + for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) { + if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) { + dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3]; + } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) { + std::uint16_t v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, half_unorm8); + } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) { + float v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, unorm8); + } else { + // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR. + // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits. + static const auto pq_to_sdr = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + const double p = std::pow(i / 1023.0, 1.0 / 78.84375); + const double linear = (10000.0 / 203.0) * + std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125); + const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055; + table[i] = unorm8(float(srgb)); + } + return table; + }(); + std::uint32_t packed; + std::memcpy(&packed, src, sizeof(packed)); + for (unsigned channel = 0; channel < 3; ++channel) { + const unsigned bits = (packed >> (10 * channel)) & 1023; + dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023); + } + if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]); + dst[3] = std::uint8_t((packed >> 30) * 85); + } + } +} + +inline std::array big_endian(std::uint32_t n) { + return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)}; +} + +inline bool chunk(std::FILE* file, const char (&type)[5], std::span data, + std::span prefix = {}) { + static constexpr auto crc_table = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + unsigned c = i; + for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0); + table[i] = c; + } + return table; + }(); + std::uint32_t crc = ~0u; + const auto write = [&](std::span bytes) { + for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8); + return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + }; + return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 && + write({reinterpret_cast(type), 4}) && write(prefix) && write(data) && + std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4; +} + +inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) { + constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10}; + std::array ihdr{}; + const auto w = big_endian(extent.width), h = big_endian(extent.height); + std::copy(w.begin(), w.end(), ihdr.begin()); + std::copy(h.begin(), h.end(), ihdr.begin() + 4); + ihdr[8] = 8; + ihdr[9] = 6; // 8-bit RGBA + constexpr std::uint8_t zlib_header[]{0x78, 0x01}; + if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) || + !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false; + + // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies + // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement). + std::vector row(1 + size_t(extent.width) * 4); + std::uint32_t a = 1, b = 0; + for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) { + rgba_row(row.data() + 1, src, extent.width, format, pq); + std::span rest(row); + while (!rest.empty()) { + auto block = rest.first(std::min(rest.size(), 65535)); + rest = rest.subspan(block.size()); + const auto len = std::uint16_t(block.size()); + const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()), + std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)}; + for (auto byte : block) { + a = (a + byte) % 65521; + b = (b + a) % 65521; + } + if (!chunk(file, "IDAT", block, header)) return false; + } + } + return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {}); +} + +class PresentDump { +public: + PresentDump() { +#ifdef _WIN32 + wchar_t* env = nullptr; + size_t length = 0; + if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) { + bad_value(); + return; + } + const std::unique_ptr owned(env, &std::free); +#else + const auto* env = std::getenv("LEONIDA_PRESENT_DUMP"); +#endif + if (!env) return; + try { + auto value = std::filesystem::path(env).native(); + std::uint64_t interval = 60; + const auto comma = value.rfind(','); + if (comma != value.npos) { + const auto n = std::filesystem::path(value.substr(comma + 1)).string(); + const auto end = n.data() + n.size(); + const auto parsed = std::from_chars(n.data(), end, interval); + if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) { + bad_value(); + return; + } + value.resize(comma); + } + if (value.empty()) { + bad_value(); + return; + } + dir_ = std::filesystem::absolute(value); + std::filesystem::create_directories(dir_); + interval_ = interval; + } catch (const std::exception&) { bad_value(); } + } + + bool enabled() const { return interval_ != 0; } + bool due(std::uint64_t frames_shown) const { + const auto n = interval_.load(); + return n && frames_shown % n == 0; + } + void disable(const char* why) { + if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why); + } + void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) { + try { + // Bound memory to one outstanding write even at N=1. Teardown joins the final writer. + if (writer_.joinable()) writer_.join(); + if (!enabled()) return; + char name[48]; + std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast(frame)); + writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name, + bytes = std::vector(src, src + size)] { + try { + if (publish(path, extent, format, pq, bytes.data())) { + const auto utf8 = path.u8string(); + std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n", + static_cast(frame), reinterpret_cast(utf8.c_str())); + return; + } + } catch (const std::exception&) {} + disable("could not write the present dump"); + }); + } catch (const std::exception&) { disable("could not queue the present dump"); } + } + +private: + static void bad_value() { + static std::once_flag once; + std::call_once(once, [] { + std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n"); + }); + } + static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq, + const std::uint8_t* src) { + // Never open an existing output for writing: it could be a link to a file outside the dump directory. + // Build a complete sibling exclusively, then replace the directory entry in a single rename. + auto tmp = path; + tmp += ".tmp"; +#ifdef _WIN32 + std::FILE* file = nullptr; + _wfopen_s(&file, tmp.c_str(), L"wbx"); +#else + auto* file = std::fopen(tmp.c_str(), "wbx"); +#endif + if (!file) return false; + bool ok = false; + try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {} + if (std::fclose(file) != 0) ok = false; + std::error_code ec; + if (ok) { + std::filesystem::rename(tmp, path, ec); + if (!ec) return true; + } + std::filesystem::remove(tmp, ec); + return false; + } + + std::filesystem::path dir_; + std::atomic interval_{0}; + std::jthread writer_; // joined before the state it uses is destroyed +}; + +} // namespace leonida::present_dump diff --git a/runtime/src/quad_index_expand.comp b/runtime/src/quad_index_expand.comp new file mode 100644 index 0000000000..697cf7665d --- /dev/null +++ b/runtime/src/quad_index_expand.comp @@ -0,0 +1,44 @@ +// Expand the index buffer of a console quad list into triangle-list indices without reading it on the CPU +// (quad_index_expand.h). Each quad (i0 i1 i2 i3) becomes (i0 i1 i2) (i0 i2 i3) as six 32-bit indices: both +// triangles start at the quad's first vertex, the one a flat input is taken from. +#version 460 +#extension GL_EXT_buffer_reference : require +layout(local_size_x = 64) in; +layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { + uint data[]; +}; +layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer WordsOut { + uint data[]; +}; +layout(push_constant) uniform Params { + WordsIn source; // the 4-byte aligned word that holds this dispatch's first index + WordsOut triangles; // six words for each quad of this dispatch + uint first_half; // 16-bit indices: 1 when the first index is the high half of its word + uint index_bits; // 16 or 32 + uint limit; // how many of this dispatch's indices the index buffer view holds; the rest read 0 + uint quads; +} p; + +uint index_at(uint i) { + if (i >= p.limit) return 0u; + if (p.index_bits == 32u) return p.source.data[i]; + const uint slot = i + p.first_half; + return (p.source.data[slot >> 1u] >> ((slot & 1u) * 16u)) & 0xffffu; +} + +void main() { + const uint quad = gl_GlobalInvocationID.x; + if (quad >= p.quads) return; + const uint first = quad * 4u; + const uint i0 = index_at(first); + const uint i1 = index_at(first + 1u); + const uint i2 = index_at(first + 2u); + const uint i3 = index_at(first + 3u); + const uint target = quad * 6u; + p.triangles.data[target] = i0; + p.triangles.data[target + 1u] = i1; + p.triangles.data[target + 2u] = i2; + p.triangles.data[target + 3u] = i0; + p.triangles.data[target + 4u] = i2; + p.triangles.data[target + 5u] = i3; +} diff --git a/runtime/src/quad_index_expand.h b/runtime/src/quad_index_expand.h new file mode 100644 index 0000000000..3c539a5406 --- /dev/null +++ b/runtime/src/quad_index_expand.h @@ -0,0 +1,182 @@ +// Indexed console quad lists (D3D_PRIMITIVE_TOPOLOGY 19) on Vulkan, which has no quad primitive. +// +// A quad is four indices and Vulkan can only draw it as triangles. A triangle fan per quad reads the application's +// index buffer in place, but gets two things wrong: a fan takes a flat input from each triangle's own first vertex +// (the quad's second and third), where the quad takes it from its first, and one draw per quad runs every instance +// of quad 0 before quad 1, where D3D12 draws instance by instance (visible when instances overlap). So the indices +// are rewritten instead: a compute pass (quad_index_expand.comp) reads the application's index buffer on the GPU and +// writes (i0 i1 i2) (i0 i2 i3) for each quad as 32-bit indices into scratch that lives until the submission +// completes (vulkan_scratch.h), and the draw is one indexed triangle list over that scratch with the application's +// instance count, base vertex and first instance. Both triangles start at the quad's first vertex, so a flat input +// is the first vertex's over the whole quad, and one draw keeps D3D12's instance order. +// +// The indices are read on the GPU, never on the host: an index buffer can be written by a copy or a shader earlier +// in the same list. Index values are copied as they are (a 16-bit index is zero-extended), so VertexIndex - +// BaseVertex is still the application's index. That includes the strip-cut value: 0xFFFF and 0xFFFFFFFF are +// ordinary indices in a quad list, as in every list topology (the replay enables primitive restart for strips only), +// and 0xFFFF stays vertex 65535 after the widening. An index past the end of the index buffer view reads 0, as +// D3D12 defines it, and a draw's last one to three indices that do not make a quad are dropped. +// +// Needs bufferDeviceAddress (the pass reads and writes through device addresses, no descriptors) and scratch with +// INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage. Non-indexed quad lists do not come here: they draw from a shared +// constant index buffer (ReplayFunctions::quad_indices). +#pragma once +#ifndef VK_NO_PROTOTYPES +#define VK_NO_PROTOTYPES +#endif +#include +#include +#include +#include "quad_index_expand_spv.h" + +namespace leonida { + +// One indexed quad-list draw's expansion. `buffer` is null for a draw that needs none. +struct QuadIndexExpansion { + VkBuffer buffer = VK_NULL_HANDLE; // the triangle-list indices, 32-bit: six for each quad + VkDeviceSize offset = 0; + VkDeviceAddress source = 0; // the 4-byte aligned word that holds the draw's first index + VkDeviceAddress triangles = 0; // `buffer` + `offset` + std::uint64_t readable = 0; // indices from the draw's first one that the index buffer view holds + std::uint32_t first_half = 0; // 16-bit indices: 1 when the first index is the high half of its word + std::uint32_t index_bits = 0; // 16 or 32 + std::uint32_t quads = 0; +}; + +class QuadIndexExpander { +public: + static constexpr std::uint32_t indices_per_quad = 6; + // vkCmdDrawIndexed counts the expanded indices in 32 bits. + static constexpr std::uint32_t max_quads = UINT32_MAX / indices_per_quad; + // The scratch bytes `quads` quads expand into. + static constexpr VkDeviceSize bytes(std::uint32_t quads) { + return VkDeviceSize(quads) * indices_per_quad * sizeof(std::uint32_t); + } + + QuadIndexExpander(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) + : get_(get), device_(device), limits_(limits) {} + ~QuadIndexExpander() { + if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); + if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); + } + QuadIndexExpander(const QuadIndexExpander&) = delete; + QuadIndexExpander& operator=(const QuadIndexExpander&) = delete; + + // `quads` quads from the indices at `index_offset` in `indices` (the draw's first index), of which the view holds + // `readable`, into bytes(quads) of `scratch` at `scratch_offset`. The pipeline is made on the first call; the + // caller serializes calls. False, with `out` cleared, when the draw cannot be expanded. + bool prepare(VkBuffer indices, VkDeviceSize index_offset, VkIndexType type, std::uint64_t readable, + std::uint32_t quads, VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + out = {}; + const std::uint32_t index_bytes = type == VK_INDEX_TYPE_UINT16 ? 2 : type == VK_INDEX_TYPE_UINT32 ? 4 : 0; + if (!indices || !scratch || !index_bytes || !quads || quads > max_quads || index_offset % index_bytes || + scratch_offset % sizeof(std::uint32_t) || !limits_.maxComputeWorkGroupCount[0] || !make_pipeline()) + return false; + const auto address = fn("vkGetBufferDeviceAddress"); + VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + info.buffer = indices; + const VkDeviceAddress source = address(device_, &info); + info.buffer = scratch; + const VkDeviceAddress target = address(device_, &info); + if (!source || !target || index_offset > UINT64_MAX - source || scratch_offset > UINT64_MAX - target || + (source % sizeof(std::uint32_t)) || (target % sizeof(std::uint32_t))) + return false; + out.buffer = scratch; + out.offset = scratch_offset; + // The shader reads whole words: a 16-bit index at an address of 2 modulo 4 is the high half of its word. + out.source = (source + index_offset) & ~VkDeviceAddress(3); + out.first_half = std::uint32_t((index_offset & 3) / 2); + out.triangles = target + scratch_offset; + out.readable = readable; + out.index_bits = index_bytes * 8; + out.quads = quads; + return true; + } + + // Records the pass: outside a render pass, before the draw that binds job.buffer as its index buffer. + void emit(VkCommandBuffer cb, const QuadIndexExpansion& job) const { + const auto barrier = fn("vkCmdPipelineBarrier"); + // Whatever wrote the application's indices earlier in the command buffer (a copy, a shader) is visible. + VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 1, &before, 0, nullptr, 0, nullptr); + fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); + struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + }; + static_assert(sizeof(Push) == push_bytes); + // A dispatch indexes its quads and their indices in 32 bits: 4 * quad + 4 and 6 * quad + 5 must fit. + constexpr VkDeviceSize index_limit = 1u << 28; + const VkDeviceSize chunk_limit = + std::min(VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * group_size, index_limit); + for (VkDeviceSize first = 0; first < job.quads;) { + const std::uint32_t quads = std::uint32_t(std::min(chunk_limit, job.quads - first)); + const VkDeviceSize first_index = first * 4; + // 16-bit indices: `first_index` is even, so the chunk starts at the same half of a word as the draw. + const VkDeviceSize source_bytes = first_index * (job.index_bits / 8); + const std::uint64_t left = job.readable > first_index ? job.readable - first_index : 0; + const Push push{job.source + source_bytes, job.triangles + first * indices_per_quad * 4, + job.first_half, job.index_bits, std::uint32_t(std::min(left, UINT32_MAX)), + quads}; + fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, + sizeof(push), &push); + fn("vkCmdDispatch")(cb, (quads - 1u) / group_size + 1u, 1, 1); + first += quads; + } + VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; + after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_INDEX_READ_BIT; + barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + 0, 1, &after, 0, nullptr, 0, nullptr); + } + +private: + static constexpr std::uint32_t group_size = 64; // local_size_x of quad_index_expand.comp + static constexpr std::uint32_t push_bytes = 32; + template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } + bool make_pipeline() { + if (pipeline_) return true; + for (const char* name : {"vkGetBufferDeviceAddress", "vkCreateShaderModule", "vkDestroyShaderModule", + "vkCreatePipelineLayout", "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", + "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) + if (!get_(device_, name)) return false; + VkShaderModule module = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkPipeline pipeline = VK_NULL_HANDLE; + VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + shader.codeSize = sizeof(quad_index_expand_spirv); + shader.pCode = quad_index_expand_spirv; + bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; + const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, push_bytes}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = ⦥ + ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.layout = layout; + ok = ok && fn("vkCreateComputePipelines")( + device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; + if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); + if (!ok) { + if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); + if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); + return false; + } + layout_ = layout; + pipeline_ = pipeline; + return true; + } + PFN_vkGetDeviceProcAddr get_; + VkDevice device_; + VkPhysicalDeviceLimits limits_; + VkPipelineLayout layout_ = VK_NULL_HANDLE; + VkPipeline pipeline_ = VK_NULL_HANDLE; +}; +} // namespace leonida diff --git a/runtime/src/quad_index_expand_spv.h b/runtime/src/quad_index_expand_spv.h new file mode 100644 index 0000000000..c7bb4b5c5f --- /dev/null +++ b/runtime/src/quad_index_expand_spv.h @@ -0,0 +1,148 @@ +// Generated with glslang 16.6.0: glslangValidator -V --target-env vulkan1.2 -Os --spirv-val quad_index_expand.comp +#pragma once +#include +namespace leonida { +inline constexpr std::uint32_t quad_index_expand_spirv[] = { + 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000149u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, + 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, + 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000015u, + 0x0000004au, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, + 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, + 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, 0x0000000fu, 0x61726150u, + 0x0000736du, 0x00050006u, 0x0000000fu, 0x00000000u, 0x72756f73u, 0x00006563u, 0x00060006u, 0x0000000fu, + 0x00000001u, 0x61697274u, 0x656c676eu, 0x00000073u, 0x00060006u, 0x0000000fu, 0x00000002u, 0x73726966u, + 0x61685f74u, 0x0000666cu, 0x00060006u, 0x0000000fu, 0x00000003u, 0x65646e69u, 0x69625f78u, 0x00007374u, + 0x00050006u, 0x0000000fu, 0x00000004u, 0x696d696cu, 0x00000074u, 0x00050006u, 0x0000000fu, 0x00000005u, + 0x64617571u, 0x00000073u, 0x00040005u, 0x00000011u, 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000011u, + 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, 0x00000013u, 0x64726f57u, 0x74754f73u, 0x00000000u, + 0x00050006u, 0x00000013u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00030005u, 0x00000015u, 0x00000070u, + 0x00080005u, 0x0000004au, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, + 0x00030047u, 0x0000000fu, 0x00000002u, 0x00050048u, 0x0000000fu, 0x00000000u, 0x00000023u, 0x00000000u, + 0x00050048u, 0x0000000fu, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x0000000fu, 0x00000002u, + 0x00000023u, 0x00000010u, 0x00050048u, 0x0000000fu, 0x00000003u, 0x00000023u, 0x00000014u, 0x00050048u, + 0x0000000fu, 0x00000004u, 0x00000023u, 0x00000018u, 0x00050048u, 0x0000000fu, 0x00000005u, 0x00000023u, + 0x0000001cu, 0x00040047u, 0x00000010u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000011u, 0x00000002u, + 0x00040048u, 0x00000011u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000011u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x00000012u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000013u, 0x00000002u, + 0x00040048u, 0x00000013u, 0x00000000u, 0x00000019u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, + 0x00000000u, 0x00040047u, 0x0000004au, 0x0000000bu, 0x0000001cu, 0x00040047u, 0x0000009au, 0x0000000bu, + 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, + 0x00000020u, 0x00000000u, 0x00030027u, 0x0000000du, 0x000014e5u, 0x00030027u, 0x0000000eu, 0x000014e5u, + 0x0008001eu, 0x0000000fu, 0x0000000du, 0x0000000eu, 0x00000006u, 0x00000006u, 0x00000006u, 0x00000006u, + 0x0003001du, 0x00000010u, 0x00000006u, 0x0003001eu, 0x00000011u, 0x00000010u, 0x00040020u, 0x0000000du, + 0x000014e5u, 0x00000011u, 0x0003001du, 0x00000012u, 0x00000006u, 0x0003001eu, 0x00000013u, 0x00000012u, + 0x00040020u, 0x0000000eu, 0x000014e5u, 0x00000013u, 0x00040020u, 0x00000014u, 0x00000009u, 0x0000000fu, + 0x0004003bu, 0x00000014u, 0x00000015u, 0x00000009u, 0x00040015u, 0x00000016u, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x00000016u, 0x00000017u, 0x00000004u, 0x00040020u, 0x00000018u, 0x00000009u, 0x00000006u, + 0x00020014u, 0x0000001bu, 0x0004002bu, 0x00000006u, 0x0000001fu, 0x00000000u, 0x0004002bu, 0x00000016u, + 0x00000021u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000024u, 0x00000020u, 0x0004002bu, 0x00000016u, + 0x00000028u, 0x00000000u, 0x00040020u, 0x00000029u, 0x00000009u, 0x0000000du, 0x00040020u, 0x0000002du, + 0x000014e5u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x00000033u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000003au, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000040u, 0x00000010u, 0x0004002bu, 0x00000006u, + 0x00000043u, 0x0000ffffu, 0x00040017u, 0x00000048u, 0x00000006u, 0x00000003u, 0x00040020u, 0x00000049u, + 0x00000001u, 0x00000048u, 0x0004003bu, 0x00000049u, 0x0000004au, 0x00000001u, 0x00040020u, 0x0000004bu, + 0x00000001u, 0x00000006u, 0x0004002bu, 0x00000016u, 0x0000004fu, 0x00000005u, 0x0004002bu, 0x00000006u, + 0x00000058u, 0x00000004u, 0x0004002bu, 0x00000006u, 0x00000065u, 0x00000002u, 0x0004002bu, 0x00000006u, + 0x0000006bu, 0x00000003u, 0x0004002bu, 0x00000006u, 0x00000071u, 0x00000006u, 0x0004002bu, 0x00000016u, + 0x00000073u, 0x00000001u, 0x00040020u, 0x00000074u, 0x00000009u, 0x0000000eu, 0x0004002bu, 0x00000006u, + 0x00000095u, 0x00000005u, 0x0004002bu, 0x00000006u, 0x00000099u, 0x00000040u, 0x0006002cu, 0x00000048u, + 0x0000009au, 0x00000099u, 0x0000003au, 0x0000003au, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, + 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x0000009bu, 0x00000000u, 0x000300fbu, 0x0000001fu, + 0x0000009cu, 0x000200f8u, 0x0000009cu, 0x00050041u, 0x0000004bu, 0x0000004cu, 0x0000004au, 0x0000001fu, + 0x0004003du, 0x00000006u, 0x0000004du, 0x0000004cu, 0x00050041u, 0x00000018u, 0x00000050u, 0x00000015u, + 0x0000004fu, 0x0004003du, 0x00000006u, 0x00000051u, 0x00000050u, 0x000500aeu, 0x0000001bu, 0x00000052u, + 0x0000004du, 0x00000051u, 0x000300f7u, 0x00000054u, 0x00000000u, 0x000400fau, 0x00000052u, 0x00000053u, + 0x00000054u, 0x000200f8u, 0x00000053u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x00000054u, 0x00050084u, + 0x00000006u, 0x00000059u, 0x0000004du, 0x00000058u, 0x000300f7u, 0x000000cbu, 0x00000000u, 0x000300fbu, + 0x0000001fu, 0x000000abu, 0x000200f8u, 0x000000abu, 0x00050041u, 0x00000018u, 0x000000adu, 0x00000015u, + 0x00000017u, 0x0004003du, 0x00000006u, 0x000000aeu, 0x000000adu, 0x000500aeu, 0x0000001bu, 0x000000afu, + 0x00000059u, 0x000000aeu, 0x000300f7u, 0x000000b1u, 0x00000000u, 0x000400fau, 0x000000afu, 0x000000b0u, + 0x000000b1u, 0x000200f8u, 0x000000b0u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000b1u, 0x00050041u, + 0x00000018u, 0x000000b2u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x000000b2u, + 0x000500aau, 0x0000001bu, 0x000000b4u, 0x000000b3u, 0x00000024u, 0x000300f7u, 0x000000bbu, 0x00000000u, + 0x000400fau, 0x000000b4u, 0x000000b5u, 0x000000bbu, 0x000200f8u, 0x000000b5u, 0x00050041u, 0x00000029u, + 0x000000b6u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000b7u, 0x000000b6u, 0x00060041u, + 0x0000002du, 0x000000b9u, 0x000000b7u, 0x00000028u, 0x00000059u, 0x0006003du, 0x00000006u, 0x000000bau, + 0x000000b9u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000bbu, 0x00050041u, + 0x00000018u, 0x000000bdu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000beu, 0x000000bdu, + 0x00050080u, 0x00000006u, 0x000000bfu, 0x00000059u, 0x000000beu, 0x00050041u, 0x00000029u, 0x000000c0u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000c1u, 0x000000c0u, 0x000500c2u, 0x00000006u, + 0x000000c3u, 0x000000bfu, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000c4u, 0x000000c1u, 0x00000028u, + 0x000000c3u, 0x0006003du, 0x00000006u, 0x000000c5u, 0x000000c4u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000c7u, 0x000000bfu, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000c8u, 0x000000c7u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000c9u, 0x000000c5u, 0x000000c8u, 0x000500c7u, 0x00000006u, + 0x000000cau, 0x000000c9u, 0x00000043u, 0x000200f9u, 0x000000cbu, 0x000200f8u, 0x000000cbu, 0x000900f5u, + 0x00000006u, 0x00000142u, 0x0000001fu, 0x000000b0u, 0x000000bau, 0x000000b5u, 0x000000cau, 0x000000bbu, + 0x00050080u, 0x00000006u, 0x00000060u, 0x00000059u, 0x0000003au, 0x000300f7u, 0x000000f2u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000d2u, 0x000200f8u, 0x000000d2u, 0x000500aeu, 0x0000001bu, 0x000000d6u, + 0x00000060u, 0x000000aeu, 0x000300f7u, 0x000000d8u, 0x00000000u, 0x000400fau, 0x000000d6u, 0x000000d7u, + 0x000000d8u, 0x000200f8u, 0x000000d7u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000d8u, 0x00050041u, + 0x00000018u, 0x000000d9u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x000000dau, 0x000000d9u, + 0x000500aau, 0x0000001bu, 0x000000dbu, 0x000000dau, 0x00000024u, 0x000300f7u, 0x000000e2u, 0x00000000u, + 0x000400fau, 0x000000dbu, 0x000000dcu, 0x000000e2u, 0x000200f8u, 0x000000dcu, 0x00050041u, 0x00000029u, + 0x000000ddu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000deu, 0x000000ddu, 0x00060041u, + 0x0000002du, 0x000000e0u, 0x000000deu, 0x00000028u, 0x00000060u, 0x0006003du, 0x00000006u, 0x000000e1u, + 0x000000e0u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000e2u, 0x00050041u, + 0x00000018u, 0x000000e4u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x000000e5u, 0x000000e4u, + 0x00050080u, 0x00000006u, 0x000000e6u, 0x00000060u, 0x000000e5u, 0x00050041u, 0x00000029u, 0x000000e7u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x000000e8u, 0x000000e7u, 0x000500c2u, 0x00000006u, + 0x000000eau, 0x000000e6u, 0x0000003au, 0x00060041u, 0x0000002du, 0x000000ebu, 0x000000e8u, 0x00000028u, + 0x000000eau, 0x0006003du, 0x00000006u, 0x000000ecu, 0x000000ebu, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x000000eeu, 0x000000e6u, 0x0000003au, 0x00050084u, 0x00000006u, 0x000000efu, 0x000000eeu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x000000f0u, 0x000000ecu, 0x000000efu, 0x000500c7u, 0x00000006u, + 0x000000f1u, 0x000000f0u, 0x00000043u, 0x000200f9u, 0x000000f2u, 0x000200f8u, 0x000000f2u, 0x000900f5u, + 0x00000006u, 0x00000144u, 0x0000001fu, 0x000000d7u, 0x000000e1u, 0x000000dcu, 0x000000f1u, 0x000000e2u, + 0x00050080u, 0x00000006u, 0x00000066u, 0x00000059u, 0x00000065u, 0x000300f7u, 0x00000119u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x000000f9u, 0x000200f8u, 0x000000f9u, 0x000500aeu, 0x0000001bu, 0x000000fdu, + 0x00000066u, 0x000000aeu, 0x000300f7u, 0x000000ffu, 0x00000000u, 0x000400fau, 0x000000fdu, 0x000000feu, + 0x000000ffu, 0x000200f8u, 0x000000feu, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x000000ffu, 0x00050041u, + 0x00000018u, 0x00000100u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000101u, 0x00000100u, + 0x000500aau, 0x0000001bu, 0x00000102u, 0x00000101u, 0x00000024u, 0x000300f7u, 0x00000109u, 0x00000000u, + 0x000400fau, 0x00000102u, 0x00000103u, 0x00000109u, 0x000200f8u, 0x00000103u, 0x00050041u, 0x00000029u, + 0x00000104u, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000105u, 0x00000104u, 0x00060041u, + 0x0000002du, 0x00000107u, 0x00000105u, 0x00000028u, 0x00000066u, 0x0006003du, 0x00000006u, 0x00000108u, + 0x00000107u, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000109u, 0x00050041u, + 0x00000018u, 0x0000010bu, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x0000010cu, 0x0000010bu, + 0x00050080u, 0x00000006u, 0x0000010du, 0x00000066u, 0x0000010cu, 0x00050041u, 0x00000029u, 0x0000010eu, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000010fu, 0x0000010eu, 0x000500c2u, 0x00000006u, + 0x00000111u, 0x0000010du, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000112u, 0x0000010fu, 0x00000028u, + 0x00000111u, 0x0006003du, 0x00000006u, 0x00000113u, 0x00000112u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x00000115u, 0x0000010du, 0x0000003au, 0x00050084u, 0x00000006u, 0x00000116u, 0x00000115u, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x00000117u, 0x00000113u, 0x00000116u, 0x000500c7u, 0x00000006u, + 0x00000118u, 0x00000117u, 0x00000043u, 0x000200f9u, 0x00000119u, 0x000200f8u, 0x00000119u, 0x000900f5u, + 0x00000006u, 0x00000146u, 0x0000001fu, 0x000000feu, 0x00000108u, 0x00000103u, 0x00000118u, 0x00000109u, + 0x00050080u, 0x00000006u, 0x0000006cu, 0x00000059u, 0x0000006bu, 0x000300f7u, 0x00000140u, 0x00000000u, + 0x000300fbu, 0x0000001fu, 0x00000120u, 0x000200f8u, 0x00000120u, 0x000500aeu, 0x0000001bu, 0x00000124u, + 0x0000006cu, 0x000000aeu, 0x000300f7u, 0x00000126u, 0x00000000u, 0x000400fau, 0x00000124u, 0x00000125u, + 0x00000126u, 0x000200f8u, 0x00000125u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000126u, 0x00050041u, + 0x00000018u, 0x00000127u, 0x00000015u, 0x00000021u, 0x0004003du, 0x00000006u, 0x00000128u, 0x00000127u, + 0x000500aau, 0x0000001bu, 0x00000129u, 0x00000128u, 0x00000024u, 0x000300f7u, 0x00000130u, 0x00000000u, + 0x000400fau, 0x00000129u, 0x0000012au, 0x00000130u, 0x000200f8u, 0x0000012au, 0x00050041u, 0x00000029u, + 0x0000012bu, 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x0000012cu, 0x0000012bu, 0x00060041u, + 0x0000002du, 0x0000012eu, 0x0000012cu, 0x00000028u, 0x0000006cu, 0x0006003du, 0x00000006u, 0x0000012fu, + 0x0000012eu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000130u, 0x00050041u, + 0x00000018u, 0x00000132u, 0x00000015u, 0x00000033u, 0x0004003du, 0x00000006u, 0x00000133u, 0x00000132u, + 0x00050080u, 0x00000006u, 0x00000134u, 0x0000006cu, 0x00000133u, 0x00050041u, 0x00000029u, 0x00000135u, + 0x00000015u, 0x00000028u, 0x0004003du, 0x0000000du, 0x00000136u, 0x00000135u, 0x000500c2u, 0x00000006u, + 0x00000138u, 0x00000134u, 0x0000003au, 0x00060041u, 0x0000002du, 0x00000139u, 0x00000136u, 0x00000028u, + 0x00000138u, 0x0006003du, 0x00000006u, 0x0000013au, 0x00000139u, 0x00000002u, 0x00000004u, 0x000500c7u, + 0x00000006u, 0x0000013cu, 0x00000134u, 0x0000003au, 0x00050084u, 0x00000006u, 0x0000013du, 0x0000013cu, + 0x00000040u, 0x000500c2u, 0x00000006u, 0x0000013eu, 0x0000013au, 0x0000013du, 0x000500c7u, 0x00000006u, + 0x0000013fu, 0x0000013eu, 0x00000043u, 0x000200f9u, 0x00000140u, 0x000200f8u, 0x00000140u, 0x000900f5u, + 0x00000006u, 0x00000148u, 0x0000001fu, 0x00000125u, 0x0000012fu, 0x0000012au, 0x0000013fu, 0x00000130u, + 0x00050084u, 0x00000006u, 0x00000072u, 0x0000004du, 0x00000071u, 0x00050041u, 0x00000074u, 0x00000075u, + 0x00000015u, 0x00000073u, 0x0004003du, 0x0000000eu, 0x00000076u, 0x00000075u, 0x00060041u, 0x0000002du, + 0x00000079u, 0x00000076u, 0x00000028u, 0x00000072u, 0x0005003eu, 0x00000079u, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000007du, 0x00000072u, 0x0000003au, 0x00060041u, 0x0000002du, + 0x0000007fu, 0x00000076u, 0x00000028u, 0x0000007du, 0x0005003eu, 0x0000007fu, 0x00000144u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000083u, 0x00000072u, 0x00000065u, 0x00060041u, 0x0000002du, + 0x00000085u, 0x00000076u, 0x00000028u, 0x00000083u, 0x0005003eu, 0x00000085u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000089u, 0x00000072u, 0x0000006bu, 0x00060041u, 0x0000002du, + 0x0000008bu, 0x00000076u, 0x00000028u, 0x00000089u, 0x0005003eu, 0x0000008bu, 0x00000142u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x0000008fu, 0x00000072u, 0x00000058u, 0x00060041u, 0x0000002du, + 0x00000091u, 0x00000076u, 0x00000028u, 0x0000008fu, 0x0005003eu, 0x00000091u, 0x00000146u, 0x00000002u, + 0x00000004u, 0x00050080u, 0x00000006u, 0x00000096u, 0x00000072u, 0x00000095u, 0x00060041u, 0x0000002du, + 0x00000098u, 0x00000076u, 0x00000028u, 0x00000096u, 0x0005003eu, 0x00000098u, 0x00000148u, 0x00000002u, + 0x00000004u, 0x000200f9u, 0x0000009bu, 0x000200f8u, 0x0000009bu, 0x000100fdu, 0x00010038u, +}; +} // namespace leonida diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h index f7a9e80e93..5682d9e543 100644 --- a/runtime/src/queue_families.h +++ b/runtime/src/queue_families.h @@ -25,6 +25,16 @@ constexpr bool copy_queue_timestamp_families_supported(std::span +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 c6e47b0c08..c807fb2bcd 100644 --- a/runtime/src/rect_list_geometry.h +++ b/runtime/src/rect_list_geometry.h @@ -42,6 +42,7 @@ namespace leonida { constexpr std::uint32_t topology_rect_list = 17; constexpr std::uint32_t topology_quad_list = 19; constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; // The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { @@ -99,6 +100,10 @@ inline std::vector rect_list_geometry(const std::vector +#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 6082681190..6e97d7f1d1 100644 --- a/runtime/src/title_va_alias.h +++ b/runtime/src/title_va_alias.h @@ -16,6 +16,7 @@ // 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). +#include #include #include #include @@ -266,6 +267,9 @@ class TitleVaAliases { resolver_ = nullptr; scanner_ = nullptr; } + // The resolver alone, for a device that scans its descriptor tables itself. + void set_resolver(void* context, Resolver resolver) { set_hooks(context, resolver, nullptr); } + void clear_resolver(void* context) { clear_hooks(context); } std::size_t size() const { return count_.load(std::memory_order_acquire); } std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h index ea65caa2d2..8f2dd61f83 100644 --- a/runtime/src/vulkan13_features.h +++ b/runtime/src/vulkan13_features.h @@ -32,6 +32,8 @@ class Vulkan13Features { 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 @@ class Vulkan13Features { 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 @@ class Vulkan13Features { 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 @@ class Vulkan13Features { // 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 @@ class Vulkan13Features { 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 237a113bae..9652fd51b7 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 @@ -97,7 +98,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) \ @@ -993,6 +994,9 @@ class VulkanContext { bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false) : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { loaded_ = vk.load(get, device); + if (loaded_ && gpu_labels_.initialize(device, get)) { + replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; + } replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; replay_.clear_color_image = vk.vkCmdClearColorImage; replay_.clear_depth_stencil_image = vk.vkCmdClearDepthStencilImage; @@ -1004,6 +1008,7 @@ class VulkanContext { 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; @@ -1152,6 +1157,7 @@ class VulkanContext { ~VulkanContext() { progress_watch_ = {}; // stop before queues, timelines or diagnostic state go away + gpu_labels_.stop(device_); fence_dispatcher_.reset(); deletion_queue_.drain(UINT64_MAX, device_, vk); for (const auto& [key, framebuffer] : resolve_framebuffers_) @@ -1198,6 +1204,13 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); counted_dispatch_ = std::make_unique(get, device_, memory, limits); } + // Indexed quad lists are drawn from triangle indices a compute pass writes into the copy scratch + // (quad_index_expand.h). Call only with bufferDeviceAddress enabled and after an enable_copy_scratch whose chunks + // have INDEX_BUFFER and SHADER_DEVICE_ADDRESS usage on memory allocated with a device address. + void configure_quad_indices(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { + std::unique_lock lock(resource_mutex_); + quad_indices_ = std::make_unique(get, device_, limits); + } VkDevice device() const { return device_; } // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets @@ -1283,6 +1296,7 @@ class VulkanContext { } { 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) { @@ -1360,7 +1374,25 @@ class VulkanContext { replay_.depth_range_unrestricted = enabled; } - // 0, 1, 2, ... as 32-bit indices, for non-indexed quad lists (ReplayFunctions::quad_indices). + 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_); + replay_.title_memory = std::move(copy); + } + + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { std::unique_lock lock(resource_mutex_); replay_.quad_indices = buffer; @@ -1461,6 +1493,23 @@ class VulkanContext { return resources_.find(id) != resources_.end(); } + // The registered buffer whose VA range holds `va`, preferring one that holds [va, va + bytes) as buffer_at does: its + // ID, first VA and size in bytes. False when none does, or when `acquire(id)` returns false. `acquire` runs with + // the registry locked, so the resource cannot finish being removed under it: it takes the caller's reference + // (Resource's destructor removes its entry first, which waits for this lock). Used where a console call names a + // buffer by VA only (Xbox device slot 70). + template + bool buffer_resource_at(std::uint64_t va, std::uint64_t bytes, ResourceId& id, std::uint64_t& start, + std::uint64_t& size, Acquire&& acquire) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + if (!buffer_vas_.find(va, hit, bytes) || !acquire(hit.id)) return false; + id = hit.id; + start = hit.start; + size = hit.size; + return true; + } + bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } @@ -1535,6 +1584,33 @@ class VulkanContext { // 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. + // (The per-device scan is from the patch descriptor-table-refresh, part 2, of + // Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b, GPL-3.0.) + 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); + } + // False when this context has no scanner of its own. + bool scan_table(std::uint64_t va, std::uint32_t descriptors) const { + if (!table_scanner_) return false; + table_scanner_(va, descriptors); + return true; + } // `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. @@ -1558,7 +1634,6 @@ class VulkanContext { const auto it = device_fault_->pipeline_names.find(id); return it == device_fault_->pipeline_names.end() ? nullptr : it->second[0]; } - void set_before_execute(std::function before) { before_execute_ = std::move(before); } void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); @@ -1583,10 +1658,13 @@ class VulkanContext { } // 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) { + // `allocate`. Without this such a copy is refused as unsupported. `extra_usage` is added to the chunks' transfer + // usage, for configure_quad_indices. + void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate, + VkBufferUsageFlags extra_usage = 0, std::vector families = {}) { std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate), device_fault_.get()); + scratch_ = std::make_unique(get, device_, std::move(allocate), extra_usage, std::move(families), + device_fault_.get()); if (!scratch_->loaded()) scratch_.reset(); } @@ -1762,10 +1840,13 @@ class VulkanContext { const ResourceBinding* resolve(ResourceId id) const { const auto it = resources_.find(id); if (it == resources_.end()) return nullptr; - if (auto* memory = it->second.deferred_memory; memory && !memory->ensure()) return nullptr; - if (auto* seen = it->second.replay_seen; seen && !seen->load(std::memory_order_relaxed)) + const auto& binding = it->second; + if (auto* memory = binding.deferred_memory; memory && !memory->ensure()) return nullptr; + // 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; + if (auto* seen = binding.replay_seen; seen && !seen->load(std::memory_order_relaxed)) seen->store(true, std::memory_order_relaxed); - return &it->second; + return &binding; } // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. @@ -1944,6 +2025,10 @@ class VulkanContext { std::map, VkFramebuffer> resolve_framebuffers_; std::function before_execute_; InputProbe input_probe_; + 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_ @@ -1959,12 +2044,15 @@ class VulkanContext { double timestamp_period_ = 0; bool order_timestamp_copies_ = false; VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; + label::Completions gpu_labels_; ReplayFunctions replay_; std::unique_ptr predicate_reducer_; std::unique_ptr predicated_copier_; std::unique_ptr counted_dispatch_; + std::unique_ptr quad_indices_; 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 @@ -2562,6 +2650,23 @@ class VulkanQueue : private QueueHolds::Holder { ReplayFunctions replay = context_.replay_; unsigned mesh_draws = 0; if (pipeline_profile::enabled()) replay.mesh_draw_count = &mesh_draws; + 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; @@ -2632,6 +2737,19 @@ class VulkanQueue : private QueueHolds::Holder { context_.counted_dispatch_->emit(cb, job); }; } + if (kind_ != QueueKind::copy && context_.quad_indices_ && context_.scratch_) { + replay.prepare_quad_indices = [this, &tracker_lock]( + VkBuffer indices, VkDeviceSize offset, VkIndexType type, std::uint64_t readable, std::uint32_t quads, + VkBuffer scratch, VkDeviceSize scratch_offset, QuadIndexExpansion& out) { + // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. + if (!tracker_lock.owns_lock()) tracker_lock.lock(); + return context_.quad_indices_->prepare(indices, offset, type, readable, quads, scratch, + scratch_offset, out); + }; + replay.emit_quad_indices = [this](VkCommandBuffer cb, const QuadIndexExpansion& job) { + context_.quad_indices_->emit(cb, job); + }; + } if (context_.depth24_ && !transfer_only) { replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, std::vector& parts) { @@ -2782,6 +2900,7 @@ class VulkanQueue : private QueueHolds::Holder { }; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + context_.gpu_labels_.begin_record(command_buffer); if (context_.observe_result(context_.vk.vkBeginCommandBuffer(command_buffer, &begin), "vkBeginCommandBuffer") != VK_SUCCESS) { discard(); @@ -2839,8 +2958,7 @@ class VulkanQueue : private QueueHolds::Holder { 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_); @@ -2966,6 +3084,7 @@ class VulkanQueue : private QueueHolds::Holder { slot->counted_dispatch = std::move(counted_batch); queries.commit(); slot->segments = std::move(queries.retained); + slot->geometry = std::move(geometry); } else { discard(); } @@ -3201,6 +3320,7 @@ class VulkanQueue : private QueueHolds::Holder { 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 { @@ -3223,6 +3343,7 @@ class VulkanQueue : private QueueHolds::Holder { auto& vk = context_.vk; VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + context_.gpu_labels_.begin_record(command_buffer); if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { slot->ticket = 0; return false; @@ -3363,6 +3484,7 @@ class VulkanQueue : private QueueHolds::Holder { 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) @@ -3503,8 +3625,10 @@ class VulkanQueue : private QueueHolds::Holder { submit.pSignalSemaphores = signals; // Publish before the driver can execute a marker or a concurrent fence wait can see the loss. if (diagnostics) context_.device_fault()->publish(std::move(*diagnostics)); - res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE), + const auto label_fence=context_.gpu_labels_.submit_fence(command_buffer); + res = context_.observe_result(context_.vk.vkQueueSubmit(queue_, 1, &submit, label_fence), "vkQueueSubmit"); + context_.gpu_labels_.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 179ba12e9c..589cadffd4 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 sampled arrays of every // single-sample dimension, the samplers and the storage arrays from the device's limits instead; the shaders declare // runtime arrays, so any count works for them. @@ -53,6 +54,7 @@ #define VK_NO_PROTOTYPES #endif #include "descriptor_table.h" +#include "queue_families.h" #include @@ -62,12 +64,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). @@ -80,7 +83,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 @@ -104,10 +107,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}, @@ -121,6 +126,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); @@ -131,8 +138,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 @@ -141,7 +152,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]; } @@ -163,12 +175,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; } @@ -206,7 +219,7 @@ struct SetLayout { }; // What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 5-10 MiB (about 160000 descriptors on an RTX 5070). +// 5-10 MiB with 153697 descriptors when all MS classes and array bindings reach their limits (an RTX 5070). inline constexpr std::uint32_t max_2d_images = 65536; // The other single-sample dimensions: a title streams far more cube maps and texture arrays (and 1D lookup // textures) than the 1024 and 256 of the defaults, each distinct T# of one taking its own index. @@ -230,8 +243,9 @@ inline constexpr std::uint32_t growth_headroom = 64; // 3. Growth towards the maximums above, in the same order, then the 2D-array, 3D and 1D images, 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. @@ -270,10 +284,13 @@ inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimi counts[sampled_binding(ImageDimension::dim_3d)] = volumes; counts[sampled_binding(ImageDimension::dim_1d)] = lines; 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; } @@ -341,8 +358,10 @@ class BindlessSet { // `descriptor_hash` is the finalizer the shaders of this device probe the table with (descriptor_table.h); it is // handed to the table before its first key is inserted, so every insert, lookup and rehash agrees with them. BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a) - : device_(device), memory_(memory), features_(features), table_(64, descriptor_hash) { + BindlessFeatures features = {}, DescriptorHashKind descriptor_hash = DescriptorHashKind::fnv1a, + std::vector families = {}) + : device_(device), memory_(memory), features_(features), families_(std::move(families)), + table_(64, descriptor_hash) { ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); } @@ -371,7 +390,8 @@ class BindlessSet { // 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)]; @@ -430,6 +450,7 @@ class BindlessSet { 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)); @@ -700,7 +721,7 @@ class BindlessSet { VkDescriptorImageInfo info; }; - static constexpr std::uint32_t dimensions = 6, classes = 3; + static constexpr std::uint32_t dimensions = 7, classes = 3; // image_used_ and sampler_used_: 0 free, in_use, or held (removed while the table was dirty: free after the next // flush that does not degrade). static constexpr std::uint8_t in_use = 1, held = 2; @@ -815,10 +836,11 @@ class BindlessSet { 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; @@ -833,6 +855,7 @@ class BindlessSet { 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); @@ -857,8 +880,9 @@ class BindlessSet { 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); @@ -884,6 +908,7 @@ class BindlessSet { (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 (const VkResult result = vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer); result != VK_SUCCESS) { made.buffer = VK_NULL_HANDLE; note_failure(what, result); @@ -1188,8 +1213,9 @@ class BindlessSet { 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, @@ -1204,6 +1230,7 @@ class BindlessSet { 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 0000000000..32590cc392 --- /dev/null +++ b/runtime/src/vulkan_gpu_labels.h @@ -0,0 +1,299 @@ +#pragma once +#include "gpu_label_memory.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include "title_page_watch.h" +#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; +} +// Stores a completed label into the title's memory: only into a committed, private, writable page of the allocation +// the label was captured in, and only while that allocation's generation is the captured one (Memory::publish). +// +// A page the D3D12 layer watches for the title's writes is read-only while it waits (title_page_watch.h), and it is +// writable as far as the title knows. Such a page is announced and opened the way a kernel write is +// (kernel_writes::begin_write), so the label reaches it and the layer copies the page again; a page that stays +// read-only after that is the title's own doing and the label is dropped, as before. Called with no shadow lock held. +inline bool store_value(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{}; + const auto in_allocation = [&] { + return 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); + }; + if (!in_allocation()) return false; + std::uint64_t pin = 0; + if ((mbi.Protect & 0xff) == PAGE_READONLY) { + pin = kernel_writes::begin_write(reinterpret_cast(address), width, nullptr); + if (!pin || !in_allocation()) { + kernel_writes::end_write(pin, false); + return false; + } + } + const auto begin = reinterpret_cast(mbi.BaseAddress); + const bool writable = (mbi.Protect & 0xff) == PAGE_READWRITE || (mbi.Protect & 0xff) == PAGE_WRITECOPY; + const bool inside = address >= begin && address - begin <= mbi.RegionSize && + mbi.RegionSize - (address - begin) >= width; + if (writable && inside) { + if (width == 4) + InterlockedExchange(reinterpret_cast(address), static_cast(value)); + else + InterlockedExchange64(reinterpret_cast(address), static_cast(value)); + } + kernel_writes::end_write(pin, false); + return writable && inside; + }); +#else + (void)target; + (void)value; + return false; +#endif +} + +// 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_; + 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 expired_ = 0, errors_ = 0; + 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) { return store_value(target, value); } + void publish(const Batch &batch) { + for (std::size_t i = 0; i < batch.labels.size(); ++i) { + const Write &op = batch.labels[i]; + std::uint64_t value = op.value; + if (op.clock == 1) { + if (results_(device_, batch.pools[i / per_pool], static_cast(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)) ++expired_; + } + } + void run() { + std::unique_lock lock(mutex_); + for (;;) { + if (pending_.empty() && !closing_) changed_.wait(lock, [&] { return closing_ || !pending_.empty(); }); + 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() { stop(device_); } + + bool initialize(VkDevice dev, PFN_vkGetDeviceProcAddr get) { + if (!enabled() || !dev || !get) return false; + std::lock_guard lock(mutex_); + if (device_) return device_ == dev; +#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 false; + device_ = dev; + closing_ = false; + worker_ = std::thread([this] { run(); }); + return true; + } + 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(); + if (errors_) { + std::fprintf(stderr, "[rt] d3d12: %llu GPU label operations failed, %llu destinations expired\n", + static_cast(errors_), static_cast(expired_)); + } + expired_ = errors_ = 0; + device_ = VK_NULL_HANDLE; + } +}; +} // 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 0000000000..f3f7ef7423 --- /dev/null +++ b/runtime/src/vulkan_graphics_shader_modules.h @@ -0,0 +1,65 @@ +#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) { + if (words.empty()) return {}; + std::uint64_t hash = 14695981039346656037ull; + for (std::uint32_t word : words) + hash = (hash ^ word) * 1099511628211ull; + { + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) 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 {}; + } + std::lock_guard lock(mutex_); + if (auto found = find_locked(hash, words)) return found; + if ((++created_ % 1024) == 0) std::erase_if(modules_, [](const auto &entry) { return entry.second.expired(); }); + modules_.emplace(hash, result); + return result; + } + + 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; +}; +} // namespace leonida diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 3b6d071329..f01167cf4a 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -29,6 +29,7 @@ #include "vulkan_present_compose.h" #include "fsdraw_probe.h" // LOCAL DIAGNOSTIC #include "local_diagnostics.h" +#include "present_dump.h" // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -657,7 +658,15 @@ class VulkanPresenter { // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - ++presented_; + const auto shown = ++presented_; + if (dump_.due(shown - 1)) { + // Presentation is already queued and the queue/tracker locks are released. A sampled frame + // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker. + if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS) + dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_)); + else + dump_.disable("present dump fence wait failed"); + } if (planes) ++composed_; if (tearing) { last_tore_ = true; @@ -1304,7 +1313,7 @@ class VulkanPresenter { const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_ && capture_buffer_) { + if (capture_buffer_ && (capture_ || dump_.due(presented_))) { // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -1331,6 +1340,10 @@ class VulkanPresenter { copy.imageExtent = {extent_.width, extent_.height, 1}; fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, ©); + auto to_host = capture_waw; + to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + 0, nullptr, 1, &to_host, 0, nullptr); layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; access = VK_ACCESS_TRANSFER_READ_BIT; } @@ -1343,7 +1356,7 @@ class VulkanPresenter { release_capture(); auto& vk = context_.vk; const VkDevice device = context_.device(); - capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; + capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = capture_size_; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; @@ -1533,7 +1546,9 @@ class VulkanPresenter { return true; } VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) + dump_.disable("surface does not support swapchain readback"); + if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if ((caps.supportedUsageFlags & usage) != usage) return false; // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it @@ -1678,13 +1693,14 @@ class VulkanPresenter { extent_ = extent; extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; hdr_active_ = chose_hdr; - if (capture_) { - // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. - const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || - format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || - format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || - format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - if (!four_bytes || !make_capture_buffer()) return false; + dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT; + if (capture_ || dump_.enabled()) { + const auto stride = present_dump::texel_size(format_); + if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel + if (!stride || !make_capture_buffer()) { + dump_.disable("cannot read back this swapchain format or allocate its capture buffer"); + if (capture_) return false; + } } vsync_ = vsync; swapchain_srgb_ = srgb; @@ -1799,6 +1815,8 @@ class VulkanPresenter { ResourceId splash_source_{}; bool splash_capture_only_ = false; bool capture_ = false; + present_dump::PresentDump dump_; + bool dump_pq_ = false; VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; VkDeviceSize capture_size_ = 0; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index aff2c07ba3..2fef871943 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include #include "resource_tiling.h" @@ -36,6 +37,7 @@ #include "deferred_image_binding.h" #include "vulkan_device_fault.h" #include "depth24.h" +#include "quad_index_expand.h" #include "rect_list_geometry.h" #include "uav_clear.h" @@ -107,6 +109,13 @@ struct ResourceBinding { bool sparse_buffer = false; DeferredImageBinding* deferred_memory = nullptr; // Owned by the placed resource until it leaves the context. std::atomic* replay_seen = nullptr; // Optional census of placed image use under the resource lock. + 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 { @@ -475,6 +484,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: @@ -816,7 +826,10 @@ 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; - std::function variant; + static constexpr std::uint32_t rectangle_stage = 1u << 9; + // IA topology requiring a fourth-corner geometry stage. Zero when the PSO already contains the stage. + std::uint32_t rectangle_variant_topology = 0; + std::function variant; std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count bool async_build = false; }; @@ -903,6 +916,7 @@ inline ReplayResult unsupported_at(int line) { struct ReplayFunctions { + std::function gpu_label; // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. VkDescriptorSet bindless_set = VK_NULL_HANDLE; @@ -913,6 +927,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; @@ -920,6 +937,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 @@ -965,6 +983,10 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; + // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false + // when the range is not readable host memory. + std::function title_memory; // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. std::function host_at; @@ -972,7 +994,7 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; - // 0, 1, 2, ... as 32-bit indices: what a non-indexed quad list is drawn with (quad_index_count of them). + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. VkBuffer quad_indices = VK_NULL_HANDLE; VkDeviceSize quad_indices_offset = 0; std::uint32_t quad_index_count = 0; @@ -1008,6 +1030,14 @@ struct ReplayFunctions { std::function prepare_counted_dispatch; std::function emit_counted_dispatch; + // An indexed quad list draws from triangle-list indices that a compute prepass writes from the application's + // index buffer (quad_index_expand.h): the index buffer and the offset of the draw's first index, the index type, + // how many indices from there the view holds, the quads, and QuadIndexExpander::bytes(quads) of `copy_scratch`. + // That scratch must be usable as an index buffer and through its device address. Without both such a draw is + // unsupported. + std::function prepare_quad_indices; + std::function emit_quad_indices; // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan @@ -1051,7 +1081,8 @@ struct ReplayFunctions { std::function&)> depth24_prepare; // whole copy in, dispatches out std::function depth24_run; // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour - // copies go through it, image to buffer to image. Without it such a copy is unsupported. + // copies go through it, image to buffer to image. Without it such a copy is unsupported. The expanded indices of + // an indexed quad list are written there too (prepare_quad_indices). std::function copy_scratch; // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. std::function query_pool; @@ -1137,6 +1168,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; @@ -1148,6 +1180,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 @@ -1155,6 +1189,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 @@ -1176,7 +1230,9 @@ struct PreparedDraw { std::vector vertex_offsets, vertex_sizes, vertex_strides; VkBuffer index_buffer = VK_NULL_HANDLE; VkDeviceSize index_offset = 0; + VkDeviceSize index_size = 0; // the bytes of the index buffer view inside its buffer; 0 with no index buffer VkIndexType index_type = VK_INDEX_TYPE_UINT16; + QuadIndexExpansion quad_indices; // an indexed quad list: the triangle indices its draw binds instead VkExtent2D area{}; std::uint32_t layers = 1; // the fewest layers any bound attachment view has // The draw is dropped at emit: its pipeline, a vertex buffer or its index buffer could not be resolved (see @@ -1196,7 +1252,9 @@ struct PreparedDraw { vertex_strides.clear(); index_buffer = VK_NULL_HANDLE; index_offset = 0; + index_size = 0; index_type = VK_INDEX_TYPE_UINT16; + quad_indices = {}; area = {}; layers = 1; } @@ -1473,14 +1531,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 = @@ -1514,7 +1570,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; @@ -1556,7 +1612,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; @@ -1569,7 +1625,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); @@ -1583,7 +1639,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); @@ -1602,7 +1658,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); @@ -1618,6 +1674,14 @@ inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer com return true; } +// The colour aspect of a block-compressed image: 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) { + return zero_image_aspect(vk, command_buffer, resource, range, VK_IMAGE_ASPECT_COLOR_BIT, dst_layout); +} + // Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed, // so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats // when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run @@ -1629,12 +1693,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)); @@ -1643,7 +1710,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, @@ -2229,6 +2299,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 { @@ -2315,6 +2456,8 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. std::uint32_t unbound = 0; + if (pipeline->rectangle_variant_topology && draw.topology == pipeline->rectangle_variant_topology) + unbound |= GraphicsPipeline::rectangle_stage; 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; @@ -2348,17 +2491,20 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct const VertexBufferView& view = draw.views->vertex_buffers[slot]; std::uint64_t size = view.size; if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { - static std::atomic logged{0}; // LOCAL DIAGNOSTIC: where the unresolved vertex data lives - if (logged.fetch_add(1, std::memory_order_relaxed) < 24) - std::fprintf(stderr, "[rt] replay: vertex buffer slot %u va 0x%llx size %llu stride %u names no buffer\n", - slot, static_cast(view.va), - static_cast(view.size), unsigned(view.stride)); - return unresolved_at(__LINE__); + size = view.size; + if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { + static std::atomic logged{0}; // LOCAL DIAGNOSTIC: where the unresolved vertex data lives + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, "[rt] replay: vertex buffer slot %u va 0x%llx size %llu stride %u names no buffer\n", + slot, static_cast(view.va), + static_cast(view.size), unsigned(view.stride)); + return unresolved_at(__LINE__); + } } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } - // A non-indexed quad list is drawn from the shared 0, 1, 2, ... index buffer (emit). + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) return unresolved_at(__LINE__); if (draw.indexed) { @@ -2372,18 +2518,46 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct } else { std::uint64_t size = draw.index.size; if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { - static std::atomic logged{0}; // LOCAL DIAGNOSTIC - if (logged.fetch_add(1, std::memory_order_relaxed) < 24) - std::fprintf(stderr, "[rt] replay: index buffer va 0x%llx size %llu names no buffer\n", - static_cast(draw.index.va), - static_cast(draw.index.size)); - return unresolved_at(__LINE__); + size = draw.index.size; + if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) { + static std::atomic logged{0}; // LOCAL DIAGNOSTIC + if (logged.fetch_add(1, std::memory_order_relaxed) < 24) + std::fprintf(stderr, "[rt] replay: index buffer va 0x%llx size %llu names no buffer\n", + static_cast(draw.index.va), + static_cast(draw.index.size)); + return unresolved_at(__LINE__); + } } + p.index_size = size; } } return ReplayResult::success; } +// An indexed quad list (D3D_PRIMITIVE_TOPOLOGY 19): the scratch and the compute job that turn the application's +// indices into triangle-list indices (quad_index_expand.h). `p` is the draw as prepare_draw left it. A draw of +// fewer than four indices has no quad and needs nothing. +inline ReplayResult prepare_quad_indices(const Draw& draw, const ReplayFunctions& vk, PreparedDraw& p) { + const std::uint32_t quads = draw.count / 4; + if (!quads) return ReplayResult::success; + if (!vk.prepare_quad_indices || !vk.emit_quad_indices || !vk.copy_scratch || + quads > QuadIndexExpander::max_quads) + return ReplayResult::unsupported; + // The indices from the draw's first one that the view holds; the pass reads the rest as 0, like D3D12. With no + // index buffer (the zero page) that is all of them. + const std::uint32_t index_bytes = p.index_type == VK_INDEX_TYPE_UINT16 ? 2 : 4; + const std::uint64_t in_view = p.index_size / index_bytes; + const std::uint64_t readable = in_view > draw.first ? in_view - draw.first : 0; + const VkDeviceSize first = readable ? p.index_offset + VkDeviceSize(draw.first) * index_bytes : p.index_offset; + VkBuffer scratch = VK_NULL_HANDLE; + VkDeviceSize scratch_offset = 0; + if (!vk.copy_scratch(QuadIndexExpander::bytes(quads), scratch, scratch_offset) || + !vk.prepare_quad_indices(p.index_buffer, first, p.index_type, readable, quads, scratch, scratch_offset, + p.quad_indices)) + return ReplayResult::unsupported; + return ReplayResult::success; +} + inline bool strip_topology(VkPrimitiveTopology topology) { return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || @@ -2401,11 +2575,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - // The console's lists (rect_list_geometry.h). A rectangle list is drawn as the triangle list of its three - // corners, the pipeline's geometry stage adds the fourth. A quad (v0 v1 v2 v3) is the fan (v0 v1 v2) (v0 v2 v3), - // which is the index pattern 0 1 2, 0 2 3; the draw below issues one fan per quad. + // Rectangles draw as triangle lists through a geometry stage, quads as triangle lists through indices: the + // shared ones for a non-indexed draw, the application's own, expanded, for an indexed one (emit). case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -2463,6 +2636,7 @@ class PreparedList { // 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; @@ -2522,6 +2696,17 @@ inline ReplayResult plan_occlusion_segments(PreparedList& out) { return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; } +// True for a command that records a compute dispatch of the layer's own before the application's work: a predicate +// capture, a predicated copy, a depth24 or rgb96 conversion, the count clamp of an ExecuteIndirect dispatch, or the +// index expansion of an indexed quad list (which is also a draw). +inline bool has_helper_dispatch(const PreparedList& out, std::size_t i) { + const auto& p = out.commands[i]; + if (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || p.counted_dispatch.indirect) + return true; + return std::holds_alternative(out.list->commands()[i]) && p.draw < out.draws.size() && + out.draws[p.draw].quad_indices.buffer; +} + // Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and // ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements // depend on heap state at planning time, so every non-timestamp resolve splits conservatively. @@ -2557,8 +2742,7 @@ inline void plan_statistics_segments(PreparedList& out) { const auto commands = out.list->commands(); for (std::size_t i = 0; i < out.commands.size(); ++i) { auto& p = out.commands[i]; - if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + if (begin && has_helper_dispatch(out, i)) { inner.push_back({&p.statistics_end, &p.statistics_begin, -1}); splits = true; } @@ -2643,13 +2827,12 @@ inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { query = &out.queries[next_query++]; if (!query) { // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical - // segment before it and open a new one after, the way resolves do. - if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { + // segment before it and open a new one after, the way resolves do. An indexed quad list is a helper and + // a draw: the new segment is the one its draw runs in, and its kind is recorded below. + if (!active.empty() && has_helper_dispatch(out, i)) { p.statistics_end = current; current = open(); p.statistics_begin = current; - continue; } // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291). int draw = -1; @@ -2741,6 +2924,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; } @@ -2758,6 +2948,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; @@ -2788,6 +2979,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]; @@ -2825,6 +3070,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 unsupported_at(__LINE__); if (const auto* buffer_barrier = std::get_if(&command)) @@ -2834,6 +3082,18 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!bind(texture->resource)) return unresolved_at(__LINE__); 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 unresolved_at(__LINE__); if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; @@ -2906,20 +3166,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 unsupported_at(__LINE__); const auto* image_layout = uav_clear::layout(p.binding.format); if (!image_layout || image_layout->bytes != p.element.size) return unsupported_at(__LINE__); - 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 unsupported_at(__LINE__); 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 unsupported_at(__LINE__); // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as @@ -2991,6 +3286,17 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun !detail::stage_unaligned_tile(vk, p, image, fmt, upload)) return unsupported_at(__LINE__); } + // A B4G4R4A4 target stored as RGBA8 moves 4-byte texels in a footprint copy, not packed 16-bit ones. + // The copy is made all the same, as the retail boot was measured with it; + // LEONIDA_RGBA4_COPY_REFUSE=1 refuses it instead. + static const bool refuse_rgba4_copy = [] { + const char* v = std::getenv("LEONIDA_RGBA4_COPY_REFUSE"); + return v && *v == '1'; + }(); + if (result == ReplayResult::success && image.rgba4_render_fallback && refuse_rgba4_copy) + 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; @@ -3126,6 +3432,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun if (!discard->partial) p.discards.push_back(range); } } + } else if (std::holds_alternative(command)) { + if (!vk.gpu_label) return ReplayResult::unsupported; } else if (const auto* write = std::get_if(&command)) { if (!vk.update_buffer || !vk.buffer_at) return unsupported_at(__LINE__); std::uint64_t bytes = 4; @@ -3385,6 +3693,11 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun const bool strict = strict_replay(); if (r != ReplayResult::unresolved_resource || strict) return r; prepared_draw.skipped = true; // dropped at emit (see the dispatch branch above) + } else if (draw->indexed && !draw->mesh && draw->topology == topology_quad_list) { + // The index expansion is a helper dispatch: inside a statistics query it needs the segment pool. + if (statistics_active && !statistics_helpers && draw->count >= 4) return ReplayResult::unsupported; + if (const auto r = detail::prepare_quad_indices(*draw, vk, prepared_draw); r != ReplayResult::success) + return r; } } } @@ -3675,6 +3988,15 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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]; @@ -3694,9 +4016,13 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk); }; // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the - // draw's own rendering scope begins. + // draw's own rendering scope begins. The index expansion of an indexed quad list runs here too: outside the + // rendering scope, and between the segments so that no query counts its dispatch (D3D-162). It stays inside + // the predicate, which skips it together with its draw. if (std::holds_alternative(command) || std::holds_alternative(command)) { end_statistics(); + if (std::holds_alternative(command) && prepared.draws[p.draw].quad_indices.buffer) + vk.emit_quad_indices(command_buffer, prepared.draws[p.draw].quad_indices); begin_statistics(); } if (const auto* predication = std::get_if(&command)) { @@ -3745,6 +4071,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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; @@ -3761,7 +4088,10 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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; }) @@ -3797,10 +4127,13 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ const VkImageLayout new_layout = image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); LayoutPieces pieces; - if (discard && !release) + // 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 && !release && !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); if (!release) detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); @@ -3838,13 +4171,17 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.pipeline_barrier2(command_buffer, &dependency); } if (tracker && !release) tracker->set(id, range, new_layout); + if (!release) finish_depth_uav_barrier(p, new_layout); } else if (const auto* color_clear = std::get_if(&command)) { if (p.skip) continue; if constexpr (Checkpoints) checkpoints->record(command_buffer, i, CheckpointKind::clear); 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, [&] { @@ -3880,7 +4217,7 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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); - float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h + 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; @@ -3942,6 +4279,21 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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, [&] { @@ -4223,6 +4575,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ 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)) { + vk.gpu_label(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 @@ -4522,7 +4876,8 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4541,29 +4896,32 @@ inline void emit_commands(const PreparedList& prepared, VkCommandBuffer command_ vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); if (vk.mesh_draw_count) ++*vk.mesh_draw_count; } else if (draw->topology == topology_quad_list) { - // One four-vertex fan per quad. The translated vertex shaders take their vertex id from the index - // value (VertexIndex - BaseVertex), so a fan must be drawn with the index values 4q..4q+3: an - // indexed draw reads them from the application's index buffer, a non-indexed one from the - // shared 0, 1, 2, ... buffer (quad_indices), with the draw's first vertex as the vertex offset, as - // VertexIndex is first + i for a plain draw. - const bool generated = !draw->indexed; // prepare() has checked that quad_indices is there - if (generated) - vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); - else - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - // The shared buffer holds quad_index_count / 4 quads: more are cut off here and said so. - const std::uint32_t wanted = draw->count / 4, room = generated ? vk.quad_index_count / 4 : UINT32_MAX; - const std::uint32_t quads = std::min(wanted, room); - if (quads < wanted) - std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", - wanted, quads); - const std::int32_t vertex_offset = generated ? std::int32_t(draw->first) : draw->base_vertex; - // All the instances of a quad are drawn together (a split by instance would zero the translated - // instance id, InstanceIndex - BaseInstance), so with several instances the primitive order is quad - // by quad, not instance by instance: only overlapping blended instances can tell. - for (std::uint32_t quad = 0; quad < quads; ++quad) - vk.draw_indexed(command_buffer, 4, draw->instances, (generated ? 0 : draw->first) + 4 * quad, - vertex_offset, draw->first_instance); + if (draw->indexed) { + // The triangle indices the compute pass wrote before this rendering scope, (i0 i1 i2) (i0 i2 i3) + // for each quad of the application's indices from draw->first on: one draw, so instances run + // in D3D12's order, flat inputs come from each quad's first vertex, and VertexIndex - BaseVertex + // is still the application's index. A draw of fewer than four indices has no quad. + const QuadIndexExpansion& quads = d.quad_indices; + if (quads.buffer) { + vk.bind_index_buffer(command_buffer, quads.buffer, quads.offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads.quads * QuadIndexExpander::indices_per_quad, + draw->instances, 0, draw->base_vertex, draw->first_instance); + } + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr auto indices_per_quad = std::uint32_t(quad_triangle_indices.size()); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h index 23626d8b16..753701e1c4 100644 --- a/runtime/src/vulkan_scratch.h +++ b/runtime/src/vulkan_scratch.h @@ -3,12 +3,15 @@ // it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour // copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own // scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24. +// The chunks are transfer sources and destinations; `extra_usage` adds what another user needs (the expanded indices +// of quad lists, quad_index_expand.h: an index buffer written through its device address). #pragma once #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif #include +#include "queue_families.h" #include "vulkan_device_fault.h" @@ -25,9 +28,10 @@ class ScratchBuffers { // A device-local allocation for a chunk; null on failure. using Allocate = std::function; - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, - DeviceFaultDiagnostics* diagnostics = nullptr) - : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)) { + ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, VkBufferUsageFlags extra_usage = 0, + std::vector families = {}, DeviceFaultDiagnostics* diagnostics = nullptr) + : device_(device), diagnostics_(diagnostics), allocate_(std::move(allocate)), extra_usage_(extra_usage), + families_(std::move(families)) { loaded_ = vk_.load(get, device); } @@ -157,7 +161,9 @@ class ScratchBuffers { bool make_chunk(std::uint64_t size, Chunk& out) { 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; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | extra_usage_; + // 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); @@ -182,6 +188,8 @@ class ScratchBuffers { VkDevice device_; DeviceFaultDiagnostics* diagnostics_; Allocate allocate_; + VkBufferUsageFlags extra_usage_ = 0; + 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 2ceecf76f0..b7d501aab1 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}) { @@ -104,12 +138,13 @@ int main() { EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); // The other dimensions grow too (a title's cube maps, texture arrays and 1D lookups outnumber the defaults); - // their storage arrays hold as many indices as the 2D one. + // their storage arrays hold as many indices as the 2D one. The storage-only 1D array keeps its 256. EXPECT(count(f, D::dim_2d_array) == bindless::max_2d_array_images && count(f, D::dim_3d) == bindless::max_3d_images && count(f, D::dim_1d) == bindless::max_1d_images); EXPECT(storage(f, D::dim_2d_array) == bindless::max_storage_indices && storage(f, D::dim_3d) == bindless::max_storage_indices && storage(f, D::dim_1d) == bindless::max_storage_indices); + EXPECT(storage(f, D::dim_1d_array) == 256 && totals(f).all == 153697); 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) @@ -117,12 +152,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 && @@ -130,6 +165,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)); } @@ -183,15 +219,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/check_pipeline_cache_seed.cmake b/runtime/test/check_pipeline_cache_seed.cmake new file mode 100644 index 0000000000..89a3c2ab6c --- /dev/null +++ b/runtime/test/check_pipeline_cache_seed.cmake @@ -0,0 +1,33 @@ +# The cache vk_pipeline_check saves must hit on the runtime's device: the checker compiles one synthetic compute +# shader into a cache, then pipeline_cache_seed_test creates the same pipeline on the runtime's device from it. +# +# The checker runs as a copy with the test program's file name: a driver can make the executable's file name part of +# the cache key (docs/pipeline_check.md, "The cache and the runtime's device"), and this test is about the device. +file(REMOVE_RECURSE "${TEST_DIR}") +file(MAKE_DIRECTORY "${TEST_DIR}/checker") +file(COPY_FILE "${SHADER}" "${TEST_DIR}/seed.spv") +file(WRITE "${TEST_DIR}/index.json" "{\"seed\":{\"stage\":\"cs\",\"bindings\":[],\"push_constant_bytes\":144," + "\"local_size\":[1,1,1],\"wave64\":false}}\n") +get_filename_component(test_name "${TEST}" NAME) +set(checker "${TEST_DIR}/checker/${test_name}") +file(COPY_FILE "${CHECKER}" "${checker}") + +execute_process(COMMAND ${RUNNER} "${checker}" "${TEST_DIR}" "${TEST_DIR}/pipeline_cache.bin" --jobs 1 + RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 120) +if(NOT log MATCHES "cs pipelines: 1 ok, 0 failed, 0 skipped" OR NOT EXISTS "${TEST_DIR}/pipeline_cache.bin") + if(log MATCHES "no Vulkan physical device|vulkan-1|libvulkan|cs pipelines: 0 ok, 0 failed, 1 skipped") + message(STATUS "SKIP: vk_pipeline_check built no pipeline here\n${log}") + return() + endif() + message(FATAL_ERROR "vk_pipeline_check did not build the pipeline (${code})\n${log}") +endif() + +execute_process(COMMAND ${RUNNER} "${TEST}" "${TEST_DIR}/seed.spv" "${TEST_DIR}/pipeline_cache.bin" + RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 120) +message(STATUS "${log}") +if(code STREQUAL "77") + return() # the test printed its own SKIP line +endif() +if(NOT code STREQUAL "0") + message(FATAL_ERROR "pipeline_cache_seed_test failed (${code})") +endif() diff --git a/runtime/test/d3d12_a8_dimensions_test.cpp b/runtime/test/d3d12_a8_dimensions_test.cpp index 82978cd0c1..362f101ecb 100644 --- a/runtime/test/d3d12_a8_dimensions_test.cpp +++ b/runtime/test/d3d12_a8_dimensions_test.cpp @@ -7,6 +7,7 @@ #include "host_adapter.h" #include "host_wine.h" #include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" #include #include #include @@ -171,6 +172,47 @@ bool round_trip(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, unsigned& readback->Unmap(0, nullptr); return same; } + +// The default SRV of a 1D (128) and a 3D (8x8x4) texture: a T# of the right image type, in R8_UNORM's GFX10 format, +// with the swizzle (0, 0, 0, X). A check of the layer alone, so it runs where there is no Windows reference. +bool default_srv_reads_alpha(ID3D12Device* device) { + namespace g = leonida::gfx10; + Ref cpu_heap; + const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + CHECK(SUCCEEDED(device->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p)))); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + CHECK(step >= sizeof(g::ImageWords)); + const std::uint32_t r8_code = g::format_from_vulkan(VK_FORMAT_R8_UNORM); + CHECK(r8_code != 0); + struct Case { + Shape shape; + g::ImageType type; + }; + const Case cases[] = { + {{"1D 128", D3D12_RESOURCE_DIMENSION_TEXTURE1D, 128, 1, 1, 1}, g::ImageType::image_1d}, + {{"3D 8x8x4", D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 1}, g::ImageType::image_3d}, + }; + for (UINT c = 0; c < 2; ++c) { + const Case& k = cases[c]; + Ref texture; + CHECK(SUCCEEDED(create(device, describe(k.shape, 0, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, + &texture.p))); + D3D12_CPU_DESCRIPTOR_HANDLE handle = cpu_heap->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T(c) * step; + std::memset(reinterpret_cast(handle.ptr), 0x77, step); + device->CreateShaderResourceView(texture.p, nullptr, handle); + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(handle.ptr), sizeof(words)); + g::Image image{}; + CHECK(g::is_image(words) && g::decode(words, image)); + CHECK(image.type == k.type && image.width == k.shape.width && image.format == r8_code); + CHECK(k.type != g::ImageType::image_3d || (image.height == k.shape.height && image.depth == k.shape.depth)); + const g::Swizzle alpha_only{g::select_zero, g::select_zero, g::select_zero, g::select_x}; + CHECK(image.swizzle == alpha_only); + std::printf("A8_UNORM %s: the default SRV reads (0, 0, 0, A)\n", k.shape.name); + } + return true; +} } // namespace int main() { @@ -192,7 +234,8 @@ int main() { info.storage_buffer_8bit = vk.storage_buffer_8bit; info.buffer_device_address = vk.buffer_device_address; 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 + if (!default_srv_reads_alpha(ours.p)) ++failures; + if (hostwine::host_is_wine()) return failures ? 1 : 77; // every other check is a comparison with Windows D3D12 Ref factory; if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { std::fprintf(stderr, "no DXGI factory\n"); diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp index 115a7d96f7..b7db739257 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 9faebb7c59..2c36434176 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -308,6 +308,7 @@ int main() { srv_struct_b(elements), srv_typed(elements), srv_null(elements); { rt::d3d12::VulkanDeviceInfo info{}; + info.prepare_on_bind=d.prepare_on_bind; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; 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 0000000000..db15589dac --- /dev/null +++ b/runtime/test/d3d12_depth_stencil_uav_test.cpp @@ -0,0 +1,559 @@ +// 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 +#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); + // The console's size of a depth-stencil target may be smaller than the PC device's (console_depth_stencil_size + // in d3d12_xs_alloc_size.h), so the guest range below takes the larger of the two. + CHECK(xbox_size.SizeInBytes && xbox_size.SizeInBytes != UINT64_MAX && xbox_size.Alignment); + size.SizeInBytes = std::max(size.SizeInBytes, xbox_size.SizeInBytes); + size.Alignment = std::max(size.Alignment, xbox_size.Alignment); + } + 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 0000000000..8800132adf --- /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 ea6b3a76b1..d107161584 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -46,6 +46,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; @@ -399,7 +417,15 @@ int main(int argc, char** argv) { // 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; + } constexpr UINT vertex_after_window = (65536 + sizeof(Vertex) - 1) / sizeof(Vertex); if (title_vertex) { std::memcpy(title_pages.get() + vertex_after_window * sizeof(Vertex), vertices, sizeof(vertices)); @@ -470,6 +496,18 @@ int main(int argc, char** argv) { 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); @@ -1204,7 +1242,12 @@ int main(int argc, char** argv) { allocator.reset(); queue.reset(); fence.reset(); - EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + // The device keeps the buffers it made over the title's vertex pages until it goes (make_title_buffer), and + // each holds a reference: the large batch leaves seven of them. + if (std::getenv("LEONIDA_TEST_GEOMETRY_BATCH")) + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) >= 1); + else + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } unsigned mismatches = 0; diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index 3d6051b0c7..d84454fce9 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -1890,6 +1890,7 @@ int main() { info.host_image_copy = vk.host_image_copy; info.bindless = vk.bindless; info.bindless_partially_bound = vk.partially_bound; + info.robust_image_access = vk.robust_image_access; // a Texture3D UAV is bound only with it if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; failures += check(ours.p, "vulkan"); const std::vector vulkan_cases = open_cases(ours.p); diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index 7b464649cf..bb8186fe55 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 (s8), [1] a table of one sampler (s9): the console's graphics layout. 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,47 @@ 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))); + // A placed sampled texture waits for its memory only where views are prepared at bind time + // (prepare_on_bind); otherwise it is backed when it is made, like every other title image. + EXPECT((rt::d3d12::vulkan_memory_flags(textures[i].p) == 0) == staged_views); + } 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 +318,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 +340,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 +408,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 +426,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 +448,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 +465,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 +546,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 +598,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 +672,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 +683,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 30ccdaded6..2108cb1b75 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -139,6 +139,8 @@ int main(int argc, char** argv) { const auto device_info = [&](bool mesh) { rt::d3d12::VulkanDeviceInfo info{}; + 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 0000000000..4eaac5bd73 --- /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 0000000000..95d32772bd --- /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_quad_index_test.cpp b/runtime/test/d3d12_quad_index_test.cpp new file mode 100644 index 0000000000..03ce0a0eec --- /dev/null +++ b/runtime/test/d3d12_quad_index_test.cpp @@ -0,0 +1,359 @@ +// Indexed console quad lists (IASetPrimitiveTopology(19) with DrawIndexedInstanced) through the D3D12-on-Vulkan +// layer (src/quad_index_expand.h). +// +// Built like d3d12_rect_list_test.cpp, with two translated shaders of its own: vs_quad_inst (vertex fetch through a +// V#, each instance after the first moved by a root constant and its red and green swapped) and ps_quad_flat (the +// colour as a Flat input, so a quad shows the colour of the vertex it takes flat inputs from: its first). Vertices +// 0..3 and 4..7 are full-screen quads with a different colour at every corner; 8..11 and 12..15 are the left and the +// right half of the target, red at every corner. Most cases use a DEFAULT heap index buffer written by a copy in +// the first command list, so nothing but the GPU can read it when the draw is recorded. Seven 64x64 frames: +// frame 0, control: a non-indexed quad, DrawInstanced(4) over vertices 0..3. Red (vertex 0) everywhere. +// frame 1: 16-bit indices 0 1 2 3. Red everywhere; a triangle fan shows vertices 1 and 2 (black and blue). +// frame 2: 32-bit indices 7 4 5 6 from StartIndexLocation 3. Green (vertex 7) everywhere. +// frame 3: 16-bit indices 0 1 2 3 from StartIndexLocation 5 (an address of 2 modulo 4) with BaseVertexLocation 3. +// The translated vertex shader's vertex id is the index without the base vertex, so this is frame 1 again; the +// base added into the indices would fetch vertices 3..6 instead (white). +// frame 4: two quads (left half, right half) and two instances; instance 1 is green and one half to the right, so +// its first quad lands on instance 0's second. D3D12 draws instance by instance: the right half ends green. +// Drawn quad by quad, instance 0's second quad comes last and leaves it red. +// frame 5: eight 16-bit indices, 0 1 2 3 and 7 4 5 6, through a view that ends after the sixth. The last two read +// 0 (D3D12: an index outside the view), which makes the second quad empty: red everywhere. Read past the view, +// the second quad covers the target in green. +// frame 6: a standalone 10-byte UPLOAD index buffer, first index 1. All four 16-bit indices are readable, with +// the last one at the end of the resource. The backing buffer must accommodate the full word load. +// Every pixel is compared, bit for bit. LEONIDA_VK_VALIDATION=1 runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_QUAD_DIR +#error "LEONIDA_TEST_QUAD_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_quad_inst.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +constexpr Pixel red = {1, 0, 0, 1}, green = {0, 1, 0, 1}, blue = {0, 0, 1, 1}, black = {0, 0, 0, 1}, + white = {1, 1, 1, 1}; + +Vertex vertex(float x, float y, const Pixel& c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +struct Frame { + const char* name; + DXGI_FORMAT index_format; // DXGI_FORMAT_UNKNOWN: DrawInstanced + UINT view_offset, view_bytes; // the index buffer view, in the index buffer + UINT count, instances, start; + INT base_vertex; + Pixel left, right; // what the left and the right half of the target must hold + bool use_upload_indices = false; +}; + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + const std::filesystem::path root_dir = LEONIDA_TEST_QUAD_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_quad_inst.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_quad_flat.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() >= 4); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + const Vertex vertices[16] = { + vertex(-1, 1, red), vertex(1, 1, black), vertex(1, -1, blue), vertex(-1, -1, white), + vertex(-1, 1, black), vertex(1, 1, blue), vertex(1, -1, white), vertex(-1, -1, green), + vertex(-1, 1, red), vertex(0, 1, red), vertex(0, -1, red), vertex(-1, -1, red), + vertex(0, 1, red), vertex(1, 1, red), vertex(1, -1, red), vertex(0, -1, red)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 512); + // Index 15 fills the gaps: a draw that starts at the wrong index shows it. + const std::uint16_t indices16[28] = {0, 1, 2, 3, 15, 0, 1, 2, 3, 15, 8, 9, 10, 11, 12, 13, 14, 15, 15, 15, + 0, 1, 2, 3, 7, 4, 5, 6}; + const std::uint32_t indices32[7] = {15, 15, 15, 7, 4, 5, 6}; + const std::uint16_t upload_indices16[] = {15, 0, 1, 2, 3}; + constexpr UINT indices32_offset = 64, index_bytes = 128; + static_assert(sizeof(indices16) <= indices32_offset && indices32_offset + sizeof(indices32) <= index_bytes); + const Frame frames[] = { + {"non-indexed (control)", DXGI_FORMAT_UNKNOWN, 0, 0, 4, 1, 0, 0, red, red}, + {"16-bit indices", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 0, 0, red, red}, + {"32-bit indices, first index 3", DXGI_FORMAT_R32_UINT, indices32_offset, sizeof(indices32), 4, 1, 3, 0, + green, green}, + {"16-bit indices, first index 5, base vertex 3", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 4, 1, 5, 3, + red, red}, + {"two overlapping instances", DXGI_FORMAT_R16_UINT, 0, sizeof(indices16), 8, 2, 10, 0, red, green}, + {"view ends inside the second quad", DXGI_FORMAT_R16_UINT, 20 * sizeof(std::uint16_t), + 6 * sizeof(std::uint16_t), 8, 1, 0, 0, red, red}, + {"16-bit indices at the end of an upload buffer", DXGI_FORMAT_R16_UINT, 0, + sizeof(upload_indices16), 4, 1, 1, 0, red, red, true}, + }; + constexpr std::size_t frame_count = std::size(frames); + std::vector pixels[frame_count]; + for (auto& p : pixels) p.resize(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; + info.shader_dir = (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)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; // quads use the triangle type + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, index_buffer, upload_index_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto ib_desc = buffer_desc(index_bytes); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &ib_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&index_buffer.p)))); + const auto upload_ib_desc = buffer_desc(sizeof(upload_indices16)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_ib_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload_index_buffer.p)))); + EXPECT(upload_index_buffer->GetDesc().Width == sizeof(upload_indices16)); + void* index_map = nullptr; + EXPECT(SUCCEEDED(upload_index_buffer->Map(0, nullptr, &index_map))); + std::memcpy(index_map, upload_indices16, sizeof(upload_indices16)); + upload_index_buffer->Unmap(0, nullptr); + constexpr UINT upload_indices = 512; // where the index bytes sit in the upload buffer + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + 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)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + std::memset(up + upload_indices, 0xee, index_bytes); // an index read from a gap is far out of the V# + std::memcpy(up + upload_indices, indices16, sizeof(indices16)); + std::memcpy(up + upload_indices + indices32_offset, indices32, sizeof(indices32)); + + // One V# over the sixteen vertices. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + const std::uint64_t index_va = index_buffer->GetGPUVirtualAddress(); + const std::uint64_t upload_index_va = upload_index_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000 && index_va >= 0x10000 && index_va % 4 == 0); + EXPECT(upload_index_va && upload_index_va % 4 == 0); + leonida::gfx10::Buffer vsharp; + vsharp.address = buffer_va; + vsharp.stride = 32; + vsharp.num_records = std::uint32_t(std::size(vertices)); + vsharp.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + vsharp.oob_select = leonida::gfx10::OobSelect::structured; + const std::array vsharp_words = leonida::gfx10::encode(vsharp); + std::memcpy(reinterpret_cast(cpu), vsharp_words.data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + // The copies that fill the vertex and index buffers are in the first frame's list, before its draw. + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + list->CopyBufferRegion(index_buffer.p, 0, upload.p, upload_indices, index_bytes); + D3D12_RESOURCE_BARRIER barriers[3] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(index_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_INDEX_BUFFER), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(3, barriers); + + const auto render_frame = [&](UINT64 number, const Frame& frame, std::vector& out) -> int { + if (number > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(quad_list); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {1, 0, 0, 0}; // each later instance: half the target to the right + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + if (frame.index_format == DXGI_FORMAT_UNKNOWN) { + list->DrawInstanced(frame.count, frame.instances, frame.start, 0); + } else { + const std::uint64_t frame_index_va = frame.use_upload_indices ? upload_index_va : index_va; + const D3D12_INDEX_BUFFER_VIEW view{frame_index_va + frame.view_offset, frame.view_bytes, frame.index_format}; + list->IASetIndexBuffer(&view); + list->DrawIndexedInstanced(frame.count, frame.instances, frame.start, frame.base_vertex, 0); + } + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, number))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(number, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + for (std::size_t i = 0; i < frame_count; ++i) EXPECT(render_frame(i + 1, frames[i], pixels[i]) == 0); + for (auto* r : {&vertex_buffer, &index_buffer, &upload_index_buffer, &upload, &readback, &target}) r->reset(); + pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + constexpr unsigned all = target_extent * target_extent; + bool ok = true; + for (std::size_t i = 0; i < frame_count; ++i) { + unsigned exact = 0, reported = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const Pixel& want = col < target_extent / 2 ? frames[i].left : frames[i].right; + const Pixel& got = pixels[i][row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) { + ++exact; + } else if (reported++ < 2) { + std::fprintf(stderr, "frame %zu (%s) pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", i, + frames[i].name, col, row, got[0], got[1], got[2], got[3], want[0], want[1], + want[2], want[3]); + } + } + } + std::printf("frame %zu, %s: %u of %u pixels exact\n", i, frames[i].name, exact, all); + ok = ok && exact == all; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + if (!ok) return 1; + std::printf("indexed quad lists: %zu frames of %u pixels exact\n", frame_count, all); + return 0; +} diff --git a/runtime/test/d3d12_r9g9b9e5_uav_test.cpp b/runtime/test/d3d12_r9g9b9e5_uav_test.cpp index 89bda1d8a4..5ed33b1dfa 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; @@ -391,6 +393,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)))); @@ -453,7 +457,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, @@ -802,27 +806,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 05b90a81c8..ae1cbc6a83 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 d778d1bc69..c424ef5bed 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 4642440faf..4f12801db9 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 007c513b4f..b32847a90c 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 0000000000..d9d9dfaea1 --- /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 0000000000..f8ef5177b6 --- /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 e7fafe5cb7..0adb72d255 100644 --- a/runtime/test/d3d12_title_va_test.cpp +++ b/runtime/test/d3d12_title_va_test.cpp @@ -551,9 +551,151 @@ int check_geometry_slab_tails(Context& c) { 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. +// (Adapted from the tests of the patches descriptor-table-refresh and descriptor-write-through of +// Sigtryggur-Mani-Gudmundsson/graphics-runtime-patches at d9a0bc1b, GPL-3.0.) +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, 0xfffffffbu}; + 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}; + // The reference uses the producer of the slot under test. Xbox CreateCBV + // addresses 16-byte rows. A PC descriptor copied through the API retains its byte layout. + const bool xbox_cbv = api_copy && pass == 0; + (xbox_cbv ? c.device : c.inner)->CreateConstantBufferView(&cbv, src); + leonida::gfx10::BufferWords words{}; + std::memcpy(words.data(), reinterpret_cast(src.ptr), sizeof(words)); + leonida::gfx10::Buffer reference_cbv{}; + EXPECT(leonida::gfx10::decode(words, reference_cbv)); + // The device writes the console's 16-byte rows for both producers unless LEONIDA_CBV_RAW=1. + wchar_t raw_env[2]{}; + const bool rows = xbox_cbv || !(GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", raw_env, 2) == 1 && raw_env[0] == L'1'); + EXPECT(reference_cbv.stride == (rows ? 16u : 0u)); + EXPECT(reference_cbv.num_records == (rows ? kBytes / 16u : kBytes)); + 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); const char* setting = std::getenv("LEONIDA_GEOMETRY_MB"); const bool geometry = setting && std::atoi(setting) > 0; vktest::Device d; @@ -591,6 +733,9 @@ int main() { if (geometry) info.host_pointer_alignment = d.host_pointer_alignment; 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; @@ -600,7 +745,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}; @@ -639,6 +784,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, geometry)) return 1; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 7497e2d152..aa3f5ec280 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,8 @@ int main() { } #else rt::d3d12::VulkanDeviceInfo info{}; + 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,7 +192,8 @@ int main() { info.queue = d.queue; info.queue_family = d.family; info.buffer_device_address = true; - info.shader_dir = (root_dir / "spirv").string(); + info.features = d.enabled; + 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; @@ -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); @@ -293,7 +344,8 @@ int main() { list->ResourceBarrier(2, barriers); // The first command list already contains the vertex upload. Reuse it for subsequent frames // after the preceding submission's fence has completed and its readback is available. - const auto render_frame = [&](UINT64 frame, float x_offset, float bias) -> int { + const auto render_frame = [&](UINT64 frame, float x_offset, float bias, + D3D_PRIMITIVE_TOPOLOGY last_topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) -> int { if (frame > 1) { EXPECT(SUCCEEDED(allocator->Reset())); EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); @@ -323,6 +375,7 @@ int main() { {0, {1, -1, 0.125f + bias, 0}, 6}, // bottom right: same V#, other constants {1, {0, 0, 0.25f + bias, 0}, 3}}; // bottom left: the second V# for (const Draw& draw : draws) { + if (draw.slot == 1) list->IASetPrimitiveTopology(last_topology); list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(draw.slot) * step}); list->SetGraphicsRoot32BitConstants(1, 4, draw.constants, 0); list->DrawInstanced(draw.vertices, 1, 0, 0); @@ -370,6 +423,32 @@ int main() { } #endif EXPECT(render_frame(1, 0.0f, 0.0f) == 0); +#ifndef LEONIDA_M15_GUEST + if (d.enabled.geometryShader) { + // The last draw covers half the lower-left quadrant as a triangle. The Xbox rectangle primitive + // fills the quadrant through the same PSO. The other three quadrants keep their original values. + const auto triangles = pixels; + constexpr auto rectangles = static_cast(17); + const Pixel lower_left = {0.75f, 0.25f, 0.75f, 1.0f}; + for (UINT64 frame : {2u, 4u}) { + EXPECT(render_frame(frame, 0.0f, 0.0f, rectangles) == 0); + for (UINT y = 0; y < target_extent; ++y) { + for (UINT x = 0; x < target_extent; ++x) { + const auto i = y * target_extent + x; + const bool covered = !derived_zero && y >= target_extent / 2 && x < target_extent / 2; + const auto& want = covered ? lower_left : triangles[i]; + if (pixels[i] != want) { + std::fprintf(stderr, "rectangle draw mismatch at (%u, %u) in frame %llu\n", x, y, + static_cast(frame)); + return 1; + } + } + } + EXPECT(render_frame(frame + 1, 0.0f, 0.0f) == 0); + EXPECT(pixels == triangles); + } + } +#endif for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); pso.reset(); root.reset(); @@ -387,6 +466,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 cc70fa4376..253fee2e73 100644 --- a/runtime/test/d3d12_xmem_placed_test.cpp +++ b/runtime/test/d3d12_xmem_placed_test.cpp @@ -7,6 +7,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" @@ -87,7 +88,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")); @@ -104,7 +105,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; @@ -122,10 +123,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); @@ -146,9 +153,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 0d1d099730..5fae4621c6 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -671,6 +671,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/fixtures/tiny_game.cpp b/runtime/test/fixtures/tiny_game.cpp index cd456f4979..21feaad5f5 100644 --- a/runtime/test/fixtures/tiny_game.cpp +++ b/runtime/test/fixtures/tiny_game.cpp @@ -112,6 +112,17 @@ int main(int argc, char** argv) { check(XSystemGetDeviceType() == 7, "XSystemGetDeviceType is answered by the gta6rt shim (Series X)"); XGameRuntimeUninitialize(); + if (has_arg(argc, argv, "first-run-ui")) { + char value[32]{}; + const auto configured = [&](const char* name, const char* expected) { + const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value)); + return n && n < sizeof(value) && std::strcmp(value, expected) == 0; + }; + check(configured("LEONIDA_D3D12", "vulkan"), "first-run UI Vulkan backend"); + check(configured("LEONIDA_PIPELINE_COMPILE", "on-demand"), "first-run UI pipeline profile"); + check(configured("LEONIDA_ARENA_MB", "768"), "first-run UI caller override"); + } + if (has_arg(argc, argv, "tls")) { int seen = -1; std::thread t([&] { seen = t_counter; t_counter = 9; }); diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index e7859698e2..7f92d51a7d 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, nullptr, true); + 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 0000000000..277a86df46 --- /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 c9879064ac..41c986a412 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 85ce43927e..a04b23c9f5 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -67,13 +67,18 @@ void main() { target.w[i] = result.w[64u + i] + pc.s[4]; return; } - if (pc.s[5] == 0u) { - // Scalar CBV reads use byte capacity for both the console row descriptor and the raw override. - const uint stride = (table.w[1] >> 16u) & 0x3FFFu; - const uint capacity = table.w[2] * max(1u, stride); - const uint byte_off = pc.s[4] + i * 4u; - if (byte_off + 4u <= capacity) { - Words cbv = at(uvec2(table.w[0], table.w[1] & 0xFFFFu)); + if (pc.s[5] == 0u || pc.s[5] == 0xFFFFFFFBu) { + // 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] == 0xFFFFFFFBu; + 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/gpu_label_store_test.cpp b/runtime/test/gpu_label_store_test.cpp new file mode 100644 index 0000000000..509a5da61a --- /dev/null +++ b/runtime/test/gpu_label_store_test.cpp @@ -0,0 +1,119 @@ +// leonida::label::store_value (runtime/src/vulkan_gpu_labels.h): where a completed GPU label may be stored in the +// title's memory, and what it does with a page the D3D12 layer keeps read-only while it watches for the title's writes +// (runtime/src/title_page_watch.h). The layer is stood in for by an opener that makes its "watched" pages writable +// again, as DeviceState's opener does. CPU only: no Vulkan device, no GPU. No game data. +#include "../src/vulkan_gpu_labels.h" + +#include +#include + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +constexpr std::size_t kPage = 4096; + +std::uintptr_t g_watched_begin = 0, g_watched_end = 0; // the pages the stand-in layer made read-only +int g_opened = 0; +std::uintptr_t g_asked_begin = 0, g_asked_end = 0; + +// Stands in for the layer's opener (open_shadow_pages): only pages it made read-only itself become writable. +void open_watched(std::uintptr_t begin, std::uintptr_t end) { + ++g_opened; + g_asked_begin = begin; + g_asked_end = end; + for (std::uintptr_t page = begin & ~(kPage - 1); page < end; page += kPage) { + if (page < g_watched_begin || page >= g_watched_end) continue; + DWORD old = 0; + VirtualProtect(reinterpret_cast(page), kPage, PAGE_READWRITE, &old); + } +} + +DWORD protection(const void* p) { + MEMORY_BASIC_INFORMATION mbi{}; + return VirtualQuery(p, &mbi, sizeof(mbi)) ? mbi.Protect : 0; +} + +bool protect(void* p, DWORD how) { + DWORD old = 0; + return VirtualProtect(p, kPage, how, &old) != FALSE; +} + +} // namespace + +int main() { + namespace label = leonida::label; + namespace writes = leonida::kernel_writes; + auto* const base = static_cast(VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!base) return 1; + const auto address = reinterpret_cast(base); + label::memory().track(address, 4 * kPage, address, false); + auto* const wide = reinterpret_cast(base + 0x40); + auto* const narrow = reinterpret_cast(base + kPage + 0x10); + const label::Target wide_target = label::memory().capture(reinterpret_cast(wide), 8); + const label::Target narrow_target = label::memory().capture(reinterpret_cast(narrow), 4); + check(wide_target.bytes == 8 && narrow_target.bytes == 4, "labels are captured in a tracked allocation"); + + // 1. A writable page: stored, with no opener asked. + writes::set_opener(&open_watched); + check(label::store_value(wide_target, 0x1122334455667788ull) && *wide == 0x1122334455667788ull && g_opened == 0, + "an 8-byte label is stored into a read-write page"); + check(label::store_value(narrow_target, 0xA1B2C3D4u) && *narrow == 0xA1B2C3D4u && narrow[1] == 0 && g_opened == 0, + "a 4-byte label is stored and leaves the next word alone"); + + // 2. A page the layer watches (read-only until written): it is opened like a kernel write and the label lands. + g_watched_begin = address; + g_watched_end = address + kPage; + check(protect(base, PAGE_READONLY), "the first page is made read-only, as a watched page is"); + check(label::store_value(wide_target, 0x0102030405060708ull), "a label for a watched read-only page is stored"); + check(*wide == 0x0102030405060708ull, "the value is in the page"); + check(g_opened == 1 && g_asked_begin == reinterpret_cast(wide) && g_asked_end == g_asked_begin + 8, + "the layer was asked to open exactly the label's bytes, once"); + check(protection(base) == PAGE_READWRITE, "the page is writable again, so the layer copies it at its next refresh"); + check(writes::state().count.load() == 0, "the write's pin has ended"); + + // 3. A page that stays read-only when the layer is asked (the title's own protection): dropped, no fault. + check(protect(base + kPage, PAGE_READONLY), "the second page is made read-only by the title"); + const int opened = g_opened; + check(!label::store_value(narrow_target, 0x55555555u) && *narrow == 0xA1B2C3D4u, + "a label for the title's own read-only page is dropped and the old value stays"); + check(g_opened == opened + 1 && writes::state().count.load() == 0, "the layer was asked and the pin has ended"); + check(protection(base + kPage) == PAGE_READONLY, "the title's protection is untouched"); + + // 4. No layer at all: a read-only page is dropped without asking anyone. + writes::set_opener(nullptr); + check(protect(base, PAGE_READONLY), "the first page is read-only again"); + check(!label::store_value(wide_target, 0x9999999999999999ull) && *wide == 0x0102030405060708ull, + "with no opener a read-only page drops the label"); + writes::set_opener(&open_watched); + check(label::store_value(wide_target, 0x9999999999999999ull) && *wide == 0x9999999999999999ull, + "with the opener back the same label is stored"); + + // 5. Guard pages, no-access pages and decommitted pages are never written, opener or not. + check(protect(base + 2 * kPage, PAGE_READWRITE | PAGE_GUARD), "the third page is a guard page"); + const label::Target guarded = label::memory().capture(address + 2 * kPage + 8, 8); + check(!label::store_value(guarded, 1) && (protection(base + 2 * kPage) & PAGE_GUARD), + "a label for a guard page is dropped and the guard is still armed"); + check(protect(base + 3 * kPage, PAGE_NOACCESS), "the fourth page is no-access"); + const label::Target hidden = label::memory().capture(address + 3 * kPage + 8, 8); + check(!label::store_value(hidden, 1), "a label for a no-access page is dropped"); + check(VirtualFree(base + 3 * kPage, kPage, MEM_DECOMMIT) != FALSE, "the fourth page is decommitted"); + check(!label::store_value(hidden, 1), "a label for a decommitted page is dropped"); + + // 6. A released allocation: the captured generation is gone, so nothing is stored whatever is mapped there now. + check(label::memory().release_pages(address, 0, true, [&] { return VirtualFree(base, 0, MEM_RELEASE) != FALSE; }), + "the allocation is released"); + check(!label::store_value(wide_target, 2), "a label captured before the release is dropped"); + writes::set_opener(nullptr); + + std::printf("gpu_label_store_test: %s (%d checks, %d failures)\n", g_failures ? "FAILED" : "ok", g_checks, + g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/present_window_test.cpp b/runtime/test/present_window_test.cpp new file mode 100644 index 0000000000..9488563c95 --- /dev/null +++ b/runtime/test/present_window_test.cpp @@ -0,0 +1,35 @@ +// The submitting thread does no message dispatch. Each hidden presentation window must still +// process messages, close on its owner thread and allow the other window to keep running. +#include "../shims/present_window.h" + +#include +#include + +namespace { +bool send(HWND window, UINT message) { + DWORD_PTR result = 0; + return SendMessageTimeoutW(window, message, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK, 2000, &result) != 0; +} +} + +int main() { + HWND control = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, + GetModuleHandleW(nullptr), nullptr); + if (!control) { + std::fprintf(stderr, "no Win32 desktop available (error %lu)\n", GetLastError()); + return 77; + } + DestroyWindow(control); + + rt::d3d12_xs::PresentWindow first; + auto second = std::make_unique(); + const HWND a = first.create(), b = second->create(); + if (!a || !b || a == b || GetWindowThreadProcessId(a, nullptr) == GetCurrentThreadId() || + !send(a, WM_NULL) || !send(b, WM_NULL)) return 1; + if (!send(a, WM_CLOSE) || IsWindow(a) || !send(b, WM_NULL)) return 1; + + std::thread release([window = std::move(second)]() mutable { window.reset(); }); + release.join(); + if (IsWindow(b)) return 1; + return 0; +} diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..0557a3e577 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,406 @@ +// Quad lists are triangle-list draws. A switch back to Vulkan triangle fans changes the provoking vertex for flat +// attributes and the order of overlapping blended instances. +// - Without an index buffer: one draw over the shared triangle indices. +// - With one: one compute dispatch that expands the application's indices into scratch (src/quad_index_expand.h), +// then one draw over that scratch. The dispatch runs before the draw's rendering scope and outside a +// pipeline-statistics query, reads no index past the view, and a draw with more quads than one dispatch may +// cover is split into several. +// No GPU: the Vulkan calls are recorded. +#include "../src/vulkan_replay.h" + +#include +#include +#include +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +// What quad_index_expand.comp reads from its push constants. +struct Push { + VkDeviceAddress source, triangles; + std::uint32_t first_half, index_bits, limit, quads; + bool operator==(const Push&) const = default; +}; + +struct Barrier { + VkPipelineStageFlags src_stages, dst_stages; + VkAccessFlags src_access, dst_access; + bool operator==(const Barrier&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; +std::vector pushes; +std::vector dispatches; // group counts +std::vector barriers; +std::vector events; // the order of everything recorded +std::vector scratch_requests; + +template +T handle(std::uintptr_t n) { + return reinterpret_cast(n); +} + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} + +// The device the expander sees: every buffer's address is 0x1000 times its handle. +VKAPI_ATTR VkDeviceAddress VKAPI_CALL device_address(VkDevice, const VkBufferDeviceAddressInfo* info) { + return VkDeviceAddress(reinterpret_cast(info->buffer)) * 0x1000; +} +VKAPI_ATTR VkResult VKAPI_CALL create_module(VkDevice, const VkShaderModuleCreateInfo* info, + const VkAllocationCallbacks*, VkShaderModule* out) { + *out = handle(20); + return info->codeSize && info->pCode[0] == 0x07230203u ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_module(VkDevice, VkShaderModule, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_layout(VkDevice, const VkPipelineLayoutCreateInfo* info, + const VkAllocationCallbacks*, VkPipelineLayout* out) { + *out = handle(21); + return info->pushConstantRangeCount == 1 && info->pPushConstantRanges[0].size == sizeof(Push) + ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; +} +VKAPI_ATTR void VKAPI_CALL destroy_layout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {} +VKAPI_ATTR VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, std::uint32_t, + const VkComputePipelineCreateInfo*, const VkAllocationCallbacks*, + VkPipeline* out) { + *out = handle(22); + return VK_SUCCESS; +} +VKAPI_ATTR void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline, const VkAllocationCallbacks*) {} +VKAPI_ATTR void VKAPI_CALL cmd_barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst, + VkDependencyFlags, std::uint32_t count, const VkMemoryBarrier* memory, + std::uint32_t, const VkBufferMemoryBarrier*, std::uint32_t, + const VkImageMemoryBarrier*) { + barriers.push_back({src, dst, count == 1 ? memory->srcAccessMask : 0, count == 1 ? memory->dstAccessMask : 0}); + events.push_back("barrier"); +} +VKAPI_ATTR void VKAPI_CALL cmd_bind_pipeline(VkCommandBuffer, VkPipelineBindPoint point, VkPipeline) { + events.push_back(point == VK_PIPELINE_BIND_POINT_COMPUTE ? "bind_compute" : "bind_graphics"); +} +VKAPI_ATTR void VKAPI_CALL cmd_push_constants(VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags stages, + std::uint32_t, std::uint32_t size, const void* values) { + if (stages != VK_SHADER_STAGE_COMPUTE_BIT || size != sizeof(Push)) return; // the draw's own user data + std::memcpy(&pushes.emplace_back(), values, sizeof(Push)); +} +VKAPI_ATTR void VKAPI_CALL cmd_dispatch(VkCommandBuffer, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + dispatches.push_back(y == 1 && z == 1 ? x : 0); + events.push_back("dispatch"); +} +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL device_proc(VkDevice, const char* name) { +#define PROC(vk_name, function) \ + if (std::strcmp(name, vk_name) == 0) return reinterpret_cast(function) + PROC("vkGetBufferDeviceAddress", device_address); + PROC("vkCreateShaderModule", create_module); + PROC("vkDestroyShaderModule", destroy_module); + PROC("vkCreatePipelineLayout", create_layout); + PROC("vkDestroyPipelineLayout", destroy_layout); + PROC("vkCreateComputePipelines", create_pipelines); + PROC("vkDestroyPipeline", destroy_pipeline); + PROC("vkCmdPipelineBarrier", cmd_barrier); + PROC("vkCmdBindPipeline", cmd_bind_pipeline); + PROC("vkCmdPushConstants", cmd_push_constants); + PROC("vkCmdDispatch", cmd_dispatch); +#undef PROC + return nullptr; +} + +VKAPI_ATTR void VKAPI_CALL begin_query(VkCommandBuffer, VkQueryPool, std::uint32_t index, VkQueryControlFlags) { + events.push_back("begin_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL end_query(VkCommandBuffer, VkQueryPool, std::uint32_t index) { + events.push_back("end_query " + std::to_string(index)); +} +VKAPI_ATTR void VKAPI_CALL destroy_query_pool(VkDevice, VkQueryPool, const VkAllocationCallbacks*) {} + +void reset() { + calls.clear(); + pushes.clear(); + dispatches.clear(); + barriers.clear(); + events.clear(); + scratch_requests.clear(); +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) { events.push_back("begin_rendering"); }; + vk.end_rendering = +[](VkCommandBuffer) { events.push_back("end_rendering"); }; + vk.bind_pipeline = cmd_bind_pipeline; + vk.push_constants = cmd_push_constants; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32 enable) { + if (enable) events.push_back("primitive_restart"); + }; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + events.push_back("draw_indexed"); + }; + + vk.quad_indices = handle(1); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = handle(2); + + GraphicsPipeline graphics{}; + graphics.pipeline = handle(3); + graphics.strip_cut = 1; // 0xFFFF cuts strips: it must not make a quad list restart + const auto collect = [&](const Draw& draw) { + reset(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + ok &= check(dispatches.empty(), "non-indexed quads need no index expansion"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + // Indexed quads, through prepare(): the real expander on the recording device above. + VkPhysicalDeviceLimits limits{}; + limits.maxComputeWorkGroupCount[0] = 65535; + QuadIndexExpander expander(device_proc, handle(9), limits); + const auto scratch = handle(5), zero_page = handle(6); + constexpr VkDeviceSize scratch_offset = 512; + std::uint64_t app_bytes = 64; // the application's buffer past the view's start + vk.graphics_pipeline = [&](std::uintptr_t) -> const GraphicsPipeline* { return &graphics; }; + vk.buffer_at = [&](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { + buffer = app_buffer; + offset = va; // the console VA is the offset in this test + size = std::min(size, app_bytes); + return true; + }; + vk.image_view = [](const ResourceBinding&, const VkImageSubresourceRange&) { return VkImageView{}; }; + vk.bind_vertex_buffers2 = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkBuffer*, + const VkDeviceSize*, const VkDeviceSize*, const VkDeviceSize*) {}; + vk.draw = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {}; + vk.zero_buffer = zero_page; + vk.zero_size = 65536; + vk.copy_scratch = [&](VkDeviceSize bytes, VkBuffer& buffer, VkDeviceSize& offset) { + scratch_requests.push_back(bytes); + buffer = scratch; + offset = scratch_offset; + return true; + }; + const auto wire = [](ReplayFunctions& functions, QuadIndexExpander& to) { + functions.prepare_quad_indices = [&to](VkBuffer indices, VkDeviceSize offset, VkIndexType type, + std::uint64_t readable, std::uint32_t quads, VkBuffer target, + VkDeviceSize target_offset, QuadIndexExpansion& out) { + return to.prepare(indices, offset, type, readable, quads, target, target_offset, out); + }; + functions.emit_quad_indices = [&to](VkCommandBuffer cb, const QuadIndexExpansion& job) { to.emit(cb, job); }; + }; + wire(vk, expander); + const auto resolve = [](ResourceId) -> const ResourceBinding* { return nullptr; }; + const auto run = [&](const Draw& indexed, const ReplayFunctions& functions) { + reset(); + CommandList list; + if (!list.draw(indexed) || !list.close()) return ReplayResult::list_open; + PreparedList prepared; + const auto result = prepare(list, resolve, functions, prepared); + if (result == ReplayResult::success) emit(prepared, VK_NULL_HANDLE, functions); + return result; + }; + + constexpr VkDeviceAddress app_address = 2 * 0x1000, scratch_address = 5 * 0x1000 + scratch_offset; + const Barrier before{VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT}; + const Barrier after{VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, + VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_INDEX_READ_BIT}; + const std::vector one_dispatch_one_draw{ + "barrier", "bind_compute", "dispatch", "barrier", "begin_rendering", "bind_graphics", "draw_indexed", + "end_rendering"}; + + // 16-bit indices: two quads and a ninth index, from index 5 of a view at byte 32 (the first index is at byte 42, + // the high half of the word at 40). The view holds 32 indices, 27 of them from index 5 on. + draw.indexed = true; + draw.index = {32, 64, 57}; // DXGI_FORMAT_R16_UINT + draw.count = 9; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall expanded{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, scratch, scratch_offset, VK_INDEX_TYPE_UINT32, + 12, 2, 0, -2, 7}; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw, + "indexed quads are one dispatch before the rendering scope and one draw inside it"); + ok &= check(calls == std::vector{expanded}, + "indexed quads draw the expanded indices once, with the draw's instances and bases"); + ok &= check(dispatches == std::vector{1} && scratch_requests == std::vector{48}, + "two quads are one work group and 48 bytes of scratch"); + ok &= check(pushes == std::vector{Push{app_address + 40, scratch_address, 1, 16, 27, 2}}, + "16-bit indices are read from the word that holds the first one, up to the view's end"); + ok &= check(barriers == std::vector{before, after}, + "earlier writes are visible to the pass, and its indices to the draw"); + + // 32-bit indices through a view of six: the last two of the second quad read 0. + draw.index = {64, 24, 42}; // DXGI_FORMAT_R32_UINT + draw.count = 8; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && events == one_dispatch_one_draw && + pushes == std::vector{Push{app_address + 64, scratch_address, 0, 32, 6, 2}}, + "32-bit indices past the view are not read"); + // A view that runs past its buffer ends where the buffer does. + draw.index = {64, 4096, 42}; + app_bytes = 20; + ok &= check(run(draw, vk) == ReplayResult::success && pushes.size() == 1 && pushes[0].limit == 5, + "a view is cut at the end of its buffer"); + app_bytes = 64; + // The first index past the view, and no index buffer at all: every index reads 0. + draw.index = {64, 24, 42}; + draw.first = 6; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == app_address + 64, + "a draw that starts past the view reads no index"); + draw.index = {0, 0, 57}; + draw.first = 0; + ok &= check(run(draw, vk) == ReplayResult::success && calls.size() == 1 && pushes.size() == 1 && + pushes[0].limit == 0 && pushes[0].source == 6 * 0x1000, + "without an index buffer every index reads 0"); + + // Fewer than four indices: nothing to expand, nothing to draw. + draw.index = {32, 64, 57}; + draw.count = 3; + ok &= check(run(draw, vk) == ReplayResult::success && calls.empty() && dispatches.empty() && + scratch_requests.empty(), + "an incomplete indexed quad needs no scratch and emits no draw"); + + // What cannot be expanded is refused when the list is prepared. + draw.count = 8; + { + ReplayFunctions without = vk; + without.prepare_quad_indices = {}; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without the expander"); + without = vk; + without.copy_scratch = [](VkDeviceSize, VkBuffer&, VkDeviceSize&) { return false; }; + ok &= check(run(draw, without) == ReplayResult::unsupported && events.empty(), + "indexed quads are unsupported without scratch"); + Draw odd = draw; + odd.index = {33, 64, 57}; + ok &= check(run(odd, vk) == ReplayResult::unsupported && events.empty(), + "16-bit indices at an odd address are refused"); + Draw huge = draw; + huge.count = UINT32_MAX; // 6 indices for each quad would not fit vkCmdDrawIndexed's count + ok &= check(run(huge, vk) == ReplayResult::unsupported && scratch_requests.empty(), + "a draw whose expanded index count overflows 32 bits is refused before taking scratch"); + } + + // More quads than one dispatch may cover: 300 quads with two work groups (128 quads) for each dispatch. Every + // dispatch starts 512 indices (1024 bytes) and 128 * 24 bytes of scratch after the one before, and the view's + // 1000 indices from the first one run out in the second. + { + VkPhysicalDeviceLimits small{}; + small.maxComputeWorkGroupCount[0] = 2; + QuadIndexExpander chunked(device_proc, handle(9), small); + ReplayFunctions split = vk; + wire(split, chunked); + Draw many = draw; + many.index = {32, 2010, 57}; + many.count = 1200; + many.first = 5; + app_bytes = 4096; + const std::vector want{{app_address + 40, scratch_address, 1, 16, 1000, 128}, + {app_address + 40 + 1024, scratch_address + 128 * 24, 1, 16, 488, 128}, + {app_address + 40 + 2048, scratch_address + 256 * 24, 1, 16, 0, 44}}; + ok &= check(run(many, split) == ReplayResult::success && pushes == want && + dispatches == std::vector{2, 2, 1}, + "a large draw is expanded by several dispatches that continue where the last one stopped"); + ok &= check(calls.size() == 1 && calls[0].count == 1800 && scratch_requests == std::vector{7200}, + "a large draw is still one draw over one piece of scratch"); + app_bytes = 64; + } + + // Inside a pipeline-statistics query the dispatch must not be counted (CSInvocations): the query's segment ends + // before it and a new one begins after it, for the draw. Without a segment pool the list is refused. + { + QueryPool heap{handle(7), d3d12_query_heap::pipeline_statistics, 1, false, {false}, {}}; + ReplayFunctions queries = vk; + queries.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; + queries.begin_query = begin_query; + queries.end_query = end_query; + queries.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; + queries.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, VkBuffer, + VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; + queries.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; + queries.query_pool = [&](QueryHeapId) { return &heap; }; + reset(); + CommandList list; + ok &= check(list.begin_query({6, d3d12_query::pipeline_statistics, 0}) && list.draw(draw) && + list.end_query({6, d3d12_query::pipeline_statistics, 0}) && list.close(), + "record a quad draw inside a statistics query"); + PreparedList prepared; + ok &= check(prepare(list, resolve, queries, prepared) == ReplayResult::unsupported && + scratch_requests.empty(), + "without a segment pool the expansion inside a statistics query is refused before its scratch"); + ok &= check(prepare(list, resolve, queries, prepared, true) == ReplayResult::success && + prepared.statistics_segment_count == 2, + "the expansion splits the statistics query in two segments"); + auto pool = std::make_shared(); + pool->pool = handle(8); + pool->destroy = destroy_query_pool; + QueryReplay plan; + ok &= check(plan.plan(prepared, {}, 0, true, pool, 4) == ReplayResult::success, "plan the split query"); + emit(prepared, VK_NULL_HANDLE, queries); + const std::vector want{ + "begin_query 4", "end_query 4", "barrier", "bind_compute", "dispatch", "barrier", "begin_query 5", + "begin_rendering", "bind_graphics", "draw_indexed", "end_rendering", "end_query 5"}; + ok &= check(events == want, "the dispatch runs between the query's two segments, the draw in the second"); + } + return ok ? 0 : 1; +} diff --git a/runtime/test/replay_texture_barrier_test.cpp b/runtime/test/replay_texture_barrier_test.cpp index 43ee9dcb7d..3a096c27af 100644 --- a/runtime/test/replay_texture_barrier_test.cpp +++ b/runtime/test/replay_texture_barrier_test.cpp @@ -64,9 +64,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]); } @@ -93,6 +95,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() { @@ -304,6 +478,7 @@ int main() { expect(tracker.layout(id, mip) == attachment, "after a release: the tracker has the new layout"); } + 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 3aa37f8b25..a11da272a3 100644 --- a/runtime/test/replay_uav_clear_offset_test.cpp +++ b/runtime/test/replay_uav_clear_offset_test.cpp @@ -318,6 +318,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/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 00c0fd47b8..2448ab7b82 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1044,6 +1044,66 @@ int main() { std::filesystem::remove_all(dir); } + // Executable embedded shaders (/exe/index.json): graphics (vs/ps) FSSM programs indexed alongside the game's + // own shaders, counted apart via exe_size(), and optional when missing or malformed. + { + const auto vs_container = container({{fixed, 25}}); + const auto ps_container = container({{stored, 40}}); + const std::string vs_hash = sha256_hex(fssm_program(vs_container)); + const std::string ps_hash = sha256_hex(fssm_program(ps_container)); + const auto code = fspx_code(0x5000); + const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; + const auto write = [&](const std::filesystem::path& file, const std::string& text) { + std::ofstream out(file, std::ios::binary | std::ios::trunc); + out << text; + }; + const std::string game = "\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}"; + const std::string vs_entry = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + vs_hash + + "\", \"input_signature\": [{\"semantic\": \"POSITION\", \"semantic_index\": 0, " + "\"register\": 0, \"system_value\": 0, \"component_type\": \"float\"}]}"; + const std::string ps_entry = "{\"stage\": \"ps\", \"fssm_sha256\": \"" + ps_hash + "\"}"; + std::filesystem::create_directories(dir / "fspx"); + std::filesystem::create_directories(dir / "bvh"); + std::filesystem::create_directories(dir / "exe"); + write(dir / "index.json", "{" + game + "}"); + write(dir / "fspx" / "index.json", + "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}"); + write(dir / "bvh" / "index.json", + "{\"BuilderProgram\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}}"); + write(dir / "exe" / "index.json", + "{\"container_00\": " + vs_entry + ",\n \"container_01\": " + ps_entry + + ",\n \"NoKey\": {\"error\": \"ValueError: synthetic\"}}"); + { + std::ofstream spv(dir / "exe" / "container_00.spv", std::ios::binary); + spv.write(reinterpret_cast(words), sizeof(words)); + std::ofstream spv_ps(dir / "exe" / "container_01.spv", std::ios::binary); + spv_ps.write(reinterpret_cast(words), sizeof(words)); + } + ShaderLibrary exe; + CHECK(exe.load(dir.string(), &error) && exe.size() == 5 && exe.fspx_size() == 1 && exe.bvh_size() == 1 && + exe.exe_size() == 2); + const ShaderEntry* vs = exe.find("vs", vs_hash); + const ShaderEntry* ps = exe.find("ps", ps_hash); + CHECK(vs && vs->name == "exe/container_00" && vs->input_signature.size() == 1 && + vs->input_signature[0].semantic == "POSITION" && exe.spirv(*vs).size() == 5); + CHECK(ps && ps->name == "exe/container_01" && exe.spirv(*ps).size() == 5); + CHECK(exe.candidates("ps", vs_hash).empty() && exe.candidates("vs", ps_hash).empty() && + exe.fspx_candidates("vs", vs_hash).empty()); + // Same program in main index and exe/: main comes first (index order). + write(dir / "index.json", "{" + game + ",\n \"vs_same\": " + vs_entry + "}"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 6 && exe.exe_size() == 2); + const auto both = exe.candidates("vs", vs_hash); + CHECK(both.size() == 2 && both[0]->name == "vs_same" && both[1]->name == "exe/container_00"); + write(dir / "index.json", "{" + game + "}"); + // Broken or missing exe/index.json leaves main, fspx, and bvh loaded and resets exe_size() to 0. + write(dir / "exe" / "index.json", "{broken"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.bvh_size() == 1 && + exe.fspx_size() == 1 && !exe.find("vs", vs_hash)); + std::filesystem::remove(dir / "exe" / "index.json"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.find("cs", hash)); + std::filesystem::remove_all(dir); + } + // The review case on #1911: one kind-6 program in two containers whose kind-0 entries differ (32x1x1 and // 64x1x1), translated to two different modules. A container picks its own entry by fspx_state_sha256; a bare // kind-6 program cannot tell them apart and is refused as ambiguous; with one module for the key it is accepted. diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 1e6c311d5c..f0ddf2f315 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -100,6 +100,7 @@ def not_found_message(build, missing): ("cs_workgroup_yz", "2x3x4", "workgroup_yz")] COMPUTE += [("cs_bvh32", "1", "bvh")] # TEST-184: image_bvh_intersect_ray, the 32-bit node pointer; same scene and words CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800, 0x40ff8000, 0x3ff00000] +CS_SMEM_VCC = list(range(0x7210, 0x7218)) CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c] # -0, and NaN checks that need SignedZeroInfNanPreserve (cs_signed_zero_nan.asm); 0 in out[4..7] means it's missing SIGNED_ZERO_NAN = [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007c00] @@ -130,7 +131,7 @@ def not_found_message(build, missing): ("cs_dpp_cmp", [3, 2, 3, 2, 1, 0, 1, 0])] WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) -CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), +CS_DUMPS = [*CS_DPP, ("cs_smem_vcc_base", CS_SMEM_VCC), ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), # SHADER-52: wave32 lane select is & 31; lane 40 wraps to 8 ("cs_w32_lane_wrap", [25, 16, 777, 777]), # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] @@ -2183,6 +2184,32 @@ 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_imgstore_cube": ("cube",), # GPU-CUBE-STORE: six-layer 2D-array views at bindings 11/12/13 + "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",), + "cs_imgload_mip": ("load-mip",), +} + + def main(): if any(arg in ("-h", "--help") for arg in sys.argv[1:]): print(__doc__) @@ -2238,10 +2265,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_imgstore_cube", ["cube"]), ("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) @@ -2249,6 +2273,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 0000000000..6dd26a845d --- /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 29f4477a4a..cd6b6a1130 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 0000000000..c9d4d33067 --- /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_smem_vcc_base.asm b/runtime/test/shaders/cs_smem_vcc_base.asm new file mode 100644 index 0000000000..234cb96fd9 --- /dev/null +++ b/runtime/test/shaders/cs_smem_vcc_base.asm @@ -0,0 +1,32 @@ +; group: 1,1,1 +; Seed eight consecutive words at byte 128. Read them back with VCC as an ordinary scalar pointer pair. +; Expected out[0..7]: 0x7210 0x7211 0x7212 0x7213 0x7214 0x7215 0x7216 0x7217. +v_mov_b32_e32 v1, 0x7210 +v_mov_b32_e32 v2, 0x7211 +v_mov_b32_e32 v3, 0x7212 +v_mov_b32_e32 v4, 0x7213 +buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:128 +v_mov_b32_e32 v1, 0x7214 +v_mov_b32_e32 v2, 0x7215 +v_mov_b32_e32 v3, 0x7216 +v_mov_b32_e32 v4, 0x7217 +buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:144 +s_waitcnt vmcnt(0) +s_mov_b32 s4, 128 +s_mov_b32 s5, 0 +s_mov_b64 vcc, s[4:5] +s_load_dwordx8 s[8:15], vcc, 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v0, 0 +v_mov_b32 v1, s8 +v_mov_b32 v2, s9 +v_mov_b32 v3, s10 +v_mov_b32 v4, s11 +buffer_store_dwordx4 v[1:4], v0, s[0:3], 0 offen +v_mov_b32 v0, 16 +v_mov_b32 v1, s12 +v_mov_b32 v2, s13 +v_mov_b32 v3, s14 +v_mov_b32 v4, s15 +buffer_store_dwordx4 v[1:4], v0, s[0:3], 0 offen +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 0000000000..b5180a881a --- /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 b8f888c131..253cd2c9e7 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/shaders/ps_quad_flat.asm b/runtime/test/shaders/ps_quad_flat.asm new file mode 100644 index 0000000000..ae84247241 --- /dev/null +++ b/runtime/test/shaders/ps_quad_flat.asm @@ -0,0 +1,15 @@ +; Pixel shader for the indexed quad-list test: param0 (a colour) read only with v_interp_mov, so the input is Flat +; and every pixel of a primitive gets the provoking vertex's colour, unscaled. Run: d3d12_quad_index_test, with +; vs_quad_inst. +; mrt0 = param0 of the primitive's provoking vertex +; A quad list takes it from the quad's first vertex. The test's quads have a different colour at each corner, so +; a quad drawn from any other vertex shows that vertex's colour instead; the colours are 0 and 1, exact in the float +; render target. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535020 +v_interp_mov_f32_e32 v2, p0, attr0.x +v_interp_mov_f32_e32 v3, p0, attr0.y +v_interp_mov_f32_e32 v4, p0, attr0.z +v_interp_mov_f32_e32 v5, p0, attr0.w +exp mrt0 v2, v3, v4, v5 done vm +s_endpgm diff --git a/runtime/test/shaders/vs_quad_inst.asm b/runtime/test/shaders/vs_quad_inst.asm new file mode 100644 index 0000000000..48adac14af --- /dev/null +++ b/runtime/test/shaders/vs_quad_inst.asm @@ -0,0 +1,28 @@ +; Vertex shader for the indexed quad-list test: vs_m15's vertex fetch through a V#, plus the instance id. Run: +; d3d12_quad_index_test (through a D3D12 graphics PSO found by the SHA-256 of its FSSM program), with ps_quad_flat. +; +; User data, from the root signature [0] descriptor table, [1] four 32-bit constants (docs/d3d12_vulkan.md 3.5): +; s[0:1] = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32) +; s2, s3 = the clip-space offset (x, y) of each instance after the first, as floats +; v0 = the vertex id and v3 = the instance id, both zero-based as on the hardware (vs_base_ids.asm): in an indexed +; draw v0 is the index the application wrote, without the draw's base vertex. +; Vertex record, 32 bytes: position xyzw at 0, colour rgba at 16 (both float). +; pos0 = (position.x + instance * s2, position.y + instance * s3, position.z, position.w) +; param0 = colour for instance 0, colour.grba (red and green swapped) for every later instance +; The test draws red quads with two instances: instance 0 stays red, instance 1 is green and one offset further on. +; fssm-at: 0x10 +; fssm-data: 0x44415551 0x20535620 +s_load_dwordx4 s[8:11], s[0:1], 0x0 +s_waitcnt lgkmcnt(0) +buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen +buffer_load_dwordx4 v[8:11], v0, s[8:11], 0 idxen offset:16 +s_waitcnt vmcnt(0) +v_cvt_f32_u32_e32 v12, v3 +v_fma_f32 v4, v12, s2, v4 +v_fma_f32 v5, v12, s3, v5 +v_cmp_ne_u32_e32 vcc_lo, 0, v3 +v_cndmask_b32_e32 v13, v8, v9, vcc_lo +v_cndmask_b32_e32 v14, v9, v8, vcc_lo +exp pos0 v4, v5, v6, v7 done +exp param0 v13, v14, v10, v11 +s_endpgm diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp index d6276d8ad4..194df74a9b 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 a247ba1707..0e39d0f621 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 @@ -55,6 +55,7 @@ #include "pipeline_summary.h" #include "../src/spirv_words.h" #include "../src/subgroup_size.h" +#include "../src/vulkan_bindless.h" #include #include @@ -71,6 +72,7 @@ #include #include #include +#include #include #include #include @@ -1101,10 +1103,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); @@ -1171,12 +1176,12 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = chain; vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported - // The runtime's device (create_vulkan_device_standalone) never enables these three, and a driver makes them part - // of a pipeline's cache key: with any of them on here, the cache this tool saves does not hit in gta6rt - // (pipeline_cache_seed_test; docs/pipeline_check.md, "The cache and the runtime's device"). + // The runtime's device (create_vulkan_device_standalone) never enables the first two, and a driver makes them part + // of a pipeline's cache key: with either of them on here, the cache this tool saves does not hit in gta6rt + // (pipeline_cache_seed_test; docs/pipeline_check.md, "The cache and the runtime's device"). The runtime enables + // robustImageAccess where supported (for 1D and 3D storage views), so its queried value is kept. f2.features.robustBufferAccess = VK_FALSE; f12.scalarBlockLayout = VK_FALSE; - f13.robustImageAccess = VK_FALSE; VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; if (ext_mesh && mesh.meshShader) { VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; @@ -1243,6 +1248,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); @@ -1296,15 +1302,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"; @@ -1319,28 +1326,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_present_dump_test.cpp b/runtime/test/vk_present_dump_test.cpp new file mode 100644 index 0000000000..a4497166f9 --- /dev/null +++ b/runtime/test/vk_present_dump_test.cpp @@ -0,0 +1,113 @@ +// Present a small solid texture through the window blit and the PresentX plane composer. Only the composed +// image has a black lower half. Decode the PNGs independently with the conformance tool's WIC reader. +#define VK_USE_PLATFORM_WIN32_KHR +#include +#include + +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../src/vulkan_present.h" +#include "../../tools/conformance/native/src/png_io.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main(int argc, char** argv) { + using namespace leonida; + namespace fs = std::filesystem; + vktest::Device d; + const auto status = d.initialize(true); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + EXPECT(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))); + testfiles::ScratchDir scratch("leonida_present_dump"); + const fs::path dir = scratch.path() / "frames"; + const std::string_view mode = argc == 2 ? argv[1] : ""; + EXPECT(mode.empty() || mode == "--default" || mode == "--invalid"); + const int interval = mode == "--default" ? 60 : 2; + const auto setting = dir.wstring() + (mode == "--default" ? L"" : mode == "--invalid" ? L",0" : L",2"); + EXPECT(_wputenv_s(L"LEONIDA_PRESENT_DUMP", setting.c_str()) == 0); + // An earlier dump might be a hard link outside the requested directory. Replacing it must leave that file intact. + const auto sentinel = scratch.path() / "outside"; + if (mode == "--default") { + EXPECT(fs::create_directory(dir)); + EXPECT(std::ofstream(sentinel).put('X')); + std::error_code ec; + fs::create_hard_link(sentinel, dir / "present_000001.png", ec); // optional on filesystems without links + } + + constexpr int width = 192, height = 100; + const HINSTANCE instance = GetModuleHandleW(nullptr); + HWND window = CreateWindowExW(0, L"STATIC", L"Leonida present dump test", WS_POPUP, 0, 0, width, height, + nullptr, nullptr, instance, nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNOACTIVATE); + VulkanContext context(d.device_proc, d.device, true); + VulkanQueue queue(context, d.queue, d.family); + EXPECT(context.loaded() && queue.ok()); + ResourceBinding back{}; + back.format = VK_FORMAT_R8G8B8A8_UNORM; + back.width = back.height = 2; + back.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + back.sampled = back.color_attachment = true; + back.image = d.image(back.format, 2, 2, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(back.image); + context.add_resource(1, back, VK_IMAGE_LAYOUT_UNDEFINED); + CommandList commands; + EXPECT(commands.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(commands.clear_render_target({1, 0, 0, 1}, {1.0f, 0.4f, 0.0f, 1.0f})); + EXPECT(commands.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(commands.close()); + const CommandList* list = &commands; + EXPECT(queue.execute({&list, 1}) == ReplayResult::success); + + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance = instance; + info.hwnd = window; + VkSurfaceKHR surface{}; + EXPECT(d.instance_fn("vkCreateWin32SurfaceKHR")( + d.instance, &info, nullptr, &surface) == VK_SUCCESS); + { + VulkanPresenter presenter(context, d.instance_proc, d.instance, d.physical, d.queue, d.family, surface, + false, [] { return VkExtent2D{width, height}; }); + EXPECT(presenter.ok()); + EXPECT(presenter.present(1, true) == VK_SUCCESS); + for (int i = 1; i < interval; ++i) EXPECT(presenter.present_blank(true) == VK_SUCCESS); + PresentPlanes planes; + planes.plane[0].source = 1; + planes.plane[0].dest[3] = 0.5f; + EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); + EXPECT(presenter.presented() == unsigned(interval + 1) && presenter.composed_presents() == 1); + } + DestroyWindow(window); + EXPECT(d.validation_errors() == 0); + if (mode == "--invalid") { + EXPECT(!fs::exists(dir)); + CoUninitialize(); + return 0; + } + if (mode == "--default") EXPECT(fs::file_size(sentinel) == 1 && std::ifstream(sentinel).get() == 'X'); + for (bool composed : {false, true}) { + const auto* name = !composed ? "present_000001.png" : interval == 2 ? "present_000003.png" : "present_000061.png"; + PixelSurface png; + EXPECT(ReadPngFile(dir / name, png)); + EXPECT(png.width == width && png.height == height); + for (int y = 0; y < height; ++y) { + const bool black = composed && y >= height / 2; + const std::array expected = black ? std::array{0, 0, 0, 255} + : std::array{255, 102, 0, 255}; + for (int x = 0; x < width; ++x) + EXPECT(std::equal(expected.begin(), expected.end(), png.At(x, y))); + } + } + EXPECT(std::distance(fs::directory_iterator(dir), fs::directory_iterator{}) == 2); + CoUninitialize(); + return 0; +} diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp index 99a602aebd..0b4c3c6f90 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 @@ -65,7 +69,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|cube]\n"); + std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|load-mip|words|signed-zero|cube]\n"); return 2; } gipa = load_vulkan(); @@ -128,8 +132,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"); @@ -248,7 +253,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; @@ -256,10 +262,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; @@ -273,6 +281,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; { @@ -364,10 +380,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]; @@ -429,7 +445,10 @@ int main(int argc, char** argv) { VkBuffer cube_rb[3]{}; void* cube_rbp[3]{}; for (int k = 0; cube_mode && k < 3; k++) CHECK(make_buffer(cube_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &cube_rb[k], &cube_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[] = { @@ -437,18 +456,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. @@ -472,7 +497,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; } @@ -488,6 +513,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; @@ -506,10 +532,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; @@ -542,6 +574,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); @@ -640,6 +673,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 f72a927855..079707aa90 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -104,6 +104,8 @@ class Device { 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 bool request_depth_range_unrestricted = false; @@ -111,11 +113,15 @@ class Device { // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as // gta6rt enables it (VulkanDeviceInfo::a8_render_target). bool a8_render_target = false; + 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 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 @@ -180,6 +186,17 @@ class Device { 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; @@ -339,7 +356,9 @@ class Device { 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); @@ -379,8 +398,17 @@ class Device { 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; 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; @@ -436,15 +464,20 @@ class Device { 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.multiViewport = features.features.multiViewport; // d3d12_multi_viewport_test, 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. @@ -509,6 +542,16 @@ class Device { host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any *v13_.next() = &host_copy; } + // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). + for (const auto& extension : extensions) { + if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; @@ -533,6 +576,22 @@ class Device { } #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}; @@ -586,16 +645,6 @@ class Device { *v13_.next() = &custom_border; } - // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). - for (const auto& extension : extensions) { - if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; - VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; - instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); - host_pointer_alignment = host_memory.minImportedHostPointerAlignment; - } - VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); @@ -616,9 +665,25 @@ class Device { if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); - if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); #ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME 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); @@ -670,6 +735,7 @@ class Device { 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 f636106153..067fa83ff7 100644 --- a/runtime/test/vulkan_scratch_test.cpp +++ b/runtime/test/vulkan_scratch_test.cpp @@ -1,5 +1,6 @@ // Unit tests for ScratchBuffers (runtime/src/vulkan_scratch.h). CPU-only, no Vulkan instance and no GPU: -// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, and spare cap. +// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, spare cap, +// and the usage a chunk is created with. #ifndef VK_NO_PROTOTYPES #define VK_NO_PROTOTYPES #endif @@ -38,6 +39,9 @@ struct FakeVulkan { int free_memory_calls = 0; int wait_idle_calls = 0; int get_counter_calls = 0; + VkBufferUsageFlags last_usage = 0; // of the last chunk created + VkSharingMode sharing_mode = VK_SHARING_MODE_EXCLUSIVE; + std::vector families; VkResult create_buffer_result = VK_SUCCESS; VkResult bind_result = VK_SUCCESS; @@ -53,9 +57,13 @@ 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; + g_vk->last_usage = info->usage; *out = make_handle(id); return VK_SUCCESS; } @@ -149,7 +157,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, 0, {2, 5}); EXPECT(scratch.loaded()); VkBuffer buf = VK_NULL_HANDLE; @@ -158,6 +166,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); @@ -290,6 +299,27 @@ int main() { EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); } + // A chunk is a transfer source and destination, plus whatever usage the owner asks for (the expanded indices of + // quad lists are an index buffer written through its device address). + { + FakeVulkan vk; + g_vk = &vk; + constexpr VkBufferUsageFlags transfer = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; + constexpr VkBufferUsageFlags extra = + VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + VkBuffer buf = VK_NULL_HANDLE; + VkDeviceSize off = 0; + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == transfer); + } + { + ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate, extra); + EXPECT(scratch.get(256, buf, off) && vk.last_usage == (transfer | extra)); + } + EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); + } + // A chunk whose used byte count is within 255 bytes of UINT64_MAX must not wrap alignment back to offset 0. { FakeVulkan vk; diff --git a/runtime/test/xbox_cbv_vector_test.cpp b/runtime/test/xbox_cbv_vector_test.cpp new file mode 100644 index 0000000000..014ad18879 --- /dev/null +++ b/runtime/test/xbox_cbv_vector_test.cpp @@ -0,0 +1,77 @@ +#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}); + // The device writes every constant-buffer V# in the console's form of sixteen-byte rows; with LEONIDA_CBV_RAW=1 + // only a view made through the console device has rows and one made on the device itself is a byte-address view. + wchar_t raw_env[2]{}; + const bool raw_cbv = GetEnvironmentVariableW(L"LEONIDA_CBV_RAW", raw_env, 2) == 1 && raw_env[0] == L'1'; + 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); + const bool bytes = variant && raw_cbv; + CHECK(decoded.stride == (bytes ? 0u : 16u) && decoded.num_records == (bytes ? 256u : 16u)); + CHECK(decoded.oob_select == + (bytes ? 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(raw_cbv ? "Xbox CBV has sixteen complete 16-byte rows; byte-address view retains 256 bytes" + : "Xbox CBV and device CBV both have sixteen complete 16-byte rows"); + 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 0000000000..8eacb3b18b --- /dev/null +++ b/runtime/test/xbox_d16s8_surface_test.cpp @@ -0,0 +1,127 @@ +#include "../shims/d3d12_xs_device.h" +#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, 255}; + CHECK(dev->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &planes, sizeof(planes)) == E_INVALIDARG); + CHECK(planes.PlaneCount == 255); + { + Ref inner, console; + CHECK(SUCCEEDED(dev->QueryInterface(IID_PPV_ARGS(&inner.p)))); + CHECK(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner.p, __uuidof(ID3D12Device), + reinterpret_cast(&console.p), true))); + inner.p = nullptr; // the proxy now owns this reference + rt::d3d12_xs::set_console_caller([](std::uint64_t) { return true; }); + for (unsigned alias = 118; alias <= 120; ++alias) { + planes = {static_cast(alias), 255}; + CHECK(SUCCEEDED(console->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &planes, sizeof(planes)))); + CHECK(planes.PlaneCount == 2); + } + rt::d3d12_xs::set_console_caller(nullptr); + } + 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() < end) + Sleep(1); + CHECK(fence->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 < extent; ++y) + for (unsigned x = 0; x < extent; ++x) + CHECK(pixels[y * fp[1].Footprint.RowPitch + x] == (x >= 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 0000000000..9f33db608b --- /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 0000000000..4d1be21610 --- /dev/null +++ b/runtime/test/xbox_gpu_label_test.cpp @@ -0,0 +1,111 @@ +#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