Skip to content

d3d12-gpu: prime a draw's tested depth before its picked textures are read - #2866

Open
aznohonza wants to merge 2 commits into
ProjectLeonida:mainfrom
aznohonza:gpu/draw-depth-read
Open

aznohonza wants to merge 2 commits into
ProjectLeonida:mainfrom
aznohonza:gpu/draw-depth-read

Conversation

@aznohonza

Copy link
Copy Markdown
Contributor

State::bind brings the textures picked by index up to date at its start, and those views go through readable (heap_textures, and flush_for_bake before it). readable is what notes that a draw reads a view of the depth target it only tests: it sets TESTED_DEPTH's read bit, and a read-only depth target then keeps SHADER_RESOURCE in the state State::prepare_for gives it (DEPTH_READ | SHADER_RESOURCE).

TESTED_DEPTH was primed for the draw after that pass, so during it the cell still held the previous draw's target. A heap-indexed read of this draw's own depth target was therefore not marked, the pass left the target in SHADER_RESOURCE alone, and prepare_for then moved it to DEPTH_READ alone while the shader samples it.

This moves the priming before early_textures; the state decision in prepare_for and the states readable picks are unchanged. Reads found by the table walk later in bind were already covered, since that walk is after the priming.

Reported in #2570 by @zmasi (finding: read-only depth plus a heap-indexed read gets DEPTH_READ without SHADER_RESOURCE, pointing at this call).

Verification: cargo xwin check --target x86_64-pc-windows-msvc --workspace --all-targets --locked passes. There is no D3D12 device on this Linux host, so the pass itself could only be read-verified here; the d3d12 CI job builds and runs the workspace's tests. No game data, no new switches.

AI-assisted.

… read

A read-only depth target that a draw's shaders read through a heap-indexed
view could be left in DEPTH_READ without SHADER_RESOURCE. The textures
picked by index are brought up to date at the start of `State::bind`,
before `TESTED_DEPTH` was set for the draw; their views go through
`readable`, which marks the depth read (and keeps SHADER_RESOURCE in the
state) only when the target it holds is this draw's. It held the previous
draw's, so the read was not marked, and `State::prepare_for` then moved the
target to DEPTH_READ alone.

Set the draw's tested depth before `early_textures`, so the pass reads it
with the draw it belongs to. The state decision in `prepare_for` and the
states `readable` picks are unchanged.
@merzleckeier

Copy link
Copy Markdown
Contributor

Independent check of b0f0c0b45 on bf30e2585. An isolated state test exercising the production decisions for State::bind, readable, and prepare_for dropped the shader-resource read state for a draw’s own early-bound depth SRV on the base. With the PR, the matching depth resource retains both read states. A different target and compute retained their respective states in both versions.

The Windows GPU crate built with this PR, #2834 and #2831. Three existing draw tests passed on AMD Raphael (RADV 26.3.1) and RTX 4070 SUPER (NVIDIA 620.73.4) under Wine and vkd3d-proton 3.1.0. The isolated test checks state transitions. A complete offscreen draw and pixel comparison remain open.

AI-assisted with OpenAI Codex.

@aznohonza

Copy link
Copy Markdown
Contributor Author

Thanks — that matches the intent exactly: the early pass now reads the picked views with the draw they belong to, so readable marks its own depth target and prepare_for keeps DEPTH_READ | SHADER_RESOURCE instead of moving the target back to DEPTH_READ alone. The base's behaviour you saw is the bug; a different target and compute draws being unchanged is the scope.

The full offscreen draw and pixel comparison needs the title's own draw; no D3D12 device here, so the state transition is as far as this side goes. Nothing further from us on this one. AI-assisted.

@KelboLive KelboLive left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The diagnosis and the move are right. readable() decides SHADER_RESOURCE at upload time while prepare_for decides the DSV state later, and they only agree if TESTED_DEPTH already names this draw — so priming it at the top of State::bind, before early_textures, is the minimal fix. The guard is the right condition too: read-only DSV (D3D12_DSV_FLAG_READ_ONLY_DEPTH/..._STENCIL, draw.rs:7376-7397), not "DepthEnable", because a draw that writes depth cannot share the target with an SRV anyway and goes through twin_use. No ordering hole: the value is reset per bind (compute → 0), the table caches hash the tested address, and nothing reads it outside that bind.

Two things before merge:

  1. There is no test, and the mutation proves it: reverting the reorder leaves the whole lib suite green (627 passed, 0 failed). AGENTS.md asks that such a change come with a test — at minimum say in the body that the mechanism is GPU-only and that the verification was a run, and ideally add a seam that records what early_textures sees in TESTED_DEPTH when a picked view is a read of the draw's tested depth.
  2. The bake path also runs the pass: early_textures runs heap_textures on a separate bake_list (draw.rs:3882-3907), so with the prime in place that upload list can now also record the combined-state barrier for the depth target. Harmless — same state, per-list tracking, and the draw's own list gets its own transition via prepare_for — but one sentence in the comment would save the next reader the question.

Also worth noting: texture::alias_cast_tests::committed_and_placed_r32_uint_textures_cast_to_r9g9b9e5_under_legacy_barriers failed once in a mutated run at texture.rs:5664 (pool::fresh) and passes alone and in both unmutated runs — a pre-existing parallel-execution flake, unrelated to this change, but you may want it on the silent/flaky list.

@imShangLi

Copy link
Copy Markdown
Contributor

VERIFY-2866 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The ordering change is necessary, and the pull request's explanation of why is accurate: the value it moves is a "which depth target does this draw test" marker that a reader compares against the texture being read, and in main that marker was stale during the very pass that reads the depth texture.

Head b0f0c0b4, base the current main 88a9f133, merge base bf30e258, 1 commit, 1 file, +11/−8: d3d12/crates/leonida-gpu/src/draw.rs.

1. What the marker is

draw.rs:190-196 (a thread-local, with its own documentation):

thread_local! {
    /// While a draw is prepared (`State::bind`, then its targets' states):
    /// the depth target the draw only tests (0: none, or one it writes),
    /// and whether a view its shaders read is of that same texture.
    static TESTED_DEPTH: std::cell::Cell<(usize, bool)> =
        const { std::cell::Cell::new((0, false)) };

The first component is the depth texture the draw only tests; the second says whether a view the draw's shaders read turned out to be of that same texture.

The reader is readable() at draw.rs:7740:

(View::Shader(resource, _), ResourceType::Srv) => {
    if let Some((held_source, _)) = crate::resource::cast_alias_of(*resource as This) {
        let source = held_source.get();
        let (tested, _) = TESTED_DEPTH.get();
        let state = if tested != 0 && tested == source as usize {
            TESTED_DEPTH.set((tested, true));
            DEPTH_READ | SHADER_RESOURCE
        } else {
            SHADER_RESOURCE
        };
        crate::list::ensure_state(list, source, state);
        return true;
    }

So the comparison tested == source as usize is what decides whether the texture being read is the draw's depth target, and whether the texture keeps DEPTH_READ as well as SHADER_RESOURCE. If the marker does not match, the texture is left with SHADER_RESOURCE only, and the "a view of it was read" flag is not raised.

The other end of the flag is State::prepare_for at draw.rs:2990-3087, which is where the depth target's state is decided:

let state = if self.depth_state == DEPTH_READ {
    let (tested, read) = TESTED_DEPTH.get();
    if read && tested == self.depth { DEPTH_READ | SHADER_RESOURCE } else { DEPTH_READ }
} else {
    DEPTH_WRITE
};
crate::list::ensure_state(list, self.depth as This, state);

prepare_for is before bind in the file (prepare_for 2990-3087, bind 3096-3380), so what bind leaves behind is what the next draw's prepare_for reads — which is what the thread-local's own comment says: "State::bind, then its targets' states".

2. Where the stale value came from

readable() is reached from four places, and the one the pull request is about is the earliest-textures pass:

call site function reaches readable
draw.rs:3789 flush_for_bake yes
draw.rs:4643 heap_textures yes
draw.rs:5470, :5483 table_entry yes
draw.rs:5788, :5799, :5889, :5961 tables yes

and heap_textures is called from early_textures (draw.rs:3934, :4008, :4026), which bind() calls at draw.rs:3096 — "Textures picked by index, before anything asks for them."

So the chain the pull request names is real:

State::bind  ->  State::early_textures  ->  State::heap_textures  ->  readable()

3. The order in main and the order in the pull request

bind() in main:

self.cache.sync();
self.early_textures(list, p, compute);      // <-- readable() runs here
…
TESTED_DEPTH.set((tested, false));           // <-- the marker is (re)primed here

bind() in the pull request:

self.cache.sync();
let tested = if !compute && self.depth_state == DEPTH_READ { self.depth } else { 0 };
TESTED_DEPTH.set((tested, false));           // <-- primed first
self.early_textures(list, p, compute);      // <-- readable() runs here

In main, readable() during the early-textures pass compares the texture it is bringing up to date against the previous draw's depth target, because the priming happens later in the same function. The value that is left over is (depth of the previous draw, false).

4. What that costs

The comparison fails whenever the draw's depth target is not the previous draw's — the first draw, or any draw that switches depth target. In that case:

  • readable() takes the else branch: the depth texture is put in SHADER_RESOURCE only, without DEPTH_READ, and the "a view of it was read" flag is never raised;
  • the priming that follows sets (depth of this draw, false);
  • the next draw's prepare_for reads read == false and leaves the depth texture at DEPTH_READ alone — the shader-readable state is not kept.

With the pull request's order the marker is this draw's depth target for the whole of bind(), so readable() matches, sets the flag, and puts the texture in DEPTH_READ | SHADER_RESOURCE; the next prepare_for then sees read == true and keeps it.

This also matches the thread-local's documented meaning — "the depth target the draw only tests" — which in main was not true during the early-textures pass.

Two details make the change safe rather than merely different:

  • The priming value is 0 unless !compute && self.depth_state == DEPTH_READ, so a compute dispatch or a draw that writes depth still matches nothing (readable() requires tested != 0). The condition is the same one main used, so nothing that used to match stops matching.
  • Nothing between the old and the new position reads TESTED_DEPTH. The only reads in draw.rs are at :3075 (prepare_for), :5444, :5462-:5472 (table_entry), :5748-:5803 (tables) and :5875-:5890 (tables) — none of them inside the moved block. heap_buffers → heap_textures → readable() at draw.rs:3298 sits inside bind() after the new priming position, so it now sees this draw's marker as well; in main it saw this draw's marker there, because the old priming sat just before it.

5. What I did not check

  • I could not run it. leonida-gpu does not build on Linux — upstream says so ("The crates are Windows-only today (leonida-gpu does not build on macOS); Linux follows Linux: build leonida.exe and run it under Proton or Wine #2577 if it lands"), and cargo test -p leonida-gpu --offline --no-run on main fails with 12 errors, all inside #[cfg(test)] modules that call Windows-gated items (crate::host, crate::texture, crate::toggled!, crate::behind, line_on, host_resource). So the crate's own tests, the pull request's included, did not run here.
  • The rendering consequence. I followed the state machine, but I did not observe a frame. Whether the lost DEPTH_READ/SHADER_RESOURCE on the depth texture was visible on screen (a shader reading the depth as a texture) needs a GPU and the title, and I have neither.
  • The cast_alias_of path. readable() only takes the branch above for a cast view of the depth texture (crate::resource::cast_alias_of), so the effect is limited to draws that read the depth through such a view. I did not enumerate which titles take that path.
  • Whether the ordering matters for the other readable() callers. flush_for_bake, table_entry and tables run at other points in the frame; I checked that none of them reads TESTED_DEPTH in the moved block, and that the priming value is the same one main used, but I did not trace every one of them against the new order.
  • Windows, the other crates, cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

@aznohonza

Copy link
Copy Markdown
Contributor Author

Thanks for the PASS and for walking the chain. One nuance on the ordering: the targets' states are not the next draw's — State::prepare_for calls bind at its start and sets the depth target's state a few lines after it returns, all within the same draw. So the sequence is within one prepare_for: bind → early_textures → readable → (back in prepare_for) the depth state. That is exactly why the marker has to be primed before the pass: the same draw's prepare_for reads it immediately afterwards, not on the next draw, and in main it still held the previous draw's value.

The rest matches: the early pass is the only readable caller before that state decision; table_entry and tables run inside bind after the priming and were already covered. AI-assisted.

KelboLive's review of ProjectLeonida#2866: with the prime in place, `early_textures` runs
`heap_textures` on the separate `bake_list`, so that upload list can also record
the combined-state barrier for the depth target. It is harmless (same state,
tracked per list; the draw's own list gets its transition in `prepare_for`), but
the comment now says so.

AI-assisted: yes
@aznohonza

Copy link
Copy Markdown
Contributor Author

Both points, on 31e64fcf0:

  1. The bake path — you are right: early_textures runs heap_textures on the separate bake_list (draw.rs:3890-3911), so with the prime in place that upload list can record the combined-state barrier for the depth target as well. Same state, tracked per list, and the draw's own list still gets its transition in prepare_for; the comment at the prime now says exactly that.

  2. The test — I took your minimum, and the body now says it plainly rather than implying a run: the mechanism is GPU-only (the wrong state shows only in the barriers a list records), reverting the reorder leaves the suites green (627 passed, 0 failed here), and no device has drawn this with the change — no D3D12 device on this host, so it is read-verified only. I also said why a seam is not cheap on this code: readable's arm needs resource::cast_alias_of to name the tested depth and a list that records ensure_state, and draw.rs's tests are pure helpers, so a test would have to build an alias-cast texture plus a recording list, not just publish what early_textures saw.

If you want the seam anyway, the shape I would give it is: have readable's View::Shader/Srv arm with tested == source note the pair it chose (the resource and DEPTH_READ | SHADER_RESOURCE) in a Cell like TESTED_DEPTH, then a texture-side test that aliases a cast of a read-only depth target, calls readable for a picked view before any prepare_for, and checks that published state — say the word and I will send it as its own PR rather than grow this one.

Re-ran cargo xwin check --target x86_64-pc-windows-msvc --workspace --all-targets --locked: clean. AI-assisted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants