From 44a7d7d3819de1a06dd51ba37495d0a70b09a29a Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:36:34 +0100 Subject: [PATCH 1/3] startup: lower cube image sampling in gfx2hlsl (#2943) image_sample, image_sample_lz, image_sample_l and image_sample_b on dim:SQ_RSRC_IMG_CUBE now lower to TextureCube, with the manifest kind texcube. The gfx10 address (s, t, face), where s = sc/|ma| + 1.5 (Mesa prepare_cube_coords) and ma is twice the major coordinate (LLVM ConstantFoldAMDGCNCubeIntrinsic), is rebuilt into a direction by an emitted helper x2w_cube_dir. Cube loads, image_sample_d, image_get_lod, a16, d16, compute stages and constant samplers with DISABLE_CUBE_WRAP stay refused by name. offscreen_check --startup-image-cube binds six 2x2 faces as a TextureCube. tests/startup_image_cube_check.py draws literal face addresses against the address meaning, 13 helper mutants, guest-input controls and the v_cube chain per face against a desktop TextureCube draw. The cube cases of the sample_l and sample_b checks change from refusal to acceptance; the 3D check's unverified-dimension case moves to MSAA, since the same words now form a valid cube sample. The runtime binding of texcube views is #2938; this must land after it. AI-assisted. Co-Authored-By: Claude Opus 5.5 --- docs/experiments.md | 4 +- docs/experiments/startup-image-cube.md | 81 ++++ docs/startup-runtime.md | 6 +- .../pixel-binary/startup_image_cube.txt | 1 + .../python-linux/startup_image_cube.txt | 1 + tests/cmake/startup_image_cube.cmake | 12 + tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 7 +- tests/startup_image_2d_array_check.py | 4 +- tests/startup_image_3d.cpp | 35 +- tests/startup_image_3d_check.py | 11 +- tests/startup_image_cube_check.py | 384 ++++++++++++++++++ tests/startup_image_sample_b_check.py | 7 +- tests/startup_image_sample_l_check.py | 7 +- tools/startup/gfx2hlsl.py | 56 ++- 15 files changed, 589 insertions(+), 29 deletions(-) create mode 100644 docs/experiments/startup-image-cube.md create mode 100644 tests/checks/pixel-binary/startup_image_cube.txt create mode 100644 tests/checks/python-linux/startup_image_cube.txt create mode 100644 tests/cmake/startup_image_cube.cmake create mode 100644 tests/startup_image_cube_check.py diff --git a/docs/experiments.md b/docs/experiments.md index f9fb98d4ec..5f2850c526 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15009,7 +15009,7 @@ For binary32 arithmetic and compare sources, the translator reads the inline int ## Startup translator: explicit-LOD image sampling -`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) +`tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) ## Startup translator: binary32 arithmetic @@ -15030,7 +15030,7 @@ Not covered: inexact products. The translation writes both `v_fma_f32`, which ro ## Startup translator: biased image sampling -`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D, cube and multisample dimensions, an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_b` form in a pixel stage to `tex.SampleBias(smp, uv, bias)` for 2D, 2D-array and 3D textures. The RDNA 2 ISA (section 8.2.4, Table 43: "_B LOD BIAS, 1: lod bias, Add this BIAS to the LOD computed"; section 8.2.5: the address is `{ offset } { bias } { z-compare } { derivative } { body }` and the bias is "One Dword float") puts the bias in the FIRST address register, so `v[0:2]` is bias, u, v and the NSA list `[v3, v1, v2]` takes the bias from `v3`. LLVM 15 agrees: `IntrinsicsAMDGPU.td` gives `AMDGPUSample_b` the extra argument `llvm_anyfloat_ty "bias"` and `MIMGInstructions.td` the gfx10 opcode `0x25`. `llvm-mc` (LLVM 15, gfx1013) assembles the contiguous 2D, 2D-array, 3D and NSA forms, and the check compares every fixture against it. HLSL `SampleBias` adds the bias to the implicit mip level and documents the range -16.0 to 15.99; the ISA text states no hardware clamp, so a bias outside that range is an unverified difference. The form needs a pixel stage whose EXEC is still the entry mask with wave-uniform control flow (implicit derivatives); a uniform (scc) join or later loop does not drop that proof, while divergent EXEC or a vcc/exec-conditioned branch before the sample does (there the plain sample is lowered to level 0, which would drop the bias). It is also refused outside a pixel stage, and so are `image_sample_b_cl`, `image_sample_c_b*`, `image_sample_b_o`, `image_gather4_b`, 1D and multisample dimensions (a cube lowers since #2943, see [startup-image-cube](experiments/startup-image-cube.md)), an empty `dmask`, the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers, set reserved MIMG bits, and a constant sampler whose LOD bias fields (word 2 bits 19:0, s6.8 and s2.4, scaled by `T#.perf_modulation` in the ISA) are not zero or whose mip filter is 0 (mipmapping disabled), or whose MIN_LOD is above its MAX_LOD. The guest clamp is kept: MIN_LOD (word 1 bits 11:0) and MAX_LOD (bits 23:12) are unsigned 4.8 fixed point (Mesa 24.0.0 `src/amd/registers/gfx10-rsrc.json`, `SQ_IMG_SAMP_WORD1`; `radeonsi/si_state.c` lines 5169-5170 encode them with `S_FIXED(x, 8)`), and the sampler of an `image_sample_b` is written as an `smpl` manifest line that the runtime decodes to `MinLOD = MIN_LOD / 256` and `MaxLOD = MAX_LOD / 256` (`src/startup_stubs/translated_sampler_bindings.h`); `smp` and `smpc` lines still leave MinLOD at 0 and MaxLOD unbounded (the next section moves `image_sample`, `_l` and `_lz` with a constant sampler to `smpl`). A sampler read from the sampler heap, including the default-sampler shortcut for a run-time heap load, or built from a register is refused for `image_sample_b`, because its LOD limits and bias cannot be shown to be irrelevant. `tests/startup_image_sample_b_check.py` translates source-built fixtures and, with `draw`, draws the 2D array through `offscreen_check --startup-image-2d-array-mips` (4x4, two slices, three mips whose cells all differ, point sampler with mip filter point; MAX_LOD 2 for the bias cases). Constant coordinates have no derivatives, so the draw rewrites only the `u` initialiser of the translated HLSL to `0.75 + 0.5 * (SV_Position.x - 0.5)`, an implicit LOD of 1 at the sampled pixel; the `SampleBias` call is untouched. Bias -1, 0 and +1 read mip 0, 1 and 2 on WARP with DXC and FXC. A uniform (scc) join before the sample is accepted and drawn (same mip as the plain bias -1 case); divergent EXEC or a vcc/exec-conditioned branch before the sample is refused. Negative controls: the same program with `image_sample` reads mip 1 for every case, and edited calls (bias replaced by 0, bias negated, bias and `u` exchanged, `Sample` for `SampleBias`) each read another cell. The sampler limits are discriminated by cases whose limit lies below a mip that exists: MAX_LOD 1 with bias +1 stays on mip 1 (unclamped: mip 2), MAX_LOD 0 with bias +1 stays on mip 0, MIN_LOD 2 with bias -1 reads mip 2 (unclamped: mip 0) and MIN_LOD 1 = MAX_LOD 1 with bias -1 reads mip 1; the MAX_LOD 2 bias cases cannot tell, because mip 2 is the last level. Each limit case is drawn again with an `smp` line instead of `smpl` (limits not carried) and must read the unclamped mip. `startup_sampler_comparison` checks the decoded MinLOD and MaxLOD. Replacing the bias by 0 or exchanging the bias with the first coordinate in `gfx2hlsl.py`, dropping the MaxLOD assignment in the runtime decoder, accepting a heap sampler, and the previous `gfx2hlsl.py`, each make a check fail. Not covered: a physical-adapter run (`startup_image_sample_b_hardware` is registered), a plain 2D or 3D draw (those forms are checked on the generated HLSL), fractional bias with a linear mip filter, bias outside -16 to 15.99, a fractional MIN_LOD or MAX_LOD (only whole mips are drawn; the 4.8 decode is checked without a device), a non-zero descriptor LOD bias (refused, not carried) and the limits of the other sample forms (see the next section). diff --git a/docs/experiments/startup-image-cube.md b/docs/experiments/startup-image-cube.md new file mode 100644 index 0000000000..6a9f18d103 --- /dev/null +++ b/docs/experiments/startup-image-cube.md @@ -0,0 +1,81 @@ +# Cube image sampling in gfx2hlsl (#2943) + +`tools/startup/gfx2hlsl.py` lowers `image_sample`, `image_sample_lz`, `image_sample_l` and `image_sample_b` with +`dim:SQ_RSRC_IMG_CUBE` to `TextureCube` `Sample`, `SampleLevel` and `SampleBias` (outside a pixel stage the +implicit-LOD form samples level 0 and the bias form is refused, as for 2D textures), and +writes the manifest kind `texcube` for the binding. Before, the stage was refused with +`image dimension SQ_RSRC_IMG_CUBE`. + +## The address + +On gfx10 a cube sample takes three address dwords after any bias: the face coordinates `s` and `t` and the face +id. Mesa's `prepare_cube_coords` (`src/amd/common/nir/ac_nir_lower_tex.c`, read at Mesa 25.0.7 through the +`openbsd/xenocara` mirror, commit `d31967950e30`) builds `s = sc / |ma| + 1.5` and `t = tc / |ma| + 1.5` from +`v_cubesc`, `v_cubetc` and `v_cubema`, and a cube-array id as `8 * layer + face`. LLVM 15.0.7 +`ConstantFoldAMDGCNCubeIntrinsic` (`llvm/lib/Analysis/ConstantFolding.cpp`) defines `v_cubema` as twice the signed +major coordinate, so `s` and `t` lie in [1, 2] and `s - 1`, `t - 1` are the position on the face. + +The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a direction whose major component is +1 or +-1 for the face and whose other components are `u = 2(s - 1.5)` and `v = 2(t - 1.5)` with the signs of the per-face +`sc` and `tc` that the existing `v_cube*` lowering uses: +X (1, -v, -u), -X (-1, -v, u), +Y (u, 1, v), -Y (u, -1, -v), ++Z (u, -v, 1), -Z (-u, -v, -1). Projecting that direction again gives back `u` and `v`. + +## Refused + +- `image_load` and `image_load_mip` on a cube (`Load is not defined on a TextureCube`), `image_sample_d` + (cube derivatives are not converted), `image_get_lod`, `a16` and `d16`. +- A cube in a compute program: the compute dispatch has no `texcube` view binding. +- A constant sampler with `DISABLE_CUBE_WRAP` (`SQ_IMG_SAMP_WORD0` bit 28, Mesa + `src/amd/registers/gfx10-rsrc.json`): the guest then filters without crossing face edges, while a D3D12 cube + always filters across them. With the bit clear both cross. +- Compare, gather and store forms were already limited to 2D and 2D arrays and are unchanged. + +## Limits + +- A cube-array view is not recognisable from the instruction (gfx10 MIMG has no array bit; the descriptor sets + the dimension). The helper keeps the face bits of the id (`id & 7`) and samples layer 0 of a `TextureCube`, + which is wrong for a later layer of a cube array. +- A face id of 6 or 7 maps to face 5, a negative, NaN or huge id to face 0, and `s` or `t` outside [1, 2] are + clamped to the face edge. Mesa does not produce these for a finite non-zero direction; none of them is measured. +- The implicit-LOD and bias forms take the desktop derivatives of the rebuilt direction. Inside one face these + follow the guest's face coordinates; a quad that straddles a face edge can choose another level. +- Heap and register samplers are not read at translation, so their `DISABLE_CUBE_WRAP` bit is not validated (a set + bit would filter differently at face edges), and their LOD range stays unvalidated as for 2D textures. +- Only pixel-stage draws are measured; the vertex-stage form is translated but not drawn. +- The runtime binding of a `texcube` view is PR #2938. Without it the main runtime parses `texcube` as an unknown + kind and would bind the slot as a buffer, so this lowering must not be merged before #2938. + +## Fixture + +`tests/startup_image_cube_check.py` (controls, `binary `, `draw `). +`offscreen_check --startup-image-cube` binds six 2x2 R32G32B32A32_FLOAT faces as a TextureCube whose texel (x, y) +of face f holds ((1 + x + 2y + 4f) / 32, x, y, f). The sampler is the all-zero inline sampler (point, wrap), and +every `s` and `t` is a texel centre. + +- Seven programs set `(s, t, face)` as constants, without `v_cube*`, so the reference is only the address meaning + (texel x = 0 below `s = 1.5`, else 1, the same for `t`). The desktop driver picks the face of the rebuilt + direction itself, so a wrong face, sign or axis in the helper reads another texel. Every face has a case whose + texel has x != y. +- `image_sample`, `image_sample_l` and `image_sample_b` each draw one case. +- Controls: the face one higher and `s`, `t` exchanged must read those texels; `image_sample_l` and + `image_sample_b` with the face in the LOD or bias dword must read face 0. +- Thirteen translator mutants edit the emitted helper (for each face the sign of the `u` term flipped, `u` and `v` + exchanged, and faces 2 and 3 exchanged). Each must read the texel a D3D cube lookup of its direction gives. +- Six programs run the `v_cube` chain (`v_cubema`, `v_cubesc`, `v_cubetc`, `v_cubeid`, `v_rcp_f32` of `|ma|` and + `v_fma_f32` with 1.5) on one direction per face. Each must match the face texel LLVM's table gives and a desktop + pixel shader that samples the same direction from the TextureCube. + +Measured on 27.11.2026, commit 6ee878d8 plus this change, Windows 11 24H2 (10.0.26100.9711), debug layer +unavailable on both adapters: the 22 reference draws (7 literal, 3 forms, 6 chain, 6 desktop TextureCube) matched +on NVIDIA Quadro M1000M (driver 32.0.15.7371) and on WARP (Microsoft Basic Render Driver 10.0.26100.9711), and all +17 controls and mutants read the texel they predict. With the translator change reverted, the controls fail on +`image dimension SQ_RSRC_IMG_CUBE`. +The 16 fixture programs reassemble to the recorded words with LLVM 15.0.7. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_image_cube_' -V +``` + +Not shown: that the console's face order and face orientation equal D3D's. That rests on LLVM's cube table being +the D3D cube face table. LOD and bias values on a cube are not tested, because only one mip is bound; the +`image_sample_l` and `image_sample_b` draws only show that the extra address dword is not read as a coordinate. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2563133bb5..90d10bd82b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2392,8 +2392,8 @@ These are measured on one executable; treat them as hypotheses for others. for a load. Before, the stage was refused and every draw through its pipeline was skipped. Two source-built pixel stages draw one texel of a 2x2 texture with two slices on WARP and hardware with DXC and FXC; a slice fixed to 0 and exchanged coordinates fail it - (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Cube, multisampled - and 1D images are still refused. Not covered: binding a single-slice 2D view to an array declaration + (`ctest --preset release --no-tests=error -R "^startup_image_2d_array_"`). Multisampled + and 1D images are still refused here; cube sampling is lowered since #2943 (`startup_image_cube_`). Not covered: binding a single-slice 2D view to an array declaration in the draw path. - **2D array depth comparison.** `image_sample_c_lz` and `image_sample_c` (sampler MAX_LOD 0) with `dim:SQ_RSRC_IMG_2D_ARRAY` take the reference, u, v and the slice as four address registers and lower to @@ -2628,7 +2628,7 @@ These are measured on one executable; treat them as hypotheses for others. mip 0 and mip 3 instead: `ctest --preset dev --no-tests=error -R '^startup_sampler_lod_' -V`. - The startup shader translator lowers `image_sample_l` (explicit level, 2D and 3D, any `dmask`) to `SampleLevel(sampler, uv, level)`, taking the level from the last address register. Offset, compare, - gather, clamp, cube, 1D and `unorm` forms are refused. Only the translation is checked + gather, clamp, 1D and `unorm` forms are refused; a cube lowers since #2943 ([note](experiments/startup-image-cube.md)). Only the translation is checked (`python -B tests/startup_image_sample_l_check.py`); a WARP readback of distinct mip levels is still open. - `image_sample_b` in a pixel stage lowers to `SampleBias(sampler, uv, bias)` for 2D, 2D-array and 3D textures; the bias is the first address register. Offset, clamp, compare and gather forms, other stages, code after a branch, a sampler with a diff --git a/tests/checks/pixel-binary/startup_image_cube.txt b/tests/checks/pixel-binary/startup_image_cube.txt new file mode 100644 index 0000000000..ea2f423737 --- /dev/null +++ b/tests/checks/pixel-binary/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py binary llvm-mc-15 diff --git a/tests/checks/python-linux/startup_image_cube.txt b/tests/checks/python-linux/startup_image_cube.txt new file mode 100644 index 0000000000..1ec2d8bd43 --- /dev/null +++ b/tests/checks/python-linux/startup_image_cube.txt @@ -0,0 +1 @@ +tests/startup_image_cube_check.py diff --git a/tests/cmake/startup_image_cube.cmake b/tests/cmake/startup_image_cube.cmake new file mode 100644 index 0000000000..1c46cfb54d --- /dev/null +++ b/tests/cmake/startup_image_cube.cmake @@ -0,0 +1,12 @@ +# gfx2hlsl cube image sampling (#2943): translation controls, then a six-face TextureCube drawn from literal face +# addresses, translator mutants and the v_cube chain, compared with the address meaning and a desktop TextureCube draw. +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + add_test(NAME startup_image_cube_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_cube_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_cube_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_image_cube_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 09beb8ce19..7b19c5fa67 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -26,7 +26,7 @@ float check_startup_sampler_heap(ID3D12Device* device, const char* vertex_path, void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array = false, UINT levels = 1, bool one_dimensional = false, bool two_dimensional = false, - UINT first_mip = 0, UINT view_levels = 0); + UINT first_mip = 0, UINT view_levels = 0, bool cube = false); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, bool depth16, std::uint32_t words[64], bool array = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index cdb1d28afd..089cd62167 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1329,7 +1329,8 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // The expected value is four comma-separated hex words. Omit the sampler line for point wrap. // --startup-image-2d-array takes the same arguments: the texels are two slices of a 2D array and the // third coordinate is the slice. --startup-image-2d-array-mips uses a 4x4 array of two slices with three -// mip levels whose cells all differ (tests/startup_image_3d.cpp). +// mip levels whose cells all differ (tests/startup_image_3d.cpp). --startup-image-cube binds six 2x2 faces as a +// TextureCube whose 24 texels all differ (#2943); z is passed through as for the other modes. OperationResult run_startup_image_3d(const OperationContext& ctx) { const bool array_mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; @@ -1337,6 +1338,7 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) const bool array = array_mips || std::strcmp(ctx.argv[2], "--startup-image-2d-array") == 0; const bool one_dimensional = one_dimensional_mips || std::strcmp(ctx.argv[2], "--startup-image-1d") == 0; const bool two_dimensional = std::strcmp(ctx.argv[2], "--startup-image-2d") == 0; + const bool cube = std::strcmp(ctx.argv[2], "--startup-image-cube") == 0; float z = 0.0f; if (two_dimensional && ctx.argv[5][0] == '0' && (ctx.argv[5][1] == 'x' || ctx.argv[5][1] == 'X')) { char* end = nullptr; @@ -1353,7 +1355,7 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) float color[4]{}; const char* sampler = ctx.argc == 8 ? ctx.argv[7] : "smp 0 0x0 0x0 0x0 0x0"; check_startup_image_3d(ctx.device, ctx.argv[3], ctx.argv[4], z, color, sampler, array, - array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional); + array_mips || one_dimensional_mips ? 3 : 1, one_dimensional, two_dimensional, 0, 0, cube); std::uint32_t bits[4]; std::memcpy(bits, color, sizeof(bits)); if (std::memcmp(bits, expected, sizeof(bits)) != 0) { @@ -1722,6 +1724,7 @@ const OperationSpec kOperations[] = { {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-cube", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, diff --git a/tests/startup_image_2d_array_check.py b/tests/startup_image_2d_array_check.py index 4aaf0edc88..728971b38a 100644 --- a/tests/startup_image_2d_array_check.py +++ b/tests/startup_image_2d_array_check.py @@ -24,7 +24,7 @@ of a slice (root constant 1) at a constant mip level. They are drawn with --startup-image-2d-array-mips: a 4x4 texture of two slices with three mip levels whose cells all differ, texel (x, y) of slice s at mip m holding ((1 + x + 4y + 16s + 32m) / 128, x, y, s + 2m). The expected colours come from mip_cell() below. -Cube maps stay refused. The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to +Cube loads stay refused (cube sampling: tests/startup_image_cube_check.py). The mip fixtures use spellings that llvm-mc 19 assembles; LLVM 15 is not known to accept them, so 'binary mip' is opt-in and CI does not pass it. """ import re @@ -261,7 +261,7 @@ def mip_controls(): G.D.MIMG_DIMS[5] = original assert G.D.MIMG_DIMS[5] == original - # Cube maps are refused as before. 2D and 3D keep their forms (same words, dim field changed). + # Cube loads are refused as before. 2D and 3D keep their forms (same words, dim field changed). cube = bytearray(MIP_IMAGE) cube[0] = 0x18 try: diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 8305017fdf..6aa54188c9 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -29,6 +29,8 @@ constexpr UINT side = 2; // The mip fixture: a 4x4 array of two slices with three mip levels (4x4, 2x2, 1x1). constexpr UINT mip_base = 4; constexpr UINT max_levels = 3; +// A cube fixture: six 2x2 faces, one level (dim:SQ_RSRC_IMG_CUBE, #2943). +constexpr UINT cube_faces = 6; // The value at texel (x, y) of slice s and mip level m. One level keeps the 2x2x2 fixture's values. With // several levels every (slice, mip, x, y) cell is distinct: the red channel is a dyadic fraction and @@ -68,8 +70,10 @@ ComPtr create_root(ID3D12Device* device, const x2w_startup: // comparison sampler (smpc), the texture uses DXGI_FORMAT_R32_FLOAT holding the red channel as depth. void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array, UINT levels, bool one_dimensional, - bool two_dimensional, UINT first_mip, UINT view_levels) + bool two_dimensional, UINT first_mip, UINT view_levels, bool cube) { + if (cube && (levels != 1 || array || one_dimensional || two_dimensional || view_levels)) + throw std::runtime_error("A cube image fixture has one level and no other layout"); if (levels < 1 || levels > max_levels || (levels > 1 && !array && !two_dimensional && !one_dimensional)) throw std::runtime_error("Unsupported image mip level count"); if (view_levels && (!two_dimensional || first_mip >= levels || view_levels > levels - first_mip)) @@ -101,19 +105,19 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const D3D12_RESOURCE_DESC td{}; td.Dimension = one_dimensional ? D3D12_RESOURCE_DIMENSION_TEXTURE1D - : (array || two_dimensional) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D + : (array || two_dimensional || cube) ? D3D12_RESOURCE_DIMENSION_TEXTURE2D : D3D12_RESOURCE_DIMENSION_TEXTURE3D; td.Width = base; td.Height = one_dimensional ? 1 : base; - td.DepthOrArraySize = (one_dimensional || two_dimensional) ? 1 : side; + td.DepthOrArraySize = cube ? cube_faces : (one_dimensional || two_dimensional) ? 1 : side; td.MipLevels = levels; td.Format = comparison ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32G32B32A32_FLOAT; td.SampleDesc.Count = 1; const auto texture = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); // A volume is one subresource of two slices; an array is two subresources of one slice each. // The subresource of slice s and mip m is m + s * levels. - const UINT subresources = (array ? side : 1) * levels; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[side * max_levels]{}; + const UINT subresources = (cube ? cube_faces : array ? side : 1) * levels; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[cube_faces * max_levels]{}; UINT64 upload_size = 0; device->GetCopyableFootprints(&td, 0, subresources, 0, footprints, nullptr, nullptr, &upload_size); const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& footprint = footprints[0]; @@ -126,13 +130,18 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const for (UINT tz = 0; tz < td.DepthOrArraySize; ++tz) for (UINT level = 0; level < levels; ++level) { const UINT extent = base >> level; - const auto& place = footprints[level + (array ? tz * levels : 0)]; + const auto& place = footprints[level + ((array || cube) ? tz * levels : 0)]; for (UINT ty = 0; ty < (one_dimensional ? 1u : extent); ++ty) for (UINT tx = 0; tx < extent; ++tx) { float texel[4]; texel_value(tx, ty, tz, level, levels, texel); if (one_dimensional) texel[3] = tx ? 0.75f : 0.5f; - auto* const slice = array ? start + place.Offset : start + place.Offset + tz * slice_pitch; + if (cube) { + // Every one of the 24 texels differs: face f, column tx and row ty. + const float face[4] = {(1.0f + tx + 2.0f * ty + 4.0f * tz) / 32.0f, float(tx), float(ty), float(tz)}; + std::memcpy(texel, face, sizeof(face)); + } + auto* const slice = (array || cube) ? start + place.Offset : start + place.Offset + tz * slice_pitch; const UINT texel_bytes = comparison ? sizeof(float) : sizeof(texel); std::memcpy(slice + ty * place.Footprint.RowPitch + tx * texel_bytes, texel, texel_bytes); } @@ -166,7 +175,15 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const view.Texture2D.MostDetailedMip = first_mip; view.Texture2D.MipLevels = view_levels; } - device->CreateShaderResourceView(texture.Get(), view_levels ? &view : nullptr, views->GetCPUDescriptorHandleForHeapStart()); + if (cube) { + view.Format = td.Format; + view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; + view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + view.TextureCube.MostDetailedMip = 0; + view.TextureCube.MipLevels = 1; + } + device->CreateShaderResourceView(texture.Get(), (view_levels || cube) ? &view : nullptr, + views->GetCPUDescriptorHandleForHeapStart()); hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image 3D RTV heap"); const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); @@ -211,7 +228,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const std::memcpy(color, static_cast(mapped) + target_footprint.Offset, 4 * sizeof(float)); readback->Unmap(0, &none); std::printf("startup_image_%s z=%g color=(%g, %g, %g, %g)\n", - one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", + cube ? "cube" : one_dimensional ? "1d" : two_dimensional ? "2d" : array ? "2d_array" : "3d", z, color[0], color[1], color[2], color[3]); } diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 0cfc30d79e..bcc2ed62ea 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -107,11 +107,16 @@ def controls(): assert 'Texture1D r0' in pipe.hlsl_ps() assert 'r0.Sample(q0, F(v0))' in pipe.hlsl_ps() assert 'srv 0 tex1d table 0 0' in pipe.manifest() - unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0')) + # The MIMG words carry no address count: the disassembler sizes the address from the dimension. With the cube + # dimension (field 3) the same words are a three-register cube sample, translated since #2943; the 2D MSAA + # dimension (field 6) stays an unverified dimension and must be refused. + cube = translate(WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('180f80f0'))).hlsl_ps() + assert 'TextureCube r0' in cube and 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))' in cube, cube + unsupported = WORDS_1D.replace(bytes.fromhex('000f80f0'), bytes.fromhex('300f80f0')) try: translate(unsupported) - except G.Unsupported: - pass + except G.Unsupported as error: + assert 'image dimension SQ_RSRC_IMG_2D_MSAA' in str(error), error else: raise AssertionError('unverified image dimension accepted') diff --git a/tests/startup_image_cube_check.py b/tests/startup_image_cube_check.py new file mode 100644 index 0000000000..b2f864eca7 --- /dev/null +++ b/tests/startup_image_cube_check.py @@ -0,0 +1,384 @@ +"""Cube images in tools/startup/gfx2hlsl.py (dim:SQ_RSRC_IMG_CUBE, #2943). + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the recorded words + draw + translate, compile (DXC ps_6_0) and draw against a six-face TextureCube + +A gfx10 cube sample addresses the face coordinates s and t and then the face id. Mesa's prepare_cube_coords +(src/amd/common/nir/ac_nir_lower_tex.c) builds s = sc/|ma| + 1.5 and t = tc/|ma| + 1.5 from v_cubesc, v_cubetc +and v_cubema, and LLVM's ConstantFoldAMDGCNCubeIntrinsic defines v_cubema as twice the major coordinate, so s and +t lie in [1, 2] and s - 1, t - 1 are the position on the face. The translator rebuilds a direction from (s, t, +face) for TextureCube (x2w_cube_dir in the HLSL). + +tests/startup_image_3d.cpp, run as --startup-image-cube, binds six 2x2 R32G32B32A32_FLOAT faces as a TextureCube +whose texel (x, y) of face f holds ((1 + x + 2y + 4f) / 32, x, y, f), so all 24 texels differ. The sampler is the +all-zero inline sampler (point, wrap); every (s, t) is a texel centre, 1.25 or 1.75. + +What the draws show: the literal cases feed (s, t, face) directly, without v_cube, and the reference is only the +address meaning above (texel x = 0 below s = 1.5, else 1; the same for t and y). The desktop driver selects the +face of the rebuilt direction itself, so a wrong face, sign or axis in x2w_cube_dir reads another texel. The +mutants edit one row of the emitted helper (sign of the u term flipped, u and v exchanged, faces 2 and 3 +exchanged) and must read the texel a D3D cube lookup of the mutated direction gives. The end-to-end cases run the +v_cube chain on six directions and must equal both that reference and a desktop PS that samples the direction. +They do not show that the console's face order and orientation equal D3D's: that rests on LLVM's cube table +being the D3D11.3 cube face table. Only one mip is bound, so LOD and bias values are not tested; the image_sample_l +and image_sample_b draws only show that the extra address dword is not taken as a coordinate. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 + +INLINE_FLOATS = {0.0: 128, 0.5: 240, -0.5: 241, 1.0: 242, -1.0: 243, 2.0: 244, -2.0: 245, 4.0: 246, -4.0: 247} +PROLOGUE = bytes.fromhex('04040cf4000000fa' '800398be' '800399be' '80039abe' '80039bbe') +PROLOGUE_SOURCE = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0 +s_mov_b32 s26, 0 +s_mov_b32 s27, 0 +""" +EPILOGUE = bytes.fromhex('703f8cbf' '0f1800f800010203' '000081bf') +EPILOGUE_SOURCE = """\ +s_waitcnt vmcnt(0) +exp mrt0 v0, v1, v2, v3 done vm +s_endpgm +""" +WAIT = bytes.fromhex('7fc08cbf') +# First and second dword of each MIMG form on dim:SQ_RSRC_IMG_CUBE (field value 3), vdata v[0:3], vaddr v0, +# s[16:23] and s[24:27]; recorded from LLVM 15. +MIMG = { + 'sample': ('image_sample v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f80f00000c400'), + 'lz': ('image_sample_lz v[0:3], v[0:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f9cf00000c400'), + 'l': ('image_sample_l v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f90f00000c400'), + 'b': ('image_sample_b v[0:3], v[0:3], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_CUBE', '180f94f00000c400'), +} + + +def bits(value): + return struct.unpack('= ax and az >= ay: + face, sc, tc, ma = (5, -x, -y, z) if z < 0 else (4, x, -y, z) + elif ay >= ax: + face, sc, tc, ma = (3, x, -z, y) if y < 0 else (2, x, z, y) + else: + face, sc, tc, ma = (1, z, -y, x) if x < 0 else (0, -z, -y, x) + inv = 1.0 / abs(2 * ma) + return address_texel(sc * inv + 1.5, tc * inv + 1.5, face) + + +# The emitted helper rows, face 0 to 5, as (x, y, z) expressions in u and v. +ROWS = [('1.0', '-v', '-u'), ('-1.0', '-v', 'u'), ('u', '1.0', 'v'), ('u', '-1.0', '-v'), ('u', '-v', '1.0'), + ('-u', '-v', '-1.0')] + + +def row_line(face, row): + body = 'return float3(%s, %s, %s);' % row + return body if face == 5 else 'if (k == %d) %s' % (face, body) + + +def helper_dir(rows, s, t, face): + u, v = 2 * (s - 1.5), 2 * (t - 1.5) + return tuple(eval(c, {}, {'u': u, 'v': v}) for c in rows[face]) # noqa: S307 (fixed expressions above) + + +def flip_u(row): + return tuple(c.replace('-u', '#').replace('u', '-u').replace('#', 'u') for c in row) + + +def swap_uv(row): + return tuple(c.replace('u', '#').replace('v', 'u').replace('#', 'v') for c in row) + + +def mutants(): + """(label, edits [(old line, new line)], mutated rows).""" + out = [] + for face in range(6): + for label, change in (('u sign flipped', flip_u), ('u and v exchanged', swap_uv)): + rows = list(ROWS) + rows[face] = change(ROWS[face]) + out.append(('face %d %s' % (face, label), [(row_line(face, ROWS[face]), row_line(face, rows[face]))], rows)) + rows = list(ROWS) + rows[2], rows[3] = ROWS[3], ROWS[2] + out.append(('faces 2 and 3 exchanged', [(row_line(2, ROWS[2]), row_line(2, ROWS[3])), + (row_line(3, ROWS[3]), row_line(3, ROWS[2]))], rows)) + return out + + +# Literal (s, t, face) cases: every face has one whose texel has x != y. +CASES = [(1.25, 1.75, 0), (1.75, 1.25, 1), (1.25, 1.75, 2), (1.75, 1.25, 3), (1.75, 1.25, 4), (1.25, 1.75, 5), + (1.75, 1.75, 2)] +# End-to-end directions, one per face, each on a texel with x != y. +DIRECTIONS = [(1.0, -0.5, 0.5), (-1.0, -0.5, -0.5), (0.5, 1.0, -0.5), (0.5, -1.0, 0.5), (0.5, 0.5, 1.0), + (-0.5, 0.5, -1.0)] +CHAIN_SOURCE = """\ +v_cubema_f32 v7, v4, v5, v6 +v_cubesc_f32 v8, v4, v5, v6 +v_cubetc_f32 v9, v4, v5, v6 +v_cubeid_f32 v2, v4, v5, v6 +v_rcp_f32_e64 v7, |v7| +v_mov_b32 v10, 0x3fc00000 +v_fma_f32 v0, v8, v7, v10 +v_fma_f32 v1, v9, v7, v10 +""" +CHAIN = bytes.fromhex('070047d5040b1a04' '080045d5040b1a04' '090046d5040b1a04' '020044d5040b1a04' + '0701aad507010000' 'ff02147e0000c03f' '00004bd5080f2a04' '01004bd5090f2a04') + + +def literal_program(s, t, face, form='lz'): + if form in ('lz', 'sample'): + return program([(0, s), (1, t), (2, float(face))], form) + if form == 'l': + return program([(0, s), (1, t), (2, float(face)), (3, 0.0)], form) + return program([(0, 0.0), (1, s), (2, t), (3, float(face))], form) # b: bias first + + +def chain_program(d): + return program([(4, d[0]), (5, d[1]), (6, d[2])], 'lz', CHAIN, CHAIN_SOURCE) + + +def desktop_ps(d): + return ('TextureCube r0 : register(t0);\nSamplerState q0 : register(s0);\n' + 'float4 main() : SV_Target { return r0.SampleLevel(q0, float3(%r, %r, %r), 0); }\n' % d) + + +def translate(words): + return G.Pipeline(VS_WORDS, words, root_blob()) + + +def expect_refused(call, needle): + try: + call() + except G.Unsupported as error: + assert needle in str(error), (needle, str(error)) + return str(error) + raise AssertionError('accepted, expected refusal containing %r' % needle) + + +def bare_image(how, mods, kind='ps'): + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + return lambda: stage.image(['v[0:3]', 'v[0:2]', 's[16:23]', 's[24:27]'], mods, how) + + +def model_controls(): + values = {texel(x, y, f) for f in range(6) for y in range(2) for x in range(2)} + assert len(values) == 24, len(values) + for s, t, face in CASES: + # The helper rebuilds a direction that a D3D lookup maps back to the address texel. + assert cube_lookup(helper_dir(ROWS, s, t, face)) == address_texel(s, t, face), (s, t, face) + assert {f for s, t, f in CASES if address_texel(s, t, f)[0] != address_texel(s, t, f)[1]} == set(range(6)) + for d in DIRECTIONS: + x, y, face = cube_lookup(d) + assert x != y, d + assert sorted(cube_lookup(d)[2] for d in DIRECTIONS) == list(range(6)) + for label, _, rows in mutants(): + assert any(cube_lookup(helper_dir(rows, s, t, f)) != address_texel(s, t, f) for s, t, f in CASES), label + print('model: 24 distinct texels; helper rows invert a D3D lookup on %d cases; %d mutants each change a case' + % (len(CASES), len(mutants()))) + + +def controls(): + model_controls() + words, _ = literal_program(1.75, 1.25, 1) + pipe = translate(words) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + assert 'TextureCube r0 : register(t0);' in ps and 'Texture2DArray' not in ps, ps + assert 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), 0)' in ps, ps + for face, row in enumerate(ROWS): + assert row_line(face, row) in ps, (face, ps) + assert ps.count('float3 x2w_cube_dir(') == 1, ps + assert 'srv 0 texcube table 0 0' in manifest.splitlines(), manifest + for form, call in (('sample', 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))'), + ('l', 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))'), + ('b', 'r0.SampleBias(q0, x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))')): + ps = translate(literal_program(1.75, 1.25, 1, form)[0]).hlsl_ps() + assert call in ps, (form, ps) + # Other dimensions keep their declarations and calls. + from startup_image_2d_array_check import SAMPLE_WORDS, SAMPLE_CALL # noqa: E402 + ps = translate(SAMPLE_WORDS).hlsl_ps() + assert SAMPLE_CALL in ps and 'x2w_cube_dir' not in ps and 'TextureCube' not in ps, ps + print('translation: TextureCube r0 with x2w_cube_dir for sample, lz, l and b; manifest srv 0 texcube') + refusals = [ + (bare_image('load', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('load_mip', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image dimension SQ_RSRC_IMG_CUBE: Load'), + (bare_image('d', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf']), 'image_sample_d on SQ_RSRC_IMG_CUBE'), + (bare_image('get_lod', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0x3']), 'image_get_lod on SQ_RSRC_IMG_CUBE'), + (bare_image('lz', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'a16']), 'image_sample_lz on SQ_RSRC_IMG_CUBE with a16'), + (bare_image('sample', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf', 'd16']), + 'image_sample on SQ_RSRC_IMG_CUBE with d16'), + (bare_image('l', ['dim:SQ_RSRC_IMG_CUBE', 'dmask:0xf'], kind='cs'), 'cube image in a compute program'), + ] + for call, needle in refusals: + expect_refused(call, needle) + # A constant sampler with DISABLE_CUBE_WRAP (word 0 bit 28) is refused; the bit clear is accepted above. + wrap = bytes.fromhex('ff0398be00000010') + words = literal_program(1.75, 1.25, 1)[0].replace(bytes.fromhex('800398be'), wrap, 1) + expect_refused(lambda: translate(words), 'DISABLE_CUBE_WRAP') + print('refused: cube load and load_mip, sample_d, get_lod, a16, d16, compute, DISABLE_CUBE_WRAP') + + +def check_binary(llvm_mc): + fixtures = [('literal %s' % (case,), *reversed(literal_program(*case))) for case in CASES] + fixtures += [('%s' % form, *reversed(literal_program(1.75, 1.25, 1, form))) for form in ('sample', 'l', 'b')] + fixtures += [('chain %s' % (d,), *reversed(chain_program(d))) for d in DIRECTIONS] + for name, source, words in fixtures: + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) + print('fixture words match llvm-mc (%d programs)' % len(fixtures)) + + +def check_draw(dxc, renderer, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + count = [0, 0] # reference draws that matched, controls and mutants that failed as predicted + + def draw(shader, expected, label, fail_reads=None, sampler=None): + run = subprocess.run([renderer, adapter, '--startup-image-cube', str(vs), str(shader), '0', expected] + + ([sampler] if sampler else []), capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if not any(count): + for line in run.stdout.splitlines(): + if line.startswith(('backend=', 'adapter=', 'driver=')): + print(line) + if 'debug_layer=enabled' in run.stdout: + assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) + if fail_reads is None: + if run.returncode: + raise AssertionError('%s\n%s\n%s' % (label, run.stdout, run.stderr)) + print('%s: %s' % (label, expected), flush=True) + count[0] += 1 + else: + if run.returncode == 0 or 'actual=%s' % fail_reads not in run.stderr: + raise AssertionError('%s: control did not read %s\n%s\n%s' + % (label, fail_reads, run.stdout, run.stderr)) + print('%s: fails as expected, reads %s' % (label, fail_reads), flush=True) + count[1] += 1 + + def build(words, name): + return compile_hlsl(dxc, 'dxc', translate(words).hlsl_ps(), name, 'ps_6_0', directory) + + def sampler_line(words): + lines = [line for line in translate(words).manifest().splitlines() if line.startswith(('smp ', 'smpl '))] + assert len(lines) == 1, lines + return lines[0] + + for i, (s, t, face) in enumerate(CASES): + draw(build(literal_program(s, t, face)[0], 'lit%d' % i), texel(*address_texel(s, t, face)), + 'image_sample_lz s=%g t=%g face=%d' % (s, t, face)) + case = (1.75, 1.25, 1) + for form in ('sample', 'l', 'b'): + words = literal_program(*case, form)[0] + draw(build(words, 'form_%s' % form), texel(*address_texel(*case)), + 'image_sample%s s=%g t=%g face=%d' % ('' if form == 'sample' else '_' + form, *case), + sampler=sampler_line(words)) + # Guest-input controls: the face one higher and s, t exchanged must read those texels. + s, t, face = case + draw(build(literal_program(s, t, face + 1)[0], 'face_plus'), texel(*address_texel(*case)), + 'control face + 1', texel(*address_texel(s, t, face + 1))) + draw(build(literal_program(t, s, face)[0], 'swap_st'), texel(*address_texel(*case)), + 'control s and t exchanged', texel(*address_texel(t, s, face))) + # l and b with the face in the slot the translator reads as LOD or bias: another texel. + draw(build(program([(0, s), (1, t), (2, 0.0), (3, float(face))], 'l')[0], 'l_swapped'), + texel(*address_texel(*case)), 'control image_sample_l face and lod exchanged', + texel(*address_texel(s, t, 0))) + words = program([(0, float(face)), (1, s), (2, t), (3, 0.0)], 'b')[0] + draw(build(words, 'b_swapped'), texel(*address_texel(*case)), 'control image_sample_b face and bias exchanged', + texel(*address_texel(s, t, 0)), sampler=sampler_line(words)) + # Translator mutants: each edits one helper row and must read the texel a D3D lookup of its direction gives. + for index, (label, edits, rows) in enumerate(mutants()): + hit = next((c for c in CASES if cube_lookup(helper_dir(rows, *c)) != address_texel(*c))) + source = translate(literal_program(*hit)[0]).hlsl_ps() + mutated = source + for old, new in edits: + assert mutated.count(old) == 1, (label, old) + mutated = mutated.replace(old, new) + assert mutated != source, label + shader = compile_hlsl(dxc, 'dxc', mutated, 'mutant%d' % index, 'ps_6_0', directory) + draw(shader, texel(*address_texel(*hit)), 'mutant %s (case %s)' % (label, hit), + texel(*cube_lookup(helper_dir(rows, *hit)))) + # End to end: the v_cube chain on six directions, against the reference and a desktop TextureCube draw. + for i, d in enumerate(DIRECTIONS): + expected = texel(*cube_lookup(d)) + draw(build(chain_program(d)[0], 'chain%d' % i), expected, 'v_cube chain d=%s' % (d,)) + native = compile_hlsl(dxc, 'dxc', desktop_ps(d), 'native%d' % i, 'ps_6_0', directory) + draw(native, expected, 'desktop TextureCube d=%s' % (d,)) + print('%d cube draws matched their references; %d controls and mutants read the texel they predict' + % tuple(count)) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(args[0]) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 552a3aa7c1..3e53aca3ec 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -528,7 +528,9 @@ def controls(): refused('c_b', 'image_sample_c_b') refused('offset', 'image_sample_b_o') refused('gather', 'image_gather4_b') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube; the bias dword comes before the face address. + cube = stage('cube').hlsl_ps() + assert 'TextureCube' in cube and 'SampleBias(' in cube and 'x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))' in cube, cube refused('msaa', 'image dimension SQ_RSRC_IMG_') refused('dim1d', 'unverified 1D image b address or modifiers') refused('unorm', 'image_sample_b modifier unorm') @@ -542,7 +544,8 @@ def controls(): refused(name, 'image_sample_b modifier reserved') refused('sampler bias', 'image_sample_b with a sampler LOD bias (word 2 0x4000001)') refused('sampler bias sec', 'image_sample_b with a sampler LOD bias (word 2 0x4004000)') - print('refused: b_cl, c_b, offset, gather4_b, cube, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' + print('cube: TextureCube SampleBias with x2w_cube_dir') + print('refused: b_cl, c_b, offset, gather4_b, MSAA, 1D, a16, d16, tfe, lwe, unorm, r128, dmask 0, ' 'reserved bits, sampler LOD bias') # Guest sampler limits: carried over for a constant descriptor, refused where they cannot be shown irrelevant. diff --git a/tests/startup_image_sample_l_check.py b/tests/startup_image_sample_l_check.py index 72d4a0fffa..c5b83c2fa5 100644 --- a/tests/startup_image_sample_l_check.py +++ b/tests/startup_image_sample_l_check.py @@ -243,7 +243,9 @@ def controls(): refused('offset', 'image_sample_l_o') refused('compare', 'image_sample_c_l') refused('gather', 'image_gather4_l') - refused('cube', 'image dimension SQ_RSRC_IMG_CUBE') + # Since #2943 a cube lowers to TextureCube with the face address rebuilt as a direction, level after it. + cube = stage('cube') + assert 'TextureCube' in cube and 'x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))' in cube, cube refused('unorm', 'image_sample_l modifier unorm') refused('tfe', 'image_sample_l modifier tfe') # the extra status register is not modelled refused('a16', 'image_sample_l modifier a16') # packed 16-bit address: v[0:1] holds u, v and the level as halves @@ -259,7 +261,8 @@ def controls(): refused('msaa', 'image dimension SQ_RSRC_IMG_') for name in RESERVED: refused(name, 'image_sample_l modifier reserved') # bits LLVM ignores must not be silently accepted - print('refused: offset, compare, gather, cube, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') + print('cube: TextureCube SampleLevel with x2w_cube_dir') + print('refused: offset, compare, gather, MSAA, unorm, a16, tfe, lwe, d16, r128, dmask 0, reserved bits') # Cache-policy bits do not change the sampled value: same lowering as the plain form. for name in ('glc', 'slc', 'dlc'): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 489148b039..9ebd7a874c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7120,13 +7120,33 @@ def image(self, ops, mods, how): raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) dim = dims[0][4:] dmask = int(dmasks[0][6:], 0) - kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} + kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da', + 'SQ_RSRC_IMG_CUBE': 'texcube'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) + # A cube sample addresses the face coordinates s and t and then the face id (#2943). The face coordinates + # are sc/|ma| + 1.5 and tc/|ma| + 1.5 with ma the v_cubema value, twice the major coordinate (Mesa + # ac_nir_lower_tex.c prepare_cube_coords; LLVM ConstantFoldAMDGCNCubeIntrinsic), so both lie in [1, 2]. + # The lowering rebuilds a direction for TextureCube (x2w_cube_dir). Loads, derivative and LOD queries, + # packed addresses and compute stages have no TextureCube equivalent here and are refused by name. + cube = dim == 'SQ_RSRC_IMG_CUBE' + if cube: + if how in ('load', 'load_mip'): + raise Unsupported('image dimension SQ_RSRC_IMG_CUBE: Load is not defined on a TextureCube') + if how == 'd': + raise Unsupported('image_sample_d on SQ_RSRC_IMG_CUBE: cube derivatives are not converted') + if how == 'get_lod': + raise Unsupported('image_get_lod on SQ_RSRC_IMG_CUBE') + for flag in ('a16', 'd16'): + if flag in mods: + raise Unsupported('image_sample%s on SQ_RSRC_IMG_CUBE with %s' + % ('' if how == 'sample' else '_' + how, flag)) + if getattr(self, 'kind', None) == 'cs': + raise Unsupported('cube image in a compute program (no texcube SRV binding)') # A 2D array takes the slice as its third address component, where a volume takes z. Sample and # Load on a Texture2DArray take it in the same place, so only the declared type differs. one = dim == 'SQ_RSRC_IMG_1D' - three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY') + three = dim in ('SQ_RSRC_IMG_3D', 'SQ_RSRC_IMG_2D_ARRAY', 'SQ_RSRC_IMG_CUBE') coords = ops[1] if coords.startswith('['): cs = [c.strip() for c in coords[1:-1].split(',')] @@ -7268,6 +7288,11 @@ def image(self, ops, mods, how): heap = self.heap_sampler(ops[3]) words = None if heap else self.const_words(ops[3]) name = 'image_sample' + ('' if how == 'sample' else '_' + how) + if cube and words and (words[0] >> 28) & 1: + # SQ_IMG_SAMP_WORD0 bit 28 DISABLE_CUBE_WRAP (Mesa src/amd/registers/gfx10-rsrc.json): filtering then + # stops at a face edge, while a D3D12 TextureCube always filters across faces. With the bit clear both + # wrap across faces. A heap or register sampler is not read here, so its bit is not validated. + raise Unsupported('%s on SQ_RSRC_IMG_CUBE with DISABLE_CUBE_WRAP' % name) if how == 'b': # The guest clamps the biased LOD to the sampler's MIN_LOD and MAX_LOD. Only a constant descriptor # can be read here, and only its limits are carried to the static sampler (line smpl), so a sampler @@ -7298,6 +7323,9 @@ def image(self, ops, mods, how): uv = 'float2(f16tof32(%s), f16tof32(%s >> 16))' % (packed, packed) elif one: uv = self.f(cs[0]) + elif cube: + self.pipe.uses_cube_dir = True + uv = 'x2w_cube_dir(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) elif three: uv = 'float3(%s, %s, %s)' % (self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) else: @@ -10170,6 +10198,7 @@ def read(fmt, data, offset): class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False + uses_cube_dir = False uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () @@ -10208,6 +10237,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_pack16_rne = False + self.uses_cube_dir = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() @@ -10428,7 +10458,7 @@ def common(self): 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D', 'texcube': 'TextureCube'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -10437,6 +10467,26 @@ def common(self): out.append('SamplerState qh[%d] : register(s0, space%d);' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE)) out.append('uint x2w_sampler_entry(uint offset) { return (offset & 15u) != 0 || offset >= %du ? %du : offset >> 4; }' % (16 * SAMPLER_HEAP_FALLBACK, SAMPLER_HEAP_FALLBACK)) + if self.uses_cube_dir: + # A direction for TextureCube from a gfx10 cube address (#2943): s and t are the face coordinates + # sc/|ma| + 1.5 and tc/|ma| + 1.5 and f the face id, with the per-face sc and tc of v_cubesc and + # v_cubetc (cube() above). A major component of +-1 reproduces u = sc/|major| and v = tc/|major|. + # A cube-array id (8 * layer + face) keeps only its face, so layer 0 is sampled; faces 6 and 7, a + # negative or NaN id become faces 5 and 0. Coordinates outside the face are clamped to its edges. + out.extend(( + 'float3 x2w_cube_dir(float s, float t, float f) {', + ' float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);', + ' float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);', + ' int k = (f >= 0.0 && f < 2147483648.0) ? ((int)f & 7) : 0;', + ' k = min(k, 5);', + ' if (k == 0) return float3(1.0, -v, -u);', + ' if (k == 1) return float3(-1.0, -v, u);', + ' if (k == 2) return float3(u, 1.0, v);', + ' if (k == 3) return float3(u, -1.0, -v);', + ' if (k == 4) return float3(u, -v, 1.0);', + ' return float3(-u, -v, -1.0);', + '}', + )) if self.uses_pack16_rne: # IEEE binary32 to binary16 round-to-nearest-even (quieting NaN while preserving its sign, # matching RDNA 2 hardware on binary32 inputs), plus exact UNORM16 ratio-to-half conversion From f7da3f69542e87cc54e9123a0a0e7a21e1dc6107 Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:39:50 +0100 Subject: [PATCH 2/3] docs: note #2938 runtime cube binding landed on main AI-assisted. --- docs/experiments/startup-image-cube.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/experiments/startup-image-cube.md b/docs/experiments/startup-image-cube.md index 6a9f18d103..52fa6c147f 100644 --- a/docs/experiments/startup-image-cube.md +++ b/docs/experiments/startup-image-cube.md @@ -42,8 +42,7 @@ The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a directi - Heap and register samplers are not read at translation, so their `DISABLE_CUBE_WRAP` bit is not validated (a set bit would filter differently at face edges), and their LOD range stays unvalidated as for 2D textures. - Only pixel-stage draws are measured; the vertex-stage form is translated but not drawn. -- The runtime binding of a `texcube` view is PR #2938. Without it the main runtime parses `texcube` as an unknown - kind and would bind the slot as a buffer, so this lowering must not be merged before #2938. +- The runtime binding of a `texcube` view landed in PR #2938 (`7fcde81f`). ## Fixture From dda0ca83145d28afe9509288b3698f780665be46 Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:08:12 +0100 Subject: [PATCH 3/3] tests: test cube coordinate scale factor with 4x4 faces (#2943) Switch --startup-image-cube to six 4x4 faces (96 distinct texels) with outer-ring texel centers so dropping the 2.0 * scale on u or v shifts texels on both WARP and hardware, add scale-2 translator mutants and controls, and clarify that clamping outside [1, 2] is an untested assumption. AI-assisted. --- docs/experiments/startup-image-cube.md | 31 +++++----- tests/offscreen_check.cpp | 4 +- tests/startup_image_3d.cpp | 9 +-- tests/startup_image_cube_check.py | 79 ++++++++++++++------------ tools/startup/gfx2hlsl.py | 3 +- 5 files changed, 70 insertions(+), 56 deletions(-) diff --git a/docs/experiments/startup-image-cube.md b/docs/experiments/startup-image-cube.md index 52fa6c147f..a4f6b9d85d 100644 --- a/docs/experiments/startup-image-cube.md +++ b/docs/experiments/startup-image-cube.md @@ -35,8 +35,9 @@ The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a directi - A cube-array view is not recognisable from the instruction (gfx10 MIMG has no array bit; the descriptor sets the dimension). The helper keeps the face bits of the id (`id & 7`) and samples layer 0 of a `TextureCube`, which is wrong for a later layer of a cube array. -- A face id of 6 or 7 maps to face 5, a negative, NaN or huge id to face 0, and `s` or `t` outside [1, 2] are - clamped to the face edge. Mesa does not produce these for a finite non-zero direction; none of them is measured. +- A face id of 6 or 7 maps to face 5, a negative, NaN or huge id to face 0, and `s` or `t` outside `[1, 2]` are + assumed to clamp to `[-1, 1]` on the face edge. Mesa does not produce these for a finite non-zero direction; + clamping outside `[1, 2]` is not tested and none of these out-of-range inputs is measured. - The implicit-LOD and bias forms take the desktop derivatives of the rebuilt direction. Inside one face these follow the guest's face coordinates; a quad that straddles a face edge can choose another level. - Heap and register samplers are not read at translation, so their `DISABLE_CUBE_WRAP` bit is not validated (a set @@ -47,28 +48,30 @@ The translator emits a helper `x2w_cube_dir(s, t, face)` that rebuilds a directi ## Fixture `tests/startup_image_cube_check.py` (controls, `binary `, `draw `). -`offscreen_check --startup-image-cube` binds six 2x2 R32G32B32A32_FLOAT faces as a TextureCube whose texel (x, y) -of face f holds ((1 + x + 2y + 4f) / 32, x, y, f). The sampler is the all-zero inline sampler (point, wrap), and -every `s` and `t` is a texel centre. +`offscreen_check --startup-image-cube` binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube whose texel (x, y) +of face f holds ((1 + x + 4y + 16f) / 128, x, y, f). The sampler is the all-zero inline sampler (point, wrap), and +every `s` and `t` is a texel centre (in `{1.125, 1.375, 1.625, 1.875}`). -- Seven programs set `(s, t, face)` as constants, without `v_cube*`, so the reference is only the address meaning - (texel x = 0 below `s = 1.5`, else 1, the same for `t`). The desktop driver picks the face of the rebuilt - direction itself, so a wrong face, sign or axis in the helper reads another texel. Every face has a case whose - texel has x != y. +- Seven programs set `(s, t, face)` as constants (`1.125` or `1.875`), without `v_cube*`, so the reference is only the + address meaning (`x = floor(4 * (s - 1))`, `y = floor(4 * (t - 1))`). The desktop driver picks the face of the + rebuilt direction itself, so a wrong face, sign, axis or `2.0 * (s - 1.5)` / `2.0 * (t - 1.5)` scale in the helper + reads another texel. Every face has a case whose texel has x != y. - `image_sample`, `image_sample_l` and `image_sample_b` each draw one case. - Controls: the face one higher and `s`, `t` exchanged must read those texels; `image_sample_l` and `image_sample_b` with the face in the LOD or bias dword must read face 0. -- Thirteen translator mutants edit the emitted helper (for each face the sign of the `u` term flipped, `u` and `v` - exchanged, and faces 2 and 3 exchanged). Each must read the texel a D3D cube lookup of its direction gives. +- Fifteen translator mutants edit the emitted helper (for each face the sign of the `u` term flipped, `u` and `v` + exchanged, faces 2 and 3 exchanged, and dropping the `2.0 *` scale on `u` or `v`). Each must read the texel a D3D + cube lookup of its direction gives. - Six programs run the `v_cube` chain (`v_cubema`, `v_cubesc`, `v_cubetc`, `v_cubeid`, `v_rcp_f32` of `|ma|` and `v_fma_f32` with 1.5) on one direction per face. Each must match the face texel LLVM's table gives and a desktop pixel shader that samples the same direction from the TextureCube. -Measured on 27.11.2026, commit 6ee878d8 plus this change, Windows 11 24H2 (10.0.26100.9711), debug layer +Measured on 28.11.2026, commit f7da3f69 plus this change, Windows 11 24H2 (10.0.26100.9711), debug layer unavailable on both adapters: the 22 reference draws (7 literal, 3 forms, 6 chain, 6 desktop TextureCube) matched on NVIDIA Quadro M1000M (driver 32.0.15.7371) and on WARP (Microsoft Basic Render Driver 10.0.26100.9711), and all -17 controls and mutants read the texel they predict. With the translator change reverted, the controls fail on -`image dimension SQ_RSRC_IMG_CUBE`. +19 controls and mutants read the texel they predict (`dev` and `release` `/O2`). With the translator change reverted, +the controls fail on `image dimension SQ_RSRC_IMG_CUBE`, and dropping the `2.0 *` scale on `u` fails both +`startup_image_cube_controls` and `startup_image_cube_warp`. The 16 fixture programs reassemble to the recorded words with LLVM 15.0.7. ```powershell diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 9f8d62a948..4520b6bd55 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1329,8 +1329,8 @@ OperationResult run_startup_sampler_heap(const OperationContext& ctx) // The expected value is four comma-separated hex words. Omit the sampler line for point wrap. // --startup-image-2d-array takes the same arguments: the texels are two slices of a 2D array and the // third coordinate is the slice. --startup-image-2d-array-mips uses a 4x4 array of two slices with three -// mip levels whose cells all differ (tests/startup_image_3d.cpp). --startup-image-cube binds six 2x2 faces as a -// TextureCube whose 24 texels all differ (#2943); z is passed through as for the other modes. +// mip levels whose cells all differ (tests/startup_image_3d.cpp). --startup-image-cube binds six 4x4 faces as a +// TextureCube whose 96 texels all differ (#2943); z is passed through as for the other modes. OperationResult run_startup_image_3d(const OperationContext& ctx) { const bool array_mips = std::strcmp(ctx.argv[2], "--startup-image-2d-array-mips") == 0; diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 85697afda7..be18b7e5b7 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -27,8 +27,9 @@ namespace { constexpr UINT entry_constants = 4; // ud0..ud3 of the fixture's manifest constexpr UINT side = 2; constexpr UINT max_levels = 3; -// A cube fixture: six 2x2 faces, one level (dim:SQ_RSRC_IMG_CUBE, #2943). +// A cube fixture: six 4x4 faces, one level (dim:SQ_RSRC_IMG_CUBE, #2943). constexpr UINT cube_faces = 6; +constexpr UINT cube_side = 4; // The value at texel (x, y) of slice s and mip level m. One level keeps the 2x2x2 fixture's values. With // several levels every (slice, mip, x, y) cell is distinct: the red channel is a dyadic fraction and @@ -78,7 +79,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const throw std::runtime_error("Unsupported image mip level count"); if (view_levels && ((!two_dimensional && !array) || first_mip >= levels || view_levels > levels - first_mip)) throw std::runtime_error("2D mip window exceeds the resource"); - const UINT base = levels > 1 ? mip_base : side; + const UINT base = cube ? cube_side : (levels > 1 ? mip_base : side); const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); x2w_startup::TranslatedSamplers samplers; @@ -153,8 +154,8 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const texel_value(tx, ty, tz, level, levels, base, texel); if (one_dimensional) texel[3] = tx ? 0.75f : 0.5f; if (cube) { - // Every one of the 24 texels differs: face f, column tx and row ty. - const float face[4] = {(1.0f + tx + 2.0f * ty + 4.0f * tz) / 32.0f, float(tx), float(ty), float(tz)}; + // Every one of the 96 texels differs: face f, column tx and row ty. + const float face[4] = {(1.0f + tx + 4.0f * ty + 16.0f * tz) / 128.0f, float(tx), float(ty), float(tz)}; std::memcpy(texel, face, sizeof(face)); } auto* const slice = (array || cube) ? start + place.Offset : start + place.Offset + tz * slice_pitch; diff --git a/tests/startup_image_cube_check.py b/tests/startup_image_cube_check.py index b2f864eca7..b507e313a3 100644 --- a/tests/startup_image_cube_check.py +++ b/tests/startup_image_cube_check.py @@ -11,16 +11,17 @@ t lie in [1, 2] and s - 1, t - 1 are the position on the face. The translator rebuilds a direction from (s, t, face) for TextureCube (x2w_cube_dir in the HLSL). -tests/startup_image_3d.cpp, run as --startup-image-cube, binds six 2x2 R32G32B32A32_FLOAT faces as a TextureCube -whose texel (x, y) of face f holds ((1 + x + 2y + 4f) / 32, x, y, f), so all 24 texels differ. The sampler is the -all-zero inline sampler (point, wrap); every (s, t) is a texel centre, 1.25 or 1.75. +tests/startup_image_3d.cpp, run as --startup-image-cube, binds six 4x4 R32G32B32A32_FLOAT faces as a TextureCube +whose texel (x, y) of face f holds ((1 + x + 4y + 16f) / 128, x, y, f), so all 96 texels differ. The sampler is the +all-zero inline sampler (point, wrap); every (s, t) is a texel centre (in {1.125, 1.375, 1.625, 1.875}). What the draws show: the literal cases feed (s, t, face) directly, without v_cube, and the reference is only the -address meaning above (texel x = 0 below s = 1.5, else 1; the same for t and y). The desktop driver selects the -face of the rebuilt direction itself, so a wrong face, sign or axis in x2w_cube_dir reads another texel. The -mutants edit one row of the emitted helper (sign of the u term flipped, u and v exchanged, faces 2 and 3 -exchanged) and must read the texel a D3D cube lookup of the mutated direction gives. The end-to-end cases run the -v_cube chain on six directions and must equal both that reference and a desktop PS that samples the direction. +address meaning above (x = floor(4 * (s - 1)), y = floor(4 * (t - 1))). The desktop driver selects the +face of the rebuilt direction itself, so a wrong face, sign, axis or 2.0 * (s - 1.5) / 2.0 * (t - 1.5) scale in +x2w_cube_dir reads another texel. The mutants edit one row of the emitted helper (sign of the u term flipped, u and v +exchanged, faces 2 and 3 exchanged, and dropping the 2.0 * scale on u or v) and must read the texel a D3D cube +lookup of the mutated direction gives. The end-to-end cases run the v_cube chain on six directions and must equal +both that reference and a desktop PS that samples the direction. They do not show that the console's face order and orientation equal D3D's: that rests on LLVM's cube table being the D3D11.3 cube face table. Only one mip is bound, so LOD and bias values are not tested; the image_sample_l and image_sample_b draws only show that the extra address dword is not taken as a coordinate. @@ -99,12 +100,12 @@ def program(moves, form='lz', middle=b'', middle_source=''): def texel(x, y, face): - return ','.join('%08x' % bits(c) for c in ((1 + x + 2 * y + 4 * face) / 32, x, y, face)) + return ','.join('%08x' % bits(c) for c in ((1 + x + 4 * y + 16 * face) / 128, x, y, face)) def address_texel(s, t, face): - """The AMD cube address meaning: face-local position s - 1 and t - 1 on a 2x2 face.""" - return (0 if s < 1.5 else 1, 0 if t < 1.5 else 1, face) + """The AMD cube address meaning: face-local position s - 1 and t - 1 on a 4x4 face.""" + return (min(3, max(0, int((s - 1.0) * 4))), min(3, max(0, int((t - 1.0) * 4))), face) # The per-face (sc, tc) of v_cubesc and v_cubetc (LLVM ConstantFoldAMDGCNCubeIntrinsic), used here to model a D3D @@ -132,8 +133,8 @@ def row_line(face, row): return body if face == 5 else 'if (k == %d) %s' % (face, body) -def helper_dir(rows, s, t, face): - u, v = 2 * (s - 1.5), 2 * (t - 1.5) +def helper_dir(rows, s, t, face, su=2.0, sv=2.0): + u, v = su * (s - 1.5), sv * (t - 1.5) return tuple(eval(c, {}, {'u': u, 'v': v}) for c in rows[face]) # noqa: S307 (fixed expressions above) @@ -146,26 +147,31 @@ def swap_uv(row): def mutants(): - """(label, edits [(old line, new line)], mutated rows).""" + """(label, edits [(old line, new line)], mutated rows, (su, sv)).""" out = [] for face in range(6): for label, change in (('u sign flipped', flip_u), ('u and v exchanged', swap_uv)): rows = list(ROWS) rows[face] = change(ROWS[face]) - out.append(('face %d %s' % (face, label), [(row_line(face, ROWS[face]), row_line(face, rows[face]))], rows)) + out.append(('face %d %s' % (face, label), [(row_line(face, ROWS[face]), row_line(face, rows[face]))], + rows, (2.0, 2.0))) rows = list(ROWS) rows[2], rows[3] = ROWS[3], ROWS[2] out.append(('faces 2 and 3 exchanged', [(row_line(2, ROWS[2]), row_line(2, ROWS[3])), - (row_line(3, ROWS[3]), row_line(3, ROWS[2]))], rows)) + (row_line(3, ROWS[3]), row_line(3, ROWS[2]))], rows, (2.0, 2.0))) + out.append(('u scale 2 dropped', [('clamp(2.0 * (s - 1.5), -1.0, 1.0)', 'clamp((s - 1.5), -1.0, 1.0)')], + ROWS, (1.0, 2.0))) + out.append(('v scale 2 dropped', [('clamp(2.0 * (t - 1.5), -1.0, 1.0)', 'clamp((t - 1.5), -1.0, 1.0)')], + ROWS, (2.0, 1.0))) return out -# Literal (s, t, face) cases: every face has one whose texel has x != y. -CASES = [(1.25, 1.75, 0), (1.75, 1.25, 1), (1.25, 1.75, 2), (1.75, 1.25, 3), (1.75, 1.25, 4), (1.25, 1.75, 5), - (1.75, 1.75, 2)] -# End-to-end directions, one per face, each on a texel with x != y. -DIRECTIONS = [(1.0, -0.5, 0.5), (-1.0, -0.5, -0.5), (0.5, 1.0, -0.5), (0.5, -1.0, 0.5), (0.5, 0.5, 1.0), - (-0.5, 0.5, -1.0)] +# Literal (s, t, face) cases: outer-ring 4x4 texel centres so every face has x != y and dropping scale 2 moves texels. +CASES = [(1.125, 1.875, 0), (1.875, 1.125, 1), (1.125, 1.875, 2), (1.875, 1.125, 3), (1.875, 1.125, 4), (1.125, 1.875, 5), + (1.875, 1.875, 2)] +# End-to-end directions, one per face, each on a 4x4 texel centre with x != y. +DIRECTIONS = [(1.0, -0.75, 0.25), (-1.0, -0.75, -0.25), (0.75, 1.0, -0.25), (0.75, -1.0, 0.25), (0.75, 0.25, 1.0), + (-0.75, 0.25, -1.0)] CHAIN_SOURCE = """\ v_cubema_f32 v7, v4, v5, v6 v_cubesc_f32 v8, v4, v5, v6 @@ -217,8 +223,8 @@ def bare_image(how, mods, kind='ps'): def model_controls(): - values = {texel(x, y, f) for f in range(6) for y in range(2) for x in range(2)} - assert len(values) == 24, len(values) + values = {texel(x, y, f) for f in range(6) for y in range(4) for x in range(4)} + assert len(values) == 96, len(values) for s, t, face in CASES: # The helper rebuilds a direction that a D3D lookup maps back to the address texel. assert cube_lookup(helper_dir(ROWS, s, t, face)) == address_texel(s, t, face), (s, t, face) @@ -227,19 +233,22 @@ def model_controls(): x, y, face = cube_lookup(d) assert x != y, d assert sorted(cube_lookup(d)[2] for d in DIRECTIONS) == list(range(6)) - for label, _, rows in mutants(): - assert any(cube_lookup(helper_dir(rows, s, t, f)) != address_texel(s, t, f) for s, t, f in CASES), label - print('model: 24 distinct texels; helper rows invert a D3D lookup on %d cases; %d mutants each change a case' + for label, _, rows, scale in mutants(): + assert any(cube_lookup(helper_dir(rows, s, t, f, *scale)) != address_texel(s, t, f) + for s, t, f in CASES), label + print('model: 96 distinct texels; helper rows invert a D3D lookup on %d cases; %d mutants each change a case' % (len(CASES), len(mutants()))) def controls(): model_controls() - words, _ = literal_program(1.75, 1.25, 1) + words, _ = literal_program(1.875, 1.125, 1) pipe = translate(words) ps, manifest = pipe.hlsl_ps(), pipe.manifest() assert 'TextureCube r0 : register(t0);' in ps and 'Texture2DArray' not in ps, ps assert 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), 0)' in ps, ps + assert 'float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);' in ps, ps + assert 'float v = clamp(2.0 * (t - 1.5), -1.0, 1.0);' in ps, ps for face, row in enumerate(ROWS): assert row_line(face, row) in ps, (face, ps) assert ps.count('float3 x2w_cube_dir(') == 1, ps @@ -247,7 +256,7 @@ def controls(): for form, call in (('sample', 'r0.Sample(q0, x2w_cube_dir(F(v0), F(v1), F(v2)))'), ('l', 'r0.SampleLevel(q0, x2w_cube_dir(F(v0), F(v1), F(v2)), F(v3))'), ('b', 'r0.SampleBias(q0, x2w_cube_dir(F(v1), F(v2), F(v3)), F(v0))')): - ps = translate(literal_program(1.75, 1.25, 1, form)[0]).hlsl_ps() + ps = translate(literal_program(1.875, 1.125, 1, form)[0]).hlsl_ps() assert call in ps, (form, ps) # Other dimensions keep their declarations and calls. from startup_image_2d_array_check import SAMPLE_WORDS, SAMPLE_CALL # noqa: E402 @@ -275,7 +284,7 @@ def controls(): def check_binary(llvm_mc): fixtures = [('literal %s' % (case,), *reversed(literal_program(*case))) for case in CASES] - fixtures += [('%s' % form, *reversed(literal_program(1.75, 1.25, 1, form))) for form in ('sample', 'l', 'b')] + fixtures += [('%s' % form, *reversed(literal_program(1.875, 1.125, 1, form))) for form in ('sample', 'l', 'b')] fixtures += [('chain %s' % (d,), *reversed(chain_program(d))) for d in DIRECTIONS] for name, source, words in fixtures: built = assemble(llvm_mc, source) @@ -325,7 +334,7 @@ def sampler_line(words): for i, (s, t, face) in enumerate(CASES): draw(build(literal_program(s, t, face)[0], 'lit%d' % i), texel(*address_texel(s, t, face)), 'image_sample_lz s=%g t=%g face=%d' % (s, t, face)) - case = (1.75, 1.25, 1) + case = (1.875, 1.125, 1) for form in ('sample', 'l', 'b'): words = literal_program(*case, form)[0] draw(build(words, 'form_%s' % form), texel(*address_texel(*case)), @@ -344,9 +353,9 @@ def sampler_line(words): words = program([(0, float(face)), (1, s), (2, t), (3, 0.0)], 'b')[0] draw(build(words, 'b_swapped'), texel(*address_texel(*case)), 'control image_sample_b face and bias exchanged', texel(*address_texel(s, t, 0)), sampler=sampler_line(words)) - # Translator mutants: each edits one helper row and must read the texel a D3D lookup of its direction gives. - for index, (label, edits, rows) in enumerate(mutants()): - hit = next((c for c in CASES if cube_lookup(helper_dir(rows, *c)) != address_texel(*c))) + # Translator mutants: each edits the emitted helper and must read the texel a D3D lookup of its direction gives. + for index, (label, edits, rows, scale) in enumerate(mutants()): + hit = next((c for c in CASES if cube_lookup(helper_dir(rows, *c, *scale)) != address_texel(*c))) source = translate(literal_program(*hit)[0]).hlsl_ps() mutated = source for old, new in edits: @@ -355,7 +364,7 @@ def sampler_line(words): assert mutated != source, label shader = compile_hlsl(dxc, 'dxc', mutated, 'mutant%d' % index, 'ps_6_0', directory) draw(shader, texel(*address_texel(*hit)), 'mutant %s (case %s)' % (label, hit), - texel(*cube_lookup(helper_dir(rows, *hit)))) + texel(*cube_lookup(helper_dir(rows, *hit, *scale)))) # End to end: the v_cube chain on six directions, against the reference and a desktop TextureCube draw. for i, d in enumerate(DIRECTIONS): expected = texel(*cube_lookup(d)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 655fbaefdb..3935d414d2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -11819,7 +11819,8 @@ def common(self): # sc/|ma| + 1.5 and tc/|ma| + 1.5 and f the face id, with the per-face sc and tc of v_cubesc and # v_cubetc (cube() above). A major component of +-1 reproduces u = sc/|major| and v = tc/|major|. # A cube-array id (8 * layer + face) keeps only its face, so layer 0 is sampled; faces 6 and 7, a - # negative or NaN id become faces 5 and 0. Coordinates outside the face are clamped to its edges. + # negative or NaN id become faces 5 and 0. Coordinates outside [1, 2] are assumed to clamp to face edges + # (untested outside [1, 2]). out.extend(( 'float3 x2w_cube_dir(float s, float t, float f) {', ' float u = clamp(2.0 * (s - 1.5), -1.0, 1.0);',