d3d12: mesh pipelines draw through compute on a GPU without mesh shaders (D3D12-MESH-COMPUTE-FALLBACK) #2580

Closed
qhukz13 wants to merge 9 commits from upstream-pr/2580 into main
qhukz13 commented 2026-11-28 17:44:43 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by qhukz13 on 2026-11-28T17:44:43Z.


Claimed in the coordination issue as: D3D12-MESH-COMPUTE-FALLBACK (#2570#issuecomment-7239097845)

What and why

leonida.exe refuses every mesh pipeline on a GPU without D3D12 mesh shaders (mesh shader tier 0: Pascal and older), so the world draws nothing there. This translates each mesh program as an ordinary compute shader writing its outputs to a buffer, and draws that buffer as a triangle list through a pass-through vertex shader of ours.

  • Translator: set_host_mesh_shaders(false):
    • a mesh program becomes cs_6_6; its four mesh output ops become raw stores into the root UAV SLOT_MESH_OUT, one MeshOut slot per group;
    • a 256-byte header holds the draw arguments, which the groups fill (no CPU read for indirect calls);
    • groups past the 64 MiB buffer go to a sink slot and draw nothing;
    • mesh_vs() reads it back: SV_VertexID gives primitive and corner, SV_InstanceID the group, and per-primitive outputs are constant inputs where the pixel shader reads them;
    • the shader cache keys on it.
  • Runtime:
    • the device check turns it on (LEONIDA_MESH_COMPUTE=1 forces it on any card, for comparison);
    • a mesh pipeline becomes a compute pipeline plus a graphics pipeline;
    • a direct dispatch becomes Dispatch + DrawInstanced;
    • an indirect dispatch becomes WriteBufferImmediate + two ExecuteIndirects (dispatch signature over the title's own record, then draw from the header).
  • shortcut: an indirect call with several records is still left out (logged).

On Windows 10 this needs #2557 (shader model 6.6).

Tested

  • MEASURED: GTX 1050 Ti 4 GB, Windows 10, 582.66, with #2557 merged locally. The title goes from its start screen through the opening cutscenes into the first playable scene at 2–5 fps. Before: the world drew nothing, and every mesh pipeline logged no host pipeline: the host GPU has no mesh shaders. Fallback pipelines made in a run: up to 567; no device removal.
  • Unit/device tests (cargo test -p leonida-shader --lib mesh, -p leonida-gpu --lib shader_cache): 7 + 2 pass on the 1050 Ti. The device test draws the triangle mesh fixture as compute and checks the texels, and compares them with the mesh pipeline texel for texel on a device with mesh shaders. dxil.dll validates the compute variant and the vertex shader.
    • Note: on Windows 10 the shader crate's device tests need the Agility SDK in the test process; I ran them with it exported locally (not part of this PR).
  • Not tested: a native comparison (no mesh-shader card here). LEONIDA_MESH_COMPUTE=1 on an RTX card would show it.

GPUs tested: GTX 1050 Ti 4 GB (Pascal, profile S), 582.66, Windows 10.

AI-assisted (Claude Code).

🤖 Generated with Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5542948032 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580). Originally posted by [qhukz13](https://github.com/qhukz13) on 2026-11-28T17:44:43Z. --- Claimed in the coordination issue as: D3D12-MESH-COMPUTE-FALLBACK (#2570#issuecomment-7239097845) ### What and why `leonida.exe` refuses every mesh pipeline on a GPU without D3D12 mesh shaders (mesh shader tier 0: Pascal and older), so the world draws nothing there. This translates each mesh program as an ordinary compute shader writing its outputs to a buffer, and draws that buffer as a triangle list through a pass-through vertex shader of ours. - **Translator:** `set_host_mesh_shaders(false)`: - a mesh program becomes `cs_6_6`; its four mesh output ops become raw stores into the root UAV `SLOT_MESH_OUT`, one `MeshOut` slot per group; - a 256-byte header holds the draw arguments, which the groups fill (no CPU read for indirect calls); - groups past the 64 MiB buffer go to a sink slot and draw nothing; - `mesh_vs()` reads it back: `SV_VertexID` gives primitive and corner, `SV_InstanceID` the group, and per-primitive outputs are constant inputs where the pixel shader reads them; - the shader cache keys on it. - **Runtime:** - the device check turns it on (`LEONIDA_MESH_COMPUTE=1` forces it on any card, for comparison); - a mesh pipeline becomes a compute pipeline plus a graphics pipeline; - a direct dispatch becomes `Dispatch` + `DrawInstanced`; - an indirect dispatch becomes `WriteBufferImmediate` + two `ExecuteIndirect`s (dispatch signature over the title's own record, then draw from the header). - shortcut: an indirect call with several records is still left out (logged). On Windows 10 this needs #2557 (shader model 6.6). ### Tested - MEASURED: GTX 1050 Ti 4 GB, Windows 10, 582.66, with #2557 merged locally. The title goes from its start screen through the opening cutscenes into the first playable scene at 2–5 fps. Before: the world drew nothing, and every mesh pipeline logged `no host pipeline: the host GPU has no mesh shaders`. Fallback pipelines made in a run: up to 567; no device removal. - Unit/device tests (`cargo test -p leonida-shader --lib mesh`, `-p leonida-gpu --lib shader_cache`): 7 + 2 pass on the 1050 Ti. The device test draws the triangle mesh fixture as compute and checks the texels, and compares them with the mesh pipeline texel for texel on a device with mesh shaders. dxil.dll validates the compute variant and the vertex shader. - Note: on Windows 10 the shader crate's device tests need the Agility SDK in the test process; I ran them with it exported locally (not part of this PR). - Not tested: a native comparison (no mesh-shader card here). `LEONIDA_MESH_COMPUTE=1` on an RTX card would show it. GPUs tested: GTX 1050 Ti 4 GB (Pascal, profile S), 582.66, Windows 10. AI-assisted (Claude Code). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
lixonik commented 2026-11-28 21:10:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T21:10:14Z.

Code review location: d3d12/crates/leonida-shader/src/emit/mesh_vs.rs; line 138

@@ -0,0 +1,206 @@
+//! The vertex shader that draws a mesh program run as compute on a host
+//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute
+//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices,
+//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`]
+//! in its [`MeshOut`] layout; the draw that follows is a triangle list of
+//! `3 * max_primitives` vertices and one instance a group, with this shader
+//! in front of the title's pixel shader, reading the same buffer as the root
+//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the
+//! header's arguments, which the groups wrote.)
+//!
+//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of
+//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own:
+//! it draws nothing. A primitive the program culled, or
+//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh
+//! path. Every corner is its own vertex here, so a per-primitive output is
+//! a vertex output with constant interpolation, the same at all three.
+//!
+//! The outputs are the mesh program's vertex outputs, register for
+//! register, and its per-primitive outputs in the registers the pixel
+//! shader reads them from (by semantic and index): a mesh pipeline's
+//! per-primitive outputs have their own signature, which a vertex shader
+//! has not.
+
+use super::bitcode::{Attr, Bin, Term, V};
+use super::container::SigElement;
+use super::shader::{MeshOut, Shader};
+use crate::ShaderError;
+use crate::dxbc::{Container, FourCC};
+
+/// The pass-through vertex shader (a DXIL container) for a mesh program
+/// translated as compute with `layout`, drawn with the translated pixel
+/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one.
+pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
+    let vertex = super::signature(&layout.osg1)?;
+    let primitive = super::signature(&layout.psg1)?;
+    let wanted = match ps {
+        Some(ps) => {
+            let c = Container::parse(ps)?;
+            match c.part(FourCC::ISG1) {
+                Some(part) => super::signature(part.data)?,
+                None => Vec::new(),
+            }
+        }
+        None => Vec::new(),
+    };
+    build(layout, vertex, &primitive, &wanted)
+}
+
+/// Where an output's value comes from: byte `at` of its vertex (`false`)
+/// or of its primitive past the indices (`true`).
+struct Source {
+    primitive: bool,
+    at: u32,
+}
+
+fn build(
+    layout: &MeshOut,
+    vertex: Vec<SigElement>,
+    primitive: &[SigElement],
+    ps_inputs: &[SigElement],
+) -> Result<Vec<u8>, ShaderError> {
+    let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
+    if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() {
+        return Err(unsupported("a mesh layout that does not match its signatures"));
+    }
+    if vertex.iter().any(|e| e.row.is_none()) {
+        return Err(unsupported("a mesh vertex output without a register"));
+    }
+    if layout.max_primitives == 0 {
+        return Err(unsupported("a mesh program without primitives"));
+    }
+    let mut outputs = Vec::new();
+    let mut sources = Vec::new();
+    for (e, &at) in vertex.iter().zip(&layout.vertex_at) {
+        outputs.push(SigElement {
+            usage: (1 << e.cols) - 1,
+            ..e.clone()
+        });
+        sources.push(Source { primitive: false, at });
+    }
+    // A per-primitive output goes where the pixel shader reads it; one the
+    // pixel shader does not read is not drawn with.
+    for (p, &at) in primitive.iter().zip(&layout.primitive_at) {
+        let Some(e) = ps_inputs
+            .iter()
+            .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some())
+        else {
+            continue;
+        };
+        let clash = outputs.iter().any(|o| {
+            o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols
+        });
+        if clash || e.cols < p.cols {
+            return Err(unsupported(
+                "a per-primitive output whose pixel shader register a vertex output takes",
+            ));
+        }
+        outputs.push(SigElement {
+            row: e.row,
+            col: e.col,
+            interp: 1,
+            usage: (1 << p.cols) - 1,
+            ..p.clone()
+        });
+        sources.push(Source { primitive: true, at });
+    }
+
+    let mut s = Shader::new(false);
+    let system = |name: &str, kind, row| SigElement {
+        name: name.into(),
+        index: 0,
+        kind,
+        comp: 5,
+        interp: 0,
+        row: Some(row),
+        col: 0,
+        cols: 1,
+        usage: 1,
+        half: false,
+    };
+    s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)];
+    s.outputs = outputs;
+    let b = s.entry;
+    let i32t = s.t.i32;
+    let k = |s: &mut Shader, v: u32| s.m.i32(v);
+
+    // (vertex id, instance id) -> primitive, corner, group.
+    let input = |s: &mut Shader, n: u32| {
+        let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)];
+        s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args)
+    };
+    let (id, group) = (input(&mut s, 0), input(&mut s, 1));
+    let three = k(&mut s, 3);
+    let prim = s.m.bin(b, Bin::UDiv, id, three);
+    let corner = s.m.bin(b, Bin::URem, id, three);
+    // A group past the cap wrote to the sink slot: it draws nothing.
+    let cap = k(&mut s, layout.groups_cap());
+    let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap);

groups_cap() counts usable slots, so slot indices below it are usable and the slot at that index is already the sink. The unsigned greater-than predicate still renders instance group == cap. I made the existing synthetic triangle fixture use a 4 KiB scratch cap, giving three usable slots. With only the last valid slot populated, it lit all 256 pixels as expected. With only the sink populated, instance 3 also lit all 256. Changing the comparison to unsigned greater-or-equal gave 0, as intended. Both the direct draw's instance count and the indirect header can currently include the sink instance. Could we exclude it at the comparison or cap the submitted draw count?

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4728819038 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#discussion_r4728819038). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T21:10:14Z. **Code review location:** `d3d12/crates/leonida-shader/src/emit/mesh_vs.rs`; line 138 ~~~~diff @@ -0,0 +1,206 @@ +//! The vertex shader that draws a mesh program run as compute on a host +//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute +//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices, +//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`] +//! in its [`MeshOut`] layout; the draw that follows is a triangle list of +//! `3 * max_primitives` vertices and one instance a group, with this shader +//! in front of the title's pixel shader, reading the same buffer as the root +//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the +//! header's arguments, which the groups wrote.) +//! +//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of +//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own: +//! it draws nothing. A primitive the program culled, or +//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh +//! path. Every corner is its own vertex here, so a per-primitive output is +//! a vertex output with constant interpolation, the same at all three. +//! +//! The outputs are the mesh program's vertex outputs, register for +//! register, and its per-primitive outputs in the registers the pixel +//! shader reads them from (by semantic and index): a mesh pipeline's +//! per-primitive outputs have their own signature, which a vertex shader +//! has not. + +use super::bitcode::{Attr, Bin, Term, V}; +use super::container::SigElement; +use super::shader::{MeshOut, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The pass-through vertex shader (a DXIL container) for a mesh program +/// translated as compute with `layout`, drawn with the translated pixel +/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one. +pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> { + let vertex = super::signature(&layout.osg1)?; + let primitive = super::signature(&layout.psg1)?; + let wanted = match ps { + Some(ps) => { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + build(layout, vertex, &primitive, &wanted) +} + +/// Where an output's value comes from: byte `at` of its vertex (`false`) +/// or of its primitive past the indices (`true`). +struct Source { + primitive: bool, + at: u32, +} + +fn build( + layout: &MeshOut, + vertex: Vec<SigElement>, + primitive: &[SigElement], + ps_inputs: &[SigElement], +) -> Result<Vec<u8>, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() { + return Err(unsupported("a mesh layout that does not match its signatures")); + } + if vertex.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a mesh vertex output without a register")); + } + if layout.max_primitives == 0 { + return Err(unsupported("a mesh program without primitives")); + } + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source { primitive: false, at }); + } + // A per-primitive output goes where the pixel shader reads it; one the + // pixel shader does not read is not drawn with. + for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + let Some(e) = ps_inputs + .iter() + .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) + else { + continue; + }; + let clash = outputs.iter().any(|o| { + o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols + }); + if clash || e.cols < p.cols { + return Err(unsupported( + "a per-primitive output whose pixel shader register a vertex output takes", + )); + } + outputs.push(SigElement { + row: e.row, + col: e.col, + interp: 1, + usage: (1 << p.cols) - 1, + ..p.clone() + }); + sources.push(Source { primitive: true, at }); + } + + let mut s = Shader::new(false); + let system = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)]; + s.outputs = outputs; + let b = s.entry; + let i32t = s.t.i32; + let k = |s: &mut Shader, v: u32| s.m.i32(v); + + // (vertex id, instance id) -> primitive, corner, group. + let input = |s: &mut Shader, n: u32| { + let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)]; + s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args) + }; + let (id, group) = (input(&mut s, 0), input(&mut s, 1)); + let three = k(&mut s, 3); + let prim = s.m.bin(b, Bin::UDiv, id, three); + let corner = s.m.bin(b, Bin::URem, id, three); + // A group past the cap wrote to the sink slot: it draws nothing. + let cap = k(&mut s, layout.groups_cap()); + let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); ~~~~ --- `groups_cap()` counts usable slots, so slot indices below it are usable and the slot at that index is already the sink. The unsigned greater-than predicate still renders instance `group == cap`. I made the existing synthetic triangle fixture use a 4 KiB scratch cap, giving three usable slots. With only the last valid slot populated, it lit all 256 pixels as expected. With only the sink populated, instance 3 also lit all 256. Changing the comparison to unsigned greater-or-equal gave 0, as intended. Both the direct draw's instance count and the indirect header can currently include the sink instance. Could we exclude it at the comparison or cap the submitted draw count?
lixonik commented 2026-11-28 21:10:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-28T21:10:14Z.

Review: COMMENTED


Reviewed 094e948e9 merged locally with main aa918e5d9. The synthetic triangle variants (plain, edge flags, culled) matched the native mesh pipeline on RTX 5070 (610.88), Windows 10 22H2 with Agility SDK 1.614.1 and DXIL validator 1.9.2609. The mesh-filtered suite reported 7 passing entries, with the optional compiler comparison and WARP device subcase skipped. One extra GPU fixture reproduced the sink-slot boundary below.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6100100062 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#pullrequestreview-6100100062). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-28T21:10:14Z. **Review:** COMMENTED --- Reviewed `094e948e9` merged locally with `main` `aa918e5d9`. The synthetic triangle variants (plain, edge flags, culled) matched the native mesh pipeline on RTX 5070 (610.88), Windows 10 22H2 with Agility SDK 1.614.1 and DXIL validator 1.9.2609. The mesh-filtered suite reported 7 passing entries, with the optional compiler comparison and WARP device subcase skipped. One extra GPU fixture reproduced the sink-slot boundary below. AI-assisted.
zmasi commented 2026-11-28 21:20:12 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T21:20:12Z.


Windows 11 + RTX 3090 D3D12 & WARP Verification (094e948e99) — GPU Verified + Rebase Needed Against main (E0063)

Verified commit 094e948e99a48d1476ac8adb33c5ce24ac8cb68d on Windows 11 (x86_64-pc-windows-msvc) with physical NVIDIA GeForce RTX 3090 (Ampere, D3D12 driver 610.88, native SM 6.6 mesh shaders enabled for direct hardware comparison) and WARP + dxil.dll.

1. Red -> Green Physical GPU & DXIL Verification

  • Red (main 1bc055e6c2): shader_cache MeshOut round-trip fails to compile (E0422/E0609/E0560: MeshOut and HostShader::mesh_out absent).
  • Green (094e948e99 standalone & merged onto main 1bc055e6c2 with the 2-field Translated update below):
    • cargo test --locked -p leonida-shader --lib -- --nocapture --test-threads=4 mesh: 7/7 passed (0.76s):
      • a_mesh_program_translates_as_compute_without_mesh_shaders: dxil.dll validated both the lowered cs_6_6 compute shader and the generated mesh_vs pass-through vertex shader.
      • a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws: passed texel-for-texel against the native mesh pipeline on both physical RTX 3090 (hardware: the mesh program drew as compute (mesh shaders there: true)) and WARP (warp: the mesh program drew as compute (mesh shaders there: true)).
    • cargo test --locked -p leonida-gpu --lib -- --nocapture --test-threads=4 shader_cache: 2/2 passed (MeshOut cache round-trip and damage rejection).
    • LEONIDA_MESH_COMPUTE=1 LEONIDA_D3D12_DEBUG=1 cargo test --locked -p leonida-gpu --features diagnostics --lib -- --nocapture --test-threads=4 pipeline::host::tests: 9/9 passed on RTX 3090 (0 D3D12 debug-layer errors) and 8/8 applicable tests passed on WARP (LEONIDA_D3D12_WARP=1).
    • python -I scripts/check_no_game_data.py (0 issues) and git diff --check clean.

2. Blocking Rebase Note Against Current main (aa918e5d9f)

Although Git merges 094e948e99 into main (aa918e5d9f) without textual conflicts, leonida-gpu fails to compile after the merge because struct Translated in d3d12/crates/leonida-gpu/src/pipeline.rs gained stores_past_views and bound on main since c1ecf04edc:

error[E0063]: missing fields `bound` and `stores_past_views` in initializer of `Translated`
  --> crates/leonida-gpu/src/pipeline.rs:224:35

Adding stores_past_views: false, and bound: Default::default(), to the synthetic vs Translated literal in Shader::mesh_fallback (d3d12/crates/leonida-gpu/src/pipeline.rs) resolves the compile error cleanly and passes all tests above on main.

3. Non-Blocking Notes

  • Host topology restoration (d3d12/crates/leonida-gpu/src/draw.rs): mesh_as_compute and mesh_indirect_as_compute call l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) on the host command list without restoring self.topology afterwards (if self.topology_set { self.set_topology(list, self.topology); }, analogous to self.mesh_scissor(list, false)). If an earlier draw on the same command list bound a non-TRIANGLELIST topology (e.g. TRIANGLESTRIP or LINELIST) and a subsequent VS/PS draw after the mesh dispatch does not re-issue IASetPrimitiveTopology, it would inherit TRIANGLELIST.
  • Visibility lint (d3d12/crates/leonida-shader/src/emit/shader.rs:260): MeshOut::new triggers #[warn(private_interfaces)] because SigElement is pub(crate) (pub(crate) fn new silences it).

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7245944143 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7245944143). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T21:20:12Z. --- ### Windows 11 + RTX 3090 D3D12 & WARP Verification (`094e948e99`) — GPU Verified + Rebase Needed Against `main` (`E0063`) Verified commit `094e948e99a48d1476ac8adb33c5ce24ac8cb68d` on Windows 11 (`x86_64-pc-windows-msvc`) with physical **NVIDIA GeForce RTX 3090** (Ampere, D3D12 driver `610.88`, native SM 6.6 mesh shaders enabled for direct hardware comparison) and **WARP** + `dxil.dll`. #### 1. Red -> Green Physical GPU & DXIL Verification - **Red (`main` `1bc055e6c2`)**: `shader_cache` `MeshOut` round-trip fails to compile (`E0422`/`E0609`/`E0560`: `MeshOut` and `HostShader::mesh_out` absent). - **Green (`094e948e99` standalone & merged onto `main` `1bc055e6c2` with the 2-field `Translated` update below)**: - `cargo test --locked -p leonida-shader --lib -- --nocapture --test-threads=4 mesh`: **`7/7` passed (`0.76s`)**: - `a_mesh_program_translates_as_compute_without_mesh_shaders`: `dxil.dll` validated both the lowered `cs_6_6` compute shader and the generated `mesh_vs` pass-through vertex shader. - `a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws`: **passed texel-for-texel against the native mesh pipeline on both physical RTX 3090 (`hardware: the mesh program drew as compute (mesh shaders there: true)`) and WARP (`warp: the mesh program drew as compute (mesh shaders there: true)`)**. - `cargo test --locked -p leonida-gpu --lib -- --nocapture --test-threads=4 shader_cache`: **`2/2` passed** (`MeshOut` cache round-trip and damage rejection). - `LEONIDA_MESH_COMPUTE=1 LEONIDA_D3D12_DEBUG=1 cargo test --locked -p leonida-gpu --features diagnostics --lib -- --nocapture --test-threads=4 pipeline::host::tests`: **`9/9` passed** on RTX 3090 (`0` D3D12 debug-layer errors) and **`8/8` applicable tests passed** on WARP (`LEONIDA_D3D12_WARP=1`). - `python -I scripts/check_no_game_data.py` (`0` issues) and `git diff --check` clean. #### 2. Blocking Rebase Note Against Current `main` (`aa918e5d9f`) Although Git merges `094e948e99` into `main` (`aa918e5d9f`) without textual conflicts, `leonida-gpu` fails to compile after the merge because `struct Translated` in `d3d12/crates/leonida-gpu/src/pipeline.rs` gained `stores_past_views` and `bound` on `main` since `c1ecf04edc`: ```text error[E0063]: missing fields `bound` and `stores_past_views` in initializer of `Translated` --> crates/leonida-gpu/src/pipeline.rs:224:35 ``` Adding `stores_past_views: false,` and `bound: Default::default(),` to the synthetic `vs` `Translated` literal in `Shader::mesh_fallback` (`d3d12/crates/leonida-gpu/src/pipeline.rs`) resolves the compile error cleanly and passes all tests above on `main`. #### 3. Non-Blocking Notes - **Host topology restoration (`d3d12/crates/leonida-gpu/src/draw.rs`)**: `mesh_as_compute` and `mesh_indirect_as_compute` call `l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST)` on the host command list without restoring `self.topology` afterwards (`if self.topology_set { self.set_topology(list, self.topology); }`, analogous to `self.mesh_scissor(list, false)`). If an earlier draw on the same command list bound a non-`TRIANGLELIST` topology (e.g. `TRIANGLESTRIP` or `LINELIST`) and a subsequent VS/PS draw after the mesh dispatch does not re-issue `IASetPrimitiveTopology`, it would inherit `TRIANGLELIST`. - **Visibility lint (`d3d12/crates/leonida-shader/src/emit/shader.rs:260`)**: `MeshOut::new` triggers `#[warn(private_interfaces)]` because `SigElement` is `pub(crate)` (`pub(crate) fn new` silences it). AI-assisted.
merzleckeier commented 2026-11-28 23:17:32 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-11-28T23:17:32Z.


Independent Wine/vkd3d-proton check on RTX 4070 SUPER (NVIDIA 620.73.04, CachyOS, Wine 11.22, vkd3d-proton 71cae091). I tested 094e948e9 merged with main adfb3821a. The unadjusted merge reproduces E0063 for the two missing Translated fields. With the two local initializers from the earlier review, native mesh and compute readbacks matched texel for texel for the plain, edge-flagged and culled triangles. The mesh, shader-cache and host-pipeline filters reported 7, 4 and 9 passing test entries respectively. The optional DXC-dependent cases skipped. DXVK returned the physical adapter for the WARP request, so the WARP-labelled pass is also hardware coverage.

I also reproduced the sink-slot finding at the stock 64 MiB capacity. The last usable slot (74,896) drew 256/256 texels. With only slot 74,897 populated, 74,897 instances drew zero texels, while 74,898 or 74,899 instances drew all 256. With the proposed IUGT → IUGE change the last usable slot still drew all 256 and all three sink-only draws stayed clear. Synthetic fixtures only. AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7247331486 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7247331486). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-11-28T23:17:32Z. --- Independent Wine/vkd3d-proton check on RTX 4070 SUPER (NVIDIA 620.73.04, CachyOS, Wine 11.22, vkd3d-proton `71cae091`). I tested `094e948e9` merged with main `adfb3821a`. The unadjusted merge reproduces `E0063` for the two missing `Translated` fields. With the two local initializers from the earlier review, native mesh and compute readbacks matched texel for texel for the plain, edge-flagged and culled triangles. The mesh, shader-cache and host-pipeline filters reported 7, 4 and 9 passing test entries respectively. The optional DXC-dependent cases skipped. DXVK returned the physical adapter for the WARP request, so the WARP-labelled pass is also hardware coverage. I also reproduced the [sink-slot finding](https://github.com/ProjectLeonida/mandy/pull/2580#discussion_r4728819038) at the stock 64 MiB capacity. The last usable slot (74,896) drew 256/256 texels. With only slot 74,897 populated, 74,897 instances drew zero texels, while 74,898 or 74,899 instances drew all 256. With the proposed `IUGT` → `IUGE` change the last usable slot still drew all 256 and all three sink-only draws stayed clear. Synthetic fixtures only. AI-assisted.
qhukz13 commented 2026-11-28 23:47:29 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by qhukz13 on 2026-11-28T23:47:29Z.


Rebased onto main a9e247cd6.

  • The E0063 the reviewers hit is fixed: the vertex half of a mesh program run as compute builds its Translated with the two fields main added (stores_past_views: false, bound).
  • draw.rs: main's is_depth_companion is kept beside mesh_buffer.

MEASURED on a GTX 1050 Ti (582.66), Windows 10, with Agility 1.614.1 for the test binary:

  • leonida-shader: 356/356 passed.
  • leonida-gpu: 516 passed; 3 WARP/device tests fail on main too.

Thanks @lixonik, @zmasi and @merzleckeier for the runs.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7247665537 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7247665537). Originally posted by [qhukz13](https://github.com/qhukz13) on 2026-11-28T23:47:29Z. --- Rebased onto `main` `a9e247cd6`. - The `E0063` the reviewers hit is fixed: the vertex half of a mesh program run as compute builds its `Translated` with the two fields `main` added (`stores_past_views: false`, `bound`). - `draw.rs`: `main`'s `is_depth_companion` is kept beside `mesh_buffer`. MEASURED on a GTX 1050 Ti (582.66), Windows 10, with Agility 1.614.1 for the test binary: - `leonida-shader`: 356/356 passed. - `leonida-gpu`: 516 passed; 3 WARP/device tests fail on `main` too. Thanks @lixonik, @zmasi and @merzleckeier for the runs. AI-assisted (Claude Code).
enlight3d commented 2026-11-29 00:56:48 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by enlight3d on 2026-11-29T00:56:48Z.


RUN of #2580 (native Windows, no game files), re-run at the new head

Heads: PR dc5818bb84 (2 commits, 656cfa15e + dc5818bb8; merge-base with main a9e247cd6, 71 commits behind), main 795e0904c2.
Machine: NVIDIA GeForce RTX 3090 24 GB (has mesh shaders), driver 621.40, Windows 11 Pro 10.0.26300, rustc 1.98.1.

Commands (in d3d12/, CARGO_TARGET_DIR set outside the repo):
cargo test -j 8 -p leonida-shader --lib mesh
cargo test -j 8 -p leonida-gpu --lib shader_cache
cargo test -j 8 -p leonida-shader --lib a_mesh_program -- --nocapture
cargo check -j 8 -p leonida-shader -p leonida-gpu --tests (on main + PR merged)

GREEN (PR head):

  • leonida-shader mesh: 7 passed, 0 failed (5 old + the 2 new: a_mesh_program_translates_as_compute_without_mesh_shaders, a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws).
  • The device test ran on the hardware adapter and on WARP, both with mesh shaders, so the texel-for-texel comparison of the compute fallback against the mesh pipeline was really exercised ("the mesh program drew as compute (mesh shaders there: true)" for both).
  • leonida-gpu shader_cache: 4 passed, 0 failed.
    Main (same filters): shader mesh 5 passed; gpu shader_cache 4 passed. Nothing failed, so nothing pre-existing to subtract.

RED:

  • Build failure by construction: TEST_MESH_COMPUTE, MeshOut and mesh_vs exist neither on main nor at the PR base, and the new tests use them.
  • Behavioural red 1 (tests and PR code kept, only host_mesh_compute() forced to false, i.e. mesh programs stay mesh): both new shader tests FAIL (translate test: panics with "no layout"; device test: unwrap on None). The 5 old tests still pass (5 passed, 2 failed).
  • Behavioural red 2 (shader cache encode() always writes "no mesh layout"): entries_round_trip_and_reject_damage and translations_come_back_from_the_cache FAIL (mesh_out: None vs Some(MeshOut ...)); the other 2 pass.
  • Worktree restored to the PR head after each red run (git status clean).

MERGE WITH CURRENT MAIN: git merge-tree reports no conflict, and the merged tree (main + PR, git merge --no-commit) now compiles: cargo check -p leonida-shader -p leonida-gpu --tests finishes with no error (warnings only). The E0063 seen at the previous head (094e948e9: missing fields bound and stores_past_views in a Translated initializer in leonida-gpu pipeline.rs) is gone; the new head sets stores_past_views there. On the merged tree: leonida-shader mesh 7 passed, leonida-gpu shader_cache 4 passed.

Not checked: the real fallback on a card without mesh shaders (Pascal), and the game.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7248458292 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7248458292). Originally posted by [enlight3d](https://github.com/enlight3d) on 2026-11-29T00:56:48Z. --- RUN of #2580 (native Windows, no game files), re-run at the new head Heads: PR dc5818bb8424d96b642ba07cd03a3251d529a147 (2 commits, 656cfa15e + dc5818bb8; merge-base with main a9e247cd6, 71 commits behind), main 795e0904c251c19bdec45423d111c8c0ac9c6cbe. Machine: NVIDIA GeForce RTX 3090 24 GB (has mesh shaders), driver 621.40, Windows 11 Pro 10.0.26300, rustc 1.98.1. Commands (in d3d12/, CARGO_TARGET_DIR set outside the repo): cargo test -j 8 -p leonida-shader --lib mesh cargo test -j 8 -p leonida-gpu --lib shader_cache cargo test -j 8 -p leonida-shader --lib a_mesh_program -- --nocapture cargo check -j 8 -p leonida-shader -p leonida-gpu --tests (on main + PR merged) GREEN (PR head): - leonida-shader mesh: 7 passed, 0 failed (5 old + the 2 new: a_mesh_program_translates_as_compute_without_mesh_shaders, a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws). - The device test ran on the hardware adapter and on WARP, both with mesh shaders, so the texel-for-texel comparison of the compute fallback against the mesh pipeline was really exercised ("the mesh program drew as compute (mesh shaders there: true)" for both). - leonida-gpu shader_cache: 4 passed, 0 failed. Main (same filters): shader mesh 5 passed; gpu shader_cache 4 passed. Nothing failed, so nothing pre-existing to subtract. RED: - Build failure by construction: TEST_MESH_COMPUTE, MeshOut and mesh_vs exist neither on main nor at the PR base, and the new tests use them. - Behavioural red 1 (tests and PR code kept, only host_mesh_compute() forced to false, i.e. mesh programs stay mesh): both new shader tests FAIL (translate test: panics with "no layout"; device test: unwrap on None). The 5 old tests still pass (5 passed, 2 failed). - Behavioural red 2 (shader cache encode() always writes "no mesh layout"): entries_round_trip_and_reject_damage and translations_come_back_from_the_cache FAIL (mesh_out: None vs Some(MeshOut ...)); the other 2 pass. - Worktree restored to the PR head after each red run (git status clean). MERGE WITH CURRENT MAIN: git merge-tree reports no conflict, and the merged tree (main + PR, git merge --no-commit) now compiles: cargo check -p leonida-shader -p leonida-gpu --tests finishes with no error (warnings only). The E0063 seen at the previous head (094e948e9: missing fields bound and stores_past_views in a Translated initializer in leonida-gpu pipeline.rs) is gone; the new head sets stores_past_views there. On the merged tree: leonida-shader mesh 7 passed, leonida-gpu shader_cache 4 passed. Not checked: the real fallback on a card without mesh shaders (Pascal), and the game.
timbot103 commented 2026-11-29 01:06:05 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by timbot103 on 2026-11-29T01:06:05Z.

Review: COMMENTED


Static audit of dc5818bb8 against 48bae6cad. Request changes.

  • d3d12/crates/leonida-gpu/src/draw.rs:5907 creates a native mesh signature before the compute branch. Select the compute signature first so tier-0 drivers can reach the fallback.
  • d3d12/crates/leonida-shader/src/emit/mesh_vs.rs:138 admits the first sink instance. Suppress group >= cap and avoid concurrent writes to the sink.
  • d3d12/crates/leonida-gpu/src/draw.rs:4707 and :4782 leave the host topology set to TRIANGLELIST. Restore the caller's topology after the fallback draw.
  • d3d12/crates/leonida-shader/src/emit/mesh_vs.rs:84 drops rasterizer-consumed layer and viewport outputs when the PS omits them. d3d12/crates/leonida-shader/src/emit/shader.rs:270 also builds the offsets before the signature is reordered. Keep rasterizer outputs and serialize each offset with its signature element.
  • d3d12/crates/leonida-gpu/src/pipeline/host.rs:658 can select the native path before the host is initialized, then cache a refusal on tier 0. Initialize the host before choosing the path.
  • d3d12/crates/leonida-gpu/src/draw.rs:4824 and :6024 only account for the graphics stages' stores. Account for mesh compute stores so subsequent indirect commands see fresh arguments.

Please add synthetic runtime coverage for the first overflow group, repeated direct and counted indirect dispatches, per-primitive outputs, and a following strip draw.

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6100839706 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#pullrequestreview-6100839706). Originally posted by [timbot103](https://github.com/timbot103) on 2026-11-29T01:06:05Z. **Review:** COMMENTED --- Static audit of `dc5818bb8` against `48bae6cad`. Request changes. - `d3d12/crates/leonida-gpu/src/draw.rs:5907` creates a native mesh signature before the compute branch. Select the compute signature first so tier-0 drivers can reach the fallback. - `d3d12/crates/leonida-shader/src/emit/mesh_vs.rs:138` admits the first sink instance. Suppress `group >= cap` and avoid concurrent writes to the sink. - `d3d12/crates/leonida-gpu/src/draw.rs:4707` and `:4782` leave the host topology set to `TRIANGLELIST`. Restore the caller's topology after the fallback draw. - `d3d12/crates/leonida-shader/src/emit/mesh_vs.rs:84` drops rasterizer-consumed layer and viewport outputs when the PS omits them. `d3d12/crates/leonida-shader/src/emit/shader.rs:270` also builds the offsets before the signature is reordered. Keep rasterizer outputs and serialize each offset with its signature element. - `d3d12/crates/leonida-gpu/src/pipeline/host.rs:658` can select the native path before the host is initialized, then cache a refusal on tier 0. Initialize the host before choosing the path. - `d3d12/crates/leonida-gpu/src/draw.rs:4824` and `:6024` only account for the graphics stages' stores. Account for mesh compute stores so subsequent indirect commands see fresh arguments. Please add synthetic runtime coverage for the first overflow group, repeated direct and counted indirect dispatches, per-primitive outputs, and a following strip draw. AI-assisted.
lixonik commented 2026-11-29 02:17:23 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-29T02:17:23Z.

Code review location: d3d12/crates/leonida-shader/src/emit/mesh_vs.rs; line 138

@@ -0,0 +1,206 @@
+//! The vertex shader that draws a mesh program run as compute on a host
+//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute
+//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices,
+//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`]
+//! in its [`MeshOut`] layout; the draw that follows is a triangle list of
+//! `3 * max_primitives` vertices and one instance a group, with this shader
+//! in front of the title's pixel shader, reading the same buffer as the root
+//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the
+//! header's arguments, which the groups wrote.)
+//!
+//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of
+//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own:
+//! it draws nothing. A primitive the program culled, or
+//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh
+//! path. Every corner is its own vertex here, so a per-primitive output is
+//! a vertex output with constant interpolation, the same at all three.
+//!
+//! The outputs are the mesh program's vertex outputs, register for
+//! register, and its per-primitive outputs in the registers the pixel
+//! shader reads them from (by semantic and index): a mesh pipeline's
+//! per-primitive outputs have their own signature, which a vertex shader
+//! has not.
+
+use super::bitcode::{Attr, Bin, Term, V};
+use super::container::SigElement;
+use super::shader::{MeshOut, Shader};
+use crate::ShaderError;
+use crate::dxbc::{Container, FourCC};
+
+/// The pass-through vertex shader (a DXIL container) for a mesh program
+/// translated as compute with `layout`, drawn with the translated pixel
+/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one.
+pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
+    let vertex = super::signature(&layout.osg1)?;
+    let primitive = super::signature(&layout.psg1)?;
+    let wanted = match ps {
+        Some(ps) => {
+            let c = Container::parse(ps)?;
+            match c.part(FourCC::ISG1) {
+                Some(part) => super::signature(part.data)?,
+                None => Vec::new(),
+            }
+        }
+        None => Vec::new(),
+    };
+    build(layout, vertex, &primitive, &wanted)
+}
+
+/// Where an output's value comes from: byte `at` of its vertex (`false`)
+/// or of its primitive past the indices (`true`).
+struct Source {
+    primitive: bool,
+    at: u32,
+}
+
+fn build(
+    layout: &MeshOut,
+    vertex: Vec<SigElement>,
+    primitive: &[SigElement],
+    ps_inputs: &[SigElement],
+) -> Result<Vec<u8>, ShaderError> {
+    let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
+    if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() {
+        return Err(unsupported("a mesh layout that does not match its signatures"));
+    }
+    if vertex.iter().any(|e| e.row.is_none()) {
+        return Err(unsupported("a mesh vertex output without a register"));
+    }
+    if layout.max_primitives == 0 {
+        return Err(unsupported("a mesh program without primitives"));
+    }
+    let mut outputs = Vec::new();
+    let mut sources = Vec::new();
+    for (e, &at) in vertex.iter().zip(&layout.vertex_at) {
+        outputs.push(SigElement {
+            usage: (1 << e.cols) - 1,
+            ..e.clone()
+        });
+        sources.push(Source { primitive: false, at });
+    }
+    // A per-primitive output goes where the pixel shader reads it; one the
+    // pixel shader does not read is not drawn with.
+    for (p, &at) in primitive.iter().zip(&layout.primitive_at) {
+        let Some(e) = ps_inputs
+            .iter()
+            .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some())
+        else {
+            continue;
+        };
+        let clash = outputs.iter().any(|o| {
+            o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols
+        });
+        if clash || e.cols < p.cols {
+            return Err(unsupported(
+                "a per-primitive output whose pixel shader register a vertex output takes",
+            ));
+        }
+        outputs.push(SigElement {
+            row: e.row,
+            col: e.col,
+            interp: 1,
+            usage: (1 << p.cols) - 1,
+            ..p.clone()
+        });
+        sources.push(Source { primitive: true, at });
+    }
+
+    let mut s = Shader::new(false);
+    let system = |name: &str, kind, row| SigElement {
+        name: name.into(),
+        index: 0,
+        kind,
+        comp: 5,
+        interp: 0,
+        row: Some(row),
+        col: 0,
+        cols: 1,
+        usage: 1,
+        half: false,
+    };
+    s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)];
+    s.outputs = outputs;
+    let b = s.entry;
+    let i32t = s.t.i32;
+    let k = |s: &mut Shader, v: u32| s.m.i32(v);
+
+    // (vertex id, instance id) -> primitive, corner, group.
+    let input = |s: &mut Shader, n: u32| {
+        let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)];
+        s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args)
+    };
+    let (id, group) = (input(&mut s, 0), input(&mut s, 1));
+    let three = k(&mut s, 3);
+    let prim = s.m.bin(b, Bin::UDiv, id, three);
+    let corner = s.m.bin(b, Bin::URem, id, three);
+    // A group past the cap wrote to the sink slot: it draws nothing.
+    let cap = k(&mut s, layout.groups_cap());
+    let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap);

Retested after the rebase at dc5818bb8424d96b642ba07cd03a3251d529a147, merged with main 02944d4ca1. The crate builds here, and the translation test passes with DXIL validator 1.9.2609. The sink-slot case still reproduces.

With synthetic triangle data and a 4 KiB scratch buffer, I drew four instances and populated one slot at a time. On RTX 5070 (610.88), Windows 10 22H2, Agility SDK 1.614.1, slot 2 lit 256/256 pixels and the sink at slot 3 also lit 256/256. Changing just IUGT to IUGE kept slot 2 at 256/256 and took the sink to 0/256. The plain, edge-flag, and culled comparisons with the native mesh pipeline passed with that local one-line change. WARP skipped for lack of SM 6.6 here.

AI-assisted. Codex (GPT-6).

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4729696044 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#discussion_r4729696044). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-29T02:17:23Z. **Code review location:** `d3d12/crates/leonida-shader/src/emit/mesh_vs.rs`; line 138 ~~~~diff @@ -0,0 +1,206 @@ +//! The vertex shader that draws a mesh program run as compute on a host +//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute +//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices, +//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`] +//! in its [`MeshOut`] layout; the draw that follows is a triangle list of +//! `3 * max_primitives` vertices and one instance a group, with this shader +//! in front of the title's pixel shader, reading the same buffer as the root +//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the +//! header's arguments, which the groups wrote.) +//! +//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of +//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own: +//! it draws nothing. A primitive the program culled, or +//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh +//! path. Every corner is its own vertex here, so a per-primitive output is +//! a vertex output with constant interpolation, the same at all three. +//! +//! The outputs are the mesh program's vertex outputs, register for +//! register, and its per-primitive outputs in the registers the pixel +//! shader reads them from (by semantic and index): a mesh pipeline's +//! per-primitive outputs have their own signature, which a vertex shader +//! has not. + +use super::bitcode::{Attr, Bin, Term, V}; +use super::container::SigElement; +use super::shader::{MeshOut, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The pass-through vertex shader (a DXIL container) for a mesh program +/// translated as compute with `layout`, drawn with the translated pixel +/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one. +pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> { + let vertex = super::signature(&layout.osg1)?; + let primitive = super::signature(&layout.psg1)?; + let wanted = match ps { + Some(ps) => { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + build(layout, vertex, &primitive, &wanted) +} + +/// Where an output's value comes from: byte `at` of its vertex (`false`) +/// or of its primitive past the indices (`true`). +struct Source { + primitive: bool, + at: u32, +} + +fn build( + layout: &MeshOut, + vertex: Vec<SigElement>, + primitive: &[SigElement], + ps_inputs: &[SigElement], +) -> Result<Vec<u8>, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() { + return Err(unsupported("a mesh layout that does not match its signatures")); + } + if vertex.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a mesh vertex output without a register")); + } + if layout.max_primitives == 0 { + return Err(unsupported("a mesh program without primitives")); + } + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source { primitive: false, at }); + } + // A per-primitive output goes where the pixel shader reads it; one the + // pixel shader does not read is not drawn with. + for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + let Some(e) = ps_inputs + .iter() + .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) + else { + continue; + }; + let clash = outputs.iter().any(|o| { + o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols + }); + if clash || e.cols < p.cols { + return Err(unsupported( + "a per-primitive output whose pixel shader register a vertex output takes", + )); + } + outputs.push(SigElement { + row: e.row, + col: e.col, + interp: 1, + usage: (1 << p.cols) - 1, + ..p.clone() + }); + sources.push(Source { primitive: true, at }); + } + + let mut s = Shader::new(false); + let system = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)]; + s.outputs = outputs; + let b = s.entry; + let i32t = s.t.i32; + let k = |s: &mut Shader, v: u32| s.m.i32(v); + + // (vertex id, instance id) -> primitive, corner, group. + let input = |s: &mut Shader, n: u32| { + let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)]; + s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args) + }; + let (id, group) = (input(&mut s, 0), input(&mut s, 1)); + let three = k(&mut s, 3); + let prim = s.m.bin(b, Bin::UDiv, id, three); + let corner = s.m.bin(b, Bin::URem, id, three); + // A group past the cap wrote to the sink slot: it draws nothing. + let cap = k(&mut s, layout.groups_cap()); + let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); ~~~~ --- Retested after the rebase at `dc5818bb8424d96b642ba07cd03a3251d529a147`, merged with `main` `02944d4ca1`. The crate builds here, and the translation test passes with DXIL validator 1.9.2609. The sink-slot case still reproduces. With synthetic triangle data and a 4 KiB scratch buffer, I drew four instances and populated one slot at a time. On RTX 5070 (610.88), Windows 10 22H2, Agility SDK 1.614.1, slot 2 lit 256/256 pixels and the sink at slot 3 also lit 256/256. Changing just `IUGT` to `IUGE` kept slot 2 at 256/256 and took the sink to 0/256. The plain, edge-flag, and culled comparisons with the native mesh pipeline passed with that local one-line change. WARP skipped for lack of SM 6.6 here. AI-assisted. Codex (GPT-6).
fiestorra commented 2026-11-29 17:38:54 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-11-29T17:38:54Z.


Mechanical note, no review: this branch conflicts with main (4364a4fa6) on a rebase, and the conflict is smaller than it sounds.

git merge-tree --write-tree origin/main refs/pull/2580/head reports 1 conflicted file(s):

  • d3d12/crates/leonida-shader/src/emit/mod.rs

main changed that file in three recent commits (0bc6e21a1, 804280d80, 0807f9cba). #2581 touches the same file, and the two branches merge with each other without conflict, so neither has to wait for the other - both just need a rebase onto main.

So a rebase is all it needs - the change itself may well be fine, I have not looked at its content, only at whether git can apply it.

Written with an AI assistant.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7259854950 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7259854950). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-11-29T17:38:54Z. --- Mechanical note, no review: this branch **conflicts with `main`** (`4364a4fa6`) on a rebase, and the conflict is smaller than it sounds. `git merge-tree --write-tree origin/main refs/pull/2580/head` reports **1** conflicted file(s): - `d3d12/crates/leonida-shader/src/emit/mod.rs` `main` changed that file in three recent commits (`0bc6e21a1`, `804280d80`, `0807f9cba`). **#2581** touches the same file, and the two branches **merge with each other without conflict**, so neither has to wait for the other - both just need a rebase onto `main`. So a rebase is all it needs - the change itself may well be fine, I have not looked at its content, only at whether git can apply it. Written with an AI assistant.
qhukz13 commented 2026-11-29 18:39:15 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by qhukz13 on 2026-11-29T18:39:15Z.


Thanks for the audit, @timbot103. All six points held up in the code and are fixed in bc0c72f50:

  • the fallback makes no mesh command signature;
  • an instance from groups_cap on (the sink) draws nothing, and the direct path draws at most cap instances;
  • the title's topology is set again after the fallback's triangle list;
  • MeshOut's OSG1/PSG1 keep elements in the order of their offsets (the test fails without it);
  • the host is made before a pipeline picks the path;
  • the mesh program's own stores count after the draw.

Also: 1b33fa2bb puts drew()'s doc comment back on drew(), and 1b6b223d3 makes MeshOut::new crate-private (the private_interfaces warning).

A per-primitive layer/viewport index is refused by mesh_vs for now: the translator does not export those yet (lower.rs refuses them), so there is nothing to carry until it does.

Runtime coverage (924b29417). What the fallback records around the pipelines the draw path binds (barriers, the direct or counted indirect dispatch, the indirect draw's header, the triangle list from the buffer, the title's topology again) is now one recorder, mesh_fallback::MeshRun, which draw.rs calls. mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip records it on a device the way a title does, in one list:

  1. a counted indirect run, count 1;
  2. a direct run of three groups;
  3. a run whose triangle is culled (the buffer still holds the previous run's triangles);
  4. a counted indirect run with a count of 0;
  5. the title's triangle strip.

Every texel must come out as the runs and the strip draw it. As a check, without the topology restore the strip draws one triangle (64 of 256 texels differ), and without the header's instance count reset the count-0 run draws the first run's groups again (100 differ). The first overflow group is the_mesh_sink_slot_draws_nothing.

Tested on GTX 1050 Ti 4 GB / NVIDIA 582.66 / Windows 10 (no mesh shaders):

  • leonida-shader --lib with the Agility SDK: 233 passed, 0 failed, including a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws and the_mesh_sink_slot_draws_nothing on the card;
  • the new leonida-gpu test passes on the card;
  • leonida-gpu --lib: 517 passed, 3 failed. The same 3 fail on the base without this PR on this card: a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is, views_are_made_beside_the_heap_and_copied_in, and depth_bounds_pipeline_loads_and_filters_draws (E_INVALIDARG).

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7260652418 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7260652418). Originally posted by [qhukz13](https://github.com/qhukz13) on 2026-11-29T18:39:15Z. --- Thanks for the audit, @timbot103. All six points held up in the code and are fixed in bc0c72f50: - the fallback makes no mesh command signature; - an instance from `groups_cap` on (the sink) draws nothing, and the direct path draws at most `cap` instances; - the title's topology is set again after the fallback's triangle list; - `MeshOut`'s OSG1/PSG1 keep elements in the order of their offsets (the test fails without it); - the host is made before a pipeline picks the path; - the mesh program's own stores count after the draw. Also: 1b33fa2bb puts `drew()`'s doc comment back on `drew()`, and 1b6b223d3 makes `MeshOut::new` crate-private (the `private_interfaces` warning). A per-primitive layer/viewport index is refused by `mesh_vs` for now: the translator does not export those yet (`lower.rs` refuses them), so there is nothing to carry until it does. **Runtime coverage (924b29417).** What the fallback records around the pipelines the draw path binds (barriers, the direct or counted indirect dispatch, the indirect draw's header, the triangle list from the buffer, the title's topology again) is now one recorder, `mesh_fallback::MeshRun`, which `draw.rs` calls. `mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip` records it on a device the way a title does, in one list: 1. a counted indirect run, count 1; 2. a direct run of three groups; 3. a run whose triangle is culled (the buffer still holds the previous run's triangles); 4. a counted indirect run with a count of 0; 5. the title's triangle strip. Every texel must come out as the runs and the strip draw it. As a check, without the topology restore the strip draws one triangle (64 of 256 texels differ), and without the header's instance count reset the count-0 run draws the first run's groups again (100 differ). The first overflow group is `the_mesh_sink_slot_draws_nothing`. Tested on GTX 1050 Ti 4 GB / NVIDIA 582.66 / Windows 10 (no mesh shaders): - leonida-shader `--lib` with the Agility SDK: 233 passed, 0 failed, including `a_mesh_program_run_as_compute_draws_what_the_mesh_pipeline_draws` and `the_mesh_sink_slot_draws_nothing` on the card; - the new leonida-gpu test passes on the card; - leonida-gpu `--lib`: 517 passed, 3 failed. The same 3 fail on the base without this PR on this card: `a_raw_view_is_moved_only_where_its_descriptor_says_where_it_is`, `views_are_made_beside_the_heap_and_copied_in`, and `depth_bounds_pipeline_loads_and_filters_draws` (E_INVALIDARG). AI-assisted (Claude Code).
qhukz13 commented 2026-11-29 20:03:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by qhukz13 on 2026-11-29T20:03:33Z.


Merged main (7c330c76d) in 58c333368, plus:

  • eab9c1e0f: the test programs from 924b29417 move to emit::test_programs (built on every platform), since a portable test needs them and emit::host is Windows-only. Before this the Linux test build did not resolve them.
  • 74ac98c64: the fallback's shaders take main's new Shader::mask / masked_twins.

The fallback now takes the per-dispatch mesh_test() mode as main's mesh paths do.

GTX 1050 Ti / 582.66 / Windows 10:

  • leonida-shader with Agility: 245 passed, 0 failed;
  • mesh_runs_in_one_list… passes;
  • leonida-gpu --lib: the same 3 failures as clean main on this card, over 3 runs each.

Linux: leonida-shader 226 passed. AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7261772461 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7261772461). Originally posted by [qhukz13](https://github.com/qhukz13) on 2026-11-29T20:03:33Z. --- Merged main (7c330c76d) in 58c333368, plus: - eab9c1e0f: the test programs from 924b29417 move to `emit::test_programs` (built on every platform), since a portable test needs them and `emit::host` is Windows-only. Before this the Linux test build did not resolve them. - 74ac98c64: the fallback's shaders take main's new `Shader::mask` / `masked_twins`. The fallback now takes the per-dispatch `mesh_test()` mode as main's mesh paths do. GTX 1050 Ti / 582.66 / Windows 10: - leonida-shader with Agility: 245 passed, 0 failed; - `mesh_runs_in_one_list…` passes; - leonida-gpu `--lib`: the same 3 failures as clean main on this card, over 3 runs each. Linux: leonida-shader 226 passed. AI-assisted (Claude Code).
lixonik commented 2026-11-29 21:06:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-11-29T21:06:14Z.

Code review location: d3d12/crates/leonida-shader/src/emit/mesh_vs.rs; line 138

@@ -0,0 +1,206 @@
+//! The vertex shader that draws a mesh program run as compute on a host
+//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute
+//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices,
+//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`]
+//! in its [`MeshOut`] layout; the draw that follows is a triangle list of
+//! `3 * max_primitives` vertices and one instance a group, with this shader
+//! in front of the title's pixel shader, reading the same buffer as the root
+//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the
+//! header's arguments, which the groups wrote.)
+//!
+//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of
+//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own:
+//! it draws nothing. A primitive the program culled, or
+//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh
+//! path. Every corner is its own vertex here, so a per-primitive output is
+//! a vertex output with constant interpolation, the same at all three.
+//!
+//! The outputs are the mesh program's vertex outputs, register for
+//! register, and its per-primitive outputs in the registers the pixel
+//! shader reads them from (by semantic and index): a mesh pipeline's
+//! per-primitive outputs have their own signature, which a vertex shader
+//! has not.
+
+use super::bitcode::{Attr, Bin, Term, V};
+use super::container::SigElement;
+use super::shader::{MeshOut, Shader};
+use crate::ShaderError;
+use crate::dxbc::{Container, FourCC};
+
+/// The pass-through vertex shader (a DXIL container) for a mesh program
+/// translated as compute with `layout`, drawn with the translated pixel
+/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one.
+pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> {
+    let vertex = super::signature(&layout.osg1)?;
+    let primitive = super::signature(&layout.psg1)?;
+    let wanted = match ps {
+        Some(ps) => {
+            let c = Container::parse(ps)?;
+            match c.part(FourCC::ISG1) {
+                Some(part) => super::signature(part.data)?,
+                None => Vec::new(),
+            }
+        }
+        None => Vec::new(),
+    };
+    build(layout, vertex, &primitive, &wanted)
+}
+
+/// Where an output's value comes from: byte `at` of its vertex (`false`)
+/// or of its primitive past the indices (`true`).
+struct Source {
+    primitive: bool,
+    at: u32,
+}
+
+fn build(
+    layout: &MeshOut,
+    vertex: Vec<SigElement>,
+    primitive: &[SigElement],
+    ps_inputs: &[SigElement],
+) -> Result<Vec<u8>, ShaderError> {
+    let unsupported = |what| ShaderError::Unsupported { offset: 0, what };
+    if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() {
+        return Err(unsupported("a mesh layout that does not match its signatures"));
+    }
+    if vertex.iter().any(|e| e.row.is_none()) {
+        return Err(unsupported("a mesh vertex output without a register"));
+    }
+    if layout.max_primitives == 0 {
+        return Err(unsupported("a mesh program without primitives"));
+    }
+    let mut outputs = Vec::new();
+    let mut sources = Vec::new();
+    for (e, &at) in vertex.iter().zip(&layout.vertex_at) {
+        outputs.push(SigElement {
+            usage: (1 << e.cols) - 1,
+            ..e.clone()
+        });
+        sources.push(Source { primitive: false, at });
+    }
+    // A per-primitive output goes where the pixel shader reads it; one the
+    // pixel shader does not read is not drawn with.
+    for (p, &at) in primitive.iter().zip(&layout.primitive_at) {
+        let Some(e) = ps_inputs
+            .iter()
+            .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some())
+        else {
+            continue;
+        };
+        let clash = outputs.iter().any(|o| {
+            o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols
+        });
+        if clash || e.cols < p.cols {
+            return Err(unsupported(
+                "a per-primitive output whose pixel shader register a vertex output takes",
+            ));
+        }
+        outputs.push(SigElement {
+            row: e.row,
+            col: e.col,
+            interp: 1,
+            usage: (1 << p.cols) - 1,
+            ..p.clone()
+        });
+        sources.push(Source { primitive: true, at });
+    }
+
+    let mut s = Shader::new(false);
+    let system = |name: &str, kind, row| SigElement {
+        name: name.into(),
+        index: 0,
+        kind,
+        comp: 5,
+        interp: 0,
+        row: Some(row),
+        col: 0,
+        cols: 1,
+        usage: 1,
+        half: false,
+    };
+    s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)];
+    s.outputs = outputs;
+    let b = s.entry;
+    let i32t = s.t.i32;
+    let k = |s: &mut Shader, v: u32| s.m.i32(v);
+
+    // (vertex id, instance id) -> primitive, corner, group.
+    let input = |s: &mut Shader, n: u32| {
+        let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)];
+        s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args)
+    };
+    let (id, group) = (input(&mut s, 0), input(&mut s, 1));
+    let three = k(&mut s, 3);
+    let prim = s.m.bin(b, Bin::UDiv, id, three);
+    let corner = s.m.bin(b, Bin::URem, id, three);
+    // A group past the cap wrote to the sink slot: it draws nothing.
+    let cap = k(&mut s, layout.groups_cap());
+    let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap);

Retested the sink fix at 74ac98c64 on native Windows 10 22H2, RTX 5070 (610.88), with Agility SDK 1.614.1 and DXIL validator 1.9.2609. The committed sink fixture ran on hardware: slot 0 lit 256/256 pixels and slot groups_cap() lit 0/256. The compute and native mesh draw comparison also passed. I used local Agility loader exports for the test binary and made the sink fixture require a hardware device. The optional WARP and external shader-compiler cases skipped.

This resolves my sink-slot finding. AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:review-comment:4733175622 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#discussion_r4733175622). Originally posted by [lixonik](https://github.com/lixonik) on 2026-11-29T21:06:14Z. **Code review location:** `d3d12/crates/leonida-shader/src/emit/mesh_vs.rs`; line 138 ~~~~diff @@ -0,0 +1,206 @@ +//! The vertex shader that draws a mesh program run as compute on a host +//! without mesh shaders (`D3D12-MESH-COMPUTE-FALLBACK`). The compute +//! variant ([`super::set_host_mesh_shaders`]) writes each group's vertices, +//! primitive indices and per-primitive outputs to [`super::SLOT_MESH_OUT`] +//! in its [`MeshOut`] layout; the draw that follows is a triangle list of +//! `3 * max_primitives` vertices and one instance a group, with this shader +//! in front of the title's pixel shader, reading the same buffer as the root +//! SRV [`super::SLOT_MESH_IN`]. (An indirect dispatch draws with the +//! header's arguments, which the groups wrote.) +//! +//! Vertex `id` of instance `g` is corner `id % 3` of primitive `id / 3` of +//! group `g`. A group past [`MeshOut::groups_cap`] had no slot of its own: +//! it draws nothing. A primitive the program culled, or +//! never wrote, has indices 0, 0, 0: a triangle of no area, as on the mesh +//! path. Every corner is its own vertex here, so a per-primitive output is +//! a vertex output with constant interpolation, the same at all three. +//! +//! The outputs are the mesh program's vertex outputs, register for +//! register, and its per-primitive outputs in the registers the pixel +//! shader reads them from (by semantic and index): a mesh pipeline's +//! per-primitive outputs have their own signature, which a vertex shader +//! has not. + +use super::bitcode::{Attr, Bin, Term, V}; +use super::container::SigElement; +use super::shader::{MeshOut, Shader}; +use crate::ShaderError; +use crate::dxbc::{Container, FourCC}; + +/// The pass-through vertex shader (a DXIL container) for a mesh program +/// translated as compute with `layout`, drawn with the translated pixel +/// shader `ps` (its [`super::HostShader::dxil`]) if the pipeline has one. +pub fn mesh_vs(layout: &MeshOut, ps: Option<&[u8]>) -> Result<Vec<u8>, ShaderError> { + let vertex = super::signature(&layout.osg1)?; + let primitive = super::signature(&layout.psg1)?; + let wanted = match ps { + Some(ps) => { + let c = Container::parse(ps)?; + match c.part(FourCC::ISG1) { + Some(part) => super::signature(part.data)?, + None => Vec::new(), + } + } + None => Vec::new(), + }; + build(layout, vertex, &primitive, &wanted) +} + +/// Where an output's value comes from: byte `at` of its vertex (`false`) +/// or of its primitive past the indices (`true`). +struct Source { + primitive: bool, + at: u32, +} + +fn build( + layout: &MeshOut, + vertex: Vec<SigElement>, + primitive: &[SigElement], + ps_inputs: &[SigElement], +) -> Result<Vec<u8>, ShaderError> { + let unsupported = |what| ShaderError::Unsupported { offset: 0, what }; + if vertex.len() != layout.vertex_at.len() || primitive.len() != layout.primitive_at.len() { + return Err(unsupported("a mesh layout that does not match its signatures")); + } + if vertex.iter().any(|e| e.row.is_none()) { + return Err(unsupported("a mesh vertex output without a register")); + } + if layout.max_primitives == 0 { + return Err(unsupported("a mesh program without primitives")); + } + let mut outputs = Vec::new(); + let mut sources = Vec::new(); + for (e, &at) in vertex.iter().zip(&layout.vertex_at) { + outputs.push(SigElement { + usage: (1 << e.cols) - 1, + ..e.clone() + }); + sources.push(Source { primitive: false, at }); + } + // A per-primitive output goes where the pixel shader reads it; one the + // pixel shader does not read is not drawn with. + for (p, &at) in primitive.iter().zip(&layout.primitive_at) { + let Some(e) = ps_inputs + .iter() + .find(|e| e.name.eq_ignore_ascii_case(&p.name) && e.index == p.index && e.row.is_some()) + else { + continue; + }; + let clash = outputs.iter().any(|o| { + o.row == e.row && o.col < e.col + p.cols && e.col < o.col + o.cols + }); + if clash || e.cols < p.cols { + return Err(unsupported( + "a per-primitive output whose pixel shader register a vertex output takes", + )); + } + outputs.push(SigElement { + row: e.row, + col: e.col, + interp: 1, + usage: (1 << p.cols) - 1, + ..p.clone() + }); + sources.push(Source { primitive: true, at }); + } + + let mut s = Shader::new(false); + let system = |name: &str, kind, row| SigElement { + name: name.into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 1, + half: false, + }; + s.inputs = vec![system("SV_VertexID", 1, 0), system("SV_InstanceID", 2, 1)]; + s.outputs = outputs; + let b = s.entry; + let i32t = s.t.i32; + let k = |s: &mut Shader, v: u32| s.m.i32(v); + + // (vertex id, instance id) -> primitive, corner, group. + let input = |s: &mut Shader, n: u32| { + let args = [s.m.i32(n), s.m.i32(0), s.m.i8(0), s.m.undef(i32t)]; + s.op(b, "loadInput.i32", Attr::ReadNone, i32t, 4, &args) + }; + let (id, group) = (input(&mut s, 0), input(&mut s, 1)); + let three = k(&mut s, 3); + let prim = s.m.bin(b, Bin::UDiv, id, three); + let corner = s.m.bin(b, Bin::URem, id, three); + // A group past the cap wrote to the sink slot: it draws nothing. + let cap = k(&mut s, layout.groups_cap()); + let past = s.m.cmp(b, super::bitcode::pred::IUGT, group, cap); ~~~~ --- Retested the sink fix at `74ac98c64` on native Windows 10 22H2, RTX 5070 (610.88), with Agility SDK 1.614.1 and DXIL validator 1.9.2609. The committed sink fixture ran on hardware: slot 0 lit 256/256 pixels and slot `groups_cap()` lit 0/256. The compute and native mesh draw comparison also passed. I used local Agility loader exports for the test binary and made the sink fixture require a hardware device. The optional WARP and external shader-compiler cases skipped. This resolves my sink-slot finding. AI-assisted.
OreoFR commented 2026-11-29 21:43:07 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-29T21:43:07Z.


Partial check by OreoFR on macOS 27.2.1 (26B131), Apple M5, Rust 1.98.1 (d3d12/rust-toolchain.toml), main 060c47160 (merges cleanly; does not force a rebase of #2566 at eade9562c), PR head 74ac98c64

  • leonida-gpu does not build on macOS, already on main (Windows-only code not isolated: queue.rs:1417/1446, list.rs:2556/2562 use #[cfg(windows)] modules from lib.rs:53/126, resource.rs:712), so its tests (incl. GPU tests) are not covered here. In-game behaviour is not covered either.
  • leonida-shader (cargo test -p leonida-shader --locked): the new tests live in emit/mod.rs with the code, so red = main where they do not exist: main 224 passed / 2 ignored → merge 226 passed / 2 ignored, 0 failed. New: emit::tests::a_mesh_program_translates_as_compute_without_mesh_shaders, emit::tests::mesh_out_parts_keep_their_elements_beside_their_offsets (MEASURED n=3, alone).
  • Cross-check cargo check --target x86_64-pc-windows-msvc --features host --tests: 0 errors. Clippy -D warnings: nothing new on macOS; on the Windows target 2 new unused imports in emit/mod.rs tests (super::bitcode::Attr l.1768, super::shader::Shader l.1919) — main already fails -D warnings there (6 lints).
  • Reviews: timbot103's requests are addressed by bc0c72f50; lixonik retested 74ac98c64 on an RTX 5070. No game data in the diff.

Verdict: leonida-shader part green (no red possible); leonida-gpu not buildable on macOS — needs a Windows/GPU verifier.

AI-assisted: Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7263095507 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7263095507). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-29T21:43:07Z. --- Partial check by OreoFR on macOS 27.2.1 (26B131), Apple M5, Rust 1.98.1 (d3d12/rust-toolchain.toml), main 060c47160 (merges cleanly; does not force a rebase of #2566 at eade9562c), PR head 74ac98c64 - **leonida-gpu does not build on macOS, already on main** (Windows-only code not isolated: `queue.rs:1417/1446`, `list.rs:2556/2562` use `#[cfg(windows)]` modules from `lib.rs:53/126`, `resource.rs:712`), so its tests (incl. GPU tests) are **not covered** here. In-game behaviour is not covered either. - **leonida-shader** (`cargo test -p leonida-shader --locked`): the new tests live in `emit/mod.rs` with the code, so red = main where they do not exist: main 224 passed / 2 ignored → merge **226 passed** / 2 ignored, 0 failed. New: `emit::tests::a_mesh_program_translates_as_compute_without_mesh_shaders`, `emit::tests::mesh_out_parts_keep_their_elements_beside_their_offsets` (MEASURED n=3, alone). - Cross-check `cargo check --target x86_64-pc-windows-msvc --features host --tests`: 0 errors. Clippy `-D warnings`: nothing new on macOS; on the Windows target 2 new unused imports in `emit/mod.rs` tests (`super::bitcode::Attr` l.1768, `super::shader::Shader` l.1919) — main already fails `-D warnings` there (6 lints). - Reviews: timbot103's requests are addressed by bc0c72f50; lixonik retested 74ac98c64 on an RTX 5070. No game data in the diff. **Verdict: leonida-shader part green (no red possible); leonida-gpu not buildable on macOS — needs a Windows/GPU verifier.** AI-assisted: Claude Code
OreoFR commented 2026-11-29 22:58:14 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-29T22:58:14Z.


Verified by OreoFR (Windows part: leonida-gpu, plus leonida-shader's Windows-only tests; oreofr-mac covered leonida-shader on macOS)

PR head 74ac98c64 merged with git merge --no-ff onto main 060c47160, no conflict. Windows 11 Pro 10.0.26300, RTX 4070 Laptop 8 GB (native mesh shaders), NVIDIA 621.40, Rust 1.98.1. The GPU is used by the D3D12 host tests.

  • cargo test -p leonida-gpu --locked: 550 passed / 0 failed / 47 ignored (main 549/0/47). The new GPU test mesh_fallback::tests::mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip runs and passes on the 4070.
  • cargo test -p leonida-shader --locked on Windows (where the emit::host D3D12 tests also run): 372 passed / 0 failed / 4 ignored (main 368/0/4).
  • Red: NO RED possible. The leonida-gpu test drives mesh_fallback, a module the PR adds, so without the change it does not compile. The leonida-shader tests are inline in the modules they test, as noted for macOS.
  • Clippy (--all-targets, leonida-gpu): no new lint in the files the PR touches.
  • #2566 (eade9562c) rebase needed after this: no (git merge-tree is clean).

Verdict: NO RED (green on Windows, no failing test possible without the change).

This verification was AI-assisted (Claude Code, oreofr-agent).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7264090554 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7264090554). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-29T22:58:14Z. --- **Verified by OreoFR** (Windows part: leonida-gpu, plus leonida-shader's Windows-only tests; oreofr-mac covered leonida-shader on macOS) PR head `74ac98c64` merged with `git merge --no-ff` onto main `060c47160`, no conflict. Windows 11 Pro 10.0.26300, RTX 4070 Laptop 8 GB (native mesh shaders), NVIDIA 621.40, Rust 1.98.1. The GPU is used by the D3D12 host tests. - `cargo test -p leonida-gpu --locked`: **550 passed / 0 failed / 47 ignored** (main 549/0/47). The new GPU test `mesh_fallback::tests::mesh_runs_in_one_list_draw_their_own_groups_and_the_strip_after_them_its_strip` runs and passes on the 4070. - `cargo test -p leonida-shader --locked` on Windows (where the `emit::host` D3D12 tests also run): **372 passed / 0 failed / 4 ignored** (main 368/0/4). - Red: **NO RED possible**. The leonida-gpu test drives `mesh_fallback`, a module the PR adds, so without the change it does not compile. The leonida-shader tests are inline in the modules they test, as noted for macOS. - Clippy (`--all-targets`, leonida-gpu): no new lint in the files the PR touches. - #2566 (`eade9562c`) rebase needed after this: **no** (`git merge-tree` is clean). Verdict: **NO RED** (green on Windows, no failing test possible without the change). This verification was AI-assisted (Claude Code, oreofr-agent).
MoonEyes commented 2026-12-02 12:47:20 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T12:47:20Z.


For information: this pull request is carried in #3128, which merges your head 74ac98c64 (your commits are kept) into current main and resolves the conflicts in mod.rs, shader.rs, lower.rs, shader_cache.rs and pipeline/host.rs, keeping both sides. If you rebase this one yourself, say so and #3128 can be closed.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7345881538 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7345881538). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T12:47:20Z. --- For information: this pull request is carried in #3128, which merges your head `74ac98c64` (your commits are kept) into current `main` and resolves the conflicts in mod.rs, shader.rs, lower.rs, shader_cache.rs and pipeline/host.rs, keeping both sides. If you rebase this one yourself, say so and #3128 can be closed. AI-assisted (Claude Code).
MoonEyes commented 2026-12-02 18:29:09 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:29:09Z.


Verification triage of #2580

Head 74ac98c64: the PR conflicts with main (dirty), and the work is carried by MoonEyes' #3128. Verdict: superseded by #3128.

AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354665322 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7354665322). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:29:09Z. --- **Verification triage of #2580** Head `74ac98c64`: the PR conflicts with `main` (`dirty`), and the work is carried by MoonEyes' #3128. **Verdict: superseded by #3128.** AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
MoonEyes commented 2026-12-03 18:02:22 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T18:02:22Z.


Thanks for the work on this. This pull request has a merge conflict with the current main and has had no new commit, comment or review for more than 5 hours, so I am closing it to keep the list of open pull requests manageable. This is not a judgement of the change. Whenever you like, merge the latest main into your branch, resolve the conflict, and reopen it (or open a new pull request that links this one). Please re-run the relevant tests on the new head; a reviewer will look at it when time allows, with no guarantee of timing or outcome.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7387497524 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2580#issuecomment-7387497524). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T18:02:22Z. --- Thanks for the work on this. This pull request has a merge conflict with the current `main` and has had no new commit, comment or review for more than 5 hours, so I am closing it to keep the list of open pull requests manageable. This is not a judgement of the change. Whenever you like, merge the latest `main` into your branch, resolve the conflict, and reopen it (or open a new pull request that links this one). Please re-run the relevant tests on the new head; a reviewer will look at it when time allows, with no guarantee of timing or outcome. --- _Generated by [Claude Code](https://claude.ai/code)_

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2580
No description provided.