diff --git a/CMakeLists.txt b/CMakeLists.txt index 252816910..11a167c86 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1913,6 +1913,11 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_mesh_xmem_writer_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_MESH86_FIXTURE_XMEM=$") endforeach() +add_executable(mesh57_derive_alloc_check tests/mesh57_derive_alloc_check.cpp src/gfx1013_isa.cpp) +target_include_directories(mesh57_derive_alloc_check PRIVATE src src/startup_stubs) +target_compile_features(mesh57_derive_alloc_check PRIVATE cxx_std_17) +add_test(NAME mesh57_derive_alloc COMMAND mesh57_derive_alloc_check) + 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") @@ -1920,6 +1925,18 @@ if(TARGET compile_dxil AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${ 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}") + foreach(mode derived derived-off derived-bad derived-depth derived-reviewed derived-untranslated derived-root derived-root-unset derived-root-table derived-slot55 derived-slot55-mask) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_NATIVE_SHADERS=${DXC_BIN_DIR}") + endforeach() + foreach(mode derived-dxc derived-dxc-reviewed) + add_test(NAME startup_indirect_mesh_${mode}_${backend} + COMMAND startup_indirect_draw_indexed ${backend} mesh-${mode}) + set_tests_properties(startup_indirect_mesh_${mode}_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_MESH57_DXC_DIR=${DXC_BIN_DIR}") + endforeach() 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}") diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index aa7396027..c993777c3 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -86,3 +86,66 @@ 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$'`. + +## Opt-in immediate allocation + +`X2W_MESH57_DERIVE_STATE=1`, together with `X2W_SHADER_CACHE` and a compiler directory, can build one desktop mesh pipeline for a direct `DispatchMesh` `ExecuteIndirect` when no reviewed `.mesh57-state` file was opened for that slot 57 pipeline. That is the `graphics/mesh_profile_missing` refusal: a slot 57 mesh with captured stages and no desktop pipeline. The switch does not change the reviewed profile. With the switch unset, the indirect call keeps the existing refusal. `graphics/no_translation` is a different refusal (no captured stages, or the call is not this slot 57 mesh) and this switch does not forward it. + +`X2W_MESH57_DXC_DIR` is the directory of `dxcompiler.dll` and `dxil.dll` for this path alone. It does not turn on native translation for other graphics or compute programs. `X2W_NATIVE_SHADERS` is still accepted as the compiler directory for this one pipeline, and setting it also turns that other translation on. When neither directory is set, the call stays refused and the log says `derived mesh needs the native shader compiler`. + +On the Windows test PC at `aed2c0c7`, `X2W_MESH57_DERIVE_STATE=1` with no compiler directory logged that refusal and forwarded nothing. Setting `X2W_NATIVE_SHADERS` compiled this path and also translated other programs, which refused fixed graphics entries and compute views before any `ExecuteIndirect`. A startup run that wants only this path sets `X2W_MESH57_DERIVE_STATE=1`, `X2W_MESH57_DXC_DIR`, and `X2W_SHADER_CACHE`, and leaves `X2W_NATIVE_SHADERS` unset. + +At `075e4611` the same PC ran 420 seconds with the derive switch and `X2W_MESH57_DXC_DIR` set and `X2W_NATIVE_SHADERS` unset. Menus stayed up. `DispatchMesh` `ExecuteIndirect` still refused 656,186 calls in the graphics-pipeline bucket and forwarded none. The log showed 16 lines, all `derived mesh needs a fixed slot 57 pair`. That 16 is the old log cap, not the number of calls that entered derivation. With the switch on, every `DispatchMesh` `ExecuteIndirect` is now counted, including ones that never enter derivation. + +Derivation runs for a direct list whose bound pipeline is slot 57, or slot 55 whose base chain ends at slot 57, when that pipeline has no desktop pipeline and no cached mesh stage. Anything else is counted and left on the existing refusal: + +- `not a direct list` +- `no pipeline bound` +- `desktop pipeline already set` +- `cached mesh stage` +- `no pipeline record` +- `pipeline is slot 86` (a stream mesh, or a pipeline that already has a slot 86 key) +- `pipeline is a derived slot 55` (the base chain does not end at slot 57) +- `pipeline is not slot 57` + +A slot 57 record is a fixed pair only when the captured descriptor is 768 bytes, the vertex span at `+0x48` is empty, the mesh length at `+0x70` is non-zero, and both the mesh and pixel bytes were copied at creation. Otherwise the call is counted under one of: + +- `slot 57 descriptor is shorter than the fixed prefix` (under 120 bytes, so the stage words were not read) +- `slot 57 descriptor is not 768 bytes` +- `slot 57 descriptor has a vertex span` (the capture skips the mesh and pixel copies) +- `slot 57 descriptor has no mesh stage length` +- `slot 57 mesh stage was not captured` (the bytes were unreadable or larger than 1 MiB) +- `slot 57 pixel stage is absent from the descriptor` (the pixel pointer and the pixel length are both zero; the mesh copy is kept) +- `slot 57 pixel stage was not captured` (the descriptor names a pixel span whose bytes were not kept) + +Those seven still refuse. The 768-byte rule stays: a shorter descriptor cannot be checked against a reviewed `.mesh57-state` file. While the switch is on, publishing a slot 57 request no longer drops the captured stage bytes, so a later call whose first refusal depended on the command list can still see them. + +The first time a reason is seen, stderr gets one `x2w-render mesh57-derive sample` line: the reason, the creating slot (`path`), the derived-from slot (`base`), descriptor and stage sizes, the vertex, mesh and pixel lengths from the descriptor, the pipeline key, the list type, whether a desktop pipeline or a slot 86 key is present, the guest root (`root`, `const`, `other`, `heap`), the first parameter types (`params`), and the first slot 55 patch tags and sizes (`patches`). The line has no file path. `params` uses `t` for a descriptor table, `cN` for an N-dword constant block, `cbv`, `srv`, and `uav`. `patches` uses `tag:bytes`. A sample with no root parameters or no patch list prints `-`. Every 300 presented frames the heartbeat adds `x2w-render mesh57-derive:` with the call count of each reason, then `x2w-render mesh57-derive forwards:` with the `forwarded` count. That count is the number of calls that installed a desktop pipeline from this path. + +A startup run on the Windows test PC recorded 653,708 refused `DispatchMesh` `ExecuteIndirect` calls in 420 seconds and forwarded none. Across draw and mesh, the graphics-pipeline census counted `graphics/no_translation` 446,421 and `graphics/mesh_profile_missing` 427,428. This switch is only the second of those, and only the immediate-allocation shape below. Slot 86 meshes with no cached stage stay refused. + +The accepted program writes `m0` with one `s_mov_b32` of an integer immediate and the next instruction is the only `s_sendmsg` `GS_ALLOC_REQ` (`0xbf900009`). The immediate is `(primitives << 12) | vertices`, both counts are in 1..64, and the high byte is clear. A group-memory count exchange (`0xbf8a0000`) or an `s_mov_b32` of `exec_lo` is refused. The derived layout is one wave64 group of 64 threads, triangle topology, and group stride 0. Stride 0 is accepted because this program does not read the group id; the lowerer skips that multiply. The pixel shader must be a constant `MRT0` export with no resource bindings. + +An empty guest root is unchanged. One 32-bit constant parameter of 1..8 dwords and no other parameters is bound, including when the guest root is heap indexed: user SGPR s8 is that block, and the draw copies it into a desktop b0 the same way a reviewed constant profile does. The constant words must already be set on the list. The heap base itself is not bound; a shader that reads it is refused by the lowerer. A heap-indexed root with any other shape (`derived mesh guest root is heap indexed`), a descriptor or root descriptor (`derived mesh guest root has descriptors`), or any other constant shape (`derived mesh guest root constants do not fit one user block`) stays refused. Those need a reviewed SGPR map; this path does not invent one. + +A slot 55 pipeline reuses that derived mesh when every patch record is a blend patch (tag 2, 0x14c bytes) or the patch list is empty. The last blend patch replaces the base blend. Tag 2 is the only slot 55 record this repository applies: the graphics path reads that blend descriptor and does not apply any other tag. Depth and raster for a slot 57 base come from its state block, not from a patch tag. A record whose tag is not 2 stays refused, and the reason names that tag (for example `slot 55 patch tag 3 is not applied`). A list whose size is not a whole number of 0x14c records stays `slot 55 patches are not applied`. The sample lists the first records either way. The base's shader, root, and depth rules are unchanged. + +Fixed function state comes from state block A. The mesh layout word at `+0x004` must be 6. Blend words are read at the mesh shift (`+0x54` on top of `+0xD0`). Depth and stencil must decode as disabled; an enabled test is refused rather than given a guessed depth format. The color target is the one single-sample target bound on that direct list, with a viewport and a scissor and no depth view. The rasterizer is solid, cull none, and depth clip. Those three values are not read from the register block. A `.mesh57-state` file that is present, including one whose bytes do not match, keeps the reviewed path and this switch does not create a pipeline. + +A failed derivation is remembered for that pipeline. Attachment and root mismatches are not: a later direct list can still be the first accepted call. The desktop pipeline then keeps the color format of that call. + +From the x64 Windows build environment, with DXC available to the native shader stand-in: + +```powershell +ctest --preset dev -j 1 --no-tests=error -R "mesh57_derive_alloc|startup_indirect_mesh_derived" +``` + +`startup_indirect_mesh_derived_{warp,hardware}` forwards one group and reads a white texel at `(2,0)` on a 4 by 2 target. `derived-dxc` does the same with only `X2W_MESH57_DXC_DIR` set, and the process clears `X2W_NATIVE_SHADERS` before the call. `derived-root` is that program plus one guest constant at s8, with the word set, and paints the same texel. `derived-slot55` draws through a slot 55 pipeline with no patches and paints the same texel. `derived-off` leaves the switch unset. `derived-bad` has no immediate allocation. `derived-depth` enables the depth test in the register block. `derived-reviewed` and `derived-dxc-reviewed` supply a profile file that does not match; the second does that with only `X2W_MESH57_DXC_DIR` set. `derived-untranslated` is a slot 57 pipeline with no captured mesh or pixel program. `derived-root-unset` omits the constant word. `derived-root-table` uses a descriptor table. `derived-slot55-mask` applies a blend patch with a zero write mask. Those leave the clear color. Each returns 77 when mesh shaders or the command signature are unavailable. `mesh57_derive_alloc` checks the allocation reader, the root decision, the slot 55 patch rule, and the forwards line without a device. + +On the Windows test PC at `f358a2ed`, a 420 second run with `X2W_TRANSLATED_INDIRECT_DRAW=1`, `X2W_MESH57_DERIVE_STATE=1`, and `X2W_MESH57_DXC_DIR` set forwarded nothing. The derive census was `slot 57 pixel stage was not captured` 47823, `derived mesh keeps a non-empty guest root refused` 152144, and `pipeline is a derived slot 55` 180066. The non-empty sample had both stages (mesh 9536 bytes, pixel 4352 bytes). The slot 55 sample was a 332-byte descriptor whose base was slot 57 and whose stage lengths were unread. That root refusal is replaced by the three root reasons above, and a slot 55 call now uses its slot 57 base when the patches are blend records. A 4352-byte pixel is still not a constant export, and a program that is not the one immediate allocation is still refused. + +On the Windows test PC at `54331137`, the same switches, a 420 second run, forwarded nothing (`x2w-render mesh57-derive forwards: 0`). The census was `derived mesh guest root is heap indexed` 353719, `slot 57 pixel stage was not captured` 130628, and `slot 55 patches are not applied` 514994. The heap-indexed sample was path 57, descriptor 768, mesh 9536, pixel 4352, state A 504, state B 80, root 5, one constant dword, four other parameters, heap 1024. The pixel sample was path 57, mesh 1408, pixel length 0, state A 464, root 5, two constant dwords, four other parameters, heap 3072. The slot 55 sample was one 332-byte record on a slot 57 base with that same five-parameter root and heap 3072. + +The capture copies a pixel stage only when its length is non-zero and the bytes are readable. A zero pointer and a zero length is an empty span: the copy is skipped and the mesh bytes stay. The 1408-byte mesh in that sample was kept, so the pixel words in the creation descriptor were zero. An unreadable non-zero span fails the snapshot and drops both stages; this sample is not that case, and nothing writes the pixel stage after creation. A slot 55 record is state, not a shader. This path does not invent a pixel shader. A zero pixel length is now `slot 57 pixel stage is absent from the descriptor`. + +Heap 1024 is the view-heap flag (`0x400`). Heap 3072 is that flag plus the sampler-heap flag (`0xC00`). No reviewed map in this repository assigns user SGPRs for a five-parameter heap-indexed root on the mesh path. The maps that do exist are different ABIs. Raw graphics, and the reflected graphics path, start user SGPRs at s8: a descriptor table is one SGPR, a 32-bit constant block is one SGPR per dword, and a root CBV, SRV, or UAV is two SGPRs, with the heaps following when their flags are set. That layout is for a graphics stage. Direct compute without a reflected stage starts at s4 with the same parameter packing, and both heap flags occupy the next two SGPRs only when they exactly fill the user SGPR count. The 1024 sample has only the view-heap flag, and s4 is the compute ABI. A reviewed `.mesh57-state` profile stores the SGPR, the root parameter, and the count for that one program. These pipelines have no such file. The missing map is the physical user SGPR of each of the five parameters, and the user SGPR of the resource heap (and of the sampler heap when `0x800` is set). The stored root parameter keeps the type, and for a constant block the dword count; a descriptor table's ranges are not kept. This path does not guess the SGPRs. The sample line records the types so the map can be raised with the measured parameter kinds. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f448bb21f..4318ed5ea 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1651,6 +1651,8 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | +| `X2W_MESH57_DXC_DIR=` | experimental, with `X2W_MESH57_DERIVE_STATE=1`: the directory of `dxcompiler.dll` and `dxil.dll` for that one slot 57 derivation. Other graphics and compute programs stay on the non-native path. Unset, the derivation may still use `X2W_NATIVE_SHADERS` when that directory is set. When neither directory is set, the call stays refused (`derived mesh needs the native shader compiler`). See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | +| `X2W_MESH57_DERIVE_STATE=1` | experimental, with `X2W_SHADER_CACHE` and `X2W_MESH57_DXC_DIR` (or `X2W_NATIVE_SHADERS`): addresses `graphics/mesh_profile_missing` for one slot 57 shape. A direct `DispatchMesh` `ExecuteIndirect` may build one desktop mesh pipeline from an immediate `GS_ALLOC_REQ` and the bound color target when captured stages exist and no `.mesh57-state` file was opened. One guest constant block of 1..8 dwords is copied into desktop b0, including when that root is heap indexed. A slot 55 pipeline whose base is that slot 57 mesh reuses it when every patch is a blend record. A patch whose tag is not 2 stays refused and the reason names that tag. The sample line lists the first root-parameter types and the first patch tags. A zero pixel length in the descriptor stays refused (`slot 57 pixel stage is absent from the descriptor`). `graphics/no_translation`, slot 86, depth, stencil, any other heap-indexed root, a descriptor root, and any other allocation shape stay refused. While the switch is on, every `DispatchMesh` `ExecuteIndirect` is counted: the first use of a reason logs `x2w-render mesh57-derive sample`, and the 300-frame heartbeat logs `x2w-render mesh57-derive:` plus `x2w-render mesh57-derive forwards:`. The rasterizer is not taken from the register block. See [Opt-in immediate allocation](experiments/native-fixed-mesh57.md#opt-in-immediate-allocation) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 4f8e00c18..1188706e2 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -48,6 +48,8 @@ struct PipelineInfo { 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. + mutable bool mesh57_reviewed_present = false; // A .mesh57-state file was opened for this pipeline. + mutable const char* mesh57_derive_reason = nullptr; // Opt-in derivation refused this pipeline for good. }; struct ViewRecord { // Capture the guest descriptor layout, independent of the desktop SDK. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78..8372b1e79 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -902,8 +902,12 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo 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(); + // The opt-in derivation reads these bytes on a later ExecuteIndirect. A retryable refusal + // (attachments, the bound root) must not become a permanent missing-stage refusal. + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + info->fixed_ms.reset(); + info->fixed_ps.reset(); + } } } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56dbe26c4..e8fa91f1f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -89,6 +89,7 @@ #include "gfx1013_compute_native.h" #include "gfx1013_pixel.h" #include "mesh_shader_pipeline.h" +#include "mesh57_alloc.h" #include #include "native_buffer_store_view.h" #include "shader_dxil_compiler.h" @@ -167,6 +168,8 @@ struct IndirectGraphicsPipeline { 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. + // Opt-in derived mesh: constant_guest names one guest constant block, and the guest root is not heap indexed. + bool plain_constants = false; }; // Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. @@ -3735,6 +3738,14 @@ bool root_srv_at_draw() } LONG root_srv_copies_skipped, root_srv_copies_made; +#ifdef X2W_NATIVE_SHADERS +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override = nullptr, + const PipelineInfo* source = nullptr); +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass); +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type); +void log_mesh57_derive_census(); +#endif + void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, void* count_buffer, u64 count_offset) { @@ -3815,6 +3826,40 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (indexed) bytes = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); else bytes = sizeof(D3D12_DRAW_ARGUMENTS); +#ifdef X2W_NATIVE_SHADERS + // Opt-in for one slot 57 shape. Every DispatchMesh is counted here when the switch is on, + // including calls that never enter derivation. Draws stay on the refusal below. + if (mesh && x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) { + const PipelineInfo* derived_info = pass.pipeline ? pipeline_info(pass.pipeline) : nullptr; + const char* skip = nullptr; + if (type != D3D12_COMMAND_LIST_TYPE_DIRECT) + skip = "not a direct list"; + else if (!pass.pipeline) + skip = "no pipeline bound"; + else if (pass.pipeline->own().real) + skip = "desktop pipeline already set"; + else if (pass.indirect_graphics.cached_mesh) + skip = "cached mesh stage"; + else if (!derived_info) + skip = "no pipeline record"; + else if (pass.pipeline->own().mesh86_key || derived_info->path == 86) + skip = "pipeline is slot 86"; + else if (derived_info->path != 57 && derived_info->path != 55) + skip = "pipeline is not slot 57"; + const bool slot55 = !skip && derived_info && derived_info->path == 55; + if (skip) { + record_mesh57_derive(skip, pass.pipeline, derived_info, static_cast(type)); + } else if (const char* why = slot55 ? derive_slot55_mesh(pass.pipeline, pass) + : derive_slot57_mesh(pass.pipeline, pass)) { + record_mesh57_derive(why, pass.pipeline, derived_info, static_cast(type)); + } else if (pass.pipeline->own().real) { + pass.indirect_graphics = pass.pipeline->own().indirect_graphics; + record_mesh57_derive("forwarded", pass.pipeline, pipeline_info(pass.pipeline), static_cast(type)); + } else { + record_mesh57_derive("derivation produced no pipeline", pass.pipeline, derived_info, static_cast(type)); + } + } +#endif if (type != D3D12_COMMAND_LIST_TYPE_DIRECT || (!translated && (!pass.indirect_graphics.root || (pass.indirect_graphics.constant_guest == UINT_MAX && pass.indirect_graphics.root != pass.graphics_root) || pass.indirect_graphics.mesh != mesh))) { @@ -3846,7 +3891,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 != 0) != (pso.constant_guest != UINT_MAX)) + const bool mapped = pso.constant_guest != UINT_MAX; + const bool indexing_matches = (pass.root_heap_flags != 0) == mapped || + (pso.plain_constants && pass.root_heap_flags == 0 && mapped); + if (!pass.root || pass.root != pso.guest_root_params || !indexing_matches) 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 || (pso.constant_guest != UINT_MAX && i != pso.constant_guest)) continue; @@ -7680,6 +7728,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (n == start) n += std::snprintf(line + n, sizeof(line) - n, " 0"); } log("%s", line); +#ifdef X2W_NATIVE_SHADERS + log_mesh57_derive_census(); +#endif } if (render_mode() && frame % 300 == 0) { // Which command-list slots the title called in the last 300 frames, per frame. diff --git a/src/startup_stubs/mesh57_alloc.h b/src/startup_stubs/mesh57_alloc.h new file mode 100644 index 000000000..4d3dced9e --- /dev/null +++ b/src/startup_stubs/mesh57_alloc.h @@ -0,0 +1,539 @@ +// Opt-in slot 57 mesh layout for X2W_MESH57_DERIVE_STATE. +// +// A reviewed .mesh57-state profile still owns the MS entry layout. This reader accepts only the +// smallest program the mesh lowerer already runs: one s_mov_b32 of an integer immediate into m0 +// immediately before the only s_sendmsg GS_ALLOC_REQ (0xbf900009). The immediate is +// (primitives << 12) | vertices. Anything else, including the group-memory count exchange, stays +// refused so a captured program cannot invent threads, a wave size, or a group stride. +#pragma once + +#include "gfx1013_isa.h" + +#include +#include +#include +#include +#include +#include + +namespace x2w_startup { + +struct MeshDerivedLayout { + unsigned threads = 0; + unsigned vertices = 0; + unsigned primitives = 0; + unsigned topology = 0; + unsigned group_stride = 0; + unsigned wave_size = 0; +}; + +// One wave64 group. group_stride stays 0: the accepted program does not read the group id, and the +// lowerer skips that multiply when the stride is 0. Returns empty when the program is not the +// single immediate allocation above, or when either count is outside 1..64. +inline std::optional derive_immediate_mesh_layout(std::string_view code) noexcept +{ + if (code.empty() || code.size() % 4 != 0) + return std::nullopt; + try { + bool previous_immediate = false; + std::uint32_t previous_word = 0; + unsigned allocations = 0; + unsigned vertices = 0; + unsigned primitives = 0; + bool wave32 = false; + bool exchange = false; + for (unsigned pc = 0; pc < code.size();) { + std::uint32_t raw = 0; + std::memcpy(&raw, code.data() + pc, sizeof(raw)); + const auto inst = x2w::gfx1013::instruction(code, pc); + if (inst.size == 0 || pc + inst.size > code.size()) + return std::nullopt; + if (raw == 0xbf8a0000u) + exchange = true; + if (raw == 0xbf900009u) { + if (!previous_immediate) + return std::nullopt; + const unsigned next_vertices = previous_word & 4095u; + const unsigned next_primitives = (previous_word >> 12) & 4095u; + if ((previous_word >> 24) != 0 || next_vertices == 0 || next_primitives == 0 || + next_vertices > 64u || next_primitives > 64u) + return std::nullopt; + vertices = next_vertices; + primitives = next_primitives; + ++allocations; + } + previous_immediate = false; + previous_word = 0; + if (inst.form == x2w::gfx1013::Form::sop1 && inst.name == "s_mov_b32") { + const unsigned dst = (raw >> 16) & 127u; + const unsigned src = raw & 255u; + if (dst == 126u) + wave32 = true; + if (dst == 124u) { + if (src >= 128u && src <= 192u) { + previous_immediate = true; + previous_word = static_cast(src - 128u); + } else if (src == 255u && inst.size >= 8u) { + std::uint32_t literal = 0; + std::memcpy(&literal, code.data() + pc + 4, sizeof(literal)); + previous_immediate = true; + previous_word = literal; + } + } + } + pc += inst.size; + } + if (allocations != 1 || wave32 || exchange) + return std::nullopt; + MeshDerivedLayout layout; + layout.threads = 64; + layout.vertices = vertices; + layout.primitives = primitives; + layout.topology = 2; + layout.group_stride = 0; + layout.wave_size = 64; + return layout; + } catch (...) { + return std::nullopt; + } +} + +// Why a slot 57 creation record is not the fixed mesh+pixel pair this path can read. +// nullptr means both stages were captured from a 768-byte descriptor with no vertex span. +// The clauses match the capture in note_pipeline: a vertex span, a zero mesh length, or a +// short descriptor leaves the stage pointers empty, and an unreadable stage is dropped. +// A zero pixel length is an empty span in the descriptor, not a copy that failed. +struct Mesh57PairRecord { + std::size_t desc_bytes = 0; + bool mesh_captured = false; + bool pixel_captured = false; + std::uint64_t vertex_pointer = 0; + std::uint64_t vertex_bytes = 0; + std::uint64_t mesh_length = 0; + std::uint64_t pixel_length = 0; +}; + +// One stage copy, matching note_pipeline's snapshot. readable is the caller's check of the +// guest bytes; this function does not read them. A zero length and a zero pointer is an empty +// span and the copy is skipped. A zero length with a pointer, or a non-zero length that is +// not readable, fails the copy. note_pipeline then drops both stages. +enum class Mesh57StageCopy : unsigned { empty = 0, copied = 1, unreadable = 2 }; + +inline Mesh57StageCopy mesh57_stage_copy(std::uint64_t pointer, std::uint64_t bytes, bool readable) noexcept +{ + if (!bytes) + return pointer ? Mesh57StageCopy::unreadable : Mesh57StageCopy::empty; + return readable ? Mesh57StageCopy::copied : Mesh57StageCopy::unreadable; +} + +// True when note_pipeline keeps the stage copies. The vertex span must be empty, the mesh +// length must be non-zero, the mesh bytes must have been copied, and neither snapshot failed. +// An empty pixel span is kept with the mesh. An unreadable pixel drops the mesh as well. +inline bool mesh57_fixed_stages_kept(bool vertex_empty, bool mesh_length, Mesh57StageCopy pixel, + Mesh57StageCopy mesh) noexcept +{ + if (!vertex_empty || !mesh_length) + return false; + if (pixel == Mesh57StageCopy::unreadable || mesh == Mesh57StageCopy::unreadable) + return false; + return mesh == Mesh57StageCopy::copied; +} + +inline const char* mesh57_fixed_pair_reason(const Mesh57PairRecord& record) noexcept +{ + if (record.desc_bytes < 15 * sizeof(std::uint64_t)) + return "slot 57 descriptor is shorter than the fixed prefix"; + if (record.desc_bytes != 0x300) + return "slot 57 descriptor is not 768 bytes"; + if (record.vertex_pointer || record.vertex_bytes) + return "slot 57 descriptor has a vertex span"; + if (!record.mesh_length) + return "slot 57 descriptor has no mesh stage length"; + if (!record.mesh_captured) + return "slot 57 mesh stage was not captured"; + if (!record.pixel_captured) { + if (!record.pixel_length) + return "slot 57 pixel stage is absent from the descriptor"; + return "slot 57 pixel stage was not captured"; + } + return nullptr; +} + +// One sample of the bound pipeline for a DispatchMesh ExecuteIndirect the opt-in did not forward. +// Counts are call counts. The sample is the first call that used that reason. +struct Mesh57DeriveSample { + int path = 0; + int base_path = 0; + std::uint64_t key = 0; + std::uint32_t desc_bytes = 0; + std::uint32_t mesh_bytes = 0; + std::uint32_t pixel_bytes = 0; + std::uint32_t state_a = 0; + std::uint32_t state_b = 0; + std::uint32_t vertex_bytes = 0; + std::uint32_t mesh_length = 0; + std::uint32_t pixel_length = 0; + int list_type = 0; + int real = 0; + int mesh86 = 0; + // Guest root at creation. type 0 in Mesh57RootParameterView is a 32-bit constant block. + // other counts every parameter that is not one. heap is the heap-indexing flag word. + std::uint32_t root_parameters = 0; + std::uint32_t root_constant_dwords = 0; + std::uint32_t root_other = 0; + std::uint32_t root_heap = 0; + // First parameters, in order. type 0 is a descriptor table, 1 is 32-bit constants + // (count is the dword count), 2 is a root CBV, 3 is a root SRV, 4 is a root UAV. + static constexpr int root_param_slots = 8; + int root_param_n = 0; + std::uint8_t root_param_type[root_param_slots]{}; + std::uint32_t root_param_count[root_param_slots]{}; + // First slot 55 patch records. tag is the record's first dword and bytes is its size. + static constexpr int patch_slots = 4; + int patch_n = 0; + std::uint32_t patch_tag[patch_slots]{}; + std::uint32_t patch_size[patch_slots]{}; +}; + +// One guest root parameter, without a D3D12 type. type 0 is 32-bit constants and +// constants is that block's dword count. Any other type is not a constant block. +struct Mesh57RootParameterView { + unsigned type = 0; + unsigned constants = 0; +}; + +// User SGPRs for a derived mesh start at s8, one dword per constant, in parameter +// order. That is the layout the mesh lowerer checks against the root signature. +// Only one constant block of 1..8 dwords fits the desktop b0 the draw path already copies. +struct Mesh57RootContract { + unsigned parameters = 0; + unsigned constant_dwords = 0; + unsigned other_parameters = 0; + unsigned heap_flags = 0; + bool bind_constants = false; + unsigned sgpr = 0; +}; + +inline Mesh57RootContract mesh57_root_contract(const Mesh57RootParameterView* params, unsigned count, + unsigned heap_flags) noexcept +{ + Mesh57RootContract out; + out.parameters = count; + out.heap_flags = heap_flags; + out.sgpr = 8; + // A heap-indexing flag does not by itself name a descriptor. One constant block is still + // copied into desktop b0; a shader that also reads the heap is refused by the lowerer. + bool constants_only = count == 1 && params; + if (constants_only) { + out.constant_dwords = params[0].constants; + constants_only = params[0].type == 0 && params[0].constants >= 1 && params[0].constants <= 8 && + out.sgpr <= 106 && params[0].constants <= 106 - out.sgpr; + } + for (unsigned i = 0; i < count; ++i) { + if (!params || params[i].type != 0) + out.other_parameters += 1; + else if (count != 1) + out.constant_dwords += params[i].constants; + } + out.bind_constants = constants_only; + return out; +} + +// nullptr when this root can take the existing empty path or the one-block constant path. +// Anything else stays refused: a descriptor or a heap flag needs a reviewed SGPR map. +inline const char* mesh57_root_bind_reason(const Mesh57RootContract& contract) noexcept +{ + if (contract.bind_constants) + return nullptr; + if (contract.parameters == 0 && contract.heap_flags == 0) + return nullptr; + if (contract.heap_flags) + return "derived mesh guest root is heap indexed"; + if (contract.other_parameters) + return "derived mesh guest root has descriptors"; + if (!contract.bind_constants) + return "derived mesh guest root constants do not fit one user block"; + return nullptr; +} + +// One slot 55 patch record. The creation path stores fixed 0x14c records. The only tag this +// repository applies is 2, the blend descriptor (derived_blend.h). Other tags are named and refused. +struct Mesh57PatchNote { + std::uint32_t tag = 0; + std::uint32_t bytes = 0; +}; + +enum class Mesh57PatchDecision : unsigned { accept = 0, unaligned = 1, other_tag = 2 }; + +struct Mesh57PatchScan { + Mesh57PatchDecision decision = Mesh57PatchDecision::accept; + std::uint32_t other_tag = 0; + int notes = 0; +}; + +// Writes the first cap records. An empty list is accepted. Every whole record must be tag 2. +// A size that is not a whole number of 0x14c records is unaligned; a trailing partial record is +// still noted when cap allows. The first tag that is not 2 is other_tag. +inline Mesh57PatchScan mesh57_scan_slot55_patches(const unsigned char* records, std::size_t bytes, + Mesh57PatchNote* notes, int cap) noexcept +{ + constexpr std::size_t record = 0x14c; + Mesh57PatchScan scan; + if (!bytes) + return scan; + if (!records || cap < 0) { + scan.decision = Mesh57PatchDecision::unaligned; + return scan; + } + const bool whole = bytes % record == 0; + const std::size_t whole_bytes = whole ? bytes : bytes - (bytes % record); + for (std::size_t at = 0; at < whole_bytes; at += record) { + std::uint32_t tag = 0; + std::memcpy(&tag, records + at, sizeof(tag)); + if (tag != 2 && scan.decision == Mesh57PatchDecision::accept) { + scan.decision = Mesh57PatchDecision::other_tag; + scan.other_tag = tag; + } + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = static_cast(record); + scan.notes += 1; + } + } + if (!whole) { + const std::size_t rest = bytes - whole_bytes; + std::uint32_t tag = 0; + if (rest >= sizeof(tag)) + std::memcpy(&tag, records + whole_bytes, sizeof(tag)); + if (notes && scan.notes < cap) { + notes[scan.notes].tag = tag; + notes[scan.notes].bytes = rest > 0xffffffffu ? 0xffffffffu : static_cast(rest); + scan.notes += 1; + } + scan.decision = Mesh57PatchDecision::unaligned; + } + return scan; +} + +// Stable text for a tag this path does not apply. The caller keeps the buffer it passes. +inline std::size_t mesh57_slot55_tag_reason(std::uint32_t tag, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + const int n = std::snprintf(out, cap, "slot 55 patch tag %u is not applied", tag); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +struct Mesh57DeriveCensus { + static constexpr int capacity = 24; + struct Row { + const char* reason = nullptr; + std::uint64_t calls = 0; + Mesh57DeriveSample sample; + }; + Row rows[capacity]; + int used = 0; + std::uint64_t overflow_calls = 0; + + Mesh57DeriveCensus() + { + for (int i = 0; i < capacity; ++i) + rows[i] = Row(); + } + + // True the first time this reason text is stored. Later calls only add to the count. + // The row keeps the first pointer, so that pointer must outlive the census. Matching is by + // text: two copies of the same characters are one reason. String-literal addresses are not. + bool note(const char* reason, const Mesh57DeriveSample& sample) noexcept + { + if (!reason) + return false; + for (int i = 0; i < used; ++i) { + if (rows[i].reason && std::strcmp(rows[i].reason, reason) == 0) { + rows[i].calls += 1; + return false; + } + } + if (used >= capacity) { + overflow_calls += 1; + return false; + } + rows[used].reason = reason; + rows[used].calls = 1; + rows[used].sample = sample; + used += 1; + return true; + } + + std::uint64_t total() const noexcept + { + std::uint64_t calls = overflow_calls; + for (int i = 0; i < used; ++i) + calls += rows[i].calls; + return calls; + } +}; + +inline void mesh57_write_root_params(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.root_param_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.root_param_n < Mesh57DeriveSample::root_param_slots + ? sample.root_param_n : Mesh57DeriveSample::root_param_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + char piece[16]; + const unsigned type = sample.root_param_type[i]; + const unsigned count = sample.root_param_count[i]; + int wrote = 0; + if (type == 0) + wrote = std::snprintf(piece, sizeof(piece), "t"); + else if (type == 1) + wrote = std::snprintf(piece, sizeof(piece), "c%u", count); + else if (type == 2) + wrote = std::snprintf(piece, sizeof(piece), "cbv"); + else if (type == 3) + wrote = std::snprintf(piece, sizeof(piece), "srv"); + else if (type == 4) + wrote = std::snprintf(piece, sizeof(piece), "uav"); + else + wrote = std::snprintf(piece, sizeof(piece), "p%u", type); + if (wrote <= 0) + break; + const int put = std::snprintf(out + used, cap - used, "%s%s", i ? "," : "", piece); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + +inline void mesh57_write_patches(const Mesh57DeriveSample& sample, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return; + out[0] = 0; + if (sample.patch_n <= 0) { + std::snprintf(out, cap, "-"); + return; + } + std::size_t used = 0; + const int n = sample.patch_n < Mesh57DeriveSample::patch_slots ? sample.patch_n : Mesh57DeriveSample::patch_slots; + for (int i = 0; i < n && used + 1 < cap; ++i) { + const int put = std::snprintf(out + used, cap - used, "%s%u:%u", i ? "," : "", + sample.patch_tag[i], sample.patch_size[i]); + if (put < 0 || static_cast(put) >= cap - used) { + out[cap - 1] = 0; + return; + } + used += static_cast(put); + } +} + +inline std::size_t mesh57_derive_sample_line(const char* reason, const Mesh57DeriveSample& sample, + char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + char params[96]; + char patches[80]; + mesh57_write_root_params(sample, params, sizeof(params)); + mesh57_write_patches(sample, patches, sizeof(patches)); + const int n = std::snprintf(out, cap, + "x2w-render mesh57-derive sample reason=%s path=%d base=%d desc=%u ms=%u ps=%u state_a=%u state_b=%u " + "vs=%u ms_len=%u ps_len=%u key=%016llx list=%d real=%d mesh86=%d root=%u const=%u other=%u heap=%u " + "params=%s patches=%s", + reason ? reason : "", sample.path, sample.base_path, sample.desc_bytes, sample.mesh_bytes, + sample.pixel_bytes, sample.state_a, sample.state_b, sample.vertex_bytes, sample.mesh_length, + sample.pixel_length, static_cast(sample.key), sample.list_type, sample.real, + sample.mesh86, sample.root_parameters, sample.root_constant_dwords, sample.root_other, sample.root_heap, + params, patches); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +inline std::size_t mesh57_derive_summary_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + int n = std::snprintf(out, cap, "x2w-render mesh57-derive:"); + if (n < 0) { + out[0] = 0; + return 0; + } + for (int i = 0; i < census.used && static_cast(n) + 1 < cap; ++i) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "%s %s %llu", + i ? ";" : "", census.rows[i].reason ? census.rows[i].reason : "", + static_cast(census.rows[i].calls)); + if (wrote < 0) + break; + if (static_cast(n) + static_cast(wrote) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + n += wrote; + } + if (census.overflow_calls && static_cast(n) + 1 < cap) { + const int wrote = std::snprintf(out + n, cap - static_cast(n), "; unlisted %llu", + static_cast(census.overflow_calls)); + if (wrote > 0 && static_cast(n) + static_cast(wrote) < cap) + n += wrote; + } + return static_cast(n); +} + +// Calls whose reason text is "forwarded": a derived pipeline installed a desktop PSO. +inline std::uint64_t mesh57_derive_forwarded(const Mesh57DeriveCensus& census) noexcept +{ + for (int i = 0; i < census.used; ++i) { + if (census.rows[i].reason && std::strcmp(census.rows[i].reason, "forwarded") == 0) + return census.rows[i].calls; + } + return 0; +} + +inline std::size_t mesh57_derive_forwards_line(const Mesh57DeriveCensus& census, char* out, std::size_t cap) noexcept +{ + if (!out || cap == 0) + return 0; + out[0] = 0; + if (!census.total()) + return 0; + const int n = std::snprintf(out, cap, "x2w-render mesh57-derive forwards: %llu", + static_cast(mesh57_derive_forwarded(census))); + if (n < 0) { + out[0] = 0; + return 0; + } + if (static_cast(n) >= cap) { + out[cap - 1] = 0; + return cap - 1; + } + return static_cast(n); +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index b8455b82d..2aef375dd 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -247,6 +247,9 @@ void prepare_native_mesh57(Wrapper* pipeline) std::ifstream file(std::filesystem::path(path), std::ios::binary); if (!file) return; + // A present profile keeps the reviewed gate even when its bytes do not match. The opt-in + // derivation below must not replace a file a person already supplied. + info->mesh57_reviewed_present = true; try { x2w_startup::Mesh57Profile profile{}; if (!file.read(reinterpret_cast(&profile), sizeof(profile))) @@ -447,4 +450,459 @@ void prepare_native_mesh57(Wrapper* pipeline) log("x2w-render native slot57 mesh %016llx refused: %s", key, e.what()); } } + +// The directory of dxcompiler.dll and dxil.dll for this path alone. X2W_MESH57_DXC_DIR does not +// turn on native translation for other programs. X2W_NATIVE_SHADERS remains a fallback so a run +// that already set it can still compile this one pipeline. +bool mesh57_derive_compiler_dir(wchar_t* sdk, DWORD capacity) +{ + DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", sdk, capacity); + if (!length || length >= capacity) + length = GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", sdk, capacity); + return length && length < capacity; +} + +// Same variant name prepare_native_mesh57 opens. Used when that function did not run because +// X2W_NATIVE_SHADERS is unset. A present file keeps the reviewed gate; this path does not parse it. +bool mesh57_reviewed_file_present(const PipelineInfo* info) +{ + if (!info || info->path != 57 || !info->fixed_ms || !info->fixed_ps || info->desc.size() != 0x300) + return false; + 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 || fields[2] != info->state_a.size() || + fields[4] != info->state_b.size()) + return false; + std::vector root_blob; + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + const auto it = root_blobs().find(root); + if (it == root_blobs().end()) + return false; + root_blob = it->second; + } + constexpr char revision[] = "x2w-startup-mesh-57-3"; + const u64 key = fnv_part(root_blob, fnv_part(*info->fixed_ps, fnv_part(*info->fixed_ms, + 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))); + wchar_t path[MAX_PATH]; + if (!cache_path(path, L"", variant, L".mesh57-state")) + return false; + std::ifstream file(std::filesystem::path(path), std::ios::binary); + return static_cast(file); +} + +x2w_startup::Mesh57DeriveCensus mesh57_derive_census; +SRWLOCK mesh57_derive_census_lock = SRWLOCK_INIT; + +std::uint32_t mesh57_derive_u32(std::size_t value) +{ + return value > 0xffffffffu ? 0xffffffffu : static_cast(value); +} + +x2w_startup::Mesh57DeriveSample mesh57_derive_sample(Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + x2w_startup::Mesh57DeriveSample sample; + sample.list_type = list_type; + if (!pipeline) + return sample; + sample.real = pipeline->own().real ? 1 : 0; + sample.mesh86 = pipeline->own().mesh86_key ? 1 : 0; + sample.key = known_pipeline_key(pipeline); + const PipelineInfo* base = info; + for (int depth = 0; base && base->path == 55 && base->base && depth < 8; ++depth) + base = pipeline_info(base->base); + if (base && base != info) + sample.base_path = base->path; + if (!info) + return sample; + sample.path = info->path; + sample.desc_bytes = mesh57_derive_u32(info->desc.size()); + sample.mesh_bytes = info->fixed_ms ? mesh57_derive_u32(info->fixed_ms->size()) : 0; + sample.pixel_bytes = info->fixed_ps ? mesh57_derive_u32(info->fixed_ps->size()) : 0; + sample.state_a = mesh57_derive_u32(info->state_a.size()); + sample.state_b = mesh57_derive_u32(info->state_b.size()); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + sample.vertex_bytes = mesh57_derive_u32(static_cast(words[10])); + sample.pixel_length = mesh57_derive_u32(static_cast(words[6])); + sample.mesh_length = mesh57_derive_u32(static_cast(words[14])); + } + if (info->path == 55) { + x2w_startup::Mesh57PatchNote notes[x2w_startup::Mesh57DeriveSample::patch_slots]; + const auto scan = x2w_startup::mesh57_scan_slot55_patches( + info->desc.data(), info->desc.size(), notes, x2w_startup::Mesh57DeriveSample::patch_slots); + sample.patch_n = scan.notes; + for (int i = 0; i < scan.notes; ++i) { + sample.patch_tag[i] = notes[i].tag; + sample.patch_size[i] = notes[i].bytes; + } + } + const PipelineInfo* root_source = info; + for (int depth = 0; root_source && root_source->path == 55 && root_source->base && depth < 8; ++depth) + root_source = pipeline_info(root_source->base); + if (root_source && root_source->desc.size() >= sizeof(u64)) { + u64 root_bits = 0; + std::memcpy(&root_bits, root_source->desc.data(), sizeof(root_bits)); + auto* root = as_wrapper(reinterpret_cast(root_bits)); + if (root && root->own().kind == root_signature_kind) { + sample.root_heap = root_heap_flags(root); + if (const auto* params = root_info(root)) { + sample.root_parameters = mesh57_derive_u32(params->size()); + for (const auto& parameter : *params) { + unsigned code = 255; + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) + code = 0; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) + code = 1; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_CBV) + code = 2; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_SRV) + code = 3; + else if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_UAV) + code = 4; + if (sample.root_param_n < x2w_startup::Mesh57DeriveSample::root_param_slots) { + sample.root_param_type[sample.root_param_n] = static_cast(code); + sample.root_param_count[sample.root_param_n] = parameter.constants_count; + sample.root_param_n += 1; + } + if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) { + if (sample.root_constant_dwords <= ~std::uint32_t{0} - parameter.constants_count) + sample.root_constant_dwords += parameter.constants_count; + else + sample.root_constant_dwords = ~std::uint32_t{0}; + } else if (sample.root_other != ~std::uint32_t{0}) { + sample.root_other += 1; + } + } + } + } + } + return sample; +} + +void record_mesh57_derive(const char* reason, Wrapper* pipeline, const PipelineInfo* info, int list_type) +{ + const x2w_startup::Mesh57DeriveSample sample = mesh57_derive_sample(pipeline, info, list_type); + bool first = false; + AcquireSRWLockExclusive(&mesh57_derive_census_lock); + first = mesh57_derive_census.note(reason, sample); + ReleaseSRWLockExclusive(&mesh57_derive_census_lock); + if (!first) + return; + char line[1024]; + if (x2w_startup::mesh57_derive_sample_line(reason, sample, line, sizeof(line))) + log("%s", line); +} + +void log_mesh57_derive_census() +{ + if (!x2w_local::env_on("X2W_MESH57_DERIVE_STATE")) + return; + x2w_startup::Mesh57DeriveCensus copy; + AcquireSRWLockShared(&mesh57_derive_census_lock); + copy = mesh57_derive_census; + ReleaseSRWLockShared(&mesh57_derive_census_lock); + char line[2048]; + if (x2w_startup::mesh57_derive_summary_line(copy, line, sizeof(line))) + log("%s", line); + if (x2w_startup::mesh57_derive_forwards_line(copy, line, sizeof(line))) + log("%s", line); +} + +// The census and the pipeline keep the first reason pointer. A formatted tag reason lives in +// this table so that pointer outlives both. Matching is by the characters, not the address. +const char* mesh57_stable_text(const char* text) +{ + static SRWLOCK lock = SRWLOCK_INIT; + struct Kept { char text[80]; }; + static Kept kept[24]; + static int used = 0; + if (!text || !text[0]) + return "slot 55 patch tag is not applied"; + AcquireSRWLockExclusive(&lock); + for (int i = 0; i < used; ++i) { + if (std::strcmp(kept[i].text, text) == 0) { + const char* found = kept[i].text; + ReleaseSRWLockExclusive(&lock); + return found; + } + } + if (used >= 24) { + ReleaseSRWLockExclusive(&lock); + return "slot 55 patch tag is not applied"; + } + std::snprintf(kept[used].text, sizeof(kept[used].text), "%s", text); + const char* stored = kept[used].text; + used += 1; + ReleaseSRWLockExclusive(&lock); + return stored; +} + +const char* derive_slot55_mesh(Wrapper* pipeline, Pass& pass) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + Wrapper* base = info->base; + const PipelineInfo* base_info = nullptr; + for (int depth = 0; base && depth < 8; ++depth) { + base_info = pipeline_info(base); + if (!base_info || base_info->path != 55) + break; + base = base_info->base; + base_info = nullptr; + } + if (!base_info || base_info->path != 57) + return "pipeline is a derived slot 55"; + const auto patches = x2w_startup::mesh57_scan_slot55_patches(info->desc.data(), info->desc.size(), nullptr, 0); + if (patches.decision == x2w_startup::Mesh57PatchDecision::unaligned) { + info->mesh57_derive_reason = "slot 55 patches are not applied"; + return info->mesh57_derive_reason; + } + if (patches.decision == x2w_startup::Mesh57PatchDecision::other_tag) { + char named[80]; + x2w_startup::mesh57_slot55_tag_reason(patches.other_tag, named, sizeof(named)); + info->mesh57_derive_reason = mesh57_stable_text(named); + return info->mesh57_derive_reason; + } + D3D12_BLEND_DESC blend{}; + std::size_t where = 0; + const bool has_blend = x2w_derived_blend::last_blend(info->desc.data(), info->desc.size(), blend, where); + return derive_slot57_mesh(pipeline, pass, has_blend ? &blend : nullptr, base_info); +} + +// Builds one desktop mesh PSO for a direct DispatchMesh when X2W_MESH57_DERIVE_STATE=1 and no +// reviewed profile was opened. Returns nullptr after publishing the PSO, or a stable reason. +// A reason that depends on the command list (attachments, the bound root) is not remembered. +const char* derive_slot57_mesh(Wrapper* pipeline, Pass& pass, const D3D12_BLEND_DESC* blend_override, + const PipelineInfo* source) +{ + if (!pipeline || pipeline->own().real) + return nullptr; + const auto* info = source ? source : pipeline_info(pipeline); + if (!info) + return "derived mesh has no captured pipeline"; + if (info->mesh57_derive_reason) + return info->mesh57_derive_reason; + auto remember = [&](const char* why) { + info->mesh57_derive_reason = why; + return why; + }; + wchar_t sdk[MAX_PATH]; + if (!mesh57_derive_compiler_dir(sdk, MAX_PATH)) + return "derived mesh needs the native shader compiler"; + wchar_t cache[MAX_PATH]; + const DWORD cache_length = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache, MAX_PATH); + if (!cache_length || cache_length >= MAX_PATH) + return "derived mesh needs a shader cache"; + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = info->desc.size(); + pair.mesh_captured = static_cast(info->fixed_ms); + pair.pixel_captured = static_cast(info->fixed_ps); + if (info->desc.size() >= 15 * sizeof(u64)) { + u64 words[15]; + std::memcpy(words, info->desc.data(), sizeof(words)); + pair.vertex_pointer = words[9]; + pair.vertex_bytes = words[10]; + pair.pixel_length = words[6]; + pair.mesh_length = words[14]; + } + if (const char* pair_why = x2w_startup::mesh57_fixed_pair_reason(pair)) + return remember(pair_why); + if (!info->mesh57_reviewed_present && mesh57_reviewed_file_present(info)) + info->mesh57_reviewed_present = true; + if (info->mesh57_reviewed_present) + return remember("a reviewed mesh profile is present"); + 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 remember("derived mesh root or state lengths do not match"); + const auto* guest_parameters = root_info(root); + x2w_startup::Mesh57RootParameterView root_views[16]; + unsigned root_view_count = 0; + if (guest_parameters && guest_parameters->size() <= 16) { + root_view_count = static_cast(guest_parameters->size()); + for (unsigned i = 0; i < root_view_count; ++i) { + const auto& parameter = (*guest_parameters)[i]; + root_views[i].type = parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS ? 0u : 1u; + root_views[i].constants = parameter.constants_count; + } + } + const auto root_contract = x2w_startup::mesh57_root_contract( + root_view_count ? root_views : nullptr, root_view_count, root_heap_flags(root)); + if (guest_parameters && guest_parameters->size() > 16) + return remember("derived mesh guest root constants do not fit one user block"); + if (const char* root_why = x2w_startup::mesh57_root_bind_reason(root_contract)) + return remember(root_why); + if (root_contract.bind_constants) { + const auto mask = static_cast((1u << root_views[0].constants) - 1u); + if ((pass.constant_words_bound[0] & mask) != mask) + return "derived mesh root constants are incomplete"; + } + if (info->state_a.size() < x2w_pipeline_state::a_layout + 4) + return remember("derived mesh state block is short"); + std::uint32_t layout_word = 0; + std::memcpy(&layout_word, info->state_a.data() + x2w_pipeline_state::a_layout, sizeof(layout_word)); + if (layout_word != x2w_pipeline_state::a_layout_mesh) + return remember("derived mesh requires the mesh layout word"); + const std::size_t shift = x2w_pipeline_state::a_mesh_shift; + if (info->state_a.size() < shift) + return remember("derived mesh state block is short"); + D3D12_BLEND_DESC blend{}; + const char* blend_why = nullptr; + // Blend words sit at +0xD0 in the vertex layout. The mesh layout shifts every field from +0x058 + // by +0x54, and the blend reader does not apply that shift itself. A slot 55 blend patch replaces it. + if (blend_override) + blend = *blend_override; + else if (!x2w_startup::state_block_blend(info->state_a.data() + shift, info->state_a.size() - shift, false, &blend, &blend_why)) + return remember(blend_why ? blend_why : "derived mesh blend was refused"); + x2w_pipeline_state::DepthStencilWords depth_words; + if (!x2w_pipeline_state::read_depth_stencil_words(info->state_a.data(), info->state_a.size(), depth_words)) + return remember("derived mesh state block is short for depth"); + const x2w_pipeline_state::DepthStencil depth = x2w_pipeline_state::decode_depth_stencil( + depth_words.depth, depth_words.stencil, depth_words.refmask, depth_words.refmask_bf); + if (!depth.ok) + return remember(depth.reason ? depth.reason : "derived mesh depth state was refused"); + if (depth.desc.DepthEnable || depth.desc.StencilEnable) + return remember("derived mesh keeps depth and stencil disabled"); + auto* desktop = static_cast(root->own().real); + if (!pass.targets_bound || !pass.viewport_set || !pass.scissor_set || !pass.targets_single_sample || + pass.target_count != 1 || !pass.target0 || pass.dsv_format != DXGI_FORMAT_UNKNOWN || + pass.target_formats[0] == DXGI_FORMAT_UNKNOWN) + return "derived mesh needs one single-sample color target, a viewport and a scissor"; + ID3D12RootSignature* bound_root = pass.root_heap_flags ? pass.deferred_root : pass.graphics_root; + if (!bound_root || bound_root != desktop || pass.root != root_info(root) || + (pass.root_heap_flags && !root_contract.bind_constants)) + return "derived mesh root is not the bound desktop root"; + const std::string ms(info->fixed_ms->begin(), info->fixed_ms->end()); + const auto layout = x2w_startup::derive_immediate_mesh_layout(ms); + if (!layout) + return remember("derived mesh needs one immediate allocation"); + try { + x2w::MeshStageLayout mesh_layout; + mesh_layout.threads = layout->threads; + mesh_layout.max_vertices = layout->vertices; + mesh_layout.max_primitives = layout->primitives; + mesh_layout.topology = layout->topology; + mesh_layout.group_stride = layout->group_stride; + mesh_layout.wave32 = false; + D3D12_ROOT_PARAMETER1 constant_parameter{}; + D3D12_ROOT_SIGNATURE_DESC1 constant_root{}; + if (root_contract.bind_constants) { + mesh_layout.root_inputs.push_back({root_contract.sgpr, 0u, root_views[0].constants}); + constant_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + constant_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + constant_parameter.Constants.Num32BitValues = root_views[0].constants; + constant_root.NumParameters = 1; + constant_root.pParameters = &constant_parameter; + } + auto native = root_contract.bind_constants + ? x2w::translate_mesh_program(ms, mesh_layout, constant_root) + : x2w::translate_mesh_program(ms, mesh_layout); + const bool constants_match = !root_contract.bind_constants || + (native.constants.size() == 1 && native.constants[0].root_parameter == 0 && + native.constants[0].first_sgpr == root_contract.sgpr && + native.constants[0].count == root_views[0].constants); + if (!constants_match || (root_contract.bind_constants ? false : !native.constants.empty()) || + !native.bindings.empty() || !native.samplers.empty() || native.sampler_heap || + !native.mesh_heap_reads.empty()) + return remember("derived mesh program needs root or heap bindings"); + const std::string ps(info->fixed_ps->begin(), info->fixed_ps->end()); + const std::string ps_ir = x2w::direct_gfx1013_constant_pixel(ps); + auto compiler = x2w::ShaderDxilCompiler::runtime_worker(sdk); + const auto cache_dir = std::filesystem::path(cache); + const auto ms_output = compiler.compile(native.dxil_ir, L"ms_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + const auto ps_output = compiler.compile(ps_ir, L"ps_6_6", cache_dir, x2w::ShaderSourceFormat::dxil_ir); + x2w::meshlet::MeshOnlyPipelineStream stream{}; + stream.root_signature.value = reinterpret_cast(root); + stream.ms.value.pShaderBytecode = ms_output.dxil.data(); + stream.ms.value.BytecodeLength = ms_output.dxil.size(); + stream.ps.value.pShaderBytecode = ps_output.dxil.data(); + stream.ps.value.BytecodeLength = ps_output.dxil.size(); + stream.blend.value = blend; + stream.sample_mask.value = UINT_MAX; + stream.rasterizer.value = x2w_startup::default_pso_rasterizer(); + stream.depth_stencil.value = depth.desc; + D3D12_RT_FORMAT_ARRAY targets{}; + targets.NumRenderTargets = 1; + targets.RTFormats[0] = pass.target_formats[0]; + stream.rtv_formats.value = targets; + stream.dsv_format.value = DXGI_FORMAT_UNKNOWN; + DXGI_SAMPLE_DESC samples; + samples.Count = 1; + samples.Quality = 0; + stream.sample_desc.value = samples; + stream.topology.value = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + D3D12_PIPELINE_STATE_STREAM_DESC desc; + desc.SizeInBytes = sizeof(stream); + desc.pPipelineStateSubobjectStream = &stream; + bool compute = false; + char why[256]{}; + x2w_startup::ComPtr host; + if (root_contract.bind_constants) { + D3D12_ROOT_PARAMETER host_parameter{}; + host_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + host_parameter.Constants.Num32BitValues = (root_views[0].constants + 3u) & ~3u; + D3D12_ROOT_SIGNATURE_DESC host_desc; + host_desc.NumParameters = 1; + host_desc.pParameters = &host_parameter; + host_desc.NumStaticSamplers = 0; + host_desc.pStaticSamplers = nullptr; + host_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; + x2w_startup::ComPtr host_blob; + if (FAILED(D3D12SerializeRootSignature(&host_desc, D3D_ROOT_SIGNATURE_VERSION_1, &host_blob, nullptr)) || + FAILED(device_of(the_device)->CreateRootSignature(0, host_blob->GetBufferPointer(), host_blob->GetBufferSize(), + IID_PPV_ARGS(&host)))) + return remember("derived mesh constant root was refused"); + } + IndirectGraphicsPipeline graphics; + ID3D12RootSignature* pipeline_root = nullptr; + auto* created = build_stream_pipeline(&desc, why, sizeof(why), compute, graphics, pipeline_root, + host ? host.Get() : desktop, true); + if (!created) { + log("x2w-render derived slot57 mesh desktop pipeline refused: %s", why); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh desktop pipeline was refused"); + } + auto* pso = static_cast(created); + if (root_contract.bind_constants) { + static constexpr GUID lifetime{0xf74c6928, 0xb063, 0x4a00, {0xa5, 0xf0, 0x79, 0xe3, 0x60, 0xa4, 0xf1, 0x09}}; + if (FAILED(pso->SetPrivateDataInterface(lifetime, host.Get()))) { + pso->Release(); + return remember("derived mesh constant root was refused"); + } + graphics.constant_guest = 0; + graphics.plain_constants = root_heap_flags(root) == 0; + } + AcquireSRWLockExclusive(¬e_lock); + if (pipeline->own().real) { + ReleaseSRWLockExclusive(¬e_lock); + pso->Release(); + return nullptr; + } + pipeline->own().indirect_graphics = graphics; + if (pipeline_root) + pipeline->own().pipeline_root = pipeline_root; + pipeline->own().real = pso; + ReleaseSRWLockExclusive(¬e_lock); + log("x2w-render derived slot57 mesh ready"); + return nullptr; + } catch (const std::exception& e) { + log("x2w-render derived slot57 mesh refused: %s", e.what()); + if (pipeline->own().real) + return nullptr; + return remember("derived mesh translation was refused"); + } +} #endif diff --git a/tests/mesh57_derive_alloc_check.cpp b/tests/mesh57_derive_alloc_check.cpp new file mode 100644 index 000000000..4683fc634 --- /dev/null +++ b/tests/mesh57_derive_alloc_check.cpp @@ -0,0 +1,297 @@ +// Host check for the opt-in immediate mesh allocation reader. No device and no shader compiler. +#include "mesh57_alloc.h" + +#include +#include +#include +#include +#include + +namespace { +int fail(const char* name) +{ + std::fprintf(stderr, "mesh57 derive alloc: %s\n", name); + return 1; +} + +std::string words_of(const std::uint32_t* words, std::size_t count) +{ + std::string out(count * sizeof(std::uint32_t), '\0'); + if (count) + std::memcpy(out.data(), words, count * sizeof(std::uint32_t)); + return out; +} + +bool accepted(std::string_view code, unsigned vertices, unsigned primitives) +{ + const auto layout = x2w_startup::derive_immediate_mesh_layout(code); + return layout && layout->vertices == vertices && layout->primitives == primitives && + layout->threads == 64 && layout->topology == 2 && layout->group_stride == 0 && + layout->wave_size == 64; +} +} // namespace + +int main() +{ + // Source-built triangle: m0 = (1 primitive << 12) | 3 vertices, then GS_ALLOC_REQ. + const std::uint32_t triangle[] = { + 0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (!accepted(words_of(triangle, sizeof(triangle) / sizeof(triangle[0])), 3, 1)) + return fail("triangle"); + + const std::uint32_t only_alloc[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf810000u}; + if (!accepted(words_of(only_alloc, 4), 3, 1)) + return fail("alloc alone"); + + const std::uint32_t endpgm[] = {0xbf810000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(endpgm, 1))) + return fail("no allocation"); + + const std::uint32_t gap[] = {0xbefc03ffu, 0x1003u, 0xbf800000u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(gap, 4))) + return fail("instruction between m0 and GS_ALLOC_REQ"); + + const std::uint32_t twice[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(twice, 6))) + return fail("two allocations"); + + const std::uint32_t high[] = {0xbefc03ffu, 0x01001003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(high, 3))) + return fail("high byte"); + + const std::uint32_t zero[] = {0xbefc03ffu, 0u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(zero, 3))) + return fail("zero counts"); + + const std::uint32_t wide[] = {0xbefc03ffu, (1u << 12) | 65u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wide, 3))) + return fail("count above one wave"); + + const std::uint32_t exchange[] = {0xbefc03ffu, 0x1003u, 0xbf900009u, 0xbf8a0000u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(exchange, 4))) + return fail("count exchange"); + + // s_mov_b32 exec_lo, 0. Wave32 writes exec with s_mov_b32; wave64 uses s_mov_b64. + const std::uint32_t wave32_mov = 0xbefe0380u; + std::string wave32_word(sizeof(wave32_mov), '\0'); + std::memcpy(wave32_word.data(), &wave32_mov, sizeof(wave32_mov)); + const auto decoded = x2w::gfx1013::instruction(wave32_word, 0); + if (decoded.name != "s_mov_b32") + return fail("exec_lo encoding"); + const std::uint32_t wave32[] = {wave32_mov, 0xbefc03ffu, 0x1003u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(wave32, 4))) + return fail("wave32 exec move"); + + const std::uint32_t from_register[] = {0xbefc0300u, 0xbf900009u}; + if (x2w_startup::derive_immediate_mesh_layout(words_of(from_register, 2))) + return fail("m0 from a register"); + + if (x2w_startup::derive_immediate_mesh_layout({})) + return fail("empty"); + + x2w_startup::Mesh57PairRecord pair; + pair.desc_bytes = 0x300; + pair.mesh_captured = true; + pair.pixel_captured = true; + pair.mesh_length = 64; + pair.pixel_length = 16; + if (x2w_startup::mesh57_fixed_pair_reason(pair)) + return fail("fixed pair"); + pair.desc_bytes = 64; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is shorter than the fixed prefix") != 0) + return fail("short descriptor"); + pair.desc_bytes = 256; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor is not 768 bytes") != 0) + return fail("descriptor length"); + pair.desc_bytes = 0x300; + pair.vertex_pointer = 0x1000; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has a vertex span") != 0) + return fail("vertex span"); + pair.vertex_pointer = 0; + pair.mesh_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 descriptor has no mesh stage length") != 0) + return fail("mesh length"); + pair.mesh_length = 64; + pair.mesh_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 mesh stage was not captured") != 0) + return fail("mesh stage"); + pair.mesh_captured = true; + pair.pixel_captured = false; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage was not captured") != 0) + return fail("pixel stage"); + pair.pixel_length = 0; + if (std::strcmp(x2w_startup::mesh57_fixed_pair_reason(pair), + "slot 57 pixel stage is absent from the descriptor") != 0) + return fail("absent pixel span"); + // The descriptor words are zero, so the copy is skipped and the mesh bytes stay. + // A non-zero span that cannot be read fails the snapshot and drops both stages. + if (x2w_startup::mesh57_stage_copy(0, 0, false) != x2w_startup::Mesh57StageCopy::empty || + !x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::empty, + x2w_startup::Mesh57StageCopy::copied)) + return fail("empty pixel keeps the mesh"); + if (x2w_startup::mesh57_stage_copy(0x1000, 1408, false) != x2w_startup::Mesh57StageCopy::unreadable || + x2w_startup::mesh57_fixed_stages_kept(true, true, x2w_startup::Mesh57StageCopy::unreadable, + x2w_startup::Mesh57StageCopy::copied)) + return fail("unreadable pixel drops the mesh"); + if (x2w_startup::mesh57_stage_copy(0, 1408, true) != x2w_startup::Mesh57StageCopy::copied) + return fail("readable pixel is copied"); + + x2w_startup::Mesh57DeriveCensus census; + x2w_startup::Mesh57DeriveSample slot86; + slot86.path = 86; + slot86.mesh86 = 1; + slot86.desc_bytes = 512; + // Two objects with the same characters. A compiler that does not pool string literals gives + // them different addresses; they are still one reason. + char first_reason[] = "pipeline is slot 86"; + char second_reason[] = "pipeline is slot 86"; + if (&first_reason[0] == &second_reason[0]) + return fail("reason copies are the same object"); + if (!census.note(first_reason, slot86)) + return fail("first slot 86 note"); + slot86.path = 57; + if (census.note(second_reason, slot86) || census.rows[0].calls != 2 || census.rows[0].sample.path != 86) + return fail("slot 86 count keeps the first sample"); + x2w_startup::Mesh57DeriveSample missing_ps; + missing_ps.path = 57; + missing_ps.desc_bytes = 0x300; + missing_ps.mesh_bytes = 128; + if (!census.note("slot 57 pixel stage was not captured", missing_ps) || census.total() != 3) + return fail("pixel stage count"); + char summary[512]; + const auto summary_n = x2w_startup::mesh57_derive_summary_line(census, summary, sizeof(summary)); + if (!summary_n || !std::strstr(summary, "pipeline is slot 86 2") || + !std::strstr(summary, "slot 57 pixel stage was not captured 1") || + std::strncmp(summary, "x2w-render mesh57-derive:", 25) != 0) + return fail("summary"); + char sample[512]; + if (!x2w_startup::mesh57_derive_sample_line(census.rows[0].reason, census.rows[0].sample, sample, sizeof(sample)) || + !std::strstr(sample, "reason=pipeline is slot 86") || !std::strstr(sample, "path=86") || + !std::strstr(sample, "desc=512") || !std::strstr(sample, "root=0") || + !std::strstr(sample, "const=0") || !std::strstr(sample, "other=0") || !std::strstr(sample, "heap=0") || + !std::strstr(sample, "params=-") || !std::strstr(sample, "patches=-") || + std::strncmp(sample, "x2w-render mesh57-derive sample ", 32) != 0) + return fail("sample"); + x2w_startup::Mesh57DeriveSample typed; + typed.path = 57; + typed.root_parameters = 5; + typed.root_constant_dwords = 1; + typed.root_other = 4; + typed.root_heap = 1024; + typed.root_param_n = 5; + const unsigned typed_codes[] = {0u, 1u, 3u, 2u, 4u}; + const unsigned typed_counts[] = {0u, 1u, 0u, 0u, 0u}; + for (int i = 0; i < 5; ++i) { + typed.root_param_type[i] = static_cast(typed_codes[i]); + typed.root_param_count[i] = typed_counts[i]; + } + typed.patch_n = 1; + typed.patch_tag[0] = 3; + typed.patch_size[0] = 0x14c; + char typed_line[640]; + if (!x2w_startup::mesh57_derive_sample_line("derived mesh guest root is heap indexed", typed, typed_line, + sizeof(typed_line)) || + !std::strstr(typed_line, "params=t,c1,srv,cbv,uav") || !std::strstr(typed_line, "patches=3:332") || + !std::strstr(typed_line, "root=5") || !std::strstr(typed_line, "heap=1024")) + return fail("parameter and patch sample"); + x2w_startup::Mesh57RootParameterView one; + one.type = 0; + one.constants = 1; + const auto bound = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (!bound.bind_constants || bound.sgpr != 8 || bound.constant_dwords != 1 || + x2w_startup::mesh57_root_bind_reason(bound)) + return fail("one constant block"); + x2w_startup::Mesh57RootParameterView two[2]; + two[0].type = 0; + two[0].constants = 1; + two[1].type = 0; + two[1].constants = 1; + const auto split = x2w_startup::mesh57_root_contract(two, 2, 0); + if (split.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(split), + "derived mesh guest root constants do not fit one user block") != 0) + return fail("two constant blocks"); + x2w_startup::Mesh57RootParameterView table; + table.type = 1; + table.constants = 0; + const auto described = x2w_startup::mesh57_root_contract(&table, 1, 0); + if (described.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(described), + "derived mesh guest root has descriptors") != 0) + return fail("descriptor root"); + const auto heaped = x2w_startup::mesh57_root_contract(&one, 1, 0x8); + if (!heaped.bind_constants || x2w_startup::mesh57_root_bind_reason(heaped)) + return fail("heap plus one constant"); + const auto heap_only = x2w_startup::mesh57_root_contract(nullptr, 0, 0x8); + if (heap_only.bind_constants || std::strcmp(x2w_startup::mesh57_root_bind_reason(heap_only), + "derived mesh guest root is heap indexed") != 0) + return fail("heap only"); + one.constants = 9; + const auto wide_root = x2w_startup::mesh57_root_contract(&one, 1, 0); + if (wide_root.bind_constants || !x2w_startup::mesh57_root_bind_reason(wide_root)) + return fail("wide constant block"); + const auto empty = x2w_startup::mesh57_root_contract(nullptr, 0, 0); + if (empty.bind_constants || x2w_startup::mesh57_root_bind_reason(empty)) + return fail("empty root"); + unsigned char blend_record[0x14c]; + std::memset(blend_record, 0, sizeof(blend_record)); + const std::uint32_t blend_tag = 2; + std::memcpy(blend_record, &blend_tag, sizeof(blend_tag)); + x2w_startup::Mesh57PatchNote notes[4]; + const auto blend_only = x2w_startup::mesh57_scan_slot55_patches(nullptr, 0, notes, 4); + const auto one_blend = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + if (blend_only.decision != x2w_startup::Mesh57PatchDecision::accept || + one_blend.decision != x2w_startup::Mesh57PatchDecision::accept || one_blend.notes != 1 || + notes[0].tag != 2 || notes[0].bytes != 0x14c) + return fail("blend patch"); + unsigned char mixed[0x14c * 2]; + std::memset(mixed, 0, sizeof(mixed)); + std::memcpy(mixed, blend_record, sizeof(blend_record)); + const std::uint32_t other_tag = 3; + std::memcpy(mixed + sizeof(blend_record), &other_tag, sizeof(other_tag)); + const auto mixed_scan = x2w_startup::mesh57_scan_slot55_patches(mixed, sizeof(mixed), notes, 4); + char tag_reason[80]; + if (mixed_scan.decision != x2w_startup::Mesh57PatchDecision::other_tag || mixed_scan.other_tag != 3 || + mixed_scan.notes != 2 || notes[0].tag != 2 || notes[1].tag != 3 || notes[1].bytes != 0x14c || + !x2w_startup::mesh57_slot55_tag_reason(mixed_scan.other_tag, tag_reason, sizeof(tag_reason)) || + std::strcmp(tag_reason, "slot 55 patch tag 3 is not applied") != 0) + return fail("named patch tag"); + char tag_reason_copy[80]; + x2w_startup::mesh57_slot55_tag_reason(3, tag_reason_copy, sizeof(tag_reason_copy)); + if (&tag_reason[0] == &tag_reason_copy[0] || std::strcmp(tag_reason, tag_reason_copy) != 0 || + !census.note(tag_reason, slot86) || census.note(tag_reason_copy, slot86)) + return fail("tag reason text is one reason"); + blend_record[0] = 1; + const auto unknown = x2w_startup::mesh57_scan_slot55_patches(blend_record, sizeof(blend_record), notes, 4); + const auto short_list = x2w_startup::mesh57_scan_slot55_patches(blend_record, 4, notes, 4); + if (unknown.decision != x2w_startup::Mesh57PatchDecision::other_tag || unknown.other_tag != 1 || + short_list.decision != x2w_startup::Mesh57PatchDecision::unaligned || short_list.notes != 1 || + notes[0].bytes != 4) + return fail("unknown patch"); + if (!census.note("forwarded", slot86) || x2w_startup::mesh57_derive_forwarded(census) != 1) + return fail("forwarded count"); + char forwards[128]; + if (!x2w_startup::mesh57_derive_forwards_line(census, forwards, sizeof(forwards)) || + std::strcmp(forwards, "x2w-render mesh57-derive forwards: 1") != 0) + return fail("forwards line"); + x2w_startup::Mesh57DeriveCensus full; + if (!full.note("overflow-probe", slot86)) + return fail("overflow first"); + const char* extras[] = { + "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", + "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", + "r21", "r22", "r23"}; + for (const char* extra : extras) { + if (!full.note(extra, slot86)) + return fail("fill census"); + } + if (full.note("r24", slot86) || full.overflow_calls != 1 || full.used != full.capacity) + return fail("census overflow"); + return 0; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 2cc49b9dc..274245fec 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1112,6 +1113,11 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ ComPtr fixed_source_heap; slot(wrapped, 25)(wrapped, graphics); slot(wrapped, 34)(wrapped, refusal == Refusal::wrong_root ? translated->wrong_root.Get() : graphics_root); + if (label && std::strcmp(label, "mesh-derived-root") == 0) { + using Constants = void (WINAPI*)(IUnknown*, UINT, UINT, const UINT*, UINT); + const UINT value = 0; + slot(wrapped, 40)(wrapped, 0, 1, &value, 0); + } if (leased) { using RootSrv = void (WINAPI*)(IUnknown*, UINT, UINT64); slot(wrapped, 44)(wrapped, 0, leased->address); @@ -2343,6 +2349,186 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, return 0; } +// Opt-in X2W_MESH57_DERIVE_STATE for a slot 57 mesh with captured stages and no reviewed profile. +// mesh-derived and mesh-derived-dxc forward one DispatchMesh and paint (2,0). The other modes +// must leave the clear color. mesh-derived-dxc uses only X2W_MESH57_DXC_DIR and clears +// X2W_NATIVE_SHADERS before the call. +static int derived_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const char* mode) +{ + struct CacheCleanup { + std::filesystem::path path; + ~CacheCleanup() + { + std::error_code error; + std::filesystem::remove_all(path, error); + } + }; + const bool enable = std::strcmp(mode, "mesh-derived-off") != 0; + check(SetEnvironmentVariableA("X2W_MESH57_DERIVE_STATE", enable ? "1" : nullptr) ? S_OK : E_FAIL, + "derived mesh switch"); + const bool dxc_only = std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0; + if (dxc_only) { + wchar_t dir[MAX_PATH]; + const DWORD length = GetEnvironmentVariableW(L"X2W_MESH57_DXC_DIR", dir, MAX_PATH); + if (!length || length >= MAX_PATH) + return 1; + check(SetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr) ? S_OK : E_FAIL, "clear native shaders"); + if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) != 0) + return 1; + } + const auto prefix = "mesh57-derived-" + std::to_string(GetCurrentProcessId()) + "-"; + CacheCleanup cache; + for (unsigned attempt = 0;; ++attempt) { + cache.path = std::filesystem::current_path() / (prefix + std::to_string(attempt)); + if (std::filesystem::create_directory(cache.path)) + break; + } + check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.path.c_str()) ? S_OK : E_FAIL, "derived mesh cache"); + ComPtr blob; + D3D12_ROOT_SIGNATURE_DESC empty{}; + const bool constant_root = std::strcmp(mode, "mesh-derived-root") == 0 || + std::strcmp(mode, "mesh-derived-root-unset") == 0; + const bool table_root = std::strcmp(mode, "mesh-derived-root-table") == 0; + D3D12_ROOT_PARAMETER parameter{}; + D3D12_DESCRIPTOR_RANGE range{}; + if (constant_root) { + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + parameter.Constants.Num32BitValues = 1; + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } else if (table_root) { + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable.NumDescriptorRanges = 1; + parameter.DescriptorTable.pDescriptorRanges = ⦥ + empty.NumParameters = 1; + empty.pParameters = ¶meter; + } + const auto root = create_root(guest, empty, &blob); + std::vector ms{0xbefc03ffu, 0x1003u, 0xbf900009u, 0xd7650000u, 0x100c1u, 0x36020081u, + 0x2c040081u, 0x7e020d01u, 0x7e040d02u, 0x7e0602f0u, 0x7e0802f2u, 0xf80008cfu, + 0x04030201u, 0x7e0a02ffu, 0x200400u, 0xf8000941u, 0x80808005u, 0xbf810000u}; + if (constant_root) + ms.insert(ms.begin(), 0xbe890308u); // s_mov_b32 s9, s8. s8 is the one guest constant at user SGPR 8. + if (std::strcmp(mode, "mesh-derived-bad") == 0) + ms.assign(1, 0xbf810000u); + const std::vector ps{0x7e0002f2u, 0xf800180fu, 0u, 0xbf810000u}; + const auto ms_size = ms.size() * sizeof(UINT); + const auto ps_size = ps.size() * sizeof(UINT); + // Long enough for the mesh-shifted blend words (+0x124) and depth words (+0x10C). + constexpr std::size_t state_bytes = 0x144; + std::vector state_a(state_bytes, 0); + const std::uint32_t mesh_layout = 6; + std::memcpy(state_a.data() + 4, &mesh_layout, sizeof(mesh_layout)); + if (std::strcmp(mode, "mesh-derived-depth") == 0) { + const std::uint32_t depth_on = 2; + std::memcpy(state_a.data() + 0x10c, &depth_on, sizeof(depth_on)); + } + std::vector state_b(4, 0); + UINT64 fields[0x300 / sizeof(UINT64)]{}; + fields[2] = state_a.size(); + fields[4] = state_b.size(); + fields[6] = ps_size; + fields[14] = ms_size; + const auto fold = [](UINT64 key, const void* data, size_t n) { + const auto* bytes = static_cast(data); + for (size_t i = 0; i < n; ++i) + key = (key ^ bytes[i]) * 1099511628211ull; + return key; + }; + const char revision[] = "x2w-startup-mesh-57-3"; + UINT64 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, static_cast(n)); + }; + key = extend(key, ms.data(), ms_size); + key = extend(key, ps.data(), ps_size); + key = extend(key, blob->GetBufferPointer(), blob->GetBufferSize()); + const UINT64 variant = extend(extend(extend(key, fields, sizeof(fields)), state_a.data(), state_a.size()), + state_b.data(), state_b.size()); + if (std::strcmp(mode, "mesh-derived-reviewed") == 0 || std::strcmp(mode, "mesh-derived-dxc-reviewed") == 0) { + char name[64]; + std::snprintf(name, sizeof(name), "%016llx.mesh57-state", static_cast(variant)); + std::ofstream out(cache.path / name, std::ios::binary); + const char marker = 'x'; + out.write(&marker, 1); + if (!out) + return 1; + } + fields[0] = reinterpret_cast(root.Get()); + fields[1] = reinterpret_cast(state_a.data()); + fields[3] = reinterpret_cast(state_b.data()); + // No captured stages: the switch must not invent a translation. The call stays refused. + if (std::strcmp(mode, "mesh-derived-untranslated") == 0) { + fields[6] = 0; + fields[14] = 0; + } else { + fields[5] = reinterpret_cast(ps.data()); + fields[13] = reinterpret_cast(ms.data()); + } + ComPtr pso; + using Create = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); + check(slot(guest, 57)(guest, fields, __uuidof(ID3D12PipelineState), reinterpret_cast(pso.GetAddressOf())), + "create derived mesh"); + const bool slot55 = std::strcmp(mode, "mesh-derived-slot55") == 0 || + std::strcmp(mode, "mesh-derived-slot55-mask") == 0; + ComPtr derived; + if (slot55) { + std::vector patch; + const void* patch_bytes = nullptr; + UINT patch_count = 0; + if (std::strcmp(mode, "mesh-derived-slot55-mask") == 0) { + D3D12_BLEND_DESC blend{}; + auto& target = blend.RenderTarget[0]; + target.SrcBlend = D3D12_BLEND_ONE; + target.DestBlend = D3D12_BLEND_ZERO; + target.BlendOp = D3D12_BLEND_OP_ADD; + target.SrcBlendAlpha = D3D12_BLEND_ONE; + target.DestBlendAlpha = D3D12_BLEND_ZERO; + target.BlendOpAlpha = D3D12_BLEND_OP_ADD; + target.LogicOp = D3D12_LOGIC_OP_NOOP; + target.RenderTargetWriteMask = 0; + patch.resize(sizeof(std::uint32_t) + sizeof(blend)); + const std::uint32_t tag = 2; + std::memcpy(patch.data(), &tag, sizeof(tag)); + std::memcpy(patch.data() + sizeof(tag), &blend, sizeof(blend)); + patch_bytes = patch.data(); + patch_count = 1; + } + using Derive = HRESULT (WINAPI*)(IUnknown*, void*, UINT, const void*, REFIID, void**); + check(slot(guest, 55)(guest, pso.Get(), patch_count, patch_bytes, __uuidof(ID3D12PipelineState), + reinterpret_cast(derived.GetAddressOf())), + "create slot 55 mesh"); + } + D3D12_INDIRECT_ARGUMENT_DESC argument{}; + argument.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + D3D12_COMMAND_SIGNATURE_DESC signature_desc; + signature_desc.ByteStride = static_cast(sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)); + signature_desc.NumArgumentDescs = 1; + signature_desc.pArgumentDescs = &argument; + signature_desc.NodeMask = 0; + ComPtr signature; + if (FAILED(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)))) { + std::puts("indirect mesh capability skip: DispatchMesh signature unavailable"); + return 77; + } + const auto work = writer_pipeline(device, writer, "write_one_mesh_group"); + x2w_startup::Mesh57Profile profile{}; + std::memcpy(profile.magic, "X2WM571", 8); + profile.targets.NumRenderTargets = 1; + profile.targets.RTFormats[0] = format; + profile.blend.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + const int pixels = std::strcmp(mode, "mesh-derived") == 0 || std::strcmp(mode, "mesh-derived-dxc") == 0 || + std::strcmp(mode, "mesh-derived-root") == 0 || std::strcmp(mode, "mesh-derived-slot55") == 0 ? 1 : 2; + const bool painted = run(device, guest, writer, work.Get(), root.Get(), slot55 ? derived.Get() : pso.Get(), + signature.Get(), DrawKind::mesh, + false, Refusal::none, mode, nullptr, false, nullptr, false, false, 0, false, false, nullptr, + nullptr, false, pixels, &profile); + return painted ? 0 : 1; +} + int main(int argc, char** argv) try { DrawKind kind = DrawKind::indexed; @@ -2364,6 +2550,20 @@ int main(int argc, char** argv) try SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", nullptr) ? S_OK : E_FAIL, "enable loose XMem root SRV"); else if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); + const bool derived_off = argc == 3 && std::strcmp(argv[2], "mesh-derived-off") == 0; + const bool derived_bad = argc == 3 && std::strcmp(argv[2], "mesh-derived-bad") == 0; + const bool derived_depth = argc == 3 && std::strcmp(argv[2], "mesh-derived-depth") == 0; + const bool derived_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-reviewed") == 0; + const bool derived_untranslated = argc == 3 && std::strcmp(argv[2], "mesh-derived-untranslated") == 0; + const bool derived_dxc = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc") == 0; + const bool derived_dxc_reviewed = argc == 3 && std::strcmp(argv[2], "mesh-derived-dxc-reviewed") == 0; + const bool derived_root = argc == 3 && (std::strcmp(argv[2], "mesh-derived-root") == 0 || + std::strcmp(argv[2], "mesh-derived-root-unset") == 0 || std::strcmp(argv[2], "mesh-derived-root-table") == 0); + const bool derived_slot55 = argc == 3 && (std::strcmp(argv[2], "mesh-derived-slot55") == 0 || + std::strcmp(argv[2], "mesh-derived-slot55-mask") == 0); + const bool derived_mesh = derived_off || derived_bad || derived_depth || derived_reviewed || derived_untranslated || + derived_dxc || derived_dxc_reviewed || derived_root || derived_slot55 || + (argc == 3 && std::strcmp(argv[2], "mesh-derived") == 0); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; const bool copy_on = argc == 3 && std::strcmp(argv[2], "copy-provenance") == 0; @@ -2387,10 +2587,10 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || derived_mesh || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) kind = DrawKind::mesh; else if (rect) kind = DrawKind::indexed_rect; - else if (argc != 2 && !count_control && !translated_indexed && !lease_writer) return 2; + else if (argc != 2 && !count_control && !translated_indexed && !lease_writer && !derived_mesh) return 2; const bool indexed = kind == DrawKind::indexed || kind == DrawKind::indexed_rect; const bool mesh = kind == DrawKind::mesh; const bool fixed_create_fixture = mesh && GetEnvironmentVariableA("X2W_FIXED_MESH_CREATE_FIXTURE", nullptr, 0); @@ -2473,6 +2673,8 @@ int main(int argc, char** argv) try 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()); + if (derived_mesh) + return derived_mesh_fixture(device.Get(), guest.Get(), writer.Get(), argv[2]); 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;