diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e37bf69c..252816910 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1916,6 +1916,38 @@ endforeach() get_filename_component(DXC_BIN_DIR "${DXC_EXECUTABLE}" DIRECTORY) if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + foreach(backend warp hardware) + add_test(NAME native_fixed_mesh57_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_mrt_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_mrt_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_varying_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_varying_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_TEST_NATIVE_MESH57_VARYING=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_uint_heap_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_uint_heap_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_UINT_HEAP=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_pixel_heap_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_pixel_heap_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_PIXEL_HEAP=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_waterfall_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_waterfall_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_WATERFALL=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_waterfall_fine_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_waterfall_fine_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_WATERFALL=1;X2W_TEST_NATIVE_MESH57_FINE_LOD=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_buffers_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_buffers_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_BUFFERS=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_constant_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_constant_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_CONSTANT=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + add_test(NAME native_fixed_mesh57_mask_${backend} COMMAND startup_indirect_draw_indexed ${backend} mesh) + set_tests_properties(native_fixed_mesh57_mask_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_TEST_NATIVE_MESH57=1;X2W_TEST_NATIVE_MESH57_MRT=1;X2W_TEST_NATIVE_MESH57_MASK=1;X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() add_executable(native_store_replay tests/native_store_replay.cpp tests/desktop_gpu.cpp) target_include_directories(native_store_replay PRIVATE src tests) target_link_libraries(native_store_replay PRIVATE x2w_shader_compiler d3d12 dxgi d3dcompiler) @@ -1974,7 +2006,7 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_native_graphics_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_native_graphics_draw_check.py" - "$" "$" "${DXC_BIN_DIR}" ${adapter}) + "$" "${DXC_BIN_DIR}" ${adapter} "$") set_tests_properties(startup_native_graphics_draw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() foreach(backend IN ITEMS hardware warp) @@ -2007,6 +2039,10 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ add_test(NAME native_compute_pack COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" "$" "$" "${DXC_BIN_DIR}") + add_test(NAME native_compute_pack_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_pack_check.py" hardware "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_pack_hardware PROPERTIES SKIP_RETURN_CODE 77) foreach(adapter IN ITEMS warp hardware) foreach(case IN ITEMS r rg rgb array volume rgba sparse) add_test(NAME native_image_store_exact_width_${adapter}_${case} diff --git a/docs/experiments.md b/docs/experiments.md index af43da338..ca3c14055 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -17959,6 +17959,8 @@ python -B tests/docs_links_check.py `startup_resource_retire_reasons` drives the `Held` attribution line; `startup_resource_retire_views` proves the design-B keep cases (a live slot stays reboundable after final `Release()` and completed fences). The tables above record contributors' local executable runs. The fixtures validate the retention behavior independently. Refs #2379, #2679, #2719, #1199. +See [fixed mesh pipelines through slot 57](experiments/native-fixed-mesh57.md) for the source-built indirect-draw fixtures. + ## Binary16 normalized integer conversions (`v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16`) across VOP1/VOP3/DPP16/DPP8/SDWA in pixel_aot [The pixel shader translator](../tools/pixel_aot.py) adds 10 exact binary16 normalized integer conversion forms across all 5 encodings (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md new file mode 100644 index 000000000..c0ef7cdae --- /dev/null +++ b/docs/experiments/native-fixed-mesh57.md @@ -0,0 +1,82 @@ +# Fixed mesh pipelines through device slot 57 + +The varying fixture sends two distinct values through PARAM12.xy to the pixel shader. With the six-attachment configuration the covered texel reads back as `0xffff00ff`. A mismatched fixed descriptor and a missing color attachment each preserve the clear color. Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_varying_(warp|hardware)$' -V` to reproduce. + +For an independently supplied raw pixel stage, `compile_dxil SDK CACHE gfx1013-raw-mesh-ps INPUT OUTPUT` reads a sibling `.pslayout` containing `meshps1 ENABLE ADDRESS WAVE_SIZE` as decimal integers. ENABLE and ADDRESS are the pixel input masks. WAVE_SIZE is 32 or 64. Append `guest_root` to load the corresponding serialized 1.1 root signature from the sibling `.root` file. A raw mesh producer using the same interface specifies `packed_parameters` in its `.mslayout`. Each PARAM occupies one signature register, following position at register zero. Channels with conflicting interpolation modes in one PARAM require a different layout. + +The source-built fixture creates a fixed pipeline with guest MS and PS instructions. The stand-in translates both to DXIL using its C++ shader library, creates a desktop mesh PSO and submits a guest command-list slot 61 indirect command. A GPU compute pass supplies the dispatch arguments. The tested interface uses an empty guest root, one to eight single-sample color attachments, explicit rasterizer, blend, depth and stencil state, and an MS with no resource bindings. The PS exports a constant to color target zero. + +From the x64 Windows build environment: + +```powershell +cmake --build --preset dev --target startup_indirect_draw_indexed +ctest --preset dev --no-tests=error --output-on-failure -R '^(native_fixed_mesh57(_mask|_mrt)?|startup_indirect_mesh_(request|cache))_(warp|hardware)$' +``` + +The three fixture variants use one color target, six color targets with depth/stencil, and the same six with a red-only target-zero write mask. The six-target formats are 29, 28, 28, 28, 34 and 28, with depth/stencil format 20. Back-face culling, counterclockwise front faces, greater-or-equal depth, depth writes and stencil replacement are enabled. The four-by-two GPU readback has a single covered texel at (2,0). It is white with all channels enabled or red with the narrower write mask. Depth/stencil at that texel changes from 0.25/3 to 0.5/7. The other color attachments retain their clear values. Changing a fixed descriptor word or removing a color attachment produces no color or depth/stencil change. + +The ten tests above passed on the working tree based on `671b9ac`, Windows build 26200, with the debug layer enabled on WARP and an NVIDIA GeForce RTX 4060 Laptop GPU (driver 32.0.16.1656). + +## Per-pixel texture selection + +The `native_fixed_mesh57_waterfall_{warp,hardware}` fixture draws a triangle covering eight pixels. The guest PS uses READFIRSTLANE, CMPX, an indexed descriptor load, IMAGE_SAMPLE and a WREXEC retry. Neighboring pixels select different Texture2D views. With a unit UV gradient the two views return red and green from mip 1. The `waterfall_fine` variant holds UV constant and both views return blue from mip 0. The shader computes quad derivatives before sampling the per-pixel texture. Both gradient cases passed on WARP and the RTX 4060 Laptop with the debug layer enabled. Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_(pixel_heap|waterfall(_fine)?)_(warp|hardware)$'` to reproduce. + +## Exact state records + +Set `X2W_SHADER_CACHE` to the request cache and `X2W_MESH57_CAPTURE_STATE=1` to retain the fixed creation state when a matching root consumes a mesh pipeline. A `req_.s57` file contains the little-endian 64-bit stage/root request key, three little-endian 32-bit lengths, and the corresponding byte spans for the normalized descriptor, register block A and register block B. The stand-in clears only the captured root and span pointer fields at DWORD-pair indices 0, 1, 3, 5 and 13. It preserves the lengths and other fields. The variant key extends the existing stage/root key with those three length-prefixed spans. Distinct fixed states can coexist for one stage pair. The fixture overwrites both blocks after creation and checks their archived bytes for accepted and refused variants. + +Native preparation reads a separately reviewed `.mesh57-state` profile from the cache. Its versioned Windows x64 header is defined by `Mesh57Profile` in `src/startup_stubs/mesh57_profile.h`. The header supplies the MS entry layout and desktop fixed-function state. The file ends with the exact descriptor, register blocks, serialized root and both guest programs. The stand-in compares every byte before building a PSO. The fixture authors this profile from its own known inputs. A captured register block alone does not establish the desktop rasterizer state or MS entry layout. + +The source-built `native_fixed_mesh57_constant_{warp,hardware}` tests exercise +one reviewed MS root-constant block with a deferred guest root. The version 3 +sidecar stores the physical SGPR, guest root index and DWORD count after the +pixel entry. Slot 61 packs all written words into desktop MS b0 after checking +the creation root and the compiler's binding metadata. Changing guest root 4 +(b5, space 2) changes the rendered green channel from 64 to 191 on the same +PSO. A missing word preserves the clear color. This profile supports one block +of up to eight words. + +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_buffers_'` +for the version 4 fixed mesh raw SRV fixture. One slot 61 command reads root +table 0 at byte 2848, root table 1 at bytes 32 and 96, a root 3 byte buffer +at offset 4, and the root 4 constant. Each contributes distinct bits to an +exported value. The expected RGBA at (2,0) is (255,62,255,255). A four-byte +view for an eight-byte span, a readable CPU address outside a GPU allocation, +and a missing root 4 word each preserve the clear color. Static tables share +immutable descriptor pages with other recorded commands on the same desktop +allocator; its queue fences govern page reuse. + +The version 5 mesh profile enables one directly indexed R32_UINT buffer read +alongside the static bindings. The compiler supplies the root word and mask. +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_uint_heap_'`. +The fixture uses two different first elements in one GPU buffer. Selectors +147 and 151 yield RGBA (64,62,64,64) and (191,62,191,191). Replacing view +147 with the second view yields the latter color; shortening the view to one +element yields (0,62,0,0) when reading element 1. A float SRV, absent slot +and out-of-range selector preserve the clear color. The guest source heap +and resource are released after recording and before submission. + +The version 6 mesh profile also binds pixel texture reads from the directly +indexed guest resource heap. An eight-DWORD descriptor load must select a +32-byte-aligned slot within a proven interval. At recording time, each slot +in that interval must contain a registered float or normalized texture SRV +of the expected dimension, or an explicit typed null. The private desktop +heap retains the selected views for the recording and reserves separate +slots for the mesh-stage buffer selector and static bindings. + +Run `ctest --preset dev --no-tests=error -R '^native_fixed_mesh57_pixel_heap_'`. +With the same mesh and pixel programs, changing root 4 selects guest slot 32 +or 36. The source-built test reads back red or green respectively. Both SRVs +expose mip 1 and both textures have a blue mip 0. A typed null reads as +transparent black. An unregistered slot or an array view in the Texture2D +interval preserves the opaque clear color. + +For offline fixed mesh pixel translation, `tools/startup/mesh57_pixel_entry.py` +takes a `req_.ps57`, its creation archive `req_.s57`, and a +reviewed `.mesh57-state`. It checks the two content keys and compares +all six input spans before printing the `meshps1` line for the offline +compiler. The enable mask, address mask and wave size come from the reviewed +pixel entry. A creation archive alone preserves the two register blocks but +does not assign hardware register meanings to their offsets. Reproduce the +source-built positive and altered-stage controls with +`ctest --preset dev --no-tests=error -R '^native_direct_mesh$'`. diff --git a/docs/experiments/native-startup-request-cache.md b/docs/experiments/native-startup-request-cache.md index b946aab35..85fe9f4c9 100644 --- a/docs/experiments/native-startup-request-cache.md +++ b/docs/experiments/native-startup-request-cache.md @@ -6,6 +6,44 @@ and compute (`x2w-startup-shader-29cs`, `req_.c67`) requests, publishes run manifests (`.vs.cso` / `.ps.cso` or `.cs.cso`, followed by `.txt`), and loads directly through the startup runtime cache loaders on WARP and hardware without manual renaming or conversion. +## First dispatch of a slot-67 compute request + +With `X2W_NATIVE_SHADERS` enabled, the runtime retains the six immutable parts +used to publish each new compute key. First dispatch takes those bytes and checks +their extents before invoking the ordinary C++ translator. Evicted requests use +the disk reader, which also verifies the key. The capture files remain available +for independent replay. + +`X2W_NATIVE_COMPUTE_REQUEST_CACHE_MIB` sets the per-process byte budget from 0 +through 256 MiB. The default is 32 MiB. Zero selects disk reads. The queue holds +at most 4,096 keys, evicts the oldest retained request first and releases each +snapshot on consumption. The render totals report hits, misses, evictions, +retained bytes and retained requests every 300 frames. Run +`ctest --preset dev --no-tests=error -R '^native_frozen_request$'` for the +ownership, budget, eviction and malformed-description controls. + +### Prewarming captured compute requests + +`compile_dxil --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY 0` validates +the six capture parts and prepares the same entry-zero frontend used at first dispatch. +It writes `CACHE_DIRECTORY/compute-0.pack` atomically. Each record contains either +DXIL IR with its binding layout or the exact typed frontend refusal. Other errors +are printed per request, omitted from the pack, and cause a nonzero command status. +If every input fails with an ordinary error, an existing pack is preserved. + +Set `X2W_NATIVE_COMPUTE_PACK` to the absolute pack path before startup. The runtime +loads the index once when native compute requests are published. At first use it +checks the frontend revision, entry offset and SHA-256 of all six frozen parts. +A miss takes the ordinary translation path. A matched refusal proceeds to the +existing published-translation loader. Successful hits run the usual binding +checks, device capability checks, bytecode compilation/cache lookup and PSO creation. +The heartbeat reports prepared hits, matched refusals and pack misses. + +```powershell +cmake --build --preset release --target compile_dxil native_compute_pack_check startup_stream_consumer d3d12_xs_shim +ctest --preset release --no-tests=error -R '^native_compute_pack(_hardware)?$' +``` + ## Alignment between `compile_dxil --requests` and the startup cache 1. **Request keys and `.psin` stream descriptions (`src/shader_compute_request.cpp`):** diff --git a/docs/experiments/patch-manifests.md b/docs/experiments/patch-manifests.md index c755a9a74..c3bca9b48 100644 --- a/docs/experiments/patch-manifests.md +++ b/docs/experiments/patch-manifests.md @@ -53,11 +53,11 @@ files = [{ ext = ".txt", file = "s001.txt", sha256 = "" }, | `pipeline` | `revision` form | Files the runtime reads | Required | |---|---|---|---| -| `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso` | all three | +| `graphics` | `x2w-startup-shader-` | `.txt`, `.vs.cso`, `.ps.cso`, `.gs.cso` | `.txt`, `.vs.cso`, `.ps.cso` | | `compute` | `x2w-startup-shader-cs` | `.txt`, `.cs.cso`, `.cs.hlsl` | `.txt`, `.cs.cso` | | `mesh86` | `x2w-startup-mesh-86-` | `.mesh86.txt`, `.ms.cso`, `.ps.cso` | `.mesh86.txt`, `.ms.cso` | -The runtime looks for a compute key's `.cs.hlsl`, the Python translator's output, only when its `.txt` has no `native` line, and reads a mesh86 key's `.ps.cso` only for a request with a pixel shader. The loader does not read the `.txt` or the request, so both stay optional. +The runtime reads a graphics key's `.gs.cso` for a published fixed rectangle pipeline, a compute key's `.cs.hlsl` when its `.txt` has no `native` line, and a mesh86 key's `.ps.cso` for a request with a pixel shader. All three stay optional in the manifest. - **Revision:** `revision` must have the form of the pipeline's key revision in the runtime (`src/startup_stubs/d3d12_draw.inl`, `src/startup_stubs/mesh86_cache.inl`), where `` is a number without leading zeros, so another pipeline's revision is refused. The loader does not check that `` is the runtime's current one: the runtime bumps it often, and a new revision changes every key. A later consumer that serves the files must compare it with the runtime; none exists yet. - **Files:** each entry is a table of exactly `ext`, `file` and `sha256`. `ext` is one of the pipeline's files and is listed once; the required ones must all be there. `file` is a bare file name, for a later consumer to resolve in the manifest's directory: a `/` or `\`, a drive (`:`), `.` and `..` are refused. That consumer is the runtime, which runs on Windows, so a name Windows would not open as a file of that name in the directory is refused too: one with `<`, `>`, `"`, `|`, `?`, `*` or a control character, one ending in a dot or a space (Windows drops them), and a device name (`CON`, `PRN`, `AUX`, `NUL`, `COM0`-`COM9`, `LPT0`-`LPT9`, `COM` and `LPT` with a superscript 1 to 3, `CONIN$`, `CONOUT$`) in any case, alone or before an extension, as Microsoft's "Naming Files, Paths, and Namespaces" lists them. `sha256` is lowercase. @@ -86,7 +86,7 @@ The check builds a synthetic PE32+ at run time with `build_pe32_plus` from - **Wrong-type `kind` through the CLI:** exit status 1 with a `patch manifest:` message, and no traceback. - **Bytes already read:** `load_data` on the image's bytes returns what `load` returns; on the flipped image it is refused as `for another input`. With the input file then replaced by the flipped image, `load_data` on the original bytes still loads and `load` on the file is refused. - **Shader patches:** one per pipeline loads beside a memory patch, mesh86 with and without its `.ps.cso`, compute with and without its `.cs.hlsl`, and the CLI lists their ids. Each of these is refused with its own message: a 15-digit key, a 17-digit one, an upper-case key, an unknown pipeline, another pipeline's revision (compute, graphics and the mesh57 cache's), a revision without its number, one with a leading zero, an integer revision, an empty `files`, an unknown or a missing file key, another pipeline's extension, an extension listed twice, a missing required file (compute and graphics), an empty `file`, a `file` with a `/` or a `\`, an absolute one, one with a drive, `..` and `.`, a `file` with `*`, `?`, `<`, `>`, `|`, `"`, a tab or U+0001, `s001.txt.` and `s001.txt ` (trailing space), the device names `NUL`, `CON.txt`, `Com1`, `nul .txt`, `CONIN$`, `conout$.txt`, `COM` + U+00B9 and `lpt` + U+00B3 + `.cso`, an upper-case `sha256`, two patches for one key, a memory key on a shader patch, a missing `files`, and kind `shaders`. -- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and the optional ones are mesh86's `.ps.cso`, read only for a request with a pixel shader, and compute's `.cs.hlsl`, looked for only when the `.txt` has no `native` line (`NativeComputeOutput::unmarked`). +- **Files pinned:** each pipeline's extensions are the ones its loader in the runtime reads for a key (`cache_path(..., L"", key, ext)` in `d3d12_draw.inl`, `d3d12_compute_dispatch.inl` and `mesh86_cache.inl`, and mesh86's `load_stage`), and the optional ones are graphics `.gs.cso` for fixed rectangles, mesh86's `.ps.cso`, read only for a request with a pixel shader, and compute's `.cs.hlsl`, looked for only when the `.txt` has no `native` line (`NativeComputeOutput::unmarked`). - **Revision forms pinned:** the runtime's current revision of each pipeline, read from its source, has the loader's form. A bump that only raises `` keeps the check green. The fixture uses revisions of each form that are not the runtime's current ones. - **Deep nesting:** with the recursion limit set to 1000 inside the test, an array nested 2000 deep is refused as `nested too deeply`, by `parse` and through the CLI (status 1, nothing on stdout, no traceback). Shape control: one nested 50 deep gets past `tomllib` and is refused only for its unknown key. - **Mutations:** diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index b677f0353..79dcc6b3c 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -691,6 +691,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view std::map interfaces; std::optional first_stage; bool exact_pair = reflected; + bool exact_pixel_code = false; Bytes entry; const bool fixed_entry = pixel_entry.size() == 12 && pixel_entry.substr(0,4) == "PSI1"; if (fixed_entry && !reflected) @@ -704,6 +705,7 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view auto matched = match_graphics_stage(raw[i],companions[i],exact); exact_pair &= exact; auto stage = matched.stage; + if (stage == GpuStage::ps) exact_pixel_code = exact; if (i == 0) first_stage = stage; if (!interfaces.emplace(stage, std::move(matched)).second) throw UnsupportedComputeShader("duplicate reflected graphics stage"); @@ -786,8 +788,12 @@ DirectGraphicsPair prepare_direct_graphics(std::string_view a, std::string_view channels[r.index / 4] |= 1u << r.first; } for (const auto &attr : attrs) { + // A specialized raw PS can read more components of the same PARAM + // than its library variant. The raw VS/PS link above has already + // checked every consumed component against a matching VS export. + const bool linked_raw_row = fixed_entry && !exact_pixel_code && attr.row == attr.location; if (attr.usage != 6 || attr.location >= channels.size() || attr.flags != 2 || - (channels[attr.location] & ~attr.mask) || !attr.mask) + (!linked_raw_row && (channels[attr.location] & ~attr.mask)) || !attr.mask) throw UnsupportedComputeShader("raw and reflected interpolation channels disagree at location " + std::to_string(attr.location) + " (usage " + std::to_string(attr.usage) + ", flags " + std::to_string(attr.flags) + ", reflected mask " + std::to_string(attr.mask) + @@ -982,8 +988,9 @@ std::optional format_compute_runtime_manifest(const NativeComputeSh uav_lines << "uav " << b.shader_register << ' ' << dimension << " float table " << b.root_parameter << ' ' << b.byte_offset << " channels " << channels << '\n'; } else if ((b.kind == ComputeViewKind::texture_uav || b.kind == ComputeViewKind::half4_texture_uav) && - (b.image_dimension == 1 || b.image_dimension == 5) && b.array_count == 1) { - uav_lines << "uav " << b.shader_register << (b.image_dimension == 5 ? " tex2da" : " tex2d") + (b.image_dimension == 1 || b.image_dimension == 5 || + (b.kind == ComputeViewKind::texture_uav && b.image_dimension == 2)) && b.array_count == 1) { + uav_lines << "uav " << b.shader_register << (b.image_dimension == 5 ? " tex2da" : b.image_dimension == 2 ? " tex3d" : " tex2d") << " float table " << b.root_parameter << ' ' << b.byte_offset << " channels 4\n"; } else { return refuse(view_shape("UAV", b)); diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 1eb5815dd..c07bf61d4 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -77,7 +77,7 @@ struct DirectCompute { unsigned compute_pc = 0; bool perspective_center_pair = false; bool exact_pixel_entry = false; - bool helper_result_unobserved = false; + std::function helper_result_unobserved; unsigned pixel_entry_vgprs = 0; std::function untouched_pixel_register; // P1/P2 consume the entry IJ pair symbolically. After an exact-mask @@ -157,7 +157,7 @@ struct DirectCompute { (!graphics_registers.count(r) || (guarded_ij.count(r) && guarded_ij.at(r).first == graphics_predicate))) { write(r, {}); guarded_ij.emplace(r, std::make_pair(graphics_predicate, value)); - } else if (exact_pixel_entry && helper_result_unobserved && pixel_entry_vgprs && r >= 256 + pixel_entry_vgprs && + } else if (exact_pixel_entry && helper_result_unobserved(r) && pixel_entry_vgprs && r >= 256 + pixel_entry_vgprs && !graphics_registers.count(r) && untouched_pixel_register(r)) { // Only covered lanes can observe this result. In particular no // subsequent implicit LOD or quad operation can inspect helpers. diff --git a/src/gfx1013_direct_graphics.inl b/src/gfx1013_direct_graphics.inl index 01d465034..2bf090b7b 100644 --- a/src/gfx1013_direct_graphics.inl +++ b/src/gfx1013_direct_graphics.inl @@ -958,7 +958,7 @@ struct GraphicsMaskRegions { bool sampled = false; for (; end < code.size(); ++end) { const auto &i = code[end]; - if (i.enc == Encoding::Image && i.op >= 0x20 && i.op <= 0x3f) sampled = true; + if (i.enc == Encoding::Image && (i.op == 0 || (i.op >= 0x20 && i.op <= 0x3f))) sampled = true; else if (i.name != "s_waitcnt" && i.name != "s_nop") break; } if (!sampled || end == code.size() || !restore_mask(code[end]) || code[end].src[0] == start.src[0]) continue; @@ -1605,6 +1605,40 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = return false; }; const auto last_lane_observer = std::find_if_not(program.code.rbegin(), program.code.rend(), lane_local); + // A later lane observer matters only if the new value can reach it. + // Conservatively record every potential touch up to the final observer, + // including inputs to ordinary instructions that could propagate the value. + std::array last_helper_touch{}; + if (pixel && straight && last_lane_observer != program.code.rend()) { + for (const auto &op : program.code) { + if (op.pc > last_lane_observer->pc) break; + auto touch = [&](unsigned r) { + if (r >= 256 && r < 512) last_helper_touch[r-256] = op.pc; + }; + if (op.enc == Encoding::Sopp || op.enc == Encoding::Smem || + op.enc == Encoding::Sop1 || op.enc == Encoding::Sop2) continue; + if (op.enc == Encoding::Interp) { + touch(256 + (op.a & 255)); + touch(256 + ((op.a >> 18) & 255)); + } else if (op.name == "v_readfirstlane_b32" || op.name == "v_cvt_i32_f32" || + op.name == "v_mov_b32" || op.name == "v_and_b32") { + for (auto r : op.src) touch(r); + touch(op.dst); + } else if (op.enc == Encoding::Image && !(op.a & 6) && + ((op.op == 32 && ((op.a >> 3) & 7) == 1) || + (op.op == 0 && ((op.a >> 3) & 7) == 5))) { + // Plain 2D sample or 2D-array load; no NSA address list. + unsigned count = op.op == 32 ? 2 : 3; + for (unsigned j = 0; j < count; ++j) touch(256 + (op.b & 255) + j); + for (unsigned j = 0; j < 4; ++j) touch(256 + op.dst + j); + } else { + last_helper_touch.fill(op.pc); + } + } + } + alu.helper_result_unobserved = [&](unsigned r) { + return straight && r >= 256 && r < 512 && alu.graphics_pc >= last_helper_touch[r-256]; + }; bool whole_quad = false; bool exact_after_wqm = false; bool exact_sample_region = false; @@ -1745,8 +1779,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = i.name.find("_b64") != Name::npos || i.enc == Encoding::Vopc ? 2 : 1; if (i.dst < mask_reg + 2 && mask_reg < i.dst + width) discard_lane.clear(); } - alu.helper_result_unobserved = straight && - (last_lane_observer == program.code.rend() || pc >= last_lane_observer->pc); + if (auto it = regions.expired.find(pc); it != regions.expired.end()) for (auto reg : it->second) alu.write(reg, {}); if (regions.vertex_anchors.count(pc) || regions.captures.count(pc)) { @@ -1952,7 +1985,7 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = i.enc != Encoding::Sop1 && i.enc != Encoding::Sop2 && i.enc != Encoding::Sopk && i.enc != Encoding::Export && !(i.name == "v_mov_b32" && i.dst >= 256 && !i.dpp_control && !i.subword) && - !(i.enc==Encoding::Image && i.op>=0x20 && i.op<=0x3f) && + !(i.enc==Encoding::Image && (i.op==0 || (i.op>=0x20 && i.op<=0x3f))) && !(i.name == "buffer_atomic_add" && !(i.a & 0x2000))) refuse(pc,"unsupported exact-mask operation after whole-quad entry"); if ((i.name == "s_wqm_b32" || i.name == "s_wqm_b64") && i.dst == 126 && i.src[0] == 126) { @@ -2187,7 +2220,8 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = break; // A scheduled FP32 FMA accesses exactly three scalar-width // sources and one destination. It cannot change EXEC. - if (j.name == "v_fma_f32" && j.dst != i.dst) + if ((j.name == "v_fma_f32" || j.name == "v_fma_mixlo_f16" || + j.name == "v_fma_mixhi_f16" || j.name == "v_mul_f32" || j.name == "s_waitcnt") && j.dst != i.dst) continue; if (j.dst == i.dst && j.name == (low ? "v_fma_mixhi_f16" : "v_fma_mixlo_f16") && std::find(i.src.begin(), i.src.end(), i.dst) == i.src.end()) @@ -2215,7 +2249,9 @@ NativeComputeShader lower_graphics(GuestShaderStage &stage, unsigned first_srv = } alu.arithmetic(i, state); if (heap_range) heap_ranges[alu.read(i.dst)]=*heap_range; - if (uniform_vertex || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && + const bool uniform_conversion = pixel && straight && alu.graphics_predicate.empty() && + i.name == "v_cvt_i32_f32" && !i.dpp_control && !i.subword && i.src[0] <= 105; + if (uniform_vertex || uniform_conversion || (pixel && i.name == "v_med3_f32" && alu.graphics_predicate.empty() && std::all_of(i.src.begin(), i.src.end(), scalar_operand))) { auto value = alu.read(i.dst); if (alu.ir.dependencies[value].none()) uniform_vector_values.insert(value); diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 05d0259d7..4f8e00c18 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -9,6 +9,28 @@ // TABL (descriptor table binds), PRES (present). tools read it with out/gamerun/capture.py. struct Translation; +bool copy_title_bytes(void* to, const void* from, std::size_t bytes) noexcept; +using FixedMeshBytes = std::shared_ptr>; +// GPU recordings can outlive guest Release. Share immutable inputs by content until the validated +// request is durably published. The index holds no strong ownership of its own. +FixedMeshBytes intern_fixed_mesh_bytes(std::vector bytes) +{ + static SRWLOCK lock = SRWLOCK_INIT; + static std::unordered_multimap>> index; + u64 hash = 1469598103934665603ull; + for (auto byte : bytes) hash = (hash ^ byte) * 1099511628211ull; + x2w_startup::ExclusiveNoteLock guard(lock); + const auto range = index.equal_range(hash); + for (auto it = range.first; it != range.second;) { + if (auto existing = it->second.lock()) { + if (*existing == bytes) return existing; + ++it; + } else it = index.erase(it); + } + auto stage = std::make_shared>(std::move(bytes)); + index.emplace(hash, stage); + return stage; +} struct PipelineInfo { Translation* stream_translation = nullptr; bool has_stream_blend = false; @@ -22,6 +44,10 @@ struct PipelineInfo { Wrapper* base = nullptr; // slot 55: the pipeline it derives from std::vector desc; std::vector state_a, state_b; // slot 57: the two state blocks, copied at creation (the title frees them) + mutable FixedMeshBytes fixed_ms, fixed_ps; + mutable std::vector mesh57_pixel_spans; + mutable UINT mesh57_heap_word = UINT_MAX; // R32_UINT at guest root constant[heap_word] & 1023. + mutable std::vector mesh57_reads; // Host SRV register order. }; struct ViewRecord { // Capture the guest descriptor layout, independent of the desktop SDK. @@ -212,6 +238,25 @@ void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std info.base = as_wrapper(base); const std::size_t have = desc ? readable_window(reinterpret_cast(desc), bytes) : 0; if (have) info.desc.assign(static_cast(desc), static_cast(desc) + have); + if (path == 57 && have >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info.desc.data(), sizeof(words)); + const auto snapshot = [&](int field, FixedMeshBytes& stage) { + const auto bytes = words[field + 1]; + if (!bytes) return !words[field]; + const auto* data = reinterpret_cast(words[field]); + if (bytes > (1u << 20) || !x2w_local::readable(data, bytes)) return false; + std::vector copy(static_cast(bytes)); + if (!copy_title_bytes(copy.data(), data, copy.size())) return false; + stage = intern_fixed_mesh_bytes(std::move(copy)); + return true; + }; + if (!words[9] && !words[10] && words[14] && + (!snapshot(5, info.fixed_ps) || !snapshot(13, info.fixed_ms))) { + info.fixed_ps.reset(); + info.fixed_ms.reset(); + } + } if (path == 57 && have >= 0x28) { u64 words[5]; std::memcpy(words, desc, sizeof(words)); diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index a5b384dd3..ce571a0f8 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -36,6 +36,10 @@ struct ComputeTranslation { Source source = root_constant; D3D12_UAV_DIMENSION uav_dimension = D3D12_UAV_DIMENSION_UNKNOWN; bool root = false; + bool array = false; + unsigned half_typed_bytes = 0; + bool packed_d16_x = false; + unsigned scalar_window = 0; bool atomic_uint_texture = false; unsigned channels = 4; D3D12_SRV_DIMENSION srv_dimension = D3D12_SRV_DIMENSION_UNKNOWN; @@ -50,6 +54,7 @@ struct ComputeTranslation { x2w_startup::ComPtr root; x2w_startup::ComPtr pipeline; const char* unmodelled = nullptr; // why a manifest that exists cannot be used + bool logged_token_output = false, logged_bound_token_output = false; u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded const char* first_refusal = nullptr; // reason of the first refused call bool input_path_logged = false; // the first time a placed input came from a GPU copy or a title snapshot @@ -106,7 +111,7 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st { // Parameter 0 keeps one constant for a program without entry values: a constants parameter cannot be empty. if (FAILED(x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.empty() ? 1 : tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), tr.heap_srvs))) + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), false, tr.heap_srvs))) return "root signature creation failed"; D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; desc.pRootSignature = tr.root.Get(); @@ -121,6 +126,10 @@ const char* create_compute_pipeline(ComputeTranslation& tr, const void* code, st const char* load_compute_translation(ComputeTranslation& tr) { tr.state = 2; + if (native_shaders_only()) { + tr.manifest_retry.found(); + return nullptr; + } wchar_t path[MAX_PATH]; std::string manifest; if (!cache_path(path, L"", tr.key, L".txt") || !read_text(path, manifest)) { @@ -278,10 +287,36 @@ bool translate_compute_natively(ComputeTranslation& tr) const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); if (!length || length >= MAX_PATH) return false; if (!cache_path(path, L"req_", tr.key, L".c67")) return false; + auto refuse_native = [&](const char* reason) { + tr.uds.clear(); + tr.srvs.clear(); + tr.uavs.clear(); + tr.root.Reset(); + tr.pipeline.Reset(); + static LONG logged; + if (first_calls(logged, 16)) + log("x2w-draw compute pipeline %016llx not translated natively: %s", tr.key, reason); + return false; + }; try { // The request as this runtime published it. The reader checks the six parts against the key in the name. // Entry 0: a source-built program starts there, and the frontend reads a capture's v_nop prefix as code. - auto program = x2w::translate_compute(x2w::read_compute_request(path), 0, true); + auto frozen = frozen_compute_requests().take(tr.key); + if (frozen) x2w::validate_compute_request_shape(*frozen); + else frozen.emplace(x2w::read_compute_request(path)); + x2w::NativeComputeShader program; + auto result = x2w::ComputePackResult::miss; + if (const auto* pack = runtime_compute_pack()) { + std::string diagnostic; + result = pack->lookup(*frozen, 0, program, diagnostic); + if (result == x2w::ComputePackResult::unsupported) { + InterlockedIncrement(&compute_pack_refused); + return refuse_native(diagnostic.c_str()); + } + InterlockedIncrement(result == x2w::ComputePackResult::prepared ? &compute_pack_prepared : &compute_pack_misses); + } + if (result == x2w::ComputePackResult::miss) + program = x2w::translate_compute(*frozen, 0, true); for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); @@ -299,13 +334,22 @@ bool translate_compute_natively(ComputeTranslation& tr) [](const auto& a, const auto& b) { return a.shader_register < b.shader_register; }); for (const auto& view : program.bindings) { const unsigned channels = x2w::exact_texture_uav_channels(view.kind); - const bool output = channels || view.kind == x2w::ComputeViewKind::raw_buffer_uav; + const bool packed_x = view.kind == x2w::ComputeViewKind::packed_d16_x_uav; + const bool half_typed = packed_x || view.kind == x2w::ComputeViewKind::half_buffer_uav; + const bool texture_input = view.kind == x2w::ComputeViewKind::texture_srv && view.image_dimension == 1; + const bool volume = view.kind == x2w::ComputeViewKind::texture_uav && view.image_dimension == 2; + const bool output = view.kind == x2w::ComputeViewKind::raw_buffer_uav || half_typed || volume || channels; auto& slots = output ? tr.uavs : tr.srvs; - if ((!output && view.kind != x2w::ComputeViewKind::raw_vector_srv) || view.array_count != 1 || + if ((!output && !texture_input && view.kind != x2w::ComputeViewKind::raw_vector_srv && !x2w::accepts_cbv_window(view.kind)) || view.array_count != 1 || view.root_parameter >= 16 || view.shader_register != slots.size()) throw std::runtime_error("view kind " + std::to_string(static_cast(view.kind)) + " is not bound for a natively translated program"); - slots.push_back({static_cast(view.root_parameter), static_cast(view.byte_offset)}); + slots.push_back({static_cast(view.root_parameter), static_cast(view.byte_offset), volume || texture_input}); + if (volume) slots.back().uav_dimension = D3D12_UAV_DIMENSION_TEXTURE3D; + slots.back().half_typed_bytes = half_typed ? view.required_bytes : 0; + slots.back().packed_d16_x = packed_x; + if (x2w::accepts_cbv_window(view.kind)) + slots.back().scalar_window = view.required_bytes; if (channels) { auto& slot = slots.back(); slot.texture = true; @@ -329,19 +373,12 @@ bool translate_compute_natively(ComputeTranslation& tr) x2w::ShaderSourceFormat::dxil_ir); if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size())) throw std::runtime_error(failure); - log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs", tr.key, - tr.uds.size(), tr.srvs.size(), tr.uavs.size()); + log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)", tr.key, + tr.uds.size(), tr.srvs.size(), tr.uavs.size(), + result == x2w::ComputePackResult::prepared ? "prepared" : "live"); return true; } catch (const std::exception& error) { - tr.uds.clear(); - tr.srvs.clear(); - tr.uavs.clear(); - tr.root.Reset(); - tr.pipeline.Reset(); - static LONG logged; - if (first_calls(logged, 16)) - log("x2w-draw compute pipeline %016llx not translated natively: %s", tr.key, error.what()); - return false; + return refuse_native(error.what()); } #else (void)tr; @@ -417,6 +454,97 @@ IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int return {native, offset, bytes, 0, false}; } +// A slot-19 token identifies a view, not a four-dword gfx1013 buffer descriptor. +struct ComputeTokenOutput { + ID3D12Resource* resource{}; + u64 offset{}, bytes{}; + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + D3D12_RESOURCE_DESC backing{}; + Placement placement{}; + bool created{}; + u64 guest_base{}, guest_resource{}, counter{}, desktop_gpuva{}; + UINT description_bytes{}; +}; + +const char* compute_token_output(Wrapper* list, const std::uint32_t* words, ComputeTokenOutput& output) +{ + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + if (words[1] < view_records().size()) { + record = view_records()[words[1]]; + output.created = view_materialized()[words[1]] != 0; + } + ReleaseSRWLockShared(¬e_lock); + if (words[2] != 19 || words[3] || record.slot != 19) + return "an output token does not identify a slot-19 UAV"; + output.guest_resource = record.resource; + output.description_bytes = record.desc_bytes; + output.counter = record.counter; + if (record.desc_bytes >= sizeof(output.view)) std::memcpy(&output.view, record.desc, sizeof(output.view)); + auto* owner = as_wrapper(reinterpret_cast(record.resource)); + auto* resource = owner && owner->own().kind == resource_kind ? static_cast(owner->own().real) : nullptr; + const ResourceInfo* info = owner && owner->own().kind == resource_kind ? resource_info(owner) : nullptr; + if (info) { + output.placement = info->placement; + output.guest_base = reinterpret_cast(owner->own().title_memory); + output.backing = info->console; + } + if (!output.created || !record.resource || record.counter || record.desc_bytes < sizeof(output.view)) + return "an output token lacks a materialized explicit counterless UAV"; + if (output.view.ViewDimension != D3D12_UAV_DIMENSION_BUFFER || !info || + info->console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + return "a raw buffer writer was bound to a non-buffer UAV"; + if (!resource) return "an output token has no desktop resource"; + output.backing = resource->GetDesc(); + if (output.backing.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + return "a raw buffer writer was bound to a non-buffer backing"; + if (!(output.backing.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) || + info->initial_state != D3D12_RESOURCE_STATE_COMMON) + return "an output token's backing lacks tracked UAV access"; + if (trace_compute_outputs()) output.desktop_gpuva = resource->GetGPUVirtualAddress(); + const auto& view = output.view.Buffer; + const bool raw = view.Flags == D3D12_BUFFER_UAV_FLAG_RAW && output.view.Format == DXGI_FORMAT_R32_TYPELESS && + !view.StructureByteStride; + const bool structured = view.Flags == D3D12_BUFFER_UAV_FLAG_NONE && output.view.Format == DXGI_FORMAT_UNKNOWN && + view.StructureByteStride; + const bool typed = view.Flags == D3D12_BUFFER_UAV_FLAG_NONE && !view.StructureByteStride; + const UINT element = raw ? 4 : structured ? view.StructureByteStride : + typed ? x2w_startup::typed_buffer_format_bytes(desktop_format(output.view.Format)) : 0; + if (!element || view.CounterOffsetInBytes || view.FirstElement > UINT64_MAX / element) + return "an output UAV has no supported byte interval"; + output.offset = view.FirstElement * element; + output.bytes = u64{view.NumElements} * element; + if (!output.bytes || output.bytes % 4 || output.bytes > (16u << 20) || + output.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || output.offset > output.backing.Width || + output.bytes > output.backing.Width - output.offset) + return "an output UAV interval is unaligned, oversized or outside its buffer"; + const auto base = reinterpret_cast(owner->own().title_memory); + if (base) { + if (output.offset > UINT64_MAX - base) return "an output UAV placement address overflows"; + const auto placed = placed_buffer_range(list->own().list_device, base + output.offset, output.bytes); + if (placed.reject) return "an output UAV range overlaps or crosses active placements"; + if (placed.owner != owner) return "an output UAV range no longer resolves to its token owner"; + // A slot-19 token identifies an object. For a complete view its committed + // backing is the host buffer used by subsequent object-based GPU commands. + // This mode does not imply CPU aliasing or make a partial view authoritative. + static const bool copied_views = x2w_local::env_on("X2W_COPIED_OBJECT_UAV"); + const bool whole_copy = copied_views && info->placement == Placement::copied_buffer && + output.offset == 0 && output.bytes == info->bytes && output.bytes == output.backing.Width; + if (placed.alias != resource && !whole_copy) + return "an output token's backing does not uniquely alias its guest byte interval"; + } else { + D3D12_HEAP_PROPERTIES heap{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(resource->GetHeapProperties(&heap, &flags)) || heap.Type != D3D12_HEAP_TYPE_DEFAULT) + return "an output UAV without guest shadow is not on the default heap"; + } + x2w_startup::ComPtr device; + if (FAILED(resource->GetDevice(IID_PPV_ARGS(device.GetAddressOf()))) || device.Get() != device_of(list->own().list_device)) + return "an output UAV belongs to a different device"; + output.resource = resource; + return nullptr; +} + // Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch) { @@ -646,7 +774,21 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } if (!output) { // Each condition of a complete GPU-backed buffer range has its own reason. - const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + auto view = indirect_table_buffer(self, words, false, &reason, 16u << 20, D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, true); + if (reason && slot.scalar_window && words[0] != view_token_magic && + !std::strcmp(reason, "an input is in title memory outside any placed buffer")) { + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 extent = u64{stride ? stride : 1} * words[2]; + const u64 bytes = extent; + u64 start{}; + ID3D12Resource* chunk{}; + if (bytes >= slot.scalar_window && bytes <= 65536 && bytes % 4 == 0 && + readable_window(address, bytes) >= bytes && frame_copy(self, address, bytes, &start, &chunk) && chunk) { + view = {chunk, start, bytes, stride, true, 2}; + reason = nullptr; + } + } if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); if (view.source == 2) { InterlockedIncrement(&compute_inputs_snapshot); @@ -666,9 +808,58 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& std::memcpy(views[i].words, words, sizeof(views[i].words)); continue; } - // An output is written by the GPU: only a placed buffer that aliases the title's memory shows the result - // to the title. shortcut: view tokens and copied placements are refused, add them with their first user. - // Each refused condition has its own reason. + if (words[0] == view_token_magic) { + ComputeTokenOutput token{}; + reason = compute_token_output(self, words, token); +#ifdef X2W_NATIVE_SHADERS + if (!reason && slot.half_typed_bytes) { + const auto kind = slot.packed_d16_x ? x2w::ComputeViewKind::packed_d16_x_uav : x2w::ComputeViewKind::half_buffer_uav; + const x2w::ComputeViewBinding binding{kind, 0, 0, 0, slot.half_typed_bytes}; + token.view.Format = desktop_format(token.view.Format); + if (!x2w::native_buffer_store_view(binding, token.view, token.backing.Width)) + reason = "formatted D16 write has an incompatible typed buffer UAV"; + } +#endif + if (reason && token.placement == Placement::copied_buffer && + trace_copied_compute_output(key, token.guest_resource, token.guest_base, token.offset, token.bytes)) { + log("x2w-compute-output-watch key=%016llx groups=%u,%u,%u indirect=%u owner=0x%llx gpuva=0x%llx", + key, x, y, z, dispatch.signature != nullptr, token.guest_resource, token.desktop_gpuva); + for (const auto& ud : tr->uds) + if (ud.source == ComputeTranslation::root_constant) + log("x2w-compute-output-constant key=%016llx root=%d word=%d value=0x%08x", key, ud.a, ud.b, + pass.compute_constants.word(ud.a, ud.b)); + } + for (const auto& ud : tr->uds) + if (ud.source >= ComputeTranslation::output_word3 && ud.a == static_cast(i - inputs) && !reason) + reason = "an output token has no original ISA descriptor words for entry constants"; + for (std::size_t input = 0; input < inputs && !reason; ++input) + if (views[input].resource == token.resource) reason = "an output buffer is also an input"; + if (!reason && !retain_with_recording(self, x2w_startup::ComPtr(token.resource))) + reason = "an output token's backing could not be retained with the recording"; + if (!tr->logged_token_output || (!reason && !tr->logged_bound_token_output)) { + tr->logged_token_output = true; + if (!reason) tr->logged_bound_token_output = true; + log("x2w-draw compute UAV %016llx table=%d+%d entry=0x%llx token=%u created=%u dim=%u fmt=%u " + "first=%llu elements=%u stride=%u flags=%u backing-dim=%u backing-bytes=%llu backing-flags=%u " + "placement=%u owner=0x%llx guest-base=0x%llx counter=0x%llx desc-bytes=%u offset=%llu bytes=%llu result=%s", + key, slot.a, slot.b, entry, words[1], token.created, token.view.ViewDimension, token.view.Format, + token.view.Buffer.FirstElement, token.view.Buffer.NumElements, token.view.Buffer.StructureByteStride, + token.view.Buffer.Flags, token.backing.Dimension, token.backing.Width, token.backing.Flags, + static_cast(token.placement), token.guest_resource, token.guest_base, token.counter, + token.description_bytes, token.offset, token.bytes, reason ? reason : "bound"); + } + views[i] = {token.resource, token.offset, token.bytes, true}; + if (!reason && slot.half_typed_bytes) { + views[i].described = true; + views[i].desc.uav = token.view; + } + continue; + } + if (slot.half_typed_bytes) { + reason = "formatted D16 write needs the original typed buffer view"; + break; + } + // Hardware descriptors address guest memory directly and must name a unique writable alias. const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); const UINT stride = (words[1] >> 16) & 0x3fff; const unsigned half_bytes = slot.half_buffer_bytes; @@ -695,6 +886,10 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& reason = "an output buffer has no unordered access"; for (std::size_t input = 0; input < inputs && !reason; ++input) if (views[input].resource == placed.alias) reason = "an output buffer is also an input"; + if (reason && !tr->first_refusal) + log("x2w-draw compute raw UAV %016llx table=%d+%d entry=0x%llx words=%08x/%08x/%08x/%08x " + "stride=%u bytes=%llu result=%s", key, slot.a, slot.b, entry, words[0], words[1], words[2], words[3], + stride, bytes, reason); views[i] = {placed.alias, offset, bytes, true}; if (!reason && half_bytes) { const auto format = x2w::native_half_buffer_format(half_bytes); @@ -893,3 +1088,65 @@ void log_compute_census() // Fixtures: the census without waiting for the frame that logs it. extern "C" __declspec(dllexport) void x2w_d3d12_compute_census() { log_compute_census(); } + +void scene_argument_probe(Wrapper* self, unsigned event, void* argument, u64 offset, const char* refused) { + static const bool enabled = GetEnvironmentVariableW(L"X2W_SCENE_ARGUMENT_PROBE",nullptr,0) != 0; + if (!enabled || !recording(self) || !draw_dump_frame() || frame_number != draw_dump_frame()) return; + auto& pass = pass_of(self); + if (!pass.pipeline) return; + const u64 key = pass.pipeline->own().compute_request_key; + static const u64 input_key = probe_key("X2W_ARGUMENT_INPUT_KEY"); + static const u64 output_key = probe_key("X2W_ARGUMENT_OUTPUT_KEY"); + static const u64 indirect_key = probe_key("X2W_ARGUMENT_INDIRECT_KEY"); + if (!key || (event == 17 && key != input_key) || (event == 22 && key != output_key) || + (event == 27 && key != indirect_key)) return; + static volatile LONG seen[28]{}; + LONG previous = seen[event]; + if (previous == frame_number || InterlockedCompareExchange(&seen[event],frame_number,previous)!=previous) return; + ID3D12Resource* resource{}; bool upload = false; + u64 entry = 0; UINT words[4]{}; UINT bytes = event == 17 ? 4 : 12; + if (event != 27) { + entry = pass.compute_tables.table(1).record(event == 17 ? 64 : 32,16); + if (!entry || !x2w_local::readable(reinterpret_cast(entry),16)) return; + std::memcpy(words,reinterpret_cast(entry),16); + if (event == 17) { + const char* why{}; + auto v = indirect_table_buffer(self,words,false,&why); + const u64 guest = words[0] | (u64{words[1]&0xffff}<<32); + UINT scalar = 0; SIZE_T got = 0; + if (words[0]!=view_token_magic) + ReadProcessMemory(GetCurrentProcess(),reinterpret_cast(guest+36),&scalar,4,&got); + log("x2w-argument-probe input frame=%ld guest=%llx cpuBytes=%zu cpu=%08x resolve=%s",frame_number,guest,got,scalar,why?why:"bound"); + if (v.bytes < 40) return; + resource=v.resource; offset=v.offset+36; upload=v.upload; + } else { + ComputeTokenOutput token{}; + const char* why = words[0]==view_token_magic ? compute_token_output(self,words,token) : "no token"; + log("x2w-argument-probe after frame=%ld token=%u owner=%llx dispatch=%s view=%s",frame_number,words[1],token.guest_resource,refused?refused:"recorded",why?why:"bound"); + if (token.view.Buffer.FirstElement != 0 || token.backing.Dimension!=D3D12_RESOURCE_DIMENSION_BUFFER) return; + auto* w=as_wrapper(reinterpret_cast(token.guest_resource)); + if (!w || w->own().kind != resource_kind) return; + resource=static_cast(w->own().real); + } + } else { + auto* w=as_wrapper(argument); + if (!w || w->own().kind != resource_kind) return; + resource=static_cast(w->own().real); + } + if (!resource || draw_dumps().full()) return; + auto desc=resource->GetDesc(); + if (desc.Dimension!=D3D12_RESOURCE_DIMENSION_BUFFER || offset>desc.Width || bytes>desc.Width-offset) return; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + D3D12_RESOURCE_DESC rd{}; rd.Dimension=D3D12_RESOURCE_DIMENSION_BUFFER; rd.Width=bytes; rd.Height=1; rd.DepthOrArraySize=1; rd.MipLevels=1; rd.SampleDesc.Count=1; rd.Layout=D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + DrawDump dump{}; + if(FAILED(device_of(the_device)->CreateCommittedResource(&heap,D3D12_HEAP_FLAG_NONE,&rd,D3D12_RESOURCE_STATE_COPY_DEST,nullptr,IID_PPV_ARGS(dump.buffer.GetAddressOf())))) return; + auto* dst=dump.buffer.Get(); dump.frame=frame_number; dump.count=event; dump.key=key; + auto* list=recording(self); + if (!retain_with_recording(self,x2w_startup::ComPtr(resource)) || !draw_dumps().record(list,std::move(dump))) return; + auto state=D3D12_RESOURCE_STATE_COMMON; + for (auto& st:pass.states) if (st.first==resource) state=st.second; + if (!upload) require_state(self,resource,D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(dst,0,resource,offset,bytes); + if (!upload) require_state(self,resource,state); + log("x2w-argument-probe copied frame=%ld event=%u owner=%p gpu=%llx offset=%llu bytes=%u",frame_number,event,argument,resource->GetGPUVirtualAddress(),offset,bytes); +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 05a7cd1b2..1933d5f78 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -153,7 +153,7 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso } struct Translation { - struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a + struct Srv { int kind, source, a, b; UINT expected_stride{}; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture, 5 cube; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable @@ -164,6 +164,7 @@ struct Translation { std::vector srvs; std::vector uavs; // manifest 'uav N tex2d table P O' (#1996 F): u0.. after the SRVs std::vector uds; + std::vector fixed_stream; x2w_startup::TranslatedSamplers samplers; x2w_startup::ExportWriteMasks write_masks; // manifest 'wmask': channels each export leaves unwritten (#1674) x2w_startup::D16ImageSrvs d16_srvs; // manifest 'd16srv': texture views that must match proven D16 formats (#2023) @@ -173,6 +174,8 @@ struct Translation { std::optional independent_indirect_entry; std::optional indexed_indirect_entry; bool indexed_rect_geometry_attempted = false; + std::string fixed_rectangle_ir; + bool fixed_rectangle_on_disk = false; x2w_startup::ComPtr indexed_rect_geometry; int indirect_base_word = -1; x2w_startup::ComPtr indexed_signature; @@ -435,12 +438,25 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; } +bool native_shaders_only() +{ + static const bool enabled = [] { + char value[2]{}; + return GetEnvironmentVariableA("X2W_NATIVE_SHADERS_ONLY", value, sizeof(value)) == 1 && value[0] == '1'; + }(); + return enabled; +} + void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}) { tr.state = 2; + if (manifest.empty() && native_shaders_only()) { + tr.manifest_retry.found(); + return; + } wchar_t path[MAX_PATH]; - if (!cache_path(path, L"", tr.key, L".txt")) return; const bool provided = !manifest.empty(); + if (!cache_path(path, L"", tr.key, L".txt")) return; if (!provided && !read_text(path, manifest)) { if (!tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); @@ -455,6 +471,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: const bool previously_missing = tr.manifest_retry.pending(); tr.manifest_retry.found(); bool matched_rtv = false; + bool fixed_manifest = false; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -469,6 +486,23 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: return; } matched_rtv = true; + } else if (line == "x2w-manifest 3") { + fixed_manifest = true; + } else if (line == "fixedrectgs") { + if (!fixed_manifest) return; + tr.fixed_rectangle_on_disk = true; + } else if (line.compare(0, 8, "fixedvb ") == 0) { + unsigned offset, format; + char extra; + if (!fixed_manifest || std::sscanf(line.c_str(), "fixedvb %u %u %c", &offset, &format, &extra) != 2 || + offset >= 2048 || tr.fixed_stream.size() >= 32 || + (format != DXGI_FORMAT_R8_UNORM && format != DXGI_FORMAT_R8G8_UNORM && format != DXGI_FORMAT_R8G8B8A8_UNORM && + format != DXGI_FORMAT_R32G32_UINT && format != DXGI_FORMAT_R32G32B32_UINT && + format != DXGI_FORMAT_R32G32B32A32_UINT && format != DXGI_FORMAT_R8_UINT) || + std::any_of(tr.fixed_stream.begin(), tr.fixed_stream.end(), [offset](const auto& e){return e.SemanticIndex == offset;})) + return; + tr.fixed_stream.push_back({"X2W_RAW_VERTEX", offset, static_cast(format), 0, offset, + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}); } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1" && line != "x2w-manifest 2") { // Version 2 adds `uav` lines. Each one is bound (a pixel-stage tex2d store) or refused by name below, // so a translation whose stores would be silently skipped is never drawn (#1723). @@ -490,6 +524,12 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : !std::strcmp(kind, "texcube") ? 5 : 0; Translation::Srv srv{texture_kind, !std::strcmp(source, "vb") ? 1 : !std::strcmp(source, "root") ? 2 : 0, x, y}; + if (!std::strcmp(kind, "idxbuf")) { + char tail; + if (std::sscanf(line.c_str(), "srv %d idxbuf table %d %d %u %c", &i, &x, &y, + &srv.expected_stride, &tail) != 4 || x < 0 || x >= 16 || y < 0 || y % 32 || + !srv.expected_stride || srv.expected_stride % 4 || srv.expected_stride > 2048) return; + } if (static_cast(i) == tr.srvs.size()) tr.srvs.push_back(srv); } else if (line.compare(0, 6, "wmask ") == 0) { if (!tr.write_masks.read_manifest_line(line)) { @@ -518,6 +558,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: return; } } + if (fixed_manifest != !tr.fixed_stream.empty()) return; if (matched_rtv != !rtv_request.empty()) { log("x2w-draw RTV manifest missing for %016llx", tr.key); return; @@ -530,8 +571,9 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: } if (!provided && (!cache_path(path, L"", tr.key, L".vs.cso") || FAILED(D3DReadFileToBlob(path, &tr.vs)))) return; if (!provided && (!cache_path(path, L"", tr.key, L".ps.cso") || FAILED(D3DReadFileToBlob(path, &tr.ps)))) return; - const HRESULT hr = x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), - static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size())); + const HRESULT hr = provided && x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE") ? E_FAIL : + x2w_startup::create_translated_root(device_of(the_device), static_cast(tr.uds.size()), + static_cast(tr.srvs.size()), tr.samplers, &tr.root, static_cast(tr.uavs.size()), fixed_manifest); if (FAILED(hr)) { log("x2w-draw root signature for %016llx failed 0x%08lx", tr.key, static_cast(hr)); return; @@ -545,18 +587,18 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: } #ifdef X2W_NATIVE_SHADERS -static bool try_native_graphics(Translation& tr) +static bool try_native_graphics(Translation& tr, bool variant = false) { wchar_t sdk[MAX_PATH], path[MAX_PATH]; const auto length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); - if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, L".a")) return false; + if (!length || length >= MAX_PATH || !cache_path(path, L"req_", tr.key, variant ? L".rtv" : L".a")) return false; try { const auto request = x2w::read_graphics_request(path); const auto cache = std::filesystem::path(path).parent_path(); bool frontend_hit = false; const auto pair = x2w::prepare_direct_graphics(request.a, request.b, cache, frontend_hit, - request.root, request.input_layout, request.pixel_entry); - auto manifest = x2w::format_graphics_runtime_manifest(pair); + request.root, request.input_layout, request.pixel_entry, true, request.rtv_formats); + auto manifest = x2w::format_graphics_runtime_manifest(pair, request.rtv_request); if (!manifest) throw std::runtime_error("unsupported graphics binding layout"); auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); auto stage = [&](const std::string& ir, const wchar_t* profile, bool& hit) { @@ -574,20 +616,24 @@ static bool try_native_graphics(Translation& tr) candidate.key = tr.key; candidate.manifest_retry = tr.manifest_retry; candidate.native_graphics_attempted = true; + if (!pair.input_layout.empty()) { + try { candidate.fixed_rectangle_ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } + catch (const x2w::UnsupportedComputeShader&) {} // Triangle lists and strips still use the original pair. + } candidate.vs = vs.Get(); candidate.ps = ps.Get(); - // Source-built first-draw fixture: fail after both stages have compiled and - // the local candidate holds both blobs. The later disk load stays valid. - if (GetEnvironmentVariableW(L"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", nullptr, 0)) - *manifest = "x2w-manifest 0\n"; - load_translation(candidate, {}, std::move(*manifest)); - const bool ready = candidate.state == 1; - log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", - tr.key, ready, frontend_hit, vs_hit, ps_hit); - if (!ready) return false; - vs.Detach(); - ps.Detach(); + if (x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_MANIFEST_FAILURE")) + manifest->append("\nx2w-manifest 999\n"); + load_translation(candidate, request.rtv_request, std::move(*manifest)); + if (candidate.state != 1) { + if (candidate.root) candidate.root->Release(); + throw std::runtime_error("native graphics manifest or root signature refused"); + } + candidate.vs = vs.Detach(); + candidate.ps = ps.Detach(); tr = std::move(candidate); + log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", + tr.key, tr.state == 1, frontend_hit, vs_hit, ps_hit); return true; } catch (const std::exception& error) { log("x2w-draw native graphics %016llx refused: %s", tr.key, error.what()); @@ -598,13 +644,15 @@ static bool try_native_graphics(Translation& tr) // draw_lock held. Both pipeline forms use the same request writer and shader cache. Translation* cached_translation(const void* a, std::size_t a_bytes, const void* b, std::size_t b_bytes, - const std::vector& root_blob, const std::string& layout = {}) + const std::vector& root_blob, const std::string& layout = {}, + const std::string& slot57_entry = {}) { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache (shader_cache::revision). const u64 seed = fnv_bytes(shader_cache::revision, sizeof(shader_cache::revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. if (!layout.empty()) key = fnv_bytes(layout.data(), layout.size(), key); + if (!slot57_entry.empty()) key = fnv_bytes(slot57_entry.data(), slot57_entry.size(), key); auto& entry = translation_by_key()[key]; if (!entry) { entry = new Translation; @@ -612,7 +660,8 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* // A legacy cache hit still needs source blobs for late RTV specialization. if (publish_shader_request(key, L".b", b, b_bytes) && publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size()))) + (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size())) && + (slot57_entry.empty() || publish_shader_request(key, L".ps57in", slot57_entry.data(), slot57_entry.size()))) publish_shader_request(key, L".a", a, a_bytes); load_translation(*entry); } @@ -664,6 +713,40 @@ LONG pointer_like_qwords(const std::vector& blob) SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } +#ifdef X2W_NATIVE_SHADERS +LONG compute_pack_prepared, compute_pack_refused, compute_pack_misses; +const x2w::ComputeFrontendPack* runtime_compute_pack() { + static const auto pack = []() -> std::optional { + wchar_t path[32768]; + const DWORD length = GetEnvironmentVariableW(L"X2W_NATIVE_COMPUTE_PACK", path, 32768); + if (!length || length >= 32768) return {}; + try { + auto loaded = x2w::ComputeFrontendPack::load(path, 0); + log("x2w-draw loaded %zu compute frontend pack records", loaded.size()); + return loaded; + } catch (const std::exception& error) { + log("x2w-draw compute frontend pack unavailable: %s", error.what()); + return {}; + } + }(); + return pack ? &*pack : nullptr; +} +x2w::FrozenComputeRequests& frozen_compute_requests() { + static x2w::FrozenComputeRequests requests([]() -> size_t { + char setting[16]{}; + auto n = GetEnvironmentVariableA("X2W_NATIVE_COMPUTE_REQUEST_CACHE_MIB", setting, sizeof(setting)); + if (!n || n >= sizeof(setting)) return 32u << 20; + unsigned mib = 0; + for (unsigned i = 0; i < n; ++i) { + if (setting[i] < '0' || setting[i] > '9') return 32u << 20; + mib = mib * 10 + unsigned(setting[i] - '0'); + if (mib > 256) return 32u << 20; + } + return size_t(mib) << 20; + }()); + return requests; +} +#endif // Returns the request key, or 0 when publishing is disabled or the description is refused. u64 publish_compute_request(const void* desc) @@ -726,7 +809,8 @@ u64 publish_compute_request(const void* desc) return publish_shader_request(key, ext, part.empty() ? &none : part.data(), part.size()); }; AcquireSRWLockExclusive(&compute_request_lock); - bool present = compute_keys_seen().count(key) != 0; + const bool already_seen = compute_keys_seen().count(key) != 0; + bool present = already_seen; bool written = present; if (!present) { present = cache_path(marker, L"req_", key, L".c67") && GetFileAttributesW(marker) != INVALID_FILE_ATTRIBUTES; @@ -736,6 +820,22 @@ u64 publish_compute_request(const void* desc) if (written) compute_keys_seen().insert(key); } ReleaseSRWLockExclusive(&compute_request_lock); +#ifdef X2W_NATIVE_SHADERS + if (written && !already_seen && GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0)) { + runtime_compute_pack(); // Read once at pipeline creation, outside the render lock. + try { + if (frozen_compute_requests().enabled()) { + auto bytes = [](const std::vector& part) { + return part.empty() ? std::string{} : std::string(reinterpret_cast(part.data()), part.size()); + }; + frozen_compute_requests().put({bytes(code), bytes(data), bytes(root_blob), bytes(fields), + bytes(state_a), bytes(state_b), key}); + } + } catch (const std::bad_alloc&) { + // The ready marker and all immutable parts remain available on disk. + } + } +#endif const LONG pointers = written && !present ? pointer_like_qwords(data) + pointer_like_qwords(state_a) + pointer_like_qwords(state_b) : 0; if (pointers) InterlockedAdd(&compute_blob_pointer_words, pointers); InterlockedIncrement(present ? &compute_requests_present : written ? &compute_requests_published : &compute_requests_failed); @@ -769,31 +869,41 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo ReleaseSRWLockShared(¬e_lock); } if (root_blob.empty()) return; - std::vector mesh, pixel; - const auto copy_stage = [&words](int field, bool required, std::vector& out) { - const auto* pointer = reinterpret_cast(words[field]); - const auto bytes = words[field + 1]; - if (!bytes) return !required && !pointer; - if (bytes > (1u << 20) || !x2w_local::readable(pointer, bytes)) return false; - out.resize(static_cast(bytes)); - return copy_title_bytes(out.data(), pointer, out.size()); - }; - if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return; - const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(shader_cache::mesh57_revision, - sizeof(shader_cache::mesh57_revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set written; x2w_startup::ExclusiveNoteLock guard(request_lock); - if (written.count(key)) return; + if (!info->fixed_ms) return; + const auto& mesh = *info->fixed_ms; + const std::vector empty; + const auto& pixel = info->fixed_ps ? *info->fixed_ps : empty; + const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(shader_cache::mesh57_revision, + sizeof(shader_cache::mesh57_revision) - 1)))); + if (x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + words[2] == info->state_a.size() && words[4] == info->state_b.size()) { + // Payload: request key, three uint32 lengths, normalized descriptor, state A, state B. + const auto desc = x2w_startup::normalize_mesh57_descriptor(info->desc); + const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(desc, key))); + std::vector packed(sizeof(key) + 3 * sizeof(UINT)); + const UINT lengths[]{static_cast(desc.size()), static_cast(info->state_a.size()), + static_cast(info->state_b.size())}; + std::memcpy(packed.data(), &key, sizeof(key)); + std::memcpy(packed.data() + sizeof(key), lengths, sizeof(lengths)); + for (const auto* bytes : {&desc, &info->state_a, &info->state_b}) + packed.insert(packed.end(), bytes->begin(), bytes->end()); + if (!publish_shader_request(variant, L".s57", packed.data(), packed.size())) + log("x2w-draw fixed mesh state %016llx could not be published", variant); + } const unsigned char none = 0; - if (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && + if (written.count(key) || (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - publish_shader_request(key, L".m57", mesh.data(), mesh.size())) { - written.insert(key); + publish_shader_request(key, L".m57", mesh.data(), mesh.size()))) { + const bool first = written.insert(key).second; static LONG logged; - if (first_calls(logged, 12)) + if (first && first_calls(logged, 12)) log("x2w-draw mesh request %016llx: slot57, MS %zu bytes, PS %zu bytes", key, mesh.size(), pixel.size()); + info->fixed_ms.reset(); + info->fixed_ps.reset(); } } @@ -1049,7 +1159,18 @@ BoundPipeline* translation_for(Wrapper* pipeline) const std::size_t a_bytes = static_cast(words[6]), b_bytes = static_cast(words[10]); if (!root_blob.empty() && a_bytes && b_bytes && a_bytes <= (1u << 20) && b_bytes <= (1u << 20) && x2w_local::readable(a, a_bytes) && x2w_local::readable(b, b_bytes)) { - result = cached_translation(a, a_bytes, b, b_bytes, root_blob); + std::string slot57_entry; +#ifdef X2W_NATIVE_SHADERS + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && + info->state_a.size() >= 0x60 && a_bytes >= 4 && b_bytes >= 4 && + std::memcmp(a, "DXBC", 4) && std::memcmp(b, "DXBC", 4)) { + // The fixed graphics state has SPI_PS_INPUT_ADDR and SPI_PS_IN_CONTROL + // in adjacent dwords. Capture both intact, including control flags. + slot57_entry = "PSI1"; + slot57_entry.append(reinterpret_cast(info->state_a.data() + 0x58), 8); + } +#endif + result = cached_translation(a, a_bytes, b, b_bytes, root_blob, {}, slot57_entry); } } by_pipeline[pipeline] = bound; @@ -1122,7 +1243,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) if (base->manifest_retry.due(GetTickCount64())) load_translation(*base); #ifdef X2W_NATIVE_SHADERS - if (base->manifest_retry.pending() && !base->native_graphics_attempted) { + if ((base->manifest_retry.pending() || native_shaders_only()) && !base->native_graphics_attempted) { base->native_graphics_attempted = true; try_native_graphics(*base); } @@ -1139,7 +1260,11 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) entry->key = key; load_translation(*entry, request); if (entry->state != 1) { - publish_shader_request(key, L".rtv", request.data(), request.size()); + const bool published = publish_shader_request(key, L".rtv", request.data(), request.size()); +#ifdef X2W_NATIVE_SHADERS + if (published && (entry->manifest_retry.pending() || native_shaders_only()) && + try_native_graphics(*entry, true)) return entry; +#endif log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); } } else if (entry->manifest_retry.due(GetTickCount64())) { @@ -1233,13 +1358,39 @@ bool effective_blend_state(const BoundPipeline& bound, const Translation& tr, UI bool prepare_translated_pso_desc(Translation& tr, bool indexed_rect, D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { desc.pRootSignature = tr.root; + desc.InputLayout = {tr.fixed_stream.data(), static_cast(tr.fixed_stream.size())}; desc.VS = {tr.vs->GetBufferPointer(), tr.vs->GetBufferSize()}; desc.PS = {tr.ps->GetBufferPointer(), tr.ps->GetBufferSize()}; if (!indexed_rect) return true; if (!tr.indexed_rect_geometry_attempted) { tr.indexed_rect_geometry_attempted = true; x2w_startup::ComPtr errors; - const HRESULT hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors); + HRESULT hr = E_NOTIMPL; + if (tr.fixed_stream.empty()) + hr = x2w_startup::compile_indexed_rect_geometry(tr.vs, tr.ps, &tr.indexed_rect_geometry, &errors); + else if (tr.fixed_rectangle_on_disk) { + wchar_t path[MAX_PATH]; + if (cache_path(path, L"", tr.key, L".gs.cso")) + hr = D3DReadFileToBlob(path, &tr.indexed_rect_geometry); + } +#ifdef X2W_NATIVE_SHADERS + else if (!tr.fixed_rectangle_ir.empty()) { + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const auto n = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (n && n < MAX_PATH && cache_path(path, L"", tr.key, L".gs.cso")) { + try { + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto result = compiler.compile(tr.fixed_rectangle_ir, L"gs_6_6", + std::filesystem::path(path).parent_path(), x2w::ShaderSourceFormat::dxil_ir); + hr = D3DCreateBlob(result.dxil.size(), &tr.indexed_rect_geometry); + if (SUCCEEDED(hr)) std::memcpy(tr.indexed_rect_geometry->GetBufferPointer(), + result.dxil.data(), result.dxil.size()); + } catch (const std::exception& e) { + log("x2w-draw %016llx native rectangle stage: %s", tr.key, e.what()); + } + } + } +#endif if (FAILED(hr)) log("x2w-draw %016llx: indexed rectangle geometry unavailable (0x%08lx) %s", tr.key, static_cast(hr), errors ? static_cast(errors->GetBufferPointer()) : ""); @@ -1939,7 +2090,13 @@ void draw_dump_after(Wrapper* self, ID3D12GraphicsCommandList* list, u64 key, UI Pass& pass = pass_of(self); const LONG wanted = draw_dump_frame(); const DrawDumpPixel pixel = draw_dump_pixel(); - if (!wanted || frame_number < wanted || frame_number > wanted + 1 || !pass.target0 || draw_dumps().full()) return; + if (!wanted || !pass.target0 || draw_dumps().full()) return; + if (frame_number < wanted || frame_number > wanted + 1) { + static const u64 sample_key = probe_key("X2W_DRAW_DUMP_SAMPLE_KEY"); + static LONG last{}; + if (!sample_key || key != sample_key || !pixel.enabled || frame_number < wanted || + frame_number % 24 || InterlockedExchange(&last, frame_number) == frame_number) return; + } const D3D12_RESOURCE_DESC desc = pass.target0->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || (!x2w_draw_bmp::supported(desc.Format) && !(pixel.enabled && x2w_startup::pixel_history_supported(desc.Format)))) return; @@ -1996,6 +2153,17 @@ void draw_dump_flush() { if (!draw_dump_frame()) return; auto completed = draw_dumps().take_completed(); + completed.erase(std::remove_if(completed.begin(), completed.end(), [](const DrawDump& d) { + if (d.rows || d.format != DXGI_FORMAT_UNKNOWN) return false; + void* data{}; + if (SUCCEEDED(d.buffer->Map(0, nullptr, &data))) { + const auto* w = static_cast(data); + log("x2w-argument-probe gpu frame=%ld event=%u key=%016llx data=%08x,%08x,%08x", d.frame, d.count, d.key, + w[0], d.count == 17 ? 0 : w[1], d.count == 17 ? 0 : w[2]); + D3D12_RANGE empty{}; d.buffer->Unmap(0,&empty); + } + return true; + }),completed.end()); if (completed.empty()) return; char folder[MAX_PATH] = "."; GetEnvironmentVariableA("X2W_DRAW_DUMP_DIR", folder, sizeof(folder)); @@ -2343,6 +2511,7 @@ bool title_input_snapshot_enabled() IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false, const char** why = nullptr, u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + UINT alignment = D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, bool allow_title_snapshot = false) { const auto refuse = [why](const char* reason) { @@ -2468,7 +2637,8 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor upload = props.Type == D3D12_HEAP_TYPE_UPLOAD; } if (!native) return refuse("an input buffer descriptor has a null address"); - if (offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) return refuse("an input buffer range is not 16-byte aligned in its resource"); + if (offset % alignment) return refuse(alignment == 4 ? "typed input range is not dword aligned" : + "an input buffer range is not 16-byte aligned in its resource"); if (!InterlockedCompareExchange(&owner->own().refs, 0, 0)) return refuse("an input buffer's resource is released"); const auto* info = resource_info(owner); if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) @@ -2479,6 +2649,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); + trace_compute_output_use(self, OutputUse::shader_gpu_read, "raw-SRV-range-resolved", owner, 0, offset, bytes); return {native, offset, bytes, stride, upload, input_source}; } @@ -2637,6 +2808,69 @@ bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding return true; } +// Keep the slot-zero view origin: the desktop input assembler applies StartVertex +// or the signed BaseVertex after reading the index, just as the fixed fetch prefix does. +bool fixed_vertex_view(Wrapper* self, const Pass& pass, const Translation& tr, bool indexed, UINT start, UINT count, + D3D12_VERTEX_BUFFER_VIEW& view, ID3D12Resource*& transition_resource) +{ + view = pass.vb[0]; + const u64 address = view.BufferLocation; + if (!indexed && count) { + unsigned attribute_end = 0; + for (const auto& e : tr.fixed_stream) { + const auto bytes = x2w_startup::typed_buffer_format_bytes(e.Format); + attribute_end = (std::max)(attribute_end, e.AlignedByteOffset + bytes); + } + if (view.StrideInBytes > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + const u64 end = (u64{start} + count - 1) * view.StrideInBytes + attribute_end; + view.SizeInBytes = static_cast((std::min)(u64{view.SizeInBytes}, end)); + } + const UINT bytes = view.SizeInBytes; + if (!address || !bytes || bytes > UINT64_MAX - address || + view.StrideInBytes > D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES) return false; + if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { + view.BufferLocation = allocation.gpu; + return view.BufferLocation != 0; + } + if (list_upload_range(self, address, 1).resource) return false; + const auto placed = placed_buffer_range(self->own().list_device, address, bytes); + if (placed.reject) return false; + ID3D12Resource* resource = nullptr; + u64 offset = 0; + if (placed.owner) { + const auto* info = resource_info(placed.owner); + if (!info || !InterlockedCompareExchange(&placed.owner->own().refs, 0, 0)) return false; + resource = static_cast(placed.owner->own().real); + offset = address - reinterpret_cast(placed.owner->own().title_memory); + if (!resource) return false; + if (!placed.alias && !list_copied_gpu_range(self, resource, offset, bytes)) { + // A non-aliased placement keeps the CPU stream in guest memory. Use the same + // recording-time snapshot as a shader-pulled VB. A partly copied GPU range + // cannot be represented by either single view without merging its sources. + for (const auto& range : pass.copied_gpu_ranges) + if (range.resource == resource && offset < range.offset + range.bytes && range.offset < offset + bytes) + return false; + resource = nullptr; + } else if (info->initial_state != D3D12_RESOURCE_STATE_COMMON) return false; + } else { + const auto alias = indirect_address_alias(self->own().list_device, address, bytes); + resource = alias.resource; + offset = alias.offset; + } + if (!resource) { + ID3D12Resource* chunk = nullptr; + if (bytes > (16u << 20) || readable_window(address, bytes) < bytes || + !frame_copy(self, address, bytes, &offset, &chunk) || !chunk) return false; + view.BufferLocation = chunk->GetGPUVirtualAddress() + offset; + return true; + } + if (!resource->GetGPUVirtualAddress() || offset > UINT64_MAX - resource->GetGPUVirtualAddress() || + !retain_with_recording(self, x2w_startup::ComPtr(resource))) return false; + view.BufferLocation = resource->GetGPUVirtualAddress() + offset; + transition_resource = resource; + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect, bool* used_fallback = nullptr) { @@ -2669,6 +2903,19 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ReleaseSRWLockExclusive(&draw_lock); return false; } + const bool fixed_stream = !tr->fixed_stream.empty(); + D3D12_VERTEX_BUFFER_VIEW fixed_view{}; + ID3D12Resource* fixed_resource = nullptr; + if (fixed_stream && (indirect || !fixed_vertex_view(self, pass, *tr, indexed, start, count, fixed_view, fixed_resource))) { + if (indirect) indirect->set_refusal("fixed vertex stream indirect arguments are unsupported", + indirect_refusal_code::unsupported_resource_or_entry); + static LONG refused; + if (first_calls(refused, 16)) + log("x2w-draw %016llx fixed vertex stream refused: rect=%u indirect=%u vb=%llx bytes=%u", + tr->key, rect, indirect != nullptr, pass.vb[0].BufferLocation, pass.vb[0].SizeInBytes); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (indirect) { if (!bound->guest_root || bound->guest_root != pass.root) { indirect->set_refusal("translated draw requires the guest pipeline's root signature", @@ -2719,7 +2966,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } } - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, indexed_rect) : nullptr; + const bool geometry_rect = indexed_rect || (rect && fixed_stream); + ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, geometry_rect) : nullptr; if (indirect && indexed_rect && !pipeline) { indirect->set_refusal("translated indexed rectangle geometry unavailable", indirect_refusal_code::indexed_rect_unavailable); @@ -2797,7 +3045,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } INT vertex_first = indexed ? 0 : static_cast(start); UINT vertex_count = indexed ? 0 : count; - if (indices_ok && !live_index_resource) { + if (indices_ok && !live_index_resource && !fixed_stream) { std::uint32_t low = ~0u, high = 0; for (UINT k = 0; k < count; ++k) { const std::uint32_t value = index_bytes == 2 ? reinterpret_cast(index_address)[k] @@ -2947,7 +3195,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI device_of(the_device)->CreateShaderResourceView(texture, texture && record.desc_bytes < 40 ? nullptr : &desc, dest); continue; } - if (indirect) { + if (indirect || srv.expected_stride) { IndirectBufferView view{}; if (srv.source == 1 && indexed) { const auto& vb = pass.vb[0]; @@ -2961,8 +3209,16 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } else if (entry_ok) { view = indirect_table_buffer(self, words); } - if (!view.resource || view.resource == indirect->argument || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) { - indirect->set_refusal( + if (srv.expected_stride && (view.stride != srv.expected_stride || view.bytes > UINT_MAX || + view.bytes % srv.expected_stride)) { + if (indirect) indirect->set_refusal("indexed raw SRV record stride mismatch", + indirect_refusal_code::incomplete_table_buffer); + log("x2w-draw indexed raw SRV %u needs stride %u, got %u", i, srv.expected_stride, view.stride); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + if (!view.resource || (indirect && view.resource == indirect->argument) || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) { + if (indirect) indirect->set_refusal( srv.source == 1 ? "translated indexed draw requires a complete GPU-backed vertex stream" : "translated draw requires a complete GPU-backed table buffer range", srv.source == 1 ? indirect_refusal_code::incomplete_vertex_stream @@ -3094,6 +3350,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ID3D12Resource* chunk = nullptr; const bool readable_range = address && bytes && readable_window(address, bytes) >= bytes; bool have = readable_range && frame_copy(self, address, bytes, &offset, &chunk); + if (have) trace_compute_output_use(self, OutputUse::shader_guest_read, "graphics-guest-upload-copied", nullptr, + address, 0, bytes, tr->key); // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. @@ -3198,6 +3456,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI } } list->SetPipelineState(pipeline); + if (fixed_stream) { + if (fixed_resource) require_state(self, fixed_resource, D3D12_RESOURCE_STATE_GENERIC_READ); + list->IASetVertexBuffers(0, 1, &fixed_view); + } // X2W_DEPTH_STATE: the reference of the decoded stencil test is list state in D3D12. It replaces the one a // preceding OMSetStencilRef set, for draws of this pipeline only when a depth view is bound. const bool scoped_stencil_ref = bound->depth_from_registers && bound->has_stencil_ref && @@ -3233,10 +3495,11 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI ID3D12Resource* index_chunk = nullptr; auto view = live_indices; if (live_index_resource) { - require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER | - (index_read_as_table ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | - D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE - : D3D12_RESOURCE_STATE_COMMON)); + if (live_index_resource != fixed_resource) + require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER | + (index_read_as_table ? D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + : D3D12_RESOURCE_STATE_COMMON)); } else if (indices_ok && frame_copy(self, index_address, index_total, &offset, &index_chunk) && index_chunk) { view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(index_total), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; @@ -3244,13 +3507,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (view.BufferLocation) { list->IASetIndexBuffer(&view); const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); - list->DrawIndexedInstanced(count, instances ? instances : 1, 0, 0, start_instance); + list->DrawIndexedInstanced(count, instances ? instances : 1, 0, fixed_stream ? base_vertex : 0, start_instance); red_producer_draw_after(self, red_samples); drawn = true; } } else { const auto red_samples = red_producer_draw_before(self, list, "translated-draw", tr->key); - list->DrawInstanced(rect ? count / 3 * 6 : count, instances ? instances : 1, 0, start_instance); + list->DrawInstanced(rect && !geometry_rect ? count / 3 * 6 : count, instances ? instances : 1, + fixed_stream ? start : 0, start_instance); red_producer_draw_after(self, red_samples); drawn = true; } @@ -3320,6 +3584,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* x2w_startup::ViewTable heap_records; UINT heap_entries = 0; x2w_startup::ViewHeapSelection view_heaps; + UINT bound_view_heaps = 0, visible_view_count = 0; if (count && count <= 4 && x2w_local::readable(heaps, std::size_t{count} * sizeof(*heaps))) { AcquireSRWLockShared(¬e_lock); for (UINT i = 0; i < count; ++i) { @@ -3328,7 +3593,10 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) view_heaps.note(heap.wrapper, heap.desktop_gpu != 0, heap.logical_count, heap.count); if (heap.wrapper == reinterpret_cast(heaps[i]) && - heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + heap.type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + { + ++bound_view_heaps; + visible_view_count = heap.desktop_gpu ? heap.logical_count : 0; heap_records = x2w_startup::resolve_view_table(heap.desktop_gpu, heap.title_cpu, heap.logical_count, heap.increment, heap.desktop_gpu); if (heap_records.address) heap_entries = heap.logical_count; @@ -3351,6 +3619,7 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* pass.title_samplers = source; pass.sampler_heap_wrapper = sampler_wrapper; pass.title_view_heap = heap_records; + pass.mesh_heap_slots = bound_view_heaps == 1 && heap_records.address ? visible_view_count : 0; pass.title_view_heap_entries = heap_entries; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 640ed4d2d..56dbe26c4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -22,6 +22,7 @@ #include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" +#include "startup_stubs/mesh57_profile.h" #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/present_readback_state.h" #include "startup_stubs/pixel_history.h" @@ -86,8 +87,13 @@ #include "native_compute_output.h" #ifdef X2W_NATIVE_SHADERS // d3d12_xs_shim only: the C++ shader compiler (startup_stubs/d3d12_compute_dispatch.inl) #include "gfx1013_compute_native.h" +#include "gfx1013_pixel.h" +#include "mesh_shader_pipeline.h" +#include +#include "native_buffer_store_view.h" #include "shader_dxil_compiler.h" #include "direct_compute_cache.h" +#include "frozen_compute_requests.h" #endif #include #include @@ -160,6 +166,7 @@ struct IndirectGraphicsPipeline { bool cached_depth_writes{}; const std::vector* guest_root_params{}; UINT cached_srv_root = UINT_MAX; + UINT constant_guest = UINT_MAX; // Single MS b0 mapped from this guest root under a deferred signature. }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -197,6 +204,7 @@ struct alignas(16) WrapperOwn { volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release. u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. + volatile LONG64 output_trace_recording; bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline bool builder_pipeline; // PipelineState: slot 62 created it for XboxBvhBuilder.dll (X2W_COMPUTE_BUILDER_GATE) @@ -1469,6 +1477,12 @@ struct DesktopAllocator { // Rectangle-list argument scratch of the recordings on this allocator. Retained with the recording, so until every // queue that ran it has passed its fence (the allocator is reused only when idle). std::vector> scratches; + // Immutable raw SRV table slices live until the allocator's last queue fence retires. + std::vector> mesh_view_pages; + UINT mesh_view_cursor = 0; + UINT mesh_heap_index = UINT_MAX; + ID3D12Resource* mesh_heap_buffer = nullptr; // Held in scratches until allocator retirement. + UINT64 mesh_heap_begin = 0, mesh_heap_size = 0; // Translated draws keep their immutable sampler tables for every submission of the recording. std::vector> sampler_snapshots; }; @@ -1526,25 +1540,41 @@ bool allocator_idle(const DesktopAllocator* allocator) // List slot 148 (Xbox order), allocate CPU-writable upload memory for this recording. void* __stdcall list_allocate_upload(Wrapper* self, UINT64 bytes, UINT64 alignment) { - if (!bytes || !alignment || (alignment & (alignment - 1)) || - bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) return nullptr; x2w_upload::Allocation allocation{}; + x2w_upload::UploadFailure failure{}; AcquireSRWLockExclusive(&allocator_lock); auto& state = self->own(); const auto found = list_recordings.find(self); - if (state.list_open && state.list_device && found != list_recordings.end() && found->second) { + const bool open = state.list_open, close_failed = state.list_close_failed; + const bool has_device = state.list_device != nullptr; + const bool recording = found != list_recordings.end() && found->second; + if (!bytes || !alignment || (alignment & (alignment - 1)) || + bytes > UINT64_MAX - (std::max)(alignment, UINT64{16})) { + failure = {"invalid request", E_INVALIDARG}; + } else if (!open || !has_device || !recording) { + failure = {!open ? "closed list" : !has_device ? "missing device" : "missing recording", E_UNEXPECTED}; + } else { try { if (!state.list_uploads) { auto arena = std::make_unique(); found->second->uploads.push_back(std::move(arena)); state.list_uploads = found->second->uploads.back().get(); } - allocation = state.list_uploads->allocate(device_of(state.list_device), bytes, alignment); + allocation = state.list_uploads->allocate(device_of(state.list_device), bytes, alignment, &failure); } catch (const std::bad_alloc&) { - // Refuse the allocation without invalidating any range already recorded. + failure = {"CPU allocation", E_OUTOFMEMORY}; } } ReleaseSRWLockExclusive(&allocator_lock); + if (!allocation.cpu) { + static LONG invalid_failures, state_failures, page_failures, cpu_failures; + auto& failures = failure.requested_page ? page_failures : failure.hr == E_INVALIDARG ? invalid_failures : + failure.hr == E_OUTOFMEMORY ? cpu_failures : state_failures; + if (first_calls(failures, 12)) + log("x2w-render slot148 list=%p stage=%s hr=0x%08lx bytes=%llu alignment=%llu pageBytes=%llu open=%d closeFailed=%d device=%d recording=%d", + static_cast(self), failure.stage, static_cast(failure.hr), bytes, alignment, + failure.requested_page, open, close_failed, has_device, recording); + } return reinterpret_cast(allocation.cpu); } @@ -1637,11 +1667,11 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_distinct_rect_scratch(void* firs return distinct; } -x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 bytes) +x2w_upload::Allocation list_upload_range(Wrapper* self, UINT64 address, UINT64 bytes, bool remaining = false) { AcquireSRWLockShared(&allocator_lock); const auto& state = self->own(); - const auto allocation = state.list_open && state.list_uploads ? state.list_uploads->range(address, bytes) : x2w_upload::Allocation{}; + const auto allocation = state.list_open && state.list_uploads ? state.list_uploads->range(address, bytes, remaining) : x2w_upload::Allocation{}; ReleaseSRWLockShared(&allocator_lock); return allocation; } @@ -1703,6 +1733,8 @@ HRESULT __stdcall allocator_reset(Wrapper* self) next->uploads.clear(); next->indexed_validation.clear(); next->scratches.clear(); + next->mesh_view_pages.clear(); + next->mesh_view_cursor = 0; next->sampler_snapshots.clear(); next->submits.clear(); next->close_failed = false; @@ -1883,6 +1915,8 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) spare->uploads.clear(); spare->indexed_validation.clear(); spare->scratches.clear(); + spare->mesh_view_pages.clear(); + spare->mesh_view_cursor = 0; spare->sampler_snapshots.clear(); spare->submits.clear(); spare->close_failed = false; @@ -1930,6 +1964,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) released_upload_chunks.erase(self); state.list_uploads = nullptr; state.list_scratch = nullptr; + InterlockedExchange64(&state.output_trace_recording, 0); state.list_ready = false; state.list_open = true; } @@ -1941,7 +1976,8 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) discard_address_uploads(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); - if (draw_dump_frame()) draw_dumps().discard(previous); + if (draw_dump_frame()) if (auto lost = draw_dumps().discard(previous)) + log("scene argument readbacks discarded on reset: list=%p mask=%08x", previous, lost); discard_red_producer(previous); } InterlockedIncrement(SUCCEEDED(hr) ? &render_resets : &render_reset_failures); @@ -1979,10 +2015,11 @@ HRESULT __stdcall list_close(Wrapper* self) discard_address_uploads(list); discard_mesh_lease_recording(list); retire_drop_recording(self); - if (draw_dump_frame()) draw_dumps().discard(list); + if (draw_dump_frame()) if (auto lost = draw_dumps().discard(list)) + log("scene argument readbacks discarded on failed Close: list=%p mask=%08x hr=%08lx", list, lost, hr); discard_red_producer(list); static LONG failures; - if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx", static_cast(hr)); + if (first_calls(failures, 6)) log("x2w-render list Close failed 0x%08lx list=%p", static_cast(hr), static_cast(self)); } return hr; } @@ -2536,7 +2573,7 @@ std::size_t desktop_stream_size(UINT type) // Converts the supported stream layout to desktop form and creates the pipeline. ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, char* why, std::size_t why_size, bool& compute, IndirectGraphicsPipeline& graphics, ID3D12RootSignature*& pipeline_root, - ID3D12RootSignature* cached_root = nullptr) + ID3D12RootSignature* cached_root = nullptr, bool reviewed_stencil = false) { const bool cached_mesh = cached_root != nullptr; const std::size_t bytes = desc->SizeInBytes; @@ -2655,7 +2692,11 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES std::memcpy(&state, stream + offset + sizeof(UINT), size); depth_enabled = state.DepthEnable; depth_writes = depth_enabled && state.DepthWriteMask != D3D12_DEPTH_WRITE_MASK_ZERO; - untracked_depth_state = state.StencilEnable || state.DepthBoundsTestEnable; + untracked_depth_state = (state.StencilEnable && !reviewed_stencil) || state.DepthBoundsTestEnable; + if (reviewed_stencil && state.StencilEnable) { + depth_enabled = true; + depth_writes |= state.StencilWriteMask != 0; + } } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC) { samples = *reinterpret_cast(stream + offset + 4); } @@ -2905,6 +2946,7 @@ struct Pass { UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler + UINT mesh_heap_slots = 0; // Logical descriptor count of a unique visible CBV/SRV/UAV source heap. u64 source_view_heap = 0; x2w_startup::ViewTable title_view_heap; // slot 32: the title memory of the list's view heap (heap records) UINT title_view_heap_entries = 0; // logical descriptor count of title_view_heap (indices 0..count-1) @@ -3539,6 +3581,7 @@ HRESULT __stdcall device_create_query_heap(Wrapper* self, const D3D12_QUERY_HEAP // Slot-61 calls by outcome and signature kind (IndirectCommand; none counts placeholder and unknown // signatures), reported with the render totals. 64-bit and never reset, so they neither wrap nor stall. +const char* bind_mesh57_buffers(Wrapper*, Pass&, ID3D12GraphicsCommandList*, ID3D12Resource*); enum { indirect_forwarded, indirect_graphics_pipeline, indirect_compute_pipeline, indirect_placeholder, indirect_other, indirect_outcomes }; volatile LONG64 indirect_calls[indirect_outcomes][5]; @@ -3566,7 +3609,73 @@ struct TranslatedDispatch { }; const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch); u64 known_pipeline_key(Wrapper* pipeline); - +// Each probe is keyed explicitly so independent captures can select their own pipelines. +u64 probe_key(const char* variable) { + char value[24]{}; + const auto n = GetEnvironmentVariableA(variable, value, sizeof(value)); + if (!n || n >= sizeof(value) || std::strspn(value, "0123456789abcdefABCDEF") != n || n > 16) return 0; + return std::strtoull(value, nullptr, 16); +} + +void scene_argument_probe(Wrapper* self, unsigned event, void* argument = nullptr, u64 offset = 0, const char* refused = nullptr); + +// Observe subsequent uses of the first rejected copied UAV owner per compute key. +// Each range is immutable once published; logging is bounded per event type and owner. +enum class OutputUse : unsigned { indirect_argument, indirect_count, indirect_recorded, copy_source, copy_destination, + copy_read_recorded, copy_write_recorded, shader_guest_read, shader_gpu_read, map, unmap }; +bool trace_compute_outputs() { + static const bool enabled = x2w_local::env_on("X2W_D3D12_COMPUTE_OUTPUT_TRACE"); + return enabled; +} +struct TracedComputeOutput { + u64 key{}, owner{}, base{}, length{}; + volatile LONG events{}; +}; +TracedComputeOutput traced_compute_outputs[32]; +volatile LONG traced_compute_output_count{}; +bool trace_copied_compute_output(u64 key, u64 owner, u64 base, u64 offset, u64 bytes) { + // Called under draw_lock. Only publish complete, representable guest intervals. + if (!trace_compute_outputs() || !base || !bytes || offset > UINT64_MAX - base || + bytes > UINT64_MAX - (base + offset)) return false; + const LONG count = InterlockedCompareExchange(&traced_compute_output_count, 0, 0); + for (LONG i = 0; i < count; ++i) + if (traced_compute_outputs[i].key == key) return false; + if (count == 32) return false; + auto& entry = traced_compute_outputs[count]; + entry.key = key; entry.owner = owner; entry.base = base + offset; entry.length = bytes; + InterlockedIncrement(&traced_compute_output_count); + return true; +} +void trace_compute_output_use(Wrapper* list, OutputUse use, const char* event, const void* object, u64 address, + u64 offset, u64 bytes, u64 pipeline = 0) { + if (!trace_compute_outputs()) return; + const LONG count = InterlockedCompareExchange(&traced_compute_output_count, 0, 0); + if (!count) return; + const Wrapper* w = object ? as_wrapper(object) : nullptr; + if (w && w->own().kind == resource_kind) address = reinterpret_cast(w->own().title_memory); + if (!address || offset > UINT64_MAX - address || !bytes) return; + const u64 first = address + offset; + for (LONG i = 0; i < count; ++i) { + auto& item = traced_compute_outputs[i]; + if (first <= item.base ? item.base - first >= bytes : first - item.base >= item.length) continue; + const bool same = reinterpret_cast(object) == item.owner; + const LONG flag = 1L << (2 * static_cast(use) + same); + if ((InterlockedCompareExchange(&item.events, 0, 0) & flag) || (InterlockedOr(&item.events, flag) & flag)) continue; + LONG64 recording_id = 0; + if (list) { + static volatile LONG64 serial; + recording_id = InterlockedCompareExchange64(&list->own().output_trace_recording, 0, 0); + if (!recording_id) { + const auto next = InterlockedIncrement64(&serial); + const auto seen = InterlockedCompareExchange64(&list->own().output_trace_recording, next, 0); + recording_id = seen ? seen : next; + } + } + log("x2w-compute-output-use producer=%016llx use=%s list=%p recording=%lld consumer=%016llx owner=%p same=%u " + "guest-first=0x%llx bytes=%llu watched=0x%llx+%llu", + item.key, event, list, recording_id, pipeline, object, same, first, bytes, item.base, item.length); + } +} namespace indirect_other_refusal_code { constexpr const char* list_closed = "list_closed"; constexpr const char* invalid_list_type = "invalid_list_type"; @@ -3629,9 +3738,16 @@ LONG root_srv_copies_skipped, root_srv_copies_made; void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { + scene_argument_probe(self, 27, argument, offset); // Every refusal is counted under the signature's kind, including those before the signature is checked. Wrapper* sig = as_wrapper(signature); IndirectCommand kind = sig && sig->own().kind == command_signature_kind ? sig->own().indirect_command : IndirectCommand::none; + if (trace_compute_outputs()) { + const u64 span = sig && sig->own().kind == command_signature_kind ? u64{count} * sig->own().indirect_bytes : 0; + trace_compute_output_use(self, OutputUse::indirect_argument, "indirect-argument-attempt", argument, 0, offset, span); + if (count_buffer) + trace_compute_output_use(self, OutputUse::indirect_count, "indirect-count-attempt", count_buffer, 0, count_offset, 4); + } Wrapper* refusal_pipeline = nullptr; u64 trace_call = 0; const auto refuse = [&kind, &refusal_pipeline, &trace_call](const char* reason, int outcome = indirect_other, @@ -3676,6 +3792,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool mesh = command == IndirectCommand::dispatch_mesh; const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); + if (mesh && pass.pipeline && pass.pipeline->own().real && x2w_local::env_on("X2W_MESH57_CAPTURE_STATE") && + (pass.requested_mesh_pipeline != pass.pipeline || pass.requested_mesh_root != pass.root)) { + pass.requested_mesh_pipeline = pass.pipeline; + pass.requested_mesh_root = pass.root; + request_slot57_mesh(pass.pipeline, pass.root); + } refusal_pipeline = pass.pipeline; // A slot 62 builder pipeline is tracked by the wrapper itself, not by a slot 67 request key. // Gate its indirect Dispatch before the signature and argument checks so a partial builder @@ -3694,7 +3816,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || - pass.indirect_graphics.root != pass.graphics_root || pass.indirect_graphics.mesh != mesh))) { + (pass.indirect_graphics.constant_guest == UINT_MAX && pass.indirect_graphics.root != pass.graphics_root) || + pass.indirect_graphics.mesh != mesh))) { // A console pipeline (no desktop pipeline) used only here still gets the request a direct draw writes; // nothing is drawn. if (mesh && type == D3D12_COMMAND_LIST_TYPE_DIRECT && pass.pipeline && !pass.pipeline->own().real && @@ -3723,10 +3846,10 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, !std::equal(pso.cached_targets, pso.cached_targets + pso.cached_target_count, pass.target_formats)) return refuse("cached mesh requires matching color and depth attachments, viewport and scissor", indirect_other, indirect_other_refusal_code::cached_mesh_attachments); - if (!pass.root || pass.root != pso.guest_root_params || pass.root_heap_flags) - return refuse("cached mesh requires a recorded root without heap indexing", indirect_graphics_pipeline); + if (!pass.root || pass.root != pso.guest_root_params || (pass.root_heap_flags != 0) != (pso.constant_guest != UINT_MAX)) + return refuse("cached mesh creation root or indexing mode differs", indirect_graphics_pipeline); for (std::size_t i = 0; i < pass.root->size(); ++i) { - if (i == pso.cached_srv_root) continue; + if (i == pso.cached_srv_root || (pso.constant_guest != UINT_MAX && i != pso.constant_guest)) continue; const auto mask = (1u << (*pass.root)[i].constants_count) - 1; if ((pass.constant_words_bound[i] & mask) != mask) return refuse("cached mesh root constants are incomplete", indirect_graphics_pipeline); @@ -3900,8 +4023,17 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } if (graphics) { list->SetPipelineState(static_cast(pass.pipeline->own().real)); - list->SetGraphicsRootSignature(pass.graphics_root); - if (pass.indirect_graphics.cached_mesh) { + const auto& pso = pass.indirect_graphics; + if (pso.constant_guest == UINT_MAX) list->SetGraphicsRootSignature(pass.graphics_root); + if (pso.constant_guest != UINT_MAX) { + const UINT guest = pso.constant_guest; + UINT words[8]{}; + const auto count = (*pass.root)[guest].constants_count; + std::copy_n(pass.constants[guest], count, words); + if (const char* why = bind_mesh57_buffers(self, pass, list, resource)) + return refuse(why, indirect_graphics_pipeline); + list->SetGraphicsRoot32BitConstants(0, (count + 3) & ~3u, words, 0); + } else if (pass.indirect_graphics.cached_mesh) { const UINT srv = pass.indirect_graphics.cached_srv_root; if (srv != UINT_MAX) list->SetGraphicsRootShaderResourceView(srv, inputs[0].resource->GetGPUVirtualAddress() + inputs[0].offset); @@ -3968,6 +4100,9 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const auto red_samples = graphics ? red_producer_draw_before(self, list, "indirect-draw", 0) : RedDrawSamples{}; list->ExecuteIndirect(static_cast(sig->own().real), count, draw_arguments, draw_offset, counts, counts ? count_offset : 0); + if (trace_compute_outputs()) + trace_compute_output_use(self, OutputUse::indirect_recorded, "indirect-recorded", argument, 0, offset, span, + known_pipeline_key(refusal_pipeline)); red_producer_draw_after(self, red_samples); if (trace_call) log("x2w-mesh86-trace call=%llu stage=record outcome=recorded", trace_call); if (scratch) x2w_startup::RectIndirectArguments::finish(list, scratch); @@ -4511,7 +4646,9 @@ void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) if (list && pass.pipeline && pass.pipeline->own().builder_pipeline && !compute_builder_dispatch_allowed(self, "Dispatch")) return; if (list && pass.pipeline && pass.pipeline->own().compute_request_key) { - record_translated_dispatch(self, {{x, y, z}}); + scene_argument_probe(self, 17); + const char* refused = record_translated_dispatch(self, {{x, y, z}}); + scene_argument_probe(self, 22, nullptr, 0, refused); return; } x2w_startup::ListDispatch request; @@ -4655,6 +4792,12 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) queue->ExecuteCommandLists(ready_count, native_lists.data()); } }); + if (trace_compute_outputs()) { + for (auto* recorded : wrappers) { + const auto id = InterlockedExchange64(&recorded->own().output_trace_recording, 0); + if (id) log("x2w-compute-output-submit list=%p recording=%lld queue=%p", recorded, id, self); + } + } retire_address_uploads(queue, native_lists); note_submits(queue, wrappers); retire_note_submission(queue, wrappers); @@ -4854,6 +4997,9 @@ void* __stdcall queue_get_desc(void* a, void* b) // pointer is that memory (subresource offsets inside it are not modeled). Others map on desktop. HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANGE* range, void** data) { + if (trace_compute_outputs() && (!range || range->End > range->Begin)) + trace_compute_output_use(nullptr, OutputUse::map, "map-guest-read-request", self, 0, range ? range->Begin : 0, + range ? range->End - range->Begin : (resource_info(self) ? resource_info(self)->console.Width : 0)); HRESULT hr = S_OK; void* mapped = self->own().title_memory; if (!mapped) hr = static_cast(self->own().real)->Map(subresource, range, &mapped); @@ -4867,6 +5013,9 @@ HRESULT __stdcall resource_map(Wrapper* self, UINT subresource, const D3D12_RANG } void __stdcall resource_unmap(Wrapper* self, UINT subresource, const D3D12_RANGE* range) { + if (trace_compute_outputs() && (!range || range->End > range->Begin)) + trace_compute_output_use(nullptr, OutputUse::unmap, "unmap-guest-written-range", self, 0, range ? range->Begin : 0, + range ? range->End - range->Begin : (resource_info(self) ? resource_info(self)->console.Width : 0)); if (!self->own().title_memory) static_cast(self->own().real)->Unmap(subresource, range); } @@ -6925,6 +7074,7 @@ bool is_fixed_mesh57_descriptor(const void* desc) ((!words[5] && !words[6]) || readable_stage(words[5], words[6])); } +#include "startup_stubs/native_mesh57.inl" // Device slots 57 and 67 (Xbox order): (desc*, riid, ppv) with the pipeline // IID. These normally return a placeholder. In render mode slot 67 also // publishes a compute translation request (d3d12_draw.inl). @@ -6957,11 +7107,30 @@ HRESULT __stdcall device_create_pipeline_placeholder(Wrapper*, const void* desc, if constexpr (N == 67) { // A translated Dispatch finds its program by this key (d3d12_compute_dispatch.inl). if (const u64 key = publish_compute_request(desc)) { + static const u64 input_key = probe_key("X2W_ARGUMENT_INPUT_KEY"); + static const u64 output_key = probe_key("X2W_ARGUMENT_OUTPUT_KEY"); + if (x2w_local::env_on("X2W_SCENE_ARGUMENT_PROBE") && (key == input_key || key == output_key)) { + u64 p[12]{}; + if (copy_title_bytes(p, desc, sizeof(p))) { + for (const auto index : {1,3,7,9,10}) { + unsigned char block[256]{}; + const auto bytes = index < 9 ? (std::min)(u64{sizeof(block)},p[index+1]) : u64{sizeof(block)}; + if (bytes && copy_title_bytes(block,reinterpret_cast(p[index]),bytes)) { + char hex[3*sizeof(block)+1]{}; + hex_text(block,bytes,hex,sizeof(hex)); + log("x2w-argument-probe create key=%016llx part=%d bytes=%llu data=%s",key,index,bytes,hex); + } + } + } + } static_cast(*out)->own().compute_request_key = key; static_cast(*out)->own().compute_request_root = as_wrapper(*static_cast(desc)); } } note_pipeline(static_cast(*out), N, nullptr, desc, 0x300); +#ifdef X2W_NATIVE_SHADERS + if constexpr (N == 57) if (render_mode()) prepare_native_mesh57(static_cast(*out)); +#endif return S_OK; } @@ -7449,6 +7618,16 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa // The null-binding total and its causes change together under draw_lock (draw_translated holds it), so they are copied there. LONG null_total = 0, null_causes[x2w_local::null_cause_count] = {}; if (render_mode() && frame % 300 == 0) { +#ifdef X2W_NATIVE_SHADERS + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0)) { + const auto stats = frozen_compute_requests().stats(); + if (compute_pack_prepared || compute_pack_refused || compute_pack_misses) + log("x2w-render compute frontend pack: prepared %ld, unsupported %ld, misses %ld", + compute_pack_prepared, compute_pack_refused, compute_pack_misses); + log("x2w-render compute request snapshots: hits %llu, misses %llu, evicted %llu, retained %zu bytes in %zu entries", + stats.hits, stats.misses, stats.evicted, stats.bytes, stats.entries); + } +#endif AcquireSRWLockExclusive(&draw_lock); null_total = null_bindings; for (int c = 0; c < x2w_local::null_cause_count; ++c) null_causes[c] = null_by_cause[c]; diff --git a/src/startup_stubs/draw_dump_tracking.h b/src/startup_stubs/draw_dump_tracking.h index 488537d83..ae71c47b4 100644 --- a/src/startup_stubs/draw_dump_tracking.h +++ b/src/startup_stubs/draw_dump_tracking.h @@ -38,7 +38,10 @@ class DrawReadbacks { Microsoft::WRL::ComPtr fence; DrawDump dump; }; - static constexpr unsigned limit = 48; + static unsigned limit() { + static const unsigned n = GetEnvironmentVariableW(L"X2W_SCENE_ARGUMENT_PROBE", nullptr, 0) ? 768 : 48; + return n; + } std::mutex mutex_; std::vector entries_; unsigned consumed_ = 0; @@ -48,13 +51,13 @@ class DrawReadbacks { bool full() { std::lock_guard lock(mutex_); - return entries_.size() + consumed_ >= limit; + return entries_.size() + consumed_ >= limit(); } bool record(ID3D12CommandList* list, DrawDump dump) { std::lock_guard lock(mutex_); - if (entries_.size() + consumed_ >= limit) return false; + if (entries_.size() + consumed_ >= limit()) return false; dump.index = ++sequence_; entries_.push_back({list, {}, std::move(dump)}); return true; @@ -67,7 +70,7 @@ class DrawReadbacks { bool record_for_test(Microsoft::WRL::ComPtr buffer, Microsoft::WRL::ComPtr fence) { std::lock_guard lock(mutex_); - if (entries_.size() + consumed_ >= limit) return false; + if (entries_.size() + consumed_ >= limit()) return false; DrawDump dump; dump.buffer = std::move(buffer); dump.index = ++sequence_; @@ -88,11 +91,17 @@ class DrawReadbacks { return nullptr; } - void discard(ID3D12CommandList* list) + unsigned discard(ID3D12CommandList* list) { std::lock_guard lock(mutex_); + unsigned probes = 0; entries_.erase(std::remove_if(entries_.begin(), entries_.end(), - [list](const Entry& e) { return e.recording == list; }), entries_.end()); + [&](const Entry& e) { + if (!list || e.recording != list) return false; + if (!e.dump.rows && e.dump.count < 32) probes |= 1u << e.dump.count; + return true; + }), entries_.end()); + return probes; } HRESULT execute(ID3D12CommandQueue* queue, UINT count, ID3D12CommandList* const* lists) diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 6538a5cd0..a755eec82 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -218,6 +218,8 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti if (!self->own().list_open) return; const CopyEndpoint to = copy_endpoint(destination); const CopyEndpoint from = copy_endpoint(source); + trace_compute_output_use(self, OutputUse::copy_source, "copy-source-attempt", from.wrapper, 0, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_destination, "copy-destination-attempt", to.wrapper, 0, destination_offset, bytes); D3D12_RESOURCE_DESC to_desc{}, from_desc{}; if (to.resource) to_desc = to.resource->GetDesc(); if (from.resource) from_desc = from.resource->GetDesc(); @@ -234,6 +236,8 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real) ->CopyBufferRegion(to.resource, destination_offset, from.resource, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_read_recorded, "copy-read-recorded", from.wrapper, 0, source_offset, bytes); + trace_compute_output_use(self, OutputUse::copy_write_recorded, "copy-write-recorded", to.wrapper, 0, destination_offset, bytes); if (mesh_xmem_tracking()) { D3D12_HEAP_TYPE source_heap; const bool upload = fixed_heap(from.resource, source_heap) && source_heap == D3D12_HEAP_TYPE_UPLOAD; diff --git a/src/startup_stubs/list_upload_pages.h b/src/startup_stubs/list_upload_pages.h index 0892816c1..d435e4c69 100644 --- a/src/startup_stubs/list_upload_pages.h +++ b/src/startup_stubs/list_upload_pages.h @@ -14,7 +14,12 @@ struct Page { unsigned char* cpu = nullptr; UINT64 gpu = 0, size = 0, cursor = 0; }; -inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page) { +struct UploadFailure { + const char* stage = nullptr; + HRESULT hr = S_OK; + UINT64 requested_page = 0; +}; +inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page, UploadFailure* failure = nullptr) { D3D12_HEAP_PROPERTIES heap{}; heap.Type = D3D12_HEAP_TYPE_UPLOAD; heap.CreationNodeMask = heap.VisibleNodeMask = 1; @@ -25,16 +30,26 @@ inline HRESULT make_page(ID3D12Device* device, UINT64 bytes, Page& page) { desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&page.resource)); - if (FAILED(hr)) return hr; + if (FAILED(hr)) { + if (failure) *failure = {"CreateCommittedResource", hr, bytes}; + return hr; + } x2w_budget::committed(device, page.resource.Get(), D3D12_HEAP_TYPE_UPLOAD); D3D12_RANGE no_reads{}; void* mapped = nullptr; hr = page.resource->Map(0, &no_reads, &mapped); - if (FAILED(hr)) return hr; + if (FAILED(hr)) { + if (failure) *failure = {"Map", hr, bytes}; + return hr; + } page.cpu = static_cast(mapped); page.gpu = page.resource->GetGPUVirtualAddress(); page.size = bytes; - return page.cpu && page.gpu ? S_OK : E_FAIL; + if (!page.cpu || !page.gpu) { + if (failure) *failure = {page.cpu ? "null GPU address" : "null mapped address", E_FAIL, bytes}; + return E_FAIL; + } + return S_OK; } struct Allocation { uintptr_t cpu; UINT64 gpu, bytes; ID3D12Resource* resource; UINT64 offset; }; struct Arena { @@ -44,23 +59,29 @@ struct Arena { // The caller must retire all recordings and GPU submissions before releasing their pages. void reset() { allocations.clear(); pages.clear(); } - Allocation range(UINT64 cpu, UINT64 bytes) const { + Allocation range(UINT64 cpu, UINT64 bytes, bool remaining = false) const { if (!bytes) return {}; for (auto it = allocations.rbegin(); it != allocations.rend(); ++it) { if (cpu < it->cpu) continue; UINT64 offset = cpu - it->cpu; if (offset < it->bytes && bytes <= it->bytes - offset) - return {static_cast(cpu), it->gpu + offset, bytes, it->resource, it->offset + offset}; + return {static_cast(cpu), it->gpu + offset, remaining ? it->bytes - offset : bytes, it->resource, it->offset + offset}; } return {}; } UINT64 translate(UINT64 cpu, UINT64 bytes) const { return range(cpu, bytes).gpu; } - Allocation allocate(ID3D12Device* device, UINT64 bytes, UINT64 alignment) { - if (!device || !bytes || !alignment || (alignment & (alignment - 1))) return {}; + Allocation allocate(ID3D12Device* device, UINT64 bytes, UINT64 alignment, UploadFailure* failure = nullptr) { + if (!device || !bytes || !alignment || (alignment & (alignment - 1))) { + if (failure) *failure = {"invalid request", E_INVALIDARG}; + return {}; + } alignment = (std::max)(alignment, UINT64{16}); - if (bytes > UINT64_MAX - alignment) return {}; + if (bytes > UINT64_MAX - alignment) { + if (failure) *failure = {"size overflow", E_INVALIDARG}; + return {}; + } auto take = [&](Page& page) -> Allocation { const auto base = reinterpret_cast(page.cpu); const UINT64 mask = alignment - 1; @@ -79,10 +100,14 @@ struct Arena { if (a.cpu) return a; } auto page = std::make_unique(); - if (FAILED(make_page(device, (std::max)(UINT64{65536}, bytes + alignment - 1), *page))) return {}; + const auto page_bytes = (std::max)(UINT64{65536}, bytes + alignment - 1); + if (FAILED(make_page(device, page_bytes, *page, failure))) return {}; pages.push_back(std::move(page)); Allocation a = take(*pages.back()); - if (!a.cpu) pages.pop_back(); + if (!a.cpu) { + pages.pop_back(); + if (failure) *failure = {"new page alignment", E_FAIL, page_bytes}; + } return a; } }; diff --git a/src/startup_stubs/mesh57_profile.h b/src/startup_stubs/mesh57_profile.h new file mode 100644 index 000000000..1250e1acf --- /dev/null +++ b/src/startup_stubs/mesh57_profile.h @@ -0,0 +1,51 @@ +#pragma once +#include "mesh_pixel_heap.h" +#include +#include +#include +#include + +namespace x2w_startup +{ +inline std::vector normalize_mesh57_descriptor(std::vector desc) +{ + if (desc.size() < 15 * sizeof(std::uint64_t)) + return {}; + for (const auto index : {0, 1, 3, 5, 13}) + std::memset(desc.data() + index * sizeof(std::uint64_t), 0, sizeof(std::uint64_t)); + return desc; +} +// A reviewed fixed-state/entry record. The header is followed by the exact normalized fixed +// descriptor, the two register blocks, creation root blob, guest MS and guest PS, in this order. +// Only the five explicitly captured pointer fields are normalized in the descriptor. +struct Mesh57Profile { + char magic[8]; + UINT lengths[6]; + UINT threads, vertices, primitives, topology, group_stride, wave_size; + D3D12_BLEND_DESC blend; + D3D12_RASTERIZER_DESC rasterizer; + D3D12_DEPTH_STENCIL_DESC depth; + D3D12_RT_FORMAT_ARRAY targets; + DXGI_FORMAT depth_format; + DXGI_SAMPLE_DESC samples; + UINT sample_mask; +}; +static_assert(sizeof(Mesh57Profile) == 532, "update the offline mesh57 profile reader when the ABI changes"); +// Version 2 stores this immediately after Mesh57Profile, before the six byte spans. +struct Mesh57PixelEntry { + UINT enable, address, wave_size; +}; +// Version 3 adds one reviewed MS entry mapping after the version 2 pixel entry. +struct Mesh57ConstantEntry { + UINT sgpr, root_parameter, count; +}; +// Version 4 adds a count followed by this many MS table/root-address SGPR mappings. +// Version 5 then stores the physical resource-heap SGPR; selector and view class come from the MS. +struct Mesh57ViewEntry { + UINT sgpr, root_parameter, root_address; +}; +struct Mesh57BufferRead { + UINT root_parameter, offset, minimum_bytes; + bool root_address; +}; +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl new file mode 100644 index 000000000..b8455b82d --- /dev/null +++ b/src/startup_stubs/native_mesh57.inl @@ -0,0 +1,450 @@ +// Included after both the native graphics compiler and the desktop stream validator. +// Resolve every SRV before recording barriers or a descriptor table. A guest root address +// has no descriptor length; use the remaining proven GPU allocation, including for indexed reads. +const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommandList* list, ID3D12Resource* arguments) +{ + const auto* info = pipeline_info(pass.pipeline); + if (!info) return "missing MS creation metadata"; + const auto& reads = info->mesh57_reads; + const auto& spans = info->mesh57_pixel_spans; + if (reads.empty() && spans.empty()) { + list->SetGraphicsRootSignature(pass.indirect_graphics.root); + return nullptr; + } + std::array views{}; + if (reads.size() > views.size()) return "too many MS buffer reads"; + for (size_t i = 0; i < reads.size(); ++i) { + const auto& read = reads[i]; + auto& view = views[i]; + if (read.root_address) { + const auto address = pass.root_address[read.root_parameter]; + if (!address) return "missing MS root SRV address"; + if (auto range = list_upload_range(self, address, read.minimum_bytes, true); range.resource) { + view = {range.resource, range.offset, range.bytes, 0, true}; + } else { + const auto placed = placed_buffer_range(self->own().list_device, address, read.minimum_bytes); + if (placed.reject || !placed.owner || !placed.owner->own().real) + return "MS root SRV lacks a complete GPU-backed range"; + auto* backing = static_cast(placed.owner->own().real); + const auto offset = address - reinterpret_cast(placed.owner->own().title_memory); + const auto width = backing->GetDesc().Width; + if (address >> 48 || offset >= width || width - offset > UINT_MAX) + return "MS root SRV range outside raw buffer limits"; + const UINT words[]{static_cast(address), static_cast(address >> 32), + static_cast(width - offset), 0}; + view = indirect_table_buffer(self, words); + } + } else { + const auto entry = pass.view_tables[read.root_parameter].record(read.offset, 32); + if (!entry || !x2w_local::readable(reinterpret_cast(entry), 32)) + return "MS descriptor table slot is absent"; + UINT words[8]{}; + std::memcpy(words, reinterpret_cast(entry), sizeof(words)); + if (words[0] == view_token_magic) { + x2w_startup::ExclusiveNoteLock lock(note_lock); + if (words[1] >= view_records().size() || view_records()[words[1]].slot != 18) + return "MS descriptor table slot is not an SRV"; + } else if (words[3] != 0x31016fac || (words[1] & 0xffff0000)) { + return "unsupported MS native byte buffer descriptor"; + } + view = indirect_table_buffer(self, words); + } + if (!view.resource || view.resource == arguments || view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT || + view.bytes < read.minimum_bytes || view.bytes % 4 || view.bytes > UINT_MAX) + return "MS buffer read exceeds its usable GPU-backed range"; + } + UINT index = UINT_MAX; + IndirectBufferView typed{}; + if (info->mesh57_heap_word != UINT_MAX) { + if (!pass.mesh_heap_slots) return "MS direct read requires one bound shader-visible view heap"; + index = pass.constants[pass.indirect_graphics.constant_guest][info->mesh57_heap_word] & 1023u; + if (index >= pass.mesh_heap_slots) return "selected MS heap index exceeds its logical descriptor count"; + const auto entry = pass.title_view_heap.record(UINT64{index} * 32, 32); + if (!entry || !x2w_local::readable(reinterpret_cast(entry), 32)) + return "selected MS heap slot is outside the bound shader-visible heap"; + UINT words[8]{}; + std::memcpy(words, reinterpret_cast(entry), sizeof(words)); + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + if (words[0] != view_token_magic || words[1] >= view_records().size()) + return "selected MS heap slot lacks a registered SRV"; + const auto& record = view_records()[words[1]]; + if (record.slot != 18 || record.desc_bytes < sizeof(view)) return "selected MS heap slot is not an SRV"; + std::memcpy(&view,record.desc,sizeof(view)); + } + if (view.Format != DXGI_FORMAT_R32_UINT || view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || + view.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_NONE || view.Buffer.StructureByteStride || + !view.Buffer.NumElements || view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) + return "selected MS heap SRV requires an R32_UINT buffer"; + typed = indirect_table_buffer(self, words, false, nullptr, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, 4); + if (!typed.resource || typed.resource == arguments || typed.stride != 4 || + typed.bytes != UINT64{view.Buffer.NumElements} * 4) + return "selected MS heap SRV lacks its complete GPU-backed range"; + if (!retain_with_recording(self, x2w_startup::ComPtr(typed.resource))) + return "selected MS heap SRV could not be retained"; + } + struct Sampled { Wrapper* owner; x2w_startup::ComPtr resource; D3D12_SHADER_RESOURCE_VIEW_DESC view; UINT slot; }; + std::vector textures; + auto* device = device_of(self->own().list_device); + for (const auto& span : spans) { + if (span.last >= pass.mesh_heap_slots) return "PS texture index exceeds the bound guest heap"; + for (UINT slot=span.first; slot<=span.last; ++slot) { + const auto at=pass.title_view_heap.record(UINT64{slot}*32,32); + if (!at || !x2w_local::readable(reinterpret_cast(at),32)) return "PS texture heap slot inaccessible"; + UINT token[2]; + std::memcpy(token,reinterpret_cast(at),sizeof(token)); + ViewRecord record{}; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + if (token[0]!=view_token_magic || token[1]>=view_records().size()) return "PS heap slot lacks a registered SRV"; + record=view_records()[token[1]]; + } + if (record.slot!=18 || record.desc_bytes=DXGI_FORMAT_BC1_TYPELESS && f<=DXGI_FORMAT_BC1_UNORM_SRGB) return DXGI_FORMAT_BC1_TYPELESS; + if (f>=DXGI_FORMAT_BC7_TYPELESS && f<=DXGI_FORMAT_BC7_UNORM_SRGB) return DXGI_FORMAT_BC7_TYPELESS; + if (f>=DXGI_FORMAT_R8G8B8A8_TYPELESS && f<=DXGI_FORMAT_R8G8B8A8_SINT) return DXGI_FORMAT_R8G8B8A8_TYPELESS; + return f; + }; + if (!float_uav_format(srv.Format) && srv.Format!=DXGI_FORMAT_R8G8B8A8_UNORM_SRGB && + srv.Format!=DXGI_FORMAT_BC1_UNORM && srv.Format!=DXGI_FORMAT_BC1_UNORM_SRGB && + srv.Format!=DXGI_FORMAT_BC7_UNORM && srv.Format!=DXGI_FORMAT_BC7_UNORM_SRGB) + return "PS heap texture requires a supported float or normalized SRV"; + if (record.resource) { + sampled.owner=as_wrapper(reinterpret_cast(record.resource)); + auto* tex=sampled_address_texture(sampled.owner); + if (!tex || tex==arguments || std::find(pass.bound_targets,pass.bound_targets+pass.target_count,tex)!=pass.bound_targets+pass.target_count || + (tex==pass.bound_depth && pass.depth_view_writable)) return "PS heap texture missing or aliased to a writable attachment"; + const auto d=tex->GetDesc(); + const UINT first=srv.Texture2D.MostDetailedMip, levels=srv.Texture2D.MipLevels; + if (d.Dimension!=D3D12_RESOURCE_DIMENSION_TEXTURE2D || d.SampleDesc.Count!=1 || + (d.Format!=srv.Format && (d.Format!=family(d.Format) || family(srv.Format)!=d.Format)) || + first>=d.MipLevels || !levels || (levels!=UINT_MAX && levels>d.MipLevels-first) || + (array ? (!srv.Texture2DArray.ArraySize || srv.Texture2DArray.FirstArraySlice>=d.DepthOrArraySize || + srv.Texture2DArray.ArraySize>d.DepthOrArraySize-srv.Texture2DArray.FirstArraySlice || srv.Texture2DArray.PlaneSlice) + : (d.DepthOrArraySize!=1 || srv.Texture2D.PlaneSlice))) return "PS texture SRV outside resource format, mip or array range"; + sampled.resource=tex; + if (!retain_with_recording(self,sampled.resource)) return "PS texture lifetime retention failed"; + } + sampled.slot=span.host_first+slot-span.first; + textures.push_back(std::move(sampled)); + } + } + for (auto& texture : textures) + if (texture.resource && !upload_texture(self,texture.owner,texture.resource.Get())) return "PS heap texture upload failed"; + const UINT prefix=spans.empty() ? (typed.resource ? index+1 : 0) : + spans.back().host_first+(spans.back().last-spans.back().first+1); + constexpr UINT capacity = 256; + const auto increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + DrawSamplerHeap heap; + UINT start; + { + x2w_startup::ExclusiveNoteLock guard(allocator_lock); + const auto recording = list_recordings.find(self); + if (!self->own().list_open || recording == list_recordings.end() || !recording->second) + return "MS descriptor table requires an open recording"; + auto& allocator = *recording->second; + const bool changed = index != allocator.mesh_heap_index || + (typed.resource && (allocator.mesh_heap_buffer != typed.resource || allocator.mesh_heap_begin != typed.offset || + allocator.mesh_heap_size != typed.bytes)); + if (!spans.empty() || allocator.mesh_view_pages.empty() || changed || reads.size() > capacity - allocator.mesh_view_cursor) { + const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, capacity + prefix, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap)))) return "MS descriptor heap allocation failed"; + try { allocator.mesh_view_pages.push_back(heap); } + catch (const std::bad_alloc&) { return "MS descriptor heap could not be retained with its recording"; } + allocator.mesh_view_cursor = 0; + allocator.mesh_heap_index = index; + allocator.mesh_heap_buffer = typed.resource; + allocator.mesh_heap_begin = typed.offset; + allocator.mesh_heap_size = typed.bytes; + if (typed.resource) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer.FirstElement = typed.offset / 4; + srv.Buffer.NumElements = static_cast(typed.bytes / 4); + auto selected = heap->GetCPUDescriptorHandleForHeapStart(); + selected.ptr += SIZE_T{index} * increment; + device->CreateShaderResourceView(typed.resource,&srv,selected); + } + } else { + heap = allocator.mesh_view_pages.back(); + } + start = allocator.mesh_view_cursor + prefix; + allocator.mesh_view_cursor = spans.empty() ? allocator.mesh_view_cursor + static_cast(reads.size()) : capacity; + } + for (auto& texture : textures) { + auto dst=heap->GetCPUDescriptorHandleForHeapStart(); + dst.ptr+=SIZE_T{texture.slot}*increment; + device->CreateShaderResourceView(texture.resource.Get(),&texture.view,dst); + if (texture.resource) { + require_state(self, texture.resource.Get(), sampled_state(self, texture.resource.Get())); + if (!texture.owner->own().tiled_address_srv) retire_hold(self, texture.owner); + } + } + auto handle = heap->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T{start} * increment; + for (size_t i = 0; i < reads.size(); ++i) { + const auto& view = views[i]; + if (!retain_with_recording(self, x2w_startup::ComPtr(view.resource))) + return "MS buffer could not be retained with its recording"; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Buffer = {view.offset / 4, static_cast(view.bytes / 4), 0, D3D12_BUFFER_SRV_FLAG_RAW}; + device->CreateShaderResourceView(view.resource, &srv, handle); + handle.ptr += increment; + } + for (size_t i = 0; i < reads.size(); ++i) + if (!views[i].upload) require_state(self, views[i].resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + if (typed.resource && !typed.upload) require_state(self, typed.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + auto* native_heap = heap.Get(); + list->SetDescriptorHeaps(1, &native_heap); + list->SetGraphicsRootSignature(pass.indirect_graphics.root); + auto gpu = heap->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += UINT64{start} * increment; + if (!reads.empty()) list->SetGraphicsRootDescriptorTable(1, gpu); + return nullptr; +} +#ifdef X2W_NATIVE_SHADERS +void prepare_native_mesh57(Wrapper* pipeline) +{ + wchar_t sdk[MAX_PATH], path[MAX_PATH]; + const DWORD sdk_length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, MAX_PATH); + if (!sdk_length || sdk_length >= MAX_PATH) + return; + const auto* info = pipeline_info(pipeline); + if (!info || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return; + const auto& ms_bytes = *info->fixed_ms; + const auto& ps_bytes = *info->fixed_ps; + u64 fields[0x300 / sizeof(u64)]; + std::memcpy(fields, info->desc.data(), sizeof(fields)); + auto* root = as_wrapper(reinterpret_cast(fields[0])); + if (!root || root->own().kind != root_signature_kind || !root->own().real || !root_info(root) || + fields[2] != info->state_a.size() || fields[4] != info->state_b.size()) + return; + std::vector root_blob; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + const auto it = root_blobs().find(root); + if (it == root_blobs().end()) + return; + root_blob = it->second; + } + constexpr char revision[] = "x2w-startup-mesh-57-3"; + const u64 key = fnv_part(root_blob, fnv_part(ps_bytes, fnv_part(ms_bytes, fnv_bytes(revision, sizeof(revision) - 1)))); + const auto normalized = x2w_startup::normalize_mesh57_descriptor(info->desc); + const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); + if (!cache_path(path, L"", variant, L".mesh57-state")) + return; + std::ifstream file(std::filesystem::path(path), std::ios::binary); + if (!file) + return; + try { + x2w_startup::Mesh57Profile profile{}; + if (!file.read(reinterpret_cast(&profile), sizeof(profile))) + throw std::runtime_error("invalid profile header"); + const bool pixel_heap = !std::memcmp(profile.magic,"X2WM576",8); + const bool direct_heap = pixel_heap || !std::memcmp(profile.magic, "X2WM575", 8); + const bool buffers = direct_heap || !std::memcmp(profile.magic, "X2WM574", 8); + const bool mapped = buffers || !std::memcmp(profile.magic, "X2WM573", 8); + const bool varying_pixel = mapped || !std::memcmp(profile.magic, "X2WM572", 8); + x2w_startup::Mesh57PixelEntry entry{}; + if (varying_pixel) { + if (!file.read(reinterpret_cast(&entry), sizeof(entry))) + throw std::runtime_error("truncated fixed pixel entry"); + } else if (std::memcmp(profile.magic, "X2WM571", 8)) { + throw std::runtime_error("unknown fixed profile version"); + } + x2w_startup::Mesh57ConstantEntry mapping{}; + if (mapped) { + if (!file.read(reinterpret_cast(&mapping), sizeof(mapping)) || mapping.root_parameter >= 16 || + !mapping.count || mapping.count > 8 || !root_heap_flags(root)) + throw std::runtime_error("invalid MS constant mapping or guest root is not deferred"); + } else if (!root_info(root)->empty() || root_heap_flags(root)) { + throw std::runtime_error("fixed mesh profile lacks guest root mapping"); + } + std::vector view_entries; + if (buffers) { + UINT count{}; + if (!file.read(reinterpret_cast(&count), sizeof(count)) || !count || count > 15) + throw std::runtime_error("invalid MS view entry count"); + view_entries.resize(count); + if (!file.read(reinterpret_cast(view_entries.data()), count * sizeof(view_entries[0]))) + throw std::runtime_error("truncated MS view mappings"); + for (const auto& e : view_entries) + if (e.root_address > 1) throw std::runtime_error("invalid MS view mapping"); + } + UINT heap_sgpr{}; + if (direct_heap && (!file.read(reinterpret_cast(&heap_sgpr), sizeof(heap_sgpr)) || + !(root_heap_flags(root) & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED))) + throw std::runtime_error("missing MS resource heap mapping"); + const auto match = [&](UINT part, const void* bytes, size_t size) { + if (size != profile.lengths[part]) + return false; + if (!size) + return true; + std::string copy(size, 0); + return file.read(copy.data(), size) && !std::memcmp(copy.data(), bytes, size); + }; + if (!match(0, normalized.data(), normalized.size()) || !match(1, info->state_a.data(), info->state_a.size()) || + !match(2, info->state_b.data(), info->state_b.size()) || !match(3, root_blob.data(), root_blob.size()) || + !match(4, ms_bytes.data(), ms_bytes.size()) || !match(5, ps_bytes.data(), ps_bytes.size()) || file.peek() != EOF) + throw std::runtime_error("profile input bytes differ"); + if (!profile.targets.NumRenderTargets || profile.targets.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT || + ((profile.depth.DepthEnable || profile.depth.StencilEnable) && profile.depth_format == DXGI_FORMAT_UNKNOWN) || + profile.samples.Count != 1 || + profile.samples.Quality || profile.sample_mask != UINT_MAX || + (profile.wave_size != 32 && profile.wave_size != 64)) + throw std::runtime_error("unsupported fixed attachment or sample state"); + const std::string ms(ms_bytes.begin(), ms_bytes.end()), ps(ps_bytes.begin(), ps_bytes.end()); + x2w::MeshStageLayout mesh_layout{profile.threads, profile.vertices, profile.primitives, + profile.topology, profile.group_stride, profile.wave_size == 32}; + mesh_layout.packed_parameters = varying_pixel; + if (direct_heap) { + mesh_layout.resource_heap_sgpr = heap_sgpr; + mesh_layout.validate_uint_heap_reads = true; + } + x2w_startup::ComPtr deserializer; + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* guest_desc = nullptr; + if (mapped) { + if (FAILED(D3D12CreateVersionedRootSignatureDeserializer(root_blob.data(), root_blob.size(), IID_PPV_ARGS(&deserializer))) || + FAILED(deserializer->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &guest_desc))) + throw std::runtime_error("invalid MS creation root signature"); + mesh_layout.root_inputs.push_back({mapping.sgpr, mapping.root_parameter, mapping.count}); + for (const auto& e : view_entries) + mesh_layout.root_inputs.push_back({e.sgpr, e.root_parameter, 0, e.root_address != 0}); + } + auto native = mapped ? x2w::translate_mesh_program(ms, mesh_layout, guest_desc->Desc_1_1) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool mapped_constants = mapped && native.constants.size() == 1 && + native.constants[0].root_parameter == mapping.root_parameter && native.constants[0].count == mapping.count && + native.constants[0].first_sgpr == mapping.sgpr; + if ((mapped ? !mapped_constants : !native.constants.empty()) || (!buffers && !native.bindings.empty()) || !native.samplers.empty() || native.sampler_heap || + (direct_heap ? native.mesh_heap_reads.empty() : !native.mesh_heap_reads.empty())) + throw std::runtime_error("MS needs root or heap bindings"); + UINT heap_word = UINT_MAX; + for (const auto& guard : native.mesh_heap_reads) { + if (guard.root_parameter != mapping.root_parameter || guard.dword >= mapping.count || guard.mask != 1023 || + (heap_word != UINT_MAX && heap_word != guard.dword)) + throw std::runtime_error("unsupported MS resource heap index contract"); + heap_word = guard.dword; + } + std::vector reads; + if (buffers) { + if (native.bindings.empty() || native.bindings.size() > 32) + throw std::runtime_error("unsupported MS buffer binding count"); + for (auto b : native.bindings) { + if (b.shader_register != reads.size() || b.root_parameter >= guest_desc->Desc_1_1.NumParameters || + b.root_parameter >= 16 || !b.required_bytes || b.array_count != 1 || b.array_position) + throw std::runtime_error("unsupported MS buffer register or span"); + const bool direct = b.kind == x2w::ComputeViewKind::root_buffer_srv; + const auto& param = guest_desc->Desc_1_1.pParameters[b.root_parameter]; + if (direct) { + if (param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_SRV || b.byte_offset) + throw std::runtime_error("MS root buffer requires a root SRV"); + } else { + if (b.kind != x2w::ComputeViewKind::buffer_srv || param.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + throw std::runtime_error("MS table read requires a scalar SRV"); + // Validate this creation root's range even when reflection already classified the slot. + using Table = x2w::ComputeViewBinding::ScalarTable; + if (b.scalar_table != Table::unknown && b.scalar_table != Table::srv) + throw std::runtime_error("MS table binding is not an SRV"); + b.scalar_table = Table::unknown; + x2w::apply_scalar_table_layout(b, param.DescriptorTable); + if (b.scalar_table != x2w::ComputeViewBinding::ScalarTable::srv || b.byte_offset % 32) + throw std::runtime_error("MS buffer slot outside a verified SRV range"); + } + reads.push_back({b.root_parameter, b.byte_offset, b.required_bytes, direct}); + } + } + std::string ps_ir; + std::vector spans; + std::vector samplers; + if (varying_pixel) { + auto pixel = x2w::translate_mesh_pixel_program(ps, entry.enable, entry.address, entry.wave_size, pixel_heap ? &guest_desc->Desc_1_1 : nullptr); + if (pixel_heap) { + if (pixel.pixel_heap_spans.empty()) throw std::runtime_error("missing PS texture heap reads"); + spans=std::move(pixel.pixel_heap_spans); + for (const auto& c:pixel.constants) + if (c.root_parameter!=mapping.root_parameter || c.count!=mapping.count) + throw std::runtime_error("PS constants differ from the bound MS constant block"); + for (const auto& s:pixel.samplers) + samplers.push_back(x2w_startup::decode_sampler(s.words,static_cast(samplers.size()),s.comparison,s.explicit_lod)); + } + if ((!pixel_heap && (!pixel.constants.empty() || !pixel.samplers.empty())) || !pixel.bindings.empty() || pixel.sampler_heap) + throw std::runtime_error("PS needs root or heap bindings"); + x2w::validate_raster_link(native, pixel); + ps_ir = std::move(pixel.dxil_ir); + } else { + ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + } + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache = std::filesystem::path(path).parent_path(); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = + compiler.compile(ps_ir, L"ps_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); + x2w::meshlet::MeshOnlyPipelineStream stream{}; + stream.root_signature.value = reinterpret_cast(root); + stream.ms.value = {ms_output.dxil.data(), ms_output.dxil.size()}; + stream.ps.value = {ps_output.dxil.data(), ps_output.dxil.size()}; + stream.blend.value = profile.blend; + stream.sample_mask.value = profile.sample_mask; + stream.rasterizer.value = profile.rasterizer; + stream.depth_stencil.value = profile.depth; + stream.rtv_formats.value = profile.targets; + stream.dsv_format.value = profile.depth_format; + stream.sample_desc.value = profile.samples; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + bool compute = false; + char why[256]{}; + auto& state = pipeline->own(); + x2w_startup::ComPtr host; + if (mapped) { + D3D12_ROOT_PARAMETER params[2]{}; + auto& block = params[0]; + block.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + block.Constants.Num32BitValues = (mapping.count + 3) & ~3u; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, static_cast(reads.size())}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + D3D12_ROOT_SIGNATURE_DESC host_desc{reads.empty() ? 1u : 2u, params, static_cast(samplers.size()), samplers.data()}; + if (direct_heap) host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + x2w_startup::ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(device_of(the_device)->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), + IID_PPV_ARGS(&host)))) + throw std::runtime_error("failed to create MS b0 constant root"); + } + state.real = build_stream_pipeline(&desc, why, sizeof(why), compute, state.indirect_graphics, state.pipeline_root, + host ? host.Get() : static_cast(root->own().real), true); + if (!state.real) + throw std::runtime_error(why); + if (mapped) { + static constexpr GUID lifetime{0xf74c6928,0xb063,0x4a00,{0xa5,0xf0,0x79,0xe3,0x60,0xa4,0xf1,0x09}}; + auto* desktop = static_cast(state.real); + if (FAILED(desktop->SetPrivateDataInterface(lifetime, host.Get()))) { + desktop->Release(); + state.real = nullptr; + state.indirect_graphics = {}; + throw std::runtime_error("could not retain MS constant root"); + } + state.indirect_graphics.constant_guest = mapping.root_parameter; + info->mesh57_pixel_spans = std::move(spans); + info->mesh57_reads = std::move(reads); + info->mesh57_heap_word = heap_word; + } + log("x2w-render native slot57 mesh %016llx ready", key); + } catch (const std::exception& e) { + log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); + } +} +#endif diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 8961082c9..658d0a5ec 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -120,7 +120,7 @@ inline UINT sampler_root_parameter(UINT views) { return views ? 2u : 1u; } // Parameter 1, when there are views, is one table: SRVs t0.. first, then UAVs u0.., then bounded resheap SRVs (space 2). inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT srvs, const TranslatedSamplers& samplers, ID3D12RootSignature** out, UINT uavs = 0, - UINT heap_srvs = 0) + bool input_assembler = false, UINT heap_srvs = 0) { D3D12_ROOT_PARAMETER parameters[3]{}; parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; @@ -146,7 +146,8 @@ inline HRESULT create_translated_root(ID3D12Device* device, UINT constants, UINT } const auto statics = decode_statics(samplers); const D3D12_ROOT_SIGNATURE_DESC desc{count, parameters, static_cast(statics.size()), statics.data(), - D3D12_ROOT_SIGNATURE_FLAG_NONE}; + input_assembler ? D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + : D3D12_ROOT_SIGNATURE_FLAG_NONE}; ComPtr blob; HRESULT hr = D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &blob, nullptr); if (SUCCEEDED(hr)) hr = device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(out)); diff --git a/tests/native_graphics_interface_library_check.py b/tests/native_graphics_interface_library_check.py index 206449002..d5475858c 100644 --- a/tests/native_graphics_interface_library_check.py +++ b/tests/native_graphics_interface_library_check.py @@ -80,6 +80,22 @@ def interpolate(attr, channel, op, dst, src): publish(folder, code, words(*vp), root, slot57_inputs=(2, count)) batch(folder, base / f"linked-{attr}-{count}", expected=error) + # The library PS consumes x only. A fixed variant also reads y, + # which is valid only when the actual VS exports that channel. + narrow = [(6, row, 1, row, 0, 0, row, 2) for row in range(2)] + (fixed / "smooth.cdxil").write_bytes(patched_pixel( + len(template), template, input_address=2, attributes=narrow)) + code = words(*template, interpolate(0, 1, 0, 5, 0), interpolate(0, 1, 1, 5, 1), + 0xf800180f, 0x05040504, end) + for mask in (15, 1): + producer = vp.copy() + producer[3] = (producer[3] & ~15) | mask + (fixed / "varying.cdxil").write_bytes(vertex(program=producer)) + run("--index-graphics-interfaces", fixed, cache) + folder = base / f"raw-channels-{mask}" + publish(folder, code, words(*producer), root, slot57_inputs=(2, 1)) + batch(folder, base / f"raw-linked-{mask}", expected=None if mask == 15 else "graphics stages disagree") + # An exact VS writes a four-component image through the second # guest slot. The serialized root covers just the first slot. # The FSSM offset, descriptor width, class and SGPR establish the diff --git a/tests/native_indexed_pixel_texture_check.py b/tests/native_indexed_pixel_texture_check.py index 51504e971..68382ebd7 100644 --- a/tests/native_indexed_pixel_texture_check.py +++ b/tests/native_indexed_pixel_texture_check.py @@ -22,8 +22,13 @@ def texture_program(original, mask, opposite, base_offset=32): # Explicit words of the fixture's point sampler (2 bits set at bit 54). sampler = [0xbeac0380, 0xbead03ff, 0x00c00000, 0xbeae0380, 0xbeaf0380] - # Define untouched halves of the fixture's packed export VGPRs. - initial = [0x7e000280 | (dst << 17) for dst in (47, 80, 81)] + # Interleave a different destination between the two writes defining v80. + # Only v47 and v81 need initial upper halves for their partial exports. + initial = [0x7e000280 | (dst << 17) for dst in (47, 81)] + lo = source.index(0xcc214000 | 80) + high, other_low = source[lo+2:lo+4], source[lo+4:lo+6] + assert high[0] == 0xcc224000 | 80 and other_low[0] == 0xcc214000 | 81 + source[lo+2:lo+6] = other_low + high def and_mask(dst, src): return 0x87000000 | (dst << 16) | ((128 + mask) << 8) | src diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py index 2fc995ec6..ad2c8b0d4 100644 --- a/tests/native_startup_request_cache_check.py +++ b/tests/native_startup_request_cache_check.py @@ -4,6 +4,7 @@ native_startup_request_cache_check.py controls native_startup_request_cache_check.py e2e """ +import hashlib import os from pathlib import Path import re @@ -307,9 +308,52 @@ def expect_graphics_refusal(label: str, setup, expected_stderr: str) -> None: return 0 +def fixed_vertex_draw(work: Path, consumer: Path, sdk: Path, backend: str): + from native_direct_container_check import words + cache = work / "fixed-vertex" + interfaces = cache / "interfaces" + interfaces.mkdir(parents=True) + vs_id = [0xd5800000, 255, 0x123, 0xd5800000, 255, 0x456] + ps_id = [0xd5800000, 255, 0x789, 0xd5800000, 255, 0xabc] + # xyz at slot-zero offset 0; export it as position with W=1, and export Z as a varying. + vs = words(*vs_id, 0xbe8c0400, 0x938dff0d, 0x80000, 0xf4080406, 0xfa000000, + 0x4a000002, 0xbf8cc07f, 0xe03c2000, 0x80040100, 0x7e0802f2, + 0xf80008cf, 0x04030201, 0xf8000201, 0x03030303, 0xbf810000) + ps = words(*ps_id, 0xc8100000, 0xc8110001, 0xf800180f, 0x04040404, 0xbf810000) + for name, raw, interface in ( + ("vs", vs, container_vertex(program=vs_id+[0xbf810000], varying=True)), + ("ps", ps, patched_pixel(7, ps_id+[0x7e0002f2], input_address=2, attributes=[(6,0,1,0,0,0,0,2)]))): + (cache/name).write_bytes(raw) + (interfaces/(hashlib.sha256(raw).hexdigest()+".cdxil")).write_bytes(interface) + for rectangle in (False, True): + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=str(sdk), + X2W_TEST_VERTEX_FETCH="1", X2W_TEST_FIXED_COLOR="1") + env.pop("X2W_TEST_FIXED_RECT", None) + if rectangle: + env["X2W_TEST_FIXED_RECT"] = "1" + result = subprocess.run([consumer, cache/"vs", cache/"ps", cache/"root", backend, cache/"pixels", + "slot57", "58:2,5c:1"], env=env, capture_output=True, text=True) + if result.returncode == 77: + return 77 + assert result.returncode == 0 and "ready=1" in result.stderr and "-> drawn;" in result.stderr, result.stderr + assert not re.search(r"x2w-d3d12-debug .* sev=[01] ", result.stderr), result.stderr + if rectangle: + assert "not aliased" in result.stderr and "topology 0x11 -> drawn" in result.stderr, result.stderr + # The rectangle draws four pixels. The indexed call in the list case adds (3,3). + expected = {(x, 0) for x in range(4)} + if not rectangle: + expected.add((3, 3)) + assert (cache/"pixels").read_bytes() == b"".join( + bytes((64,)*4) if (x,y) in expected else bytes((0,0,255,255)) for y in range(4) for x in range(8)) + return 0 + + def check_e2e(cli: Path, consumer: Path, offscreen: Path, sdk: Path, backend: str) -> int: with tempfile.TemporaryDirectory() as tmp: work = Path(tmp) + if fixed_vertex_draw(work, consumer, sdk, backend) == 77: + return 77 frontend = work / "frontend" # Part 1: .psin VS/PS requests compiled by compile_dxil --requests and executed on GPU. diff --git a/tests/patch_manifest_check.py b/tests/patch_manifest_check.py index 8c353bc7d..75708a40b 100644 --- a/tests/patch_manifest_check.py +++ b/tests/patch_manifest_check.py @@ -192,15 +192,15 @@ def test_load_data_gates_the_bytes_given(self): def test_shader_patches(self): sha = self.digest ok = manifest_text(sha, self.original) - # Accepted beside a memory patch: each pipeline with its required files, mesh86 also with its pixel shader - # and compute also with its Python translator's HLSL. + # Each pipeline loads both its base files and the optional stage or source. text = (ok + shader_patch("s001") + shader_patch("s002", "0123456789abcdef", "graphics") + shader_patch("s003", "fedcba9876543210", "mesh86") + shader_patch("s004", "0000000000000001", "mesh86", exts=(".mesh86.txt", ".ms.cso", ".ps.cso")) - + shader_patch("s005", "0000000000000002", "compute", exts=(".txt", ".cs.cso", ".cs.hlsl"))) + + shader_patch("s005", "0000000000000002", "compute", exts=(".txt", ".cs.cso", ".cs.hlsl")) + + shader_patch("s006", "0000000000000003", "graphics", exts=(".txt", ".vs.cso", ".ps.cso", ".gs.cso"))) target, patches = patch_manifest.parse(text) self.assertEqual([(p["id"], p["kind"]) for p in patches], [("p001", "memory")] + [ - (pid, "shader") for pid in ("s001", "s002", "s003", "s004", "s005")]) + (pid, "shader") for pid in ("s001", "s002", "s003", "s004", "s005", "s006")]) s001 = patches[1] self.assertEqual((s001["key"], s001["pipeline"], s001["revision"]), ("00c0ffee0badf00d", "compute", "x2w-startup-shader-12cs")) @@ -209,11 +209,12 @@ def test_shader_patches(self): {"ext": ".cs.cso", "file": "s001.cs.cso", "sha256": hashlib.sha256(b"s001.cs.cso").hexdigest()}]) self.assertEqual([f["ext"] for f in patches[4]["files"]], [".mesh86.txt", ".ms.cso", ".ps.cso"]) self.assertEqual([f["ext"] for f in patches[5]["files"]], [".txt", ".cs.cso", ".cs.hlsl"]) + self.assertEqual([f["ext"] for f in patches[6]["files"]], [".txt", ".vs.cso", ".ps.cso", ".gs.cso"]) # The CLI lists shader ids with the memory ones. self.manifest.write_text(text, encoding="utf-8", newline="\n") result = self.cli(self.input) self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004", "s005"]) + self.assertEqual(json.loads(result.stdout)["patch_ids"], ["p001", "s001", "s002", "s003", "s004", "s005", "s006"]) good = shader_patch() cases = { "key must be 16 lowercase hex digits": ok + shader_patch(key="00c0ffee0badf00"), @@ -239,7 +240,7 @@ def test_shader_patches(self): "s001 lists .txt twice": ok + shader_patch(exts=(".txt", ".cs.cso", ".txt")), "s001 compute override is missing: .cs.cso": ok + shader_patch(exts=(".txt",)), "s002 graphics override is missing: .vs.cso, .ps.cso": - ok + shader_patch("s002", pipeline="graphics", exts=(".txt",)), + ok + shader_patch("s002", pipeline="graphics", exts=(".txt", ".gs.cso")), "files[0] file must be a non-empty string": ok + good.replace('file = "s001.txt"', 'file = ""'), **{f"files[0] file {name!r} must be a bare file name": ok + good.replace('file = "s001.txt"', f"file = '{name}'") @@ -291,8 +292,8 @@ def test_shader_revision_forms_match_the_runtime(self): def test_shader_files_match_the_runtime(self): # The translation files each pipeline's loader in the runtime reads for one key: cache_path(..., L"", key, ext) - # and mesh86's load_stage(ext, ...). mesh86 reads its .ps.cso only for a request with a pixel shader, and - # compute looks for its .cs.hlsl only when the .txt has no native line: neither is required. + # and mesh86's load_stage(ext, ...). The fixed rectangle geometry stage, mesh86 pixel stage + # and Python compute source are optional. reads = re.compile(r'(?:cache_path\(\w+, L"", [\w.]+, |load_stage\()L"(\.[a-z0-9.]+)"') sources = {"graphics": "d3d12_draw.inl", "compute": "d3d12_compute_dispatch.inl", "mesh86": "mesh86_cache.inl"} self.assertEqual(set(sources), set(patch_manifest.PIPELINES)) @@ -300,6 +301,10 @@ def test_shader_files_match_the_runtime(self): text = (ROOT / "src/startup_stubs" / name).read_text(encoding="utf-8") with self.subTest(pipeline): self.assertEqual(set(reads.findall(text)), set(patch_manifest.PIPELINES[pipeline][1])) + graphics = (ROOT / "src/startup_stubs/d3d12_draw.inl").read_text(encoding="utf-8") + self.assertIn("else if (tr.fixed_rectangle_on_disk) {", graphics) + self.assertEqual(set(patch_manifest.PIPELINES["graphics"][1]) - set(patch_manifest.PIPELINES["graphics"][2]), + {".gs.cso"}) mesh86 = (ROOT / "src/startup_stubs/mesh86_cache.inl").read_text(encoding="utf-8") self.assertIn('(!request.ps.empty() && !load_stage(L".ps.cso", ps))', mesh86) self.assertEqual(set(patch_manifest.PIPELINES["mesh86"][1]) - set(patch_manifest.PIPELINES["mesh86"][2]), diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 78f2a3171..0033e03da 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -496,7 +496,25 @@ int draw_formatted_view(void* guest, void* list) desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; void* placed = nullptr; - if (FAILED(static_cast(invoke(guest, 133, ptr(bytes), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + char indexed_stride[16]{}; + const bool indexed = GetEnvironmentVariableA("X2W_TEST_INDEXED_STRIDE", indexed_stride, sizeof(indexed_stride)) != 0; + if (indexed) { + unsigned stride = 0; + if (std::sscanf(indexed_stride, "%u", &stride) != 1 || !stride || stride > 64 || 64 % stride) return 48; + auto* upload = reinterpret_cast(invoke(list, 148, 64, 256)); + if (!upload || ptr(upload) >> 48) return 47; + std::memcpy(upload, bytes, 64); + alignas(64) static std::array descriptors{}; + Word cpu = 0; + const Word increment = invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (increment < 32 || increment > sizeof(descriptors) || + !bind_view_table(guest, list, cpu, 1, ptr(descriptors.data()), increment) || cpu != ptr(descriptors.data())) return 42; + descriptors[0] = static_cast(ptr(upload)); + descriptors[1] = static_cast(ptr(upload) >> 32) | stride << 16; + descriptors[2] = 64 / stride; + invoke(list, 12, 3, 1); + return 0; + } else if (FAILED(static_cast(invoke(guest, 133, ptr(bytes), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; Word cpu = 0; if (!bind_view_table(guest, list, cpu)) return 42; diff --git a/tests/startup_compute_dispatch_native_check.py b/tests/startup_compute_dispatch_native_check.py index 027565cc4..02b5432cf 100644 --- a/tests/startup_compute_dispatch_native_check.py +++ b/tests/startup_compute_dispatch_native_check.py @@ -26,6 +26,7 @@ """ import os from pathlib import Path +import struct import subprocess import sys import tempfile @@ -46,7 +47,41 @@ def mismatch(got, expected, result): wrong[0], got[wrong[0]], expected[wrong[0]], len(wrong), result.stderr[-3000:]) +def scalar_window_case(consumer, dxc_dir, adapter): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary) + _, env = prepare_case(directory, adapter) + env.update(X2W_NATIVE_SHADERS=dxc_dir, X2W_NATIVE_SHADERS_ONLY='1') + program = directory / 'program' + words = program.read_bytes() + op = {instruction: offset for offset, _, instruction, _ in G.decode(words)} + # Keep case A's output address calculation. Read the scalar pair at +36 + # through the three-record input at table byte 64, then store s10. + load_descriptors = bytes.fromhex('050308f4400000fa 050408f4200000fa') + read_scalar = bytes.fromhex('860224f4240000fa 7fc08cbf 0a020a7e') + wait = next(row[0] for row in G.decode(words) if row[2] == 's_waitcnt') + program.write_bytes(words[:op['s_load_dwordx8']] + load_descriptors + + words[wait:op['buffer_load_dword']] + read_scalar + words[op['buffer_store_dword']:]) + source = directory / 'input' + env['X2W_TEST_DISPATCH_IN'] = str(source) + for value in (1024, 0x45678): + data = [0x11000000 + i for i in range(C.WORDS)] + data[9] = value + source.write_bytes(struct.pack(f'<{C.WORDS}I', *data)) + expected = [value] * 288 + [C.SENTINEL] * 32 + got, result = dispatch(directory, consumer, env, 'dispatch-scalar-window') + if lines(result, NO_WAVES): + assert got == [C.SENTINEL] * C.WORDS + return + assert not mismatch(got, expected, result), mismatch(got, expected, result) + assert lines(result, 'translated natively'), result.stderr[-3000:] + got, result = dispatch(directory, consumer, env, 'dispatch-scalar-window-short') + assert got == [C.SENTINEL] * C.WORDS, result.stderr[-3000:] + assert lines(result, 'refused: an input is in title memory outside any placed buffer'), result.stderr[-3000:] + + def main(consumer, dxc_dir, adapter): + scalar_window_case(consumer, dxc_dir, adapter) with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare_case(directory, adapter) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 563e9ab30..9cfe434b3 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -7,6 +7,7 @@ #include "desktop_gpu.h" #include "xmem_section_lease.h" #include "startup_stubs/rect_indirect_args.h" +#include "startup_stubs/mesh57_profile.h" #include "startup_indirect_mesh_mesh.h" #include "startup_indirect_mesh_amplify.h" #include "startup_indirect_mesh_amplified_mesh.h" @@ -599,7 +600,7 @@ enum class Refusal { none, index_upload_cross, index_upload_foreign, index_uploa insufficient_table_range, copied_table_buffer, upload_range_crossing, unproven_copy, indexed_base_overrun, indexed_vertex_range, invalid_mesh_tag, rect_bad_index, rect_bad_count, rect_bad_w, rect_bad_shape, - incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute }; + mesh_pixel_array, mesh_pixel_hole, mesh_wrong_heap_format, mesh_empty_heap_slot, mesh_outside_heap, mesh_short_table, mesh_bad_root_address, incomplete_mesh_constants, mesh_attachment_count, mesh_pending, overflowing_count, rect_live_compute }; enum class DrawKind { indexed, vertices, mesh, indexed_rect, rect }; ComPtr make_gpu_table_buffer(ID3D12Device* guest, UINT64 bytes) @@ -748,13 +749,139 @@ void report_rect_conversion(ID3D12Device* device, const Words& observed, UINT wo converted[3] == source_words[3] ? "matches the CPU reference" : "differs from the CPU reference"); } +// Two table bases in a shader-visible guest heap and an independent guest root address. +// Each source contributes different bits to the output color. The raw records keep byte bounds. +static bool bind_fixed_mesh_buffers(ID3D12Device* device, ID3D12Device* guest, IUnknown* list, Refusal refusal, + const x2w_startup::Mesh57Profile& profile, int variant, ComPtr& heap_resource, + ComPtr& heap, std::vector>& textures) +{ + using Allocate = void* (WINAPI*)(IUnknown*, UINT64, UINT64); + using Heaps = void (WINAPI*)(IUnknown*, UINT, ID3D12DescriptorHeap* const*); + using Root = void (WINAPI*)(IUnknown*, UINT, UINT64); + constexpr UINT bytes = 16384, bank = 4096; + alignas(64) static UINT table[bytes / 4]; + std::fill_n(table, bytes / 4, 0u); + const UINT step = guest->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!step || bank % step) return false; + struct { D3D12_DESCRIPTOR_HEAP_DESC desc; UINT64 address, bytes; } desc{ + {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, bytes / step, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, + reinterpret_cast(table),bytes}; + using Handle = UINT64 (WINAPI*)(IUnknown*); + if (FAILED(guest->CreateDescriptorHeap(&desc.desc,IID_PPV_ARGS(&heap))) || + slot(heap.Get(),9)(heap.Get()) != desc.address) return false; + const auto gpu = slot(heap.Get(),10)(heap.Get()); + auto* native = heap.Get(); + slot(list,32)(list,1,&native); + slot(list,36)(list,0,gpu); + slot(list,36)(list,1,gpu + bank); + const auto alloc = [&](unsigned value) { + auto* data = static_cast(slot(list,148)(list,16,256)); + if (data) { std::fill_n(data,4,0u); data[1] = value; } + return reinterpret_cast(data); + }; + const auto a = alloc(0x00400000), b = alloc(0x00200000), c = alloc(0x00100000), d = alloc(0x00080000); + if (!a || !b || !c || !d) return false; + const auto record = [&](UINT at, UINT64 address, UINT size) { + table[at/4] = static_cast(address); + table[at/4+1] = static_cast(address >> 32); + table[at/4+2] = size; + table[at/4+3] = 0x31016fac; + }; + record(2848,a,16); + record(bank + 32,d,16); + record(bank + 96,b,refusal == Refusal::mesh_short_table ? 4 : 16); + const bool pixel_heap = !std::memcmp(profile.magic,"X2WM576",8); + if (pixel_heap || !std::memcmp(profile.magic,"X2WM575",8)) { + // Seed one actual desktop buffer. Distinct nonzero view bases and element 1 distinguish + // selecting the wrong slot, losing FirstElement, or fetching the first element. + heap_resource = make_gpu_table_buffer(guest,48); + auto buffer = native_object(device,guest,heap_resource.Get()); + auto upload = make_buffer(device,48,D3D12_HEAP_TYPE_UPLOAD,D3D12_RESOURCE_STATE_GENERIC_READ); + void* mapped = nullptr; + D3D12_RANGE none{}; + check(upload->Map(0,&none,&mapped),"map typed heap fixture input"); + auto* values = static_cast(mapped); + std::fill_n(values,12,0u); + values[4] = 0x3e800000; + values[8] = 0x3f400000; + upload->Unmap(0,nullptr); + ComputeCommands seed(device,nullptr,D3D12_COMMAND_LIST_TYPE_DIRECT); + seed.list->CopyBufferRegion(buffer.Get(),0,upload.Get(),0,48); + seed.submit_and_wait(device); + using View = void (WINAPI*)(IUnknown*,IUnknown*,const D3D12_SHADER_RESOURCE_VIEW_DESC*,UINT64); + for (const UINT index : {147u,151u}) { + if (index == 147 && refusal == Refusal::mesh_empty_heap_slot) continue; + D3D12_SHADER_RESOURCE_VIEW_DESC view{index == 147 && refusal == Refusal::mesh_wrong_heap_format ? + DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R32_UINT, D3D12_SRV_DIMENSION_BUFFER,D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Buffer.FirstElement = index == 147 && variant != 4 ? 3 : 7; + view.Buffer.NumElements = variant == 5 ? 1 : 2; + // Create on a guest API descriptor boundary, then copy its recorded bytes into + // the shader-native heap, whose independently indexed descriptors are 32 bytes. + const UINT scratch = index == 147 ? 0 : step; + slot(guest,18)(guest,heap_resource.Get(),&view,desc.address + scratch); + std::memcpy(table + index * 8,reinterpret_cast(table) + scratch,32); + } + } + if (pixel_heap) { + using View = void (WINAPI*)(IUnknown*,IUnknown*,const D3D12_SHADER_RESOURCE_VIEW_DESC*,UINT64); + using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, + UINT, const void*, void*, UINT, const void*, REFIID, void**); + for (UINT index=32; index<=36; ++index) { + if (index==34 && refusal==Refusal::mesh_pixel_hole) continue; + ComPtr wrapped; + D3D12_SHADER_RESOURCE_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM,D3D12_SRV_DIMENSION_TEXTURE2D,D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + view.Texture2D.MostDetailedMip=1; + view.Texture2D.MipLevels=1; + if (GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)) { + view.Texture2D.MostDetailedMip=0; + view.Texture2D.MipLevels=2; + } + if ((index==32 && variant!=5) || index==36) { + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC texture{D3D12_RESOURCE_DIMENSION_TEXTURE2D,0,2,2,1,2,DXGI_FORMAT_R8G8B8A8_UNORM,{1,0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN,D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + check(slot(guest,127)(guest,&props,0,&texture,D3D12_RESOURCE_STATE_COMMON,nullptr,nullptr, + 0,nullptr,IID_PPV_ARGS(&wrapped)), "create material texture"); + auto resource=native_object(device,guest,wrapped.Get()); + D3D12_DESCRIPTOR_HEAP_DESC rtv{D3D12_DESCRIPTOR_HEAP_TYPE_RTV,2}; + ComPtr views; + check(device->CreateDescriptorHeap(&rtv,IID_PPV_ARGS(&views)), "create material RTVs"); + auto handle=views->GetCPUDescriptorHandleForHeapStart(); + ComputeCommands seed(device,nullptr,D3D12_COMMAND_LIST_TYPE_DIRECT); + transition(seed.list.Get(),resource.Get(),D3D12_RESOURCE_STATE_COMMON,D3D12_RESOURCE_STATE_RENDER_TARGET); + for (UINT mip=0;mip<2;++mip) { + const float color[]{float(mip && index==32),float(mip && index==36),float(!mip),1.f}; + D3D12_RENDER_TARGET_VIEW_DESC output{texture.Format,D3D12_RTV_DIMENSION_TEXTURE2D}; + output.Texture2D.MipSlice=mip; + device->CreateRenderTargetView(resource.Get(),&output,handle); + seed.list->ClearRenderTargetView(handle,color,0,nullptr); + handle.ptr+=device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + } + transition(seed.list.Get(),resource.Get(),D3D12_RESOURCE_STATE_RENDER_TARGET,D3D12_RESOURCE_STATE_COMMON); + seed.submit_and_wait(device); + textures.push_back(wrapped); + } else { view.Texture2D.MostDetailedMip=0; view.Texture2D.MipLevels=1; } + if (index==36 && refusal==Refusal::mesh_pixel_array) { + view.ViewDimension=D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + view.Texture2DArray.ArraySize=1; + } + slot(guest,18)(guest,wrapped.Get(),&view,desc.address+index*step); + std::memmove(table+index*8,reinterpret_cast(table)+index*step,32); + } + } + // A readable CPU address outside the GPU allocations must fail even when it holds the right word. + slot(list,44)(list,3,refusal == Refusal::mesh_bad_root_address ? desc.address : c); + return true; +} + bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_root, ID3D12PipelineState* writer, ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature, DrawKind kind, bool draw_right, Refusal refusal, const char* label, const TranslatedDrawFixture* translated = nullptr, bool upload_table = false, const ReplayCopy* replay = nullptr, bool upload_index = false, bool alias_index = false, UINT cached_mesh_targets = 0, bool cached_depth_only = false, bool restore_compute = false, - const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false) + const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false, + int fixed_mesh_pixels = 0, const x2w_startup::Mesh57Profile* fixed_profile = nullptr) { std::unique_lock recording; if (gate) recording = std::unique_lock(gate->state); @@ -803,7 +930,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ constexpr float clear[]{0, 0, 0, 1}; D3D12_CLEAR_VALUE clear_value{target_format, {0, 0, 0, 1}}; if (cached_depth_only) clear_value.DepthStencil = {1, 0}; - const UINT target_count = cached_mesh_targets ? cached_mesh_targets : 1; + const UINT target_count = fixed_profile ? fixed_profile->targets.NumRenderTargets : cached_mesh_targets ? cached_mesh_targets : 1; std::vector> targets; const auto heap_kind = cached_depth_only ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : D3D12_DESCRIPTOR_HEAP_TYPE_RTV; const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{heap_kind, target_count, @@ -822,7 +949,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ rtv = heap->GetCPUDescriptorHandleForHeapStart(); } for (UINT i = 0; i < target_count; ++i) { - targets.push_back(resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value)); + auto attachment = target_desc; + auto initial_color = clear_value; + if (fixed_profile) attachment.Format = initial_color.Format = fixed_profile->targets.RTFormats[i]; + targets.push_back(resource(device, attachment, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &initial_color)); if (cached_depth_only) { D3D12_DEPTH_STENCIL_VIEW_DESC depth_view{}; depth_view.Format = target_format; @@ -832,6 +962,24 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ rtvs.push_back(rtv); rtv.ptr += device->GetDescriptorHandleIncrementSize(heap_kind); } + ComPtr fixed_depth; + ComPtr fixed_depth_heap; + D3D12_CPU_DESCRIPTOR_HANDLE fixed_dsv{}, desktop_fixed_dsv{}; + if (fixed_profile && fixed_profile->depth_format != DXGI_FORMAT_UNKNOWN) { + auto desc = target_desc; + desc.Format = fixed_profile->depth_format; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + D3D12_CLEAR_VALUE initial_depth{}; + initial_depth.Format = desc.Format; + initial_depth.DepthStencil = {0.25f, 3}; + fixed_depth = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &initial_depth); + const D3D12_DESCRIPTOR_HEAP_DESC descriptors{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1}; + check(guest->CreateDescriptorHeap(&descriptors,IID_PPV_ARGS(&fixed_depth_heap)), "create fixture DSV heap"); + using GetCpu = UINT64(WINAPI*)(IUnknown*, void*); + fixed_dsv.ptr = slot(fixed_depth_heap.Get(),9)(fixed_depth_heap.Get(),nullptr); + desktop_fixed_dsv = native_object(device,guest,fixed_depth_heap.Get())->GetCPUDescriptorHandleForHeapStart(); + guest->CreateDepthStencilView(fixed_depth.Get(), nullptr, fixed_dsv); + } ComPtr allocator; check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create guest allocator"); @@ -925,7 +1073,12 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ using Scissor = void (WINAPI*)(IUnknown*, UINT, const D3D12_RECT*); using Index = void (WINAPI*)(IUnknown*, const D3D12_INDEX_BUFFER_VIEW*); using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); - const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const bool material_waterfall = fixed_profile && + GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)!=0; + // NDC vertices (0,0), (1,0), (0,1) map to (0,2), (8,2), (0,-6). + // All eight target pixel centers lie strictly inside the triangle. + const D3D12_VIEWPORT viewport = material_waterfall ? D3D12_VIEWPORT{-8,-6,16,16,0,1} : + D3D12_VIEWPORT{0,0,width,height,0,1}; const D3D12_RECT scissor{rect ? 1 : 0, 0, width, height}; if (cached_depth_only) { slot(wrapped, 50)(wrapped, 0, nullptr, FALSE, rtvs.data()); @@ -947,13 +1100,31 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ } for (const auto target_view : rtvs) slot(wrapped, 52)(wrapped, target_view.ptr, clear, 0, nullptr); const UINT bound_targets = target_count - (refusal == Refusal::mesh_attachment_count ? 1 : 0); - slot(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, nullptr); + slot(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, fixed_depth ? &fixed_dsv : nullptr); + if (fixed_depth) { + list->ClearDepthStencilView(desktop_fixed_dsv, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.25f, 3, 0, nullptr); + using StencilRef = void(WINAPI*)(IUnknown*,UINT); + slot(wrapped,24)(wrapped,7); + } } + std::vector> fixed_textures; + ComPtr fixed_heap_resource; + ComPtr fixed_source_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); + } else if (fixed_profile && (!std::memcmp(fixed_profile->magic, "X2WM573", 8) || !std::memcmp(fixed_profile->magic, "X2WM574", 8) || + !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8))) { + // Guest root4 is b5/space2. DXIL expects the first word of host b0/space0. + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + const bool heap = !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8); + const bool buffers = heap || !std::memcmp(fixed_profile->magic, "X2WM574", 8); + if (buffers && !bind_fixed_mesh_buffers(device, guest, wrapped, refusal, *fixed_profile, fixed_mesh_pixels, fixed_heap_resource, fixed_source_heap, fixed_textures)) return false; + const UINT value = heap ? 0x3e000000u + (refusal == Refusal::mesh_outside_heap ? 490u : fixed_mesh_pixels == 3 ? 151u : 147u) : buffers ? 0x3e000000 : fixed_mesh_pixels == 3 ? 0x3f400000 : 0x3e800000; // 0.75 or 0.25 in PARAM12.y / green + if (refusal != Refusal::incomplete_mesh_constants) + slot(wrapped, 40)(wrapped, 4, 1, &value, 0); } else if (cached_mesh_targets || cached_depth_only) { using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); const UINT values[]{17, 29}; @@ -1075,6 +1246,10 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ? sizeof(initial_words) - command_stride(kind) + sizeof(std::uint32_t) : indexed_argument_offset; slot(wrapped, 61)(wrapped, signature, 1, external_arguments ? leased->argument : arguments->wrapped.Get(), external_arguments ? leased->argument_offset : offset, nullptr, 0); + // Slot 61 has already frozen the desktop heap and retained its backing. Release the guest + // resource before closing/submitting the list, including for the positive readbacks. + fixed_source_heap.Reset(); + fixed_heap_resource.Reset(); if (restore_compute) { // Leave the previously forwarded root + SRV alone. Only install the // consumer PSO and the output UAV that this fixture owns. @@ -1180,8 +1355,9 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; UINT64 bytes = 0; - device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); for (const auto& target : targets) { + const auto desc = target->GetDesc(); + device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); const auto pixel_readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); ComputeCommands copy(device, kept_direct_queue(device), nullptr); transition(copy.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -1205,10 +1381,38 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const bool covered = (cached_depth_only && !cached_depth_pixel) || (indexed ? right_half == draw_right : translated || !right_half || draw_right); const bool drawn = writer && refusal == Refusal::none && covered; // overflowing_count draws nothing - const std::uint32_t background = cached_depth_only ? 0xffff : black; + const std::uint32_t background = cached_depth_only ? 0xffff : desc.Format == DXGI_FORMAT_R16G16_FLOAT ? 0 : black; const auto depth_word = cached_depth_pixel ? 0x4000u : 0u; // D16_UNORM encodes SV_Depth 0.25. auto wanted = drawn ? (cached_depth_only ? depth_word : translated ? (draw_right ? green : red) : (right_half ? green : red)) : background; + if (fixed_mesh_pixels) { + const bool white = (fixed_mesh_pixels == 1 || fixed_mesh_pixels >= 3) && target.Get() == targets.front().Get() && x == 2 && y == 0; + if (target.Get() == targets.front().Get() && x == 2 && y == 0) + std::printf("%s: target zero (2,0) packed RGBA = 0x%08x\n", label, actual); + wanted = background; + if (white) { + const auto mask = fixed_profile->blend.RenderTarget[0].RenderTargetWriteMask; + const bool linked = !std::memcmp(fixed_profile->magic, "X2WM572", 8); + const bool heap = !std::memcmp(fixed_profile->magic, "X2WM575", 8) || !std::memcmp(fixed_profile->magic, "X2WM576", 8); + if (heap) wanted = 0; // This fixture writes all four channels, including alpha. + for (UINT channel=0; channel<4; ++channel) + if ((mask & (1u<= 3 ? 191u : 64u) : + channel == 1 && !std::memcmp(fixed_profile->magic, "X2WM574", 8) ? 62u : + channel == 1 && !std::memcmp(fixed_profile->magic, "X2WM573", 8) ? + (fixed_mesh_pixels == 3 ? 0xbfu : 0x40u) : 0xffu) << (8*channel); + if (!std::memcmp(fixed_profile->magic,"X2WM576",8)) + wanted = fixed_mesh_pixels==5 ? 0 : fixed_mesh_pixels==3 ? 0xff00ff00u : 0xff0000ffu; + } + if (material_waterfall && target.Get()==targets.front().Get() && fixed_mesh_pixels!=2) { + // floor(SV_Position.x) selects slot 32 on even pixels + // and 36 on odd ones. Variant 5 binds typed null at 32. + const bool fine=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_FINE_LOD",nullptr,0)!=0; + wanted=!(x&1) && fixed_mesh_pixels==5 ? 0u : + fine ? 0xffff0000u : (x&1) ? 0xff00ff00u : 0xff0000ffu; + if (!y) std::printf("waterfall x=%u RGBA=%08x\n",x,actual); + } + } if (leased) wanted = right_half ? leased->expected_right.value_or(leased->expected) : leased->expected; if (rect) { // NDC pixel centers are x=(-.75,-.25,.25,.75), y=(.5,-.5). @@ -1230,6 +1434,43 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ return false; } } + if (fixed_depth) { + const auto desc = fixed_depth->GetDesc(); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT planes[2]{}; + UINT64 row_sizes[2]{}; + device->GetCopyableFootprints(&desc, 0, 2, 0, planes, nullptr, row_sizes, &bytes); + const auto rb = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands copy(device, kept_direct_queue(device), nullptr); + transition(copy.list.Get(), fixed_depth.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT plane=0; plane<2; ++plane) { + D3D12_TEXTURE_COPY_LOCATION src{fixed_depth.Get(),D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,{}}; + src.SubresourceIndex=plane; + D3D12_TEXTURE_COPY_LOCATION dst{rb.Get(),D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,{}}; + dst.PlacedFootprint=planes[plane]; + copy.list->CopyTextureRegion(&dst,0,0,0,&src,nullptr); + } + copy.submit_and_wait(device); + const D3D12_RANGE range{0,static_cast(bytes)}; + check(rb->Map(0,&range,&memory),"map depth/stencil planes"); + bool match=true; + for (UINT y=0;y(memory)+planes[plane].Offset+ + y*planes[plane].Footprint.RowPitch+x*row_sizes[plane]/width; + }; + float z; std::memcpy(&z,texel(0),sizeof(z)); + const auto stencil=*texel(1); + const bool hit=fixed_mesh_pixels==1 && x==2 && y==0; + if (z!=(hit?0.5f:0.25f) || stencil!=(hit?7:3)) { + std::fprintf(stderr,"%s: depth/stencil (%u,%u) got %.3f/%u, row sizes %llu/%llu\n",label,x,y,z,stencil,row_sizes[0],row_sizes[1]); + match=false; + } + } + rb->Unmap(0,&untouched); + if (!match) return false; + std::printf("%s: 8 depth/stencil texels matched, selected pixel %.2f/%u\n", + label,fixed_mesh_pixels==1?0.5:0.25,fixed_mesh_pixels==1?7:3); + } return true; } // Calls refused before any argument is read: one per counted reason, and one with two commands, which is @@ -1763,6 +2004,297 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) #include "startup_indirect_mesh_lease.inl" } // namespace +static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer) +{ + const bool mrt = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MRT", nullptr, 0) != 0; + const bool waterfall=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_WATERFALL",nullptr,0)!=0; + const bool pixel_heap=waterfall || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_PIXEL_HEAP",nullptr,0)!=0; + const bool heap = pixel_heap || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_UINT_HEAP",nullptr,0) != 0; + const bool buffers = heap || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_BUFFERS", nullptr, 0) != 0; + const bool constants = buffers || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_CONSTANT", nullptr, 0) != 0; + const bool varying = constants || GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_VARYING", nullptr, 0) != 0; + // Windows recycles process IDs. Retain failed runs for inspection without reading an old archive. + const auto prefix = "mesh57-native-" + std::to_string(GetCurrentProcessId()) + "-"; + std::filesystem::path cache; + for (unsigned attempt = 0; ; ++attempt) { + cache = std::filesystem::current_path() / (prefix + std::to_string(attempt)); + if (std::filesystem::create_directory(cache)) break; + } + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "native mesh cache"); + ComPtr blob; + D3D12_ROOT_SIGNATURE_DESC empty{}; + D3D12_ROOT_PARAMETER params[5]{}; + D3D12_DESCRIPTOR_RANGE ranges[2]{}; + if (constants) { + for (UINT i = 0; i < 5; ++i) { + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[i].Constants = {i + 1, 2, 1}; + } + if (buffers) { + for (UINT i = 0; i < 2; ++i) { + ranges[i] = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 128, 0, i, 0}; + params[i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[i].DescriptorTable = {1, &ranges[i]}; + } + params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[3].Descriptor = {0, 3}; + } + if (pixel_heap) params[2].ShaderVisibility=D3D12_SHADER_VISIBILITY_VERTEX; + empty.NumParameters = 5; + empty.pParameters = params; + empty.Flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED; + } + const auto root = create_root(guest, empty, &blob); + // Guest ALU derives positions (0,0), (1,0), (0,1) from lane indices and exports triangle 0,1,2. + std::vector ms{0xbefc03ff, 0x1003, 0xbf900009, 0xd7650000, 0x100c1, 0x36020081, + 0x2c040081, 0x7e020d01, 0x7e040d02, 0x7e0602f0, 0x7e0802f2, 0xf80008cf, + 0x04030201, 0x7e0a02ff, 0x200400, 0xf8000941, 0x80808005, 0xbf810000}; + std::vector ps{0x7e0002f2, 0xf800180f, 0, 0xbf810000}; + if (varying) { + // Export PARAM12.xy = (1,0). The PS reads p0.x and p0.y back as (x,y,x,x). + ms.insert(ms.end()-1, {constants ? 0x7e0c020cu : 0x7e0c0280u, 0xf80002c3, heap ? 0x0000060au : 0x00000604u}); + ps = {0xc8023002, 0xc8063102, 0xf800180f, 0x00000100, 0xbf810000}; + } + if (buffers) { + // s_load_dwordx4 table0+2848 and table1+32/+96; s_buffer_load_dword at +4 of each SRV. + // Read root3+4 through its synthesized byte descriptor. Combine their disjoint bits with root4 in s12. + ms.insert(ms.begin(), {0xbe910380, 0xbe930380, 0xf4080608, 0xfa000b20, 0xf4080709, 0xfa000060, + 0xf420080c, 0xfa000004, 0xf420084e, 0xfa000004, 0xbe960390, 0xbe9703ff, 0x31016fac, 0xf420088a, 0xfa000004, + 0xf4080a09, 0xfa000020, 0xf42008d4, 0xfa000004, + 0x880c200c, 0x880c210c, 0x880c220c, 0x880c230c}); + } + if (heap) { + // Guest slot = root4[0] & 1023. Read typed element 1 into v10. + ms.insert(ms.begin(), {0xbe9e032f,0xbe9f0380,0x872dff0c,1023,0x8f2d852d, + 0xf408080f,0x5a000000,0x7e020281,0xe0002000,0x80080a01}); + } + if (pixel_heap) { + // ((root4 & 4) << 5) + 1024 selects slot 32 or 36. Both views begin at mip 1. + ps={0xbe8f0380,0x8712840d,0x8f128512,0xf40c0507,0x24000400, + 0xbe9c0380,0xbe9d03ff,0x00fff000,0xbe9e03ff,0x04000000,0xbe9f0380, + 0x7e0002f0,0x7e0202f0,0xf09c0f08,0x00e50000,0xf800180f,0x03020100,0xbf810000}; + } + if (waterfall) { + // slot = 32 | ((uint(SV_Position.x) & 1) << 2). Each iteration + // samples exactly the lanes with the first active lane's slot. + // Preserve the incoming float position before converting v0 to a slot + // selector. A unit texcoord gradient on a 2x2 view selects mip 1; + // constant coordinates select the blue mip 0 with the same sampler. + const bool fine=GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_FINE_LOD",nullptr,0)!=0; + ps={fine ? 0x7e0a02f0u : 0x7e0a0300u,0xbe8f0380,0x7e000f00,0x362e0081,0x342e2e82,0x382e2ea0, + 0x7e0c02f0,0xbe9c0380,0xbe9d03ff,0x00fff000,0xbe9e03ff,0x04000000,0xbe9f0380, + 0xbebc047e,0xbeb4047e, + 0x7e240517,0x7d242e12,0x8f128512,0xf40c0507,0x24000000, + 0xf0800f08,0x00e50005,0xbeb43a34,0xbf85fff7,0xbefe043c, + 0xf800180f,0x03020100,0xbf810000}; + } + const auto ms_size = ms.size()*sizeof(UINT), ps_size = ps.size()*sizeof(UINT); + const std::array expected_a{0x12345678, 0x9abcdef0}; + const bool masked = GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57_MASK", nullptr, 0) != 0; + const std::array expected_b{masked ? 0x55aa5501u : 0x55aa55aau}; + auto state_a = expected_a; + auto state_b = expected_b; + UINT64 fields[0x300 / sizeof(UINT64)]{}; + fields[2] = sizeof(state_a); + fields[4] = sizeof(state_b); + fields[6] = ps_size; + fields[14] = ms_size; + const auto fold = [](UINT64 key, const void* data, size_t n) { + const auto* p = static_cast(data); + for (size_t i = 0; i < n; ++i) + key = (key ^ p[i]) * 1099511628211ull; + return key; + }; + const char revision[] = "x2w-startup-mesh-57-3"; + auto key = fold(1469598103934665603ull, revision, sizeof(revision) - 1); + const auto extend = [&](UINT64 base, const void* data, UINT64 n) { return fold(fold(base, &n, sizeof(n)), data, n); }; + const auto part = [&](const void* data, UINT64 n) { key = extend(key,data,n); }; + part(ms.data(), ms_size); + part(ps.data(), ps_size); + part(blob->GetBufferPointer(), blob->GetBufferSize()); + char name[64]; + const auto variant = [&] { + return extend(extend(extend(key,fields,sizeof(fields)),state_a.data(),sizeof(state_a)),state_b.data(),sizeof(state_b)); + }; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", variant()); + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, pixel_heap ? "X2WM576" : heap ? "X2WM575" : buffers ? "X2WM574" : constants ? "X2WM573" : varying ? "X2WM572" : "X2WM571", 8); + profile.lengths[0] = sizeof(fields); + profile.lengths[3] = static_cast(blob->GetBufferSize()); + profile.lengths[1] = sizeof(state_a); + profile.lengths[2] = sizeof(state_b); + profile.lengths[4] = static_cast(ms_size); + profile.lengths[5] = static_cast(ps_size); + profile.threads = 64; + profile.vertices = 3; + profile.primitives = 1; + profile.topology = 2; + profile.group_stride = 64; + profile.wave_size = 64; + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = format; + profile.samples.Count = 1; + profile.sample_mask = UINT_MAX; + profile.rasterizer.FillMode = D3D12_FILL_MODE_SOLID; + profile.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + profile.rasterizer.DepthClipEnable = TRUE; + auto& blend = profile.blend.RenderTarget[0]; + blend.SrcBlend = blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlend = blend.DestBlendAlpha = D3D12_BLEND_ZERO; + blend.BlendOp = blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + blend.LogicOp = D3D12_LOGIC_OP_NOOP; + blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + profile.depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + if (mrt) { + const DXGI_FORMAT formats[]{DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, format, format, format, DXGI_FORMAT_R16G16_FLOAT, format}; + profile.targets.NumRenderTargets = static_cast(std::size(formats)); + std::copy(std::begin(formats), std::end(formats), profile.targets.RTFormats); + profile.blend.IndependentBlendEnable = TRUE; + for (UINT i=1; i(data), n); }; + put(&profile, sizeof(profile)); + if (varying) { + const UINT position_x = waterfall ? 1u<<8 : 0; + const x2w_startup::Mesh57PixelEntry entry{position_x,position_x,64}; + put(&entry,sizeof(entry)); + if (constants) { + const x2w_startup::Mesh57ConstantEntry mapping{12,4,1}; + put(&mapping,sizeof(mapping)); + if (buffers) { + const UINT count = 3; + const x2w_startup::Mesh57ViewEntry inputs[]{{16,0,0},{18,1,0},{20,3,1}}; + put(&count,sizeof(count)); + put(inputs,sizeof(inputs)); + if (heap) { const UINT sgpr = 47; put(&sgpr,sizeof(sgpr)); } + } + } + } + put(fields, sizeof(fields)); + put(state_a.data(), sizeof(state_a)); + put(state_b.data(), sizeof(state_b)); + put(blob->GetBufferPointer(), blob->GetBufferSize()); + put(ms.data(), ms_size); + put(ps.data(), ps_size); + if (!out) + return 1; + } + fields[15]=1; + char other_name[64]; + std::snprintf(other_name,sizeof(other_name),"%016llx.mesh57-state",variant()); + std::filesystem::copy_file(cache/name,cache/other_name,std::filesystem::copy_options::overwrite_existing); + fields[15]=0; + fields[0] = reinterpret_cast(root.Get()); + fields[1] = reinterpret_cast(state_a.data()); + fields[3] = reinterpret_cast(state_b.data()); + fields[5] = reinterpret_cast(ps.data()); + fields[13] = reinterpret_cast(ms.data()); + const auto create = [&] { + ComPtr pso; + using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), + reinterpret_cast(pso.GetAddressOf())), + "create native fixed mesh"); + return pso; + }; + const auto pso = create(); + fields[15] = 1; // Same stages and root, unreviewed fixed pipeline state. + const auto mismatched = create(); + state_a.fill(0); + state_b.fill(0); + check(SetEnvironmentVariableA("X2W_MESH57_CAPTURE_STATE", "1") ? S_OK : E_FAIL, "enable fixed-state archive"); + D3D12_INDIRECT_ARGUMENT_DESC arg{}; + arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC desc{sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), 1, &arg, 0}; + ComPtr signature; + check(guest->CreateCommandSignature(&desc, nullptr, IID_PPV_ARGS(&signature)), "mesh signature"); + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + const bool ok = run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, + Refusal::none, "native fixed mesh triangle", nullptr, false, nullptr, false, false, 0, false, false, + nullptr, nullptr, false, 1, &profile) && + run(device, guest, writer, work.Get(), root.Get(), mismatched.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, "unreviewed fixed mesh state", nullptr, false, nullptr, false, false, 0, false, + false, nullptr, nullptr, false, 2, &profile); + if (ok && mrt && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::mesh_attachment_count, "native fixed mesh missing color attachment", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + if (ok && constants && (!buffers || heap) && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::none, "native fixed mesh changed root4", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 3, &profile)) return 1; + if (ok && pixel_heap && !run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false, + Refusal::mesh_pixel_hole,"PS bounded range has an unregistered slot",nullptr,false,nullptr,false,false,0,false,false, + nullptr,nullptr,false,2,&profile)) return 1; + if (ok && pixel_heap && !run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false, + Refusal::mesh_pixel_array,"PS Texture2DArray supplied to Texture2D",nullptr,false,nullptr,false,false,0,false,false, + nullptr,nullptr,false,2,&profile)) return 1; + if (ok && heap) { + for (int variant : {4,5}) { + if (!run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false,Refusal::none, + variant == 4 ? "heap slot 147 replaced view" : pixel_heap ? "PS explicit typed null" : "heap element beyond view",nullptr,false,nullptr,false, + false,0,false,false,nullptr,nullptr,false,variant,&profile)) return 1; + } + for (auto failure : {Refusal::mesh_wrong_heap_format,Refusal::mesh_empty_heap_slot,Refusal::mesh_outside_heap}) { + const char* label = failure == Refusal::mesh_wrong_heap_format ? "heap R32_FLOAT" : + failure == Refusal::mesh_empty_heap_slot ? "heap empty slot" : "heap index out of range"; + if (!run(device,guest,writer,work.Get(),root.Get(),pso.Get(),signature.Get(),DrawKind::mesh,false,failure, + label,nullptr,false,nullptr,false,false,0,false,false,nullptr,nullptr,false,2,&profile)) return 1; + } + } + if (ok && buffers) { + for (auto failure : {Refusal::mesh_short_table, Refusal::mesh_bad_root_address}) + if (!run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, false, failure, + failure == Refusal::mesh_short_table ? "short table1 SRV" : "unbacked root3 address", nullptr, false, + nullptr, false, false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + } + if (ok && constants && !run(device, guest, writer, work.Get(), root.Get(), pso.Get(), signature.Get(), DrawKind::mesh, + false, Refusal::incomplete_mesh_constants, "native fixed mesh missing root4", nullptr, false, nullptr, false, + false, 0, false, false, nullptr, nullptr, false, 2, &profile)) return 1; + if (!ok) + return 1; + for (const auto i : {0, 1, 3, 5, 13}) + fields[i] = 0; + const UINT sizes[]{sizeof(fields), sizeof(expected_a), sizeof(expected_b)}; + std::vector expected; + const auto append = [&](const void* p, size_t n) { + const auto bytes = static_cast(p); + expected.insert(expected.end(), bytes, bytes + n); + }; + append(&key, sizeof(key)); + append(sizes, sizeof(sizes)); + append(fields, sizeof(fields)); + append(expected_a.data(), sizeof(expected_a)); + append(expected_b.data(), sizeof(expected_b)); + auto valid = expected; + std::fill_n(valid.begin() + sizeof(key) + sizeof(sizes) + 15 * sizeof(UINT64), sizeof(UINT64), 0); + bool saw_valid = false, saw_other = false; + for (const auto& f : std::filesystem::directory_iterator(cache)) + if (f.path().extension() == ".s57") { + std::ifstream in(f.path(), std::ios::binary); + const std::vector persisted(std::istreambuf_iterator(in), {}); + if (persisted == valid && !saw_valid) saw_valid = true; + else if (persisted == expected && !saw_other) saw_other = true; + else return 1; + } + std::printf("fixed mesh state archives matching creation bytes: accepted=%d refused=%d\n", saw_valid, saw_other); + if (!saw_valid || !saw_other) return 1; + std::filesystem::remove_all(cache); + return 0; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -1891,6 +2423,8 @@ int main(int argc, char** argv) try const auto root_flags = mesh ? D3D12_ROOT_SIGNATURE_FLAG_NONE : D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; const D3D12_ROOT_SIGNATURE_DESC graphics_desc{0, nullptr, 0, nullptr, root_flags}; const auto writer = create_root(device.Get(), writer_desc); + if (mesh && GetEnvironmentVariableA("X2W_TEST_NATIVE_MESH57", nullptr, 0)) + return native_fixed_mesh_fixture(device.Get(), guest.Get(), writer.Get()); wchar_t mesh86_dir[MAX_PATH]{}; if (mesh && GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", mesh86_dir, MAX_PATH)) { const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; @@ -2105,18 +2639,24 @@ int main(int argc, char** argv) try const auto ms_size = exchange_size ? source_ms.size() : sizeof(default_ms); const auto ps_size = exchange_size ? source_ps.size() : sizeof(default_ps); const auto make_pso = [&](bool with_pixel, bool with_vertex, bool incomplete_pixel) { + const auto* ms_begin = static_cast(ms); + const auto* ps_begin = static_cast(ps); + std::vector caller_ms(ms_begin, ms_begin + ms_size); + std::vector caller_ps(ps_begin, ps_begin + ps_size); std::array fields{}; fields[0] = reinterpret_cast(root.Get()); - fields[5] = with_pixel ? reinterpret_cast(ps) : 0; + fields[5] = with_pixel ? reinterpret_cast(caller_ps.data()) : 0; fields[6] = with_pixel && !incomplete_pixel ? ps_size : 0; fields[9] = with_vertex ? reinterpret_cast(ps) : 0; fields[10] = with_vertex ? ps_size : 0; - fields[13] = reinterpret_cast(ms); + fields[13] = reinterpret_cast(caller_ms.data()); fields[14] = ms_size; using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); ComPtr pso; check(slot(guest.Get(), 57)(guest.Get(), fields.data(), __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), "create fixed mesh placeholder"); + std::fill(caller_ms.begin(), caller_ms.end(), 0xcc); + std::fill(caller_ps.begin(), caller_ps.end(), 0xcc); return pso; }; D3D12_INDIRECT_ARGUMENT_DESC mesh_argument{}; diff --git a/tests/startup_native_graphics_draw_check.py b/tests/startup_native_graphics_draw_check.py index b70a6ec9d..b62230cca 100644 --- a/tests/startup_native_graphics_draw_check.py +++ b/tests/startup_native_graphics_draw_check.py @@ -1,5 +1,6 @@ """Exercise first-use native graphics translation and a fresh-process cache hit.""" import os +import struct import subprocess import sys import tempfile @@ -17,7 +18,7 @@ def triangle(): return vertex(program=code) -def check(folder, consumer, cli, sdk, adapter): +def check(folder, consumer, sdk, adapter, compiler): cache = folder / "cache" cache.mkdir() vs, ps, root, pixels = [folder / name for name in ("vs", "ps", "root", "pixels")] @@ -25,7 +26,6 @@ def check(folder, consumer, cli, sdk, adapter): ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001))) env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1") - env.pop("X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST", None) clear = bytes((0, 0, 255, 255)) red = bytes((255, 0, 0, 255)) args = [consumer, vs, ps, root, adapter, pixels] @@ -43,42 +43,66 @@ def check(folder, consumer, cli, sdk, adapter): print(run.stdout.strip()) assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 print(f"{adapter} {name}: cache={hits}, 16 red and 16 clear pixels") - # A published disk pair must be used without attempting native compilation. - offline = subprocess.run([cli, "--watch", sdk, folder / "offline", cache, "--once"], - capture_output=True, text=True, timeout=45) - assert offline.returncode == 0 and "compiled graphics" in offline.stdout, (offline.stdout, offline.stderr) - key = next(cache.glob("req_*.a")).stem.removeprefix("req_") - published = [cache / f"{key}{suffix}" for suffix in (".txt", ".vs.cso", ".ps.cso")] - contents = [path.read_bytes() for path in published] - run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) - assert run.returncode == 0 and "-> drawn;" in run.stderr, run.stderr - assert "native graphics " not in run.stderr, run.stderr + # Publish a verified disk pair, then hold back its ready marker until after the first draw. + subprocess.run([compiler, "--watch", sdk, cache, cache, "--once"], check=True, timeout=45) + marker, = cache.glob("req_*.a") + key = marker.stem.removeprefix("req_") + manifest = cache / f"{key}.txt" + published = {p: p.read_bytes() for p in + (manifest, manifest.with_suffix(".vs.cso"), manifest.with_suffix(".ps.cso"))} + published_draw = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert published_draw.returncode == 0 and "-> drawn;" in published_draw.stderr, published_draw.stderr + assert "native graphics " not in published_draw.stderr, published_draw.stderr assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 - assert [path.read_bytes() for path in published] == contents - print(f"{adapter} published disk pair: 16 red and 16 clear pixels, cache files unchanged") - - manifest = published[0] - retries = ( - ("unavailable DXC", {"X2W_NATIVE_SHADERS": str(folder / "missing-sdk")}, - (f"native graphics {key} refused:",)), - ("invalid native manifest", {"X2W_TEST_NATIVE_GRAPHICS_BAD_MANIFEST": "1"}, - (f"unsupported manifest version for {key}", f"native graphics {key} ready=0")), + assert all(path.read_bytes() == expected for path, expected in published.items()) + print(f"{adapter} existing disk pair takes precedence with native enabled") + faults = ( + ("missing DXC", {"X2W_NATIVE_SHADERS": str(folder / "missing-sdk")}, f"native graphics {key} refused:"), + ("manifest", {"X2W_TEST_NATIVE_GRAPHICS_MANIFEST_FAILURE": "1"}, "unsupported manifest version"), + ("root", {"X2W_TEST_NATIVE_GRAPHICS_ROOT_FAILURE": "1"}, "failed 0x80004005"), ) - for failure, override, diagnostics in retries: - manifest.rename(Path(str(manifest) + ".pending")) - retry_env = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), **override) - run = subprocess.run(args, env=retry_env, capture_output=True, text=True, timeout=45) - assert run.returncode == 0 and all(text in run.stderr for text in diagnostics), run.stderr - assert Path(str(pixels) + ".first").read_bytes() == clear * 32 + for fault, override, diagnostic in faults: + manifest.rename(str(manifest) + ".pending") + first = Path(str(pixels) + ".first") + first.unlink(missing_ok=True) + pixels.unlink() + fault_env = dict(env, X2W_TEST_PUBLISH_MANIFEST=str(manifest), X2W_NATIVE_SHADERS_ONLY="0", **override) + run = subprocess.run(args, env=fault_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and diagnostic in run.stderr and "-> drawn;" in run.stderr, run.stderr + assert first.read_bytes() == clear * 32 assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 - assert [path.read_bytes() for path in published] == contents - print(f"{adapter} {failure}: disk publication recovers the next draw in the same process") - + assert all(path.read_bytes() == expected for path, expected in published.items()) + print(f"{adapter} {fault}: same-process fallback drew 16 red pixels after publication") ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001))) run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr assert pixels.read_bytes() == clear * 32 print("unsupported stage: all 32 pixels retain the clear color") + # The first DWORD is 0.25 in record zero, 1.0 in record one. Its byte-1 window is 0x003e8000. + records = bytearray(64) + struct.pack_into(" drawn;" not in run.stderr, run.stderr[-7000:] + assert image == clear * 32 + else: + assert "-> drawn;" in run.stderr, run.stderr[-7000:] + color = red if index == 1 else bytes((0, 0, 0, 255)) + assert image == (color * 4 + clear * 4) * 4, (image.hex(), run.stderr[-6000:]) + print(f"{adapter} idxbuf index={index:#x} actual stride={stride}: first RGBA {image[:4].hex()}") return 0 diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index e0a7f665f..092b6e91e 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -383,6 +383,20 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin } else { std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); } + if (mode == "dispatch-scalar-window" || mode == "dispatch-scalar-window-short") { + // An unplaced, three-record view at table byte 64. Only this + // descriptor names the scalar input; byte 0 still names a decoy. + std::memcpy(reinterpret_cast(between), buffers[0], 48); + // Point the placed decoy four words further into the source so that + // taking table byte 0 instead of byte 64 produces a distinct value. + const UINT64 decoy = reinterpret_cast(buffers[0] + 4); + const UINT decoy_view[]{static_cast(decoy), static_cast(decoy >> 32) | (16u << 16), 3, 0x2403c}; + std::memcpy(reinterpret_cast(cpu), decoy_view, sizeof(decoy_view)); + const UINT window[]{static_cast(between), static_cast(between >> 32) | (16u << 16), + mode == "dispatch-scalar-window-short" ? 2u : 3u, 0x2403c}; + std::memcpy(reinterpret_cast(cpu + 64), window, sizeof(window)); + std::memcpy(reinterpret_cast(cpu + 32), descriptors[1], sizeof(descriptors[1])); + } if (mode == "dispatch-records32" || typed_output_offset || shared_uav) { // output at byte 32, none at byte 16 std::memset(reinterpret_cast(cpu + sizeof(descriptors[0])), 0, sizeof(descriptors[1])); std::memcpy(reinterpret_cast(cpu + 32), descriptors[1], sizeof(descriptors[1])); @@ -391,6 +405,37 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (change_table_heap && (FAILED(static_cast(invoke(device, 14, word(&heap_desc), word(&__uuidof(ID3D12DescriptorHeap)), word(&other_heap)))) || !other_heap || other_heap == heap)) return 72; + void* copied_token_output = nullptr; + if (mode.rfind("dispatch-uav-token-", 0) == 0) { + D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; + view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.Buffer.FirstElement = 4; + view.Buffer.NumElements = words - 8; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + if (mode == "dispatch-uav-token-structured") { + view.Format = DXGI_FORMAT_UNKNOWN; + view.Buffer.StructureByteStride = 8; + view.Buffer.FirstElement /= 2; + view.Buffer.NumElements /= 2; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + } + if (mode == "dispatch-uav-token-typed") { + view.Format = DXGI_FORMAT_R32_UINT; + view.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; + } + void* output = placed[1]; + if (mode == "dispatch-uav-token-copied") { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + if (FAILED(static_cast(invoke(device, 133, between, word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(&output))))) return 71; + } + if (mode == "dispatch-uav-token-copied") copied_token_output = output; + invoke(device, 19, word(output), 0, word(&view), cpu + 32); + if (mode == "dispatch-uav-token-wrong-slot") + reinterpret_cast(cpu + 32)[2] = 18; + } const bool heap_record = mode.rfind("dispatch-heap", 0) == 0 && !heap_waterfall; if (heap_record) for (const UINT at : {0u, 32u, 64u}) @@ -635,6 +680,10 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); else if (mode != "dispatch-none" && mode != "dispatch-root-srv-none") invoke(list, 14, 3, 2, 2); + if (copied_token_output) { + // An attempted read of the very placement whose UAV could not be made guest-visible. + invoke(list, 15, word(placed[1]), 16, word(copied_token_output), 16, 16); + } if (const int rc = submit(pixel ? 2 : 1)) return rc; if (pixel) { std::printf("guest queue=%p consumer fence=2 completed\n", queue); @@ -642,6 +691,13 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const bool stale = mode == "dispatch-indirect-pixel-5-stale"; record.draw_pixels(adapter, device, queue, placed[stale ? 0 : 1], stale); } + if (copied_token_output) { + D3D12_RANGE range{16, 32}, none{}; + void* mapped = nullptr; + if (FAILED(static_cast(invoke(copied_token_output, 8, 0, word(&range), word(&mapped)))) || + mapped != reinterpret_cast(between)) return 83; + invoke(copied_token_output, 9, 0, word(&none)); + } if (indirect && !pixel && !record.check_record(groups)) return 80; for (UINT i = 0; i < words; ++i) if (buffers[0][i] != input[i]) return 79; // the input must stay as written diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 80ec40222..d59971e41 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -426,6 +426,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* GetEnvironmentVariableA("X2W_TEST_INDEX_PROBE", index_probe, sizeof(index_probe)); void* index_resource = nullptr; void* vertex_resource = nullptr; + void* copied_vertex_memory = nullptr; if (index_probe[0]) { bool initial_visible = false, final_visible = false; const bool wide_indices = !std::strcmp(index_probe, "late-visible-r32"); @@ -554,15 +555,37 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* corners(positions + 3, {-0.75f, 0.5f, -0.25f, -0.5f}); corners(texcoords + 9, {-0.25f, -0.5f, 0.0f, -1.0f}); corners(positions + 9, {-1.0f, 1.0f, -0.75f, -1.0f}); + // Keep the interpolated fixed-stream color at the center of an RGBA8 quantization bin. + if (GetEnvironmentVariableW(L"X2W_TEST_FIXED_COLOR", nullptr, 0)) + for (auto& vertex : texcoords) vertex[2] = 64.0f / 255.0f; static const std::uint16_t indices[6] = {4, 5, 6, 7, 8, 9}; - const D3D12_VERTEX_BUFFER_VIEW views[2] = { + D3D12_VERTEX_BUFFER_VIEW views[2] = { {reinterpret_cast(texcoords), sizeof(texcoords), sizeof(texcoords[0])}, {reinterpret_cast(positions), sizeof(positions), sizeof(positions[0])}}; const D3D12_INDEX_BUFFER_VIEW index_view{reinterpret_cast(indices), sizeof(indices), DXGI_FORMAT_R16_UINT}; + const bool fixed_rect = GetEnvironmentVariableW(L"X2W_TEST_FIXED_RECT", nullptr, 0) != 0; + if (fixed_rect) { + // A byte offset of four prevents an existing-heap alias. The CPU vertices + // are written after placement, so reading its separate desktop buffer fails. + copied_vertex_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!copied_vertex_memory) return 73; + auto* data = static_cast(copied_vertex_memory) + 4; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1,0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast(invoke(guest, 133, arg(data), arg(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, arg(&__uuidof(ID3D12Resource)), arg(&vertex_resource)))) || !vertex_resource) return 74; + std::memcpy(data, texcoords, sizeof(texcoords)); + views[0].BufferLocation = arg(data); + } invoke(list, 48, 0, 2, arg(views)); - invoke(list, 12, 6, 1, 3, 0); - invoke(list, 47, arg(&index_view)); - invoke(list, 13, 6, 1, 0, 5, 0); + if (fixed_rect) { + invoke(list, 20, 0x11); + invoke(list, 12, 3, 1, 3, 0); + } else { + invoke(list, 12, 6, 1, 3, 0); + invoke(list, 47, arg(&index_view)); + invoke(list, 13, 6, 1, 0, 5, 0); + } } else if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { extern int draw_root_reset(void*, void*); if (const int result = draw_root_reset(guest, list)) return result; @@ -733,6 +756,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* if (const int rc = submit(last)) return rc; if (index_resource) invoke(index_resource, 2); // The backing heap can outlive the resource. if (vertex_resource) invoke(vertex_resource, 2); + if (copied_vertex_memory) VirtualFree(copied_vertex_memory, 0, MEM_RELEASE); if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { extern int report_pixel_uavs(const char*); if (const int rc = report_pixel_uavs(pixels)) return rc; diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index b57bb465f..a9d0f07d3 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -49,11 +49,10 @@ KINDS = {"memory": {"rva", "expect_sha256", "bytes"}, "shader": {"key", "pipeline", "revision", "files"}} # Shader patches, per pipeline: the form of the runtime's key revision (src/startup_stubs/d3d12_draw.inl and # mesh86_cache.inl; is the number each revision bump raises), the translation files the runtime reads for one -# key, and the ones without which it has no translation. A later consumer must check which is current. compute -# also needs .cs.hlsl when its .txt has no native line, and mesh86 reads .ps.cso only for a request with a pixel -# shader; this loader reads neither, so both stay optional. +# key, and the ones without which it has no translation. The fixed rectangle geometry stage, Python compute +# source, and mesh86 pixel stage are required only for their specific pipelines or requests. PIPELINES = { - "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), + "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso", ".gs.cso"), (".txt", ".vs.cso", ".ps.cso")), "compute": ("x2w-startup-shader-cs", (".txt", ".cs.cso", ".cs.hlsl"), (".txt", ".cs.cso")), "mesh86": ("x2w-startup-mesh-86-", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), }