Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 37 additions & 3 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2453,6 +2453,23 @@ impl Em {

// ---------------------------------------------------------------- images (MIMG)

/// SM 6.6 has no comparison sample with gradients. For each pixel in a quad, build a
/// footprint centered at its coordinate and let SampleCmp do its usual filtering.
/// Evaluate all four samples before selecting so the texture derivatives see the whole quad.
fn sample_cmp_grad(&mut self, t: &str, ty: &str, coord: &str, dx: &str, dy: &str, args: &str) -> String {
self.line(&format!("int2 {t}_xy = int2(xi.xcl_pos.x > QuadReadAcrossX(xi.xcl_pos.x), xi.xcl_pos.y > QuadReadAcrossY(xi.xcl_pos.y));"));
self.line(&format!("float4 {t}_values; [unroll] for (uint {t}_q = 0; {t}_q < 4; ++{t}_q) {{"));
self.line(&format!(" int2 {t}_delta = {t}_xy - int2({t}_q & 1u, {t}_q >> 1);"));
self.line(&format!(" {ty} {t}_p = QuadReadLaneAt({coord}, {t}_q);"));
self.line(&format!(" {ty} {t}_dx = QuadReadLaneAt({dx}, {t}_q), {t}_dy = QuadReadLaneAt({dy}, {t}_q);"));
// Keep the coordinate on each stationary axis even for a nonfinite gradient (0 * inf is NaN).
self.line(&format!(" {t}_p = {t}_delta.x == 0 ? {t}_p : {t}_p + {t}_delta.x * {t}_dx;"));
self.line(&format!(" {t}_p = {t}_delta.y == 0 ? {t}_p : {t}_p + {t}_delta.y * {t}_dy;"));
self.line(&format!(" {t}_values[{t}_q] = {t}_T.SampleCmp({t}_S, {args});"));
self.line("}");
format!("{t}_values[{t}_xy.x + 2 * {t}_xy.y].xxxx")
}

/// MIMG → SM 6.6 dynamic resources. XCL image descriptors (T#, 8 dwords) keep the GFX10
/// layout, but BASE_ADDRESS (word 0) holds the index of the SRV in the CBV/SRV/UAV heap
/// (UAV at +1); FORMAT (word 1 [28:20]) selects the typed view (float/uint/sint).
Expand Down Expand Up @@ -2718,8 +2735,10 @@ impl Em {
}
let samp = if has_c { "SamplerComparisonState" } else { "SamplerState" };
let gather = base.starts_with("gather4");
let implicit_lod = ps && !gather && !has_lz && grads.is_none() && lod.is_none();
let idx = if implicit_lod {
// Implicit derivatives, and a comparison with gradients (`sample_cmp_grad`), need every
// lane of the quad, including the helper lanes that EXEC leaves out without s_wqm.
let whole_quad = ps && !gather && !has_lz && lod.is_none() && (grads.is_none() || has_c);
let idx = if whole_quad {
self.line(&format!("uint {t}_tw0 = select({t}_ok, {tw0}, 0u);"));
format!("{t}_tw0")
} else {
Expand Down Expand Up @@ -2755,6 +2774,21 @@ impl Em {
None => l,
};
match (&cmp, &grads, &lod, &bias) {
(Some(z), Some((dx, dy)), _, _) if ps => {
let ty = ["float", "float2", "float3"][dx.len() - 1];
let vector = |v: &[String]| if v.len() == 1 { v[0].clone() } else { format!("{ty}({})", v.join(", ")) };
// Array layers have no derivatives. Cube gradients are in face space:
// project the footprint back to directions on the selected pixel's face.
let location = match dim {
3 => {
let face = format!("QuadReadLaneAt({}, {t}_q)", coords[2]);
format!("float4(cube_dir({t}_p.x, {t}_p.y, {face}), cube_slice({face}))")
}
4 | 5 => format!("float{}({t}_p, round({}))", dx.len() + 1, coords[dx.len()]),
_ => format!("{t}_p"),
};
self.sample_cmp_grad(&t, ty, &vector(&coords[..dx.len()]), &vector(dx), &vector(dy), &tail(format!("{location}, {z}")))
}
(Some(z), _, _, _) if has_lz || !ps => format!("float4({t}_T.SampleCmpLevelZero({t}_S, {coord}, {z}).xxxx)"),
(Some(z), _, _, _) => format!("float4({t}_T.SampleCmp({t}_S, {}).xxxx)", tail(format!("{coord}, {z}"))),
// cube maps: RDNA takes face-space 2D gradients, HLSL wants direction-space 3D
Expand Down Expand Up @@ -2807,7 +2841,7 @@ impl Em {
_ => format!("{t}_T.Sample({t}_S, {})", tail(coord.clone())),
}
};
if implicit_lod {
if whole_quad {
self.line(&format!("uint4 {t}_r = ({t}_ok ? asuint({call}) : uint4(0u, 0u, 0u, 0u));"));
} else {
self.line(&format!("{t}_r = asuint({call}); }}"));
Expand Down
23 changes: 15 additions & 8 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,9 @@ fn draw_gs_views(
pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?;
let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] };
draw_indexed_on(dev, &pso, &rs, vertices, stride, indices, &[draw], mem, textures, samplers, size, clear)
// the GPU lock is held: submit on its queue rather than creating one per draw (#350)
gpu.value += 1;
draw_indexed_on(dev, &gpu.queue, &gpu.fence, gpu.value, &pso, &rs, vertices, stride, indices, &[draw], mem, textures, samplers, size, clear)
}
}

Expand Down Expand Up @@ -1083,13 +1085,22 @@ pub fn draw_on_multi(
size: u32,
clear: [f32; 4],
) -> Result<Vec<[f32; 4]>, String> {
draw_indexed_on(dev, pso, rs, vertices, stride, &[], draws, mem, textures, samplers, size, clear)
unsafe {
let queue: ID3D12CommandQueue =
dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;
draw_indexed_on(dev, &queue, &fence, 1, pso, rs, vertices, stride, &[], draws, mem, textures, samplers, size, clear)
}
}

/// `draw_on_multi`, the draws indexed when there are `indices` (one index buffer for all).
/// `draw_on_multi`, the draws indexed when there are `indices` (one index buffer for all),
/// submitted on `queue` and waited for with `fence` reaching `value`.
#[allow(clippy::too_many_arguments)]
fn draw_indexed_on(
dev: &ID3D12Device,
queue: &ID3D12CommandQueue,
fence: &ID3D12Fence,
value: u64,
pso: &ID3D12PipelineState,
rs: &ID3D12RootSignature,
vertices: &[f32],
Expand All @@ -1103,10 +1114,6 @@ fn draw_indexed_on(
clear: [f32; 4],
) -> Result<Vec<[f32; 4]>, String> {
unsafe {
let queue: ID3D12CommandQueue =
dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?;

let tex = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: size as u64,
Expand Down Expand Up @@ -1223,7 +1230,7 @@ fn draw_indexed_on(
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
list.Close().map_err(e)?;
queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
wait_for_submission(dev, &queue, &fence, 1, "draw")?;
wait_for_submission(dev, queue, fence, value, "draw")?;
let mut p = std::ptr::null_mut();
readback.Map(0, None, Some(&mut p)).map_err(e)?;
let pitch = layout_fp.Footprint.RowPitch as usize;
Expand Down
97 changes: 97 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2288,6 +2288,51 @@ fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> V
draw_console_views(vs, ps, tris_px, &[], &[], &[])
}

/// The first draw has matching screen/explicit gradients. The others request coarser and
/// finer mips than the screen footprint, once with just dV/dY setting the coarser mip.
#[test]
fn gpu_ps_compare_mip_gradients() {
if !gpu_ready() {
return;
}
let mut failures = Vec::new();
// screen footprint, dU/dX, dV/dY, minimum LOD, expected mip. In the final case
// dU/dX grows across the quad: column zero selects mip 0, its neighbor selects mip 1.
for (op, scale, dx, dy, min_lod, mip, slope) in [
("IMAGE_SAMPLE_C_D", 0.125f32, 0.125f32, 0.125f32, 0.0f32, 0, 0.0f32),
("IMAGE_SAMPLE_C_D", 0.125, 0.0, 0.25, 0.0, 1, 0.0),
("IMAGE_SAMPLE_C_D_CL", 0.25, 0.125, 0.125, 0.0, 0, 0.0),
// Pin the mip while checking that an infinite gradient cannot move the sampling pixel.
("IMAGE_SAMPLE_C_D_CL", 0.125, f32::INFINITY, 0.125, 1.0, 1, 0.0),
("IMAGE_SAMPLE_C_D_CL", 0.125, 0.125, f32::NEG_INFINITY, 1.0, 1, 0.0),
("IMAGE_SAMPLE_C_D_CL", 0.125, f32::NAN, 0.125, 1.0, 1, 0.0),
("IMAGE_SAMPLE_C_CD_O", 0.125, 0.25, 0.0, 0.0, 1, 0.0),
("IMAGE_SAMPLE_C_CD_CL_O", 0.125, 0.125, 0.125, 1.0, 1, 0.0),
("IMAGE_SAMPLE_C_D", 0.125, 0.10, 0.0, 0.0, 0, 0.0625),
] {
let ps = prog(&[
("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 240)], None), // compare 0.5
("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 255)], Some(dx.to_bits())),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 128)], None),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", 255)], Some(dy.to_bits())),
("V_MUL_F32", "ENC_VOP2", &[("VDST", 13), ("SRC0", 255), ("VSRC1", 2)], Some(scale.to_bits())),
("V_MUL_F32", "ENC_VOP2", &[("VDST", 14), ("SRC0", 255), ("VSRC1", 3)], Some(scale.to_bits())),
("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), // zero texel offset for _O
("V_MOV_B32", "ENC_VOP1", &[("VDST", 15), ("SRC0", 255)], Some(min_lod.to_bits())),
("V_MUL_F32", "ENC_VOP2", &[("VDST", 16), ("SRC0", 255), ("VSRC1", 2)], Some(slope.to_bits())),
("V_ADD_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V + 16), ("VSRC1", 9)], None),
(op, "ENC_MIMG", &[("VDATA", 20), ("VADDR", if op.ends_with("_O") { 7 } else { 8 }), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 1), ("DIM", 1)], None),
("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 1), ("VSRC0", 20), ("DONE", 1), ("VM", 1)], None),
]);
let want = |x| if slope == 0.0 { mip } else { u32::from(x > 0) };
if let Err(error) = check_ps_depth_mip(&ps, scale, want) {
failures.push(format!("{op}, scale {scale}, slope {slope}: {error}"));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}

/// `draw_console` with initial SGPRs and textures / samplers (see `runner::ViewTexture`).
fn draw_console_views(
vs: Option<&[u8]>,
Expand Down Expand Up @@ -2326,6 +2371,58 @@ fn draw_console_views(
runner::draw_views(&vsb, &psb, &layout, &verts, 24, sgprs, &[], textures, samplers, 16, [-1.0; 4]).unwrap()
}

/// Both depth mips contain a checkerboard, in opposite phases. Check the comparison result at
/// each pixel so that selecting a neighbor's coordinates is distinguishable from selecting its mip.
fn check_ps_depth_mip(ps: &[u8], coord_scale: f32, mip_at: impl Fn(usize) -> u32) -> Result<(), String> {
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_TYPELESS, DXGI_SAMPLE_DESC};
let mut data = Vec::new();
for level in 0..2 {
let size = 8 >> level;
for y in 0..size {
for x in 0..size {
let depth = if (x + y + level) % 2 == 0 { 0.25f32 } else { 0.75f32 };
data.extend_from_slice(&depth.to_le_bytes());
}
}
}
let res = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 8, Height: 8, DepthOrArraySize: 1, MipLevels: 2,
Format: DXGI_FORMAT_R32_TYPELESS, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, ..Default::default()
};
let mut srv = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default()
};
srv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 2, ..Default::default() };
let tex = runner::ViewTexture { res, srv, data, row_bytes: 8 * 4 };
// Clamp U/V/W, LESS_EQUAL, point min/mag/mip, LOD range 0..15.99.
let sampler = [2 | 2 << 3 | 2 << 6 | 3 << 12, 0xFFF << 12, 1 << 26, 0];
let mut sgprs = [0; 32];
sgprs[16..24].copy_from_slice(&tsharp(0, 77, 9));
sgprs[24..28].copy_from_slice(&sampler);
let samplers = [crate::gpu::desc::sampler_d3d12(&sampler, true)];
// The second triangle cuts through 2x2 quads. Its diagonal is 4*x + 3*y = 48;
// no pixel center lies exactly on it. Uncovered pixels must retain the clear value.
for (width, height) in [(32.0, 32.0), (12.0, 16.0)] {
let tri = [[0.0, 0.0], [0.0, height], [width, 0.0]];
let pixels = draw_console_views(None, Some(ps), &tri, &sgprs, std::slice::from_ref(&tex), &samplers);
for (i, pixel) in pixels.iter().enumerate() {
let (x, y) = (i % 16, i / 16);
let mip = mip_at(x);
let size = 8u32 >> mip;
let texel = |p: usize| (((p as f32 + 0.5) * coord_scale * size as f32) as u32).min(size - 1);
let covered = (x as f32 + 0.5) * height + (y as f32 + 0.5) * width < width * height;
let expected = if covered { ((texel(x) + texel(y) + mip) % 2) as f32 } else { -1.0 };
if pixel[0] != expected {
return Err(format!("{width}x{height} triangle, pixel ({x},{y}): {} instead of {expected} at mip {mip}", pixel[0]));
}
}
}
Ok(())
}

/// `image_sample_o` in a pixel shader, implicit LOD between two mips (trilinear): the console
/// moves each mip's texel coordinate by the offset in that mip's texels. A 4-level texture
/// (8², 4², 2², 1²; level k texel x holds 100·k + x), point min / mag, linear mip, clamp;
Expand Down
Loading