Skip to content

Shaders: honor the mesh allocation request counts - #586

Open
Kam471 wants to merge 21 commits into
Marvisak:mainfrom
Kam471:mesh-alloc-counts
Open

Kam471 wants to merge 21 commits into
Marvisak:mainfrom
Kam471:mesh-alloc-counts

Conversation

@Kam471

@Kam471 Kam471 commented Nov 24, 2026

Copy link
Copy Markdown

Problem

Console mesh shaders declare their output maxima in the container, then request the group's real vertex and primitive counts with s_sendmsg(GS_ALLOC_REQ) in M0 (vertices = m0 & 0xFFF, primitives = m0 >> 12). The translator ignored the request and declared the maxima. A culled group, whose request path is skipped, still exported its declared 128 vertices and 128 primitives; stale or undefined positions become full-screen garbage with a deferred pixel shader. In the world, the transform family took 0.8-5 s per dispatch and hit the 2 s watchdog.

Change

  • Find every allocation request, decode the scalar value stored to M0 just before it, and require one shared immediate postdominator that is uniform, cycle-free, and dominates every export.
  • Stage the request's M0 in one LDS dword (thread 0 zeroes it at entry). After a group barrier, broadcast it and emit exactly one SetMeshOutputCounts at the join: the decoded counts, clamped to the declared maxima.
  • On a path that skips the request, the LDS word stays zero, so the group declares (0,0), emits a defined zero-area vertex 0 and zero indices; real exports overwrite both.
  • Exports before the join are dropped, which is the console's dummy null-primitive path.

Validator

dxil.dll rejects the natural two-call shape:

error: SetMeshOUtputCounts cannot be called multiple times.
error: Non-Dominating SetMeshOutputCounts call.

so the only accepted shape is one call at a uniform join. That is the form emitted, and the test asserts it.

Tests

  • mesh_alloc_counts_translate_and_validate: a 128-thread mesh with a uniform two-way branch, requests (3,3) and the console dummy (1,1); both forms validate.
  • gpu_mesh_alloc_counts_culled_group_draws_nothing: a culled (1,1) group leaves the target clear; the (3,3) control rasterizes.
  • gpu_mesh_alloc_counts_culled_dispatch_cost.
  • cargo test -p victory-shader: 113 passed, 0 failed.
  • Real shaders translated and validated with dxil.dll: nine MS_VS_Transform* / MSNC_VS_Transform* variants, !MS_VS_DepthSkin, and MS_VS_BreakableGlassNoCrack.

In-game

With this and the rendezvous bound in the first commit, seven previously hanging transform hashes (37f363f0a5dcd806, 14c00e888b4df658, 0d9d1c59733d6340, 89036e16fa081505, 3fd417e7d6f55114, 857b2e13c9cc107f, c9dee8dc4ad07dd4) translated and ran with no mesh dispatch over 50 ms and no device removal. One hash (c962201cddbdd7dd) still took 5.1 s; that turned out to be a root-SRV read past the host copy and is fixed by #493, not by this change. No title data is included here.

Stack

The first two commits are #464 and #459; the last two are this PR (the rendezvous bound and the allocation counts). Review the last two.

Kam471 and others added 21 commits November 24, 2026 01:32
Port of upstream PR Marvisak#123. The host requires a raw SRV/UAV's first element
to sit on a 16-byte boundary (four 4-byte elements); the console only asks
for 4 bytes. CreateShaderResourceView then fails and the device is removed
with 0x887A0001, which our world run hit. Such a view now becomes a null
view of its kind (reads zeros) with a one-time warning, like a view that
does not start on an element.
A world frame records some thirty lists. In one ExecuteCommandLists the GPU
ran them for 5+ s without draining, and Windows removed the device with
0x887A0006. Whole runs now go in groups of four, with the existing fence wait
between groups, so the GPU finishes a group and the watchdog sees progress.
Order and all cross-list state are unchanged; the device-removed check after
each group stops submitting the rest of a dead device.
- dualsense: reads USB (0x01) and Bluetooth (0x31) DualSense reports via
  SetupAPI/HID, maps sticks, triggers, d-pad, face/shoulder/option buttons to
  the pad state the title sees, and plays as pad 1 when no XInput pad answers.
  Unit tests cover both report layouts; the reader logs when it connects.
- host: a click-through, always-on-top counter over the title's window shows
  fps, ms/frame, draws/frame and shader-cache hits/misses; VICTORY_FPS_OVERLAY=0
  turns it off. The window caption keeps working as before.
- shader cache was already present and is verified populated (707 files,
  130.4 MB under %LOCALAPPDATA%\\victory\\cache\\shaders); the counter now
  surfaces its hits and misses.
The counter was a green-on-black layered window with a colour key. It now
renders text with per-pixel alpha: a white rate, a dimmer ms/draws line and a
one-pixel black outline, so it reads as a HUD over the picture rather than a
box. It follows the title's client origin and is still click-through.

DualSense logs its connection, and O on the keyboard plays Circle (B) next to
Enter's Cross.
Mesh shaders cannot declare a wave size, so console mesh programs that
read lane numbers, other lanes or lane masks as numbers were running
with host lane numbers (the previous diagnostic asked for WaveSize(64),
which NVIDIA refuses): their output was silently wrong and the device
could hang. Generalize the Wave64 compute emulation to the mesh stage:
a console lane is a flattened thread id within each 64-thread wave,
exchanges and ballots go through group-shared memory, and vertex and
primitive outputs stay keyed by SV_GroupIndex.

The uniformity analysis now follows lane-wise VALU results (and SGPR
writes under lane guards) whose sources are uniform, so a uniform
v_readfirstlane in divergent control flow uses the host's first-lane
read, which is exact for a value every active lane holds, instead of a
barrier those lanes cannot all reach. Mesh shared memory declared in
PSV0 is now only what the module actually allocates.

Synthetic GPU tests cover 64/96/128-thread mesh groups, a partial last
console wave, readlane, ds_swizzle, title LDS coexisting with the
exchange scratch, uniform readfirstlane in divergent flow, and a 3-D
compute group. The four DRED mesh programs translate, validate and
create host mesh pipelines.
A console wave64 mesh lane is the flat thread id's low six bits, so
v_mbcnt, quad-local swizzles and DPPs, and constant lane-mask tests are
host-independent and need no group-shared memory or barriers. Only a
program that reads another lane's value (an unresolved v_readlane,
v_writelane, non-quad swizzle/DPP/permute, a mask as data, an opaque-mask
guard, or a non-uniform v_readfirstlane) still emulates.

An unguarded v_readfirstlane in a mesh wave now has console lane 0
publish its value into the exchange slot and reads it back after two
barriers, instead of an atomic-min election and four barriers.

Synthetic 64/128-thread meshes whose only cross-lane need is the lane
number report 0 B of mesh LDS (264/528 B when a forced exchange is
added). Tests cover the fast-path lane and constant-mask arithmetic, the
firstlane exchange, and per-dispatch timing with DispatchMesh.
A loop that only rereads one address until another workgroup, queue or
the command processor changes it (decoupled look-back, persistent-thread
queues, locks) waits microseconds on the console. On the host the write
may never come: the writer's view can be another host resource, null or
not yet mirrored, and the host compiler may hoist a load out of a loop
that writes nothing (bufferLoad is readonly). The loop then runs to the
2^20 limit in every lane: about a second per wave of uncached reads,
the order of the 650-930 ms world submissions spend on an RX 7600.

Such loops are found in the IR (emit/spin.rs): no stores, exports, LDS
writes, barriers or messages; every memory read and atomic at an
address the loop does not change; and nothing loop-carried made by
arithmetic, only lane masks, compares and what was read. They stop at
VICTORY_SHADER_SPIN_LIMIT (default 4096, never above the loop limit);
the shader cache keys on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
A world frame spends 650-930 ms of GPU time per host submission on an
RX 7600, mostly in compute pipelines. Translated loops stop at 2^20
iterations per lane; a loop that waits on memory the host never updates
runs that long in every lane. A lower limit shows whether such loops are
the cost, and the user runs release builds: the switch is no longer
gated on the diagnostics feature. The shader cache already keys on the
limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AZ9pSB4ZoXYUifuXg8gm66
A mesh group of several console waves can have one wave on a different
scalar branch or loop iteration than another, so an emulation group
barrier can wait for a wave that never arrives. Multi-wave mesh groups
now rendezvous through one monotonic LDS counter per virtual wave: each
invocation adds the wave's lane count, so every lane computes the same
target and no reset or generation is needed. Groups of 64 threads or
fewer keep the hardware barrier.

The 96/128-thread mesh tests with cross-wave readlane, ballots and
firstlane exchanges pass repeatedly. A stress test of thousands of
exchanges in a loop shows the software barrier is slower than a
hardware one; the known mesh programs do not put barriers in loops.
A copy of view memory (physical-page views, which cannot be
write-watched) guards each 64 KiB block it took read-only. A block that
is not mapped (a placeholder between views of a GPU heap) cannot be made
read-only, so it never became clean: every asking reported it written
again, and the copy read it through the per-page fallback, whose
failing kernel reads cost hundreds of ms per world frame.

Note such blocks absent (only after VirtualProtect fails and the block is
not committed). An absent block is not reported again until
title_memory_remapped, which the runtime calls after mapping or
unmapping views, clears it. The copy keeps the zeros it took.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A translated mesh shader declared the console's vertex and primitive
maxima (up to 256 each) whatever its outputs took, so wide outputs at
those maxima passed the 32 KiB that D3D12 allows a mesh shader and the
validator refused the module ("vertex plus primitive output size is
greater than 32768").

The prologue now measures the outputs as the validator does (4 bytes
per component of every vertex and primitive signature element, times
the maxima rounded up to 32). Past the cap, the maxima come down to the
lane count: lane n writes only vertex n and primitive n, so no group
writes more. Outputs that pass the cap even at the lane count are still
emitted as before, with the lower maxima, so no draw that works today is
dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A translated multi-wave mesh shader synchronizes each virtual wave's emulated exchange through an LDS counter. That rendezvous spun up to 2^20 times when a lane of the wave did not arrive, unlike title spin waits (4096). On a GPU that can hold one atomic loop past the 2 s TDR by itself, turning an emulation miss into a device removal. The rendezvous now stops at spin_limit(), which VICTORY_SHADER_SPIN_LIMIT can lower further.

The test translates a 128-thread mesh program with a non-uniform v_readfirstlane and checks the timeout emitted, and the exchange dispatch benchmark now fails if a dispatch takes a second or more.
A mesh shader declares its output maxima, then asks for the group's real
vertex and primitive counts with GS_ALLOC_REQ in M0. The translator kept
the maxima, so culled groups still rasterized 128 stale primitives and
the transform family took 0.8-5 s per dispatch.

Find the uniform join after every request, broadcast the request's M0
through LDS, and emit exactly one SetMeshOutputCounts there: the decoded
vertices/primitives, clamped to the declared maxima. A culled group
declares (0,0) with a defined zero-area vertex and zero indices; real
exports overwrite both. Validated with dxil.dll on the transform and
DepthSkin variants; a GPU test shows a culled group leaves the target
clear.
@iurysf

iurysf commented Nov 24, 2026

Copy link
Copy Markdown

Tested offline against main d2a4bae with victory translate --list --validate over the title's shaders.rpf + executable (26,096 programs), dxil.dll 1.9.2602.17. This branch carries the #464 and #459 commits, so the numbers measure the stack:

  • Translation failures: 3,733 on main -> 4,342 with this stack (+609). A new refusal, "v_readfirstlane in divergent control flow", rejects 690 mesh programs that main emitted. Mesh emitted drops 8,191 -> 7,582 (-609); vertex/pixel and compute are unchanged.
  • 592 mesh modules that emitted and validated on main no longer emit. Among the modules that still emit, validation only improves: 185 rejected on main -> 167 here, and no module that validated on main fails the validator now.
  • So offline, the trade is 592 previously valid mesh programs dropped (their draws would be dropped in game) against the hang fix. Is the divergent v_readfirstlane refusal meant to be this broad? The GPU side is being measured on an RTX 4070 and I'll post it here.

AI-assisted.

@iurysf

iurysf commented Nov 24, 2026

Copy link
Copy Markdown

In-game data point, following my offline numbers above. RTX 4070 (driver 32.0.16.2101), diag build, default loop limit, VICTORY_D3D12_DRED=1, 300 s runs. One run each, and the host CPU was busy with other jobs, so treat the timings loosely.

device removed time in world draws/frame in world slowest submission
main d2a4bae at 163 s 64 s ~1,300 4.9 s
main + this PR at 214 s 95 s 1–6, 0 indirect 6.75 s, 32 compute lists (slow host list ms=6732 commands=42)

AI-assisted.

@fuzeofficlal

Copy link
Copy Markdown
Contributor

For the #201 output-size case, I tested an incremental change on 9b5e239 that uses the two output limits encoded by proven literal M0 definitions. It takes the maxima across all planned requests and changes the declaration only when the result fits the output budget. It also gates dummy vertex initialization on a nonzero vertex count.

My synthetic 128-thread mesh exports 19 signature elements (67 components). With a literal allocation of 96 vertices and 1 primitive, this head declares 128/128 and the Windows SDK validator rejects the output size. The follow-up declares 96/1, validates, and native D3D12 reads back 16/16 expected pixels using the last vertex output. The zero-count case validates and leaves all 16 pixels clear. The literal-97 and runtime-count controls retain the old declarations and validator result. The serial shader suite passed 114 tests, including a portable test for two different literal request sites and a runtime operand.

Incremental source change on this head

@EduBertozzi

Copy link
Copy Markdown
Contributor

Windows 10 + Pascal run of this PR's own tests, and a design question on the mesh rendezvous.

Setup: Windows 10 Education 22H2 (19045), GTX 1060 6 GB (582.66, 32-lane waves, no mesh shaders), Rust 1.98.1, debug. I tested this PR's head 9b5e239 on its own base, with #486 merged locally so the test binaries get SM 6.6 from the Agility SDK runtime. The redistributable WARP 1.0.22 (Microsoft.Direct3D.WARP: SM 6.6, waves of 4 to 128 lanes, mesh shaders) was beside the test binary.

cargo test -p victory-shader wave64 -- --test-threads=1:

  • Hardware adapter only (in-box WARP stays at SM 6.5 and is skipped): 35 passed, 0 failed.
  • With WARP 1.0.22: 23 passed, 12 failed. Only one of those is a failure of its own.
    • gpu_128_threads_ds_swizzle_and_dpp_row_mask, in Wave32 mode on WARP, fails at the dispatch with the device removed, 3 of 3 times when run alone. The same test passes on the GTX 1060.
    • The WARP device is shared within the process, so the next 10 compute GPU tests fail at PSO creation on the removed device. Each of those passes when run alone.
    • recommended_wave64_mode_matches_device_capabilities asserts that WARP recommends Emulate. That holds for in-box WARP (4-lane waves), but WARP 1.0.22 recommends Native. GitHub's runners list the in-box WARP, so CI won't see this.
  • The mesh GPU tests print no dxc for a pixel shader; PSO skipped here (Windows SDK 10.0.28000 installed, dxil.dll found). So where the tests find no DXC, they pass without building a mesh pipeline or drawing anything.

On the mesh wave rendezvous (wave_barrier, the spin-wait bounded by spin_limit). A wave that waits on an LDS counter for another wave of its group to arrive depends on that wave being scheduled meanwhile, and D3D12 doesn't promise that. #439's design notes (docs/wave64-on-wave32.md, "Groups of several console waves") dropped this approach for that reason. Their measurement on an RTX 5070: the upper half of a group didn't write LDS before the lower half read it unless a barrier ordered them, 20 of 20 runs. Where the partner wave isn't running, the bounded wait ends after 4096 rounds with the program going on as if it had arrived. That gives a wrong result, at the cost of the spin. That fits the RTX 4070 and 5090 runs above, which still remove the device. For mesh groups of one console wave (64 threads), #439's console flow needs no wait at all: group barriers, with both halves taking every branch together.

Splitting: +1 to the split suggested above. The DualSense/HUD input, list splitting, guarded views and spin-wait limits could each be measured and merged on their own. That would also show which part changes the NVIDIA runs.

For the group-size question this leaves open, I've asked for a census of the title's mesh programs on #778 (victory mesh-census: group sizes, LDS, barriers, lane reads). Every one of them is wave64, so whether they fit in one console wave decides a lot.

AI-assisted (Claude Code); runs on my machine, no game data.

@ricarmandoagent

ricarmandoagent commented Nov 24, 2026 •

Copy link
Copy Markdown

This branch carries four other unmerged PRs, and the body has no Depends on line:

The description covers only the mesh allocation request. As it stands the diff cannot be reviewed as one topic, and merging it lands four unrelated changes at once — #150 is not even in the same subsystem.

Please rebase on main, and either split this into the stack it is (with Depends on: naming each parent) or wait for them to land first.

AI-assisted review.

@BaggyALPHA

Copy link
Copy Markdown
Contributor

I checked whether the literal-M0 approach discussed here could tighten the vertex declaration for the 53 output-size failures in #201. I used an offline diagnostic on #459 head dc838d6, paired its request analysis with the SDK validator results, and left the emitted DXIL unchanged.

All 53 failing modules had one allocation request each. None of the 53 request operands was a literal. I also traced the low 12 vertex-count bits separately, propagating known bits through scalar moves, bitwise operations, shifts, and SSA joins. This let the probe consider the vertex bound even if the primitive field was unknown. It proved a bound of 96 or fewer for 0 of 53 and left all 53 unresolved.

That does not establish that any request exceeds 96 at runtime. It does show that the literal-M0 change demonstrated on synthetic shaders would not match this group as written. This check did not run the #586 runtime code or exercise rendering.

AI-assisted analysis and write-up (OpenAI Codex). Aggregate counts only.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs rebase. This PR does not merge cleanly into current main (ac2525d). Conflicting files: README.md, crates/victory-gpu/src/descriptor/host.rs, crates/victory-gpu/src/draw.rs, crates/victory-gpu/src/host.rs, crates/victory-gpu/src/list.rs, crates/victory-gpu/src/shader_cache.rs, crates/victory-gpu/src/watch.rs, crates/victory-hle/src/modules/mod.rs and 5 more.

The content has not been reviewed yet; it will be once the branch is rebased onto main.


Generated by Claude Code

geiyiliyabumo pushed a commit to geiyiliyabumo/VIctory that referenced this pull request Nov 25, 2026
Docs: why Wine's builtin d3dcompiler_47 refuses the runtime helper shaders
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.