Skip to content
Merged
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
95 changes: 69 additions & 26 deletions crates/xcl/src/gpu/recomp/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,23 @@ fn dpp16_src(ctrl: u64) -> Option<String> {
/// The lane `lane` of a 32-lane half reads with `ds_swizzle_b32` (the RDNA ISA's DS_SWIZZLE_B32):
/// offset ≥ 0xE000 FFT, ≥ 0xC000 rotate, bit 15 quad permute, otherwise the and/or/xor bit
/// mode (xor = offset[14:10], so 0x401F swaps the 16-lane halves).
/// MIMG sample coordinates per DIM as HLSL takes them (array layer rounded); empty for cubes.
fn sample_coord(dim: u64, c: &[String]) -> String {
match dim {
0 => c[0].clone(),
1 => format!("float2({}, {})", c[0], c[1]),
2 => format!("float3({}, {}, {})", c[0], c[1], c[2]),
4 => format!("float2({}, round({}))", c[0], c[1]),
5 => format!("float3({}, {}, round({}))", c[0], c[1], c[2]),
_ => String::new(),
}
}

/// The coordinates moved by the offset vector `o` (from `texel_offset`); array layers stay.
fn moved_coords(dim: u64, c: &[String], o: &str) -> Vec<String> {
c.iter().enumerate().map(|(k, x)| if (dim == 4 && k == 1) || (dim == 5 && k == 2) { x.clone() } else { format!("({x} + {o}[{k}])") }).collect()
}

pub(crate) fn swizzle_lane(offset: u64, lane: u32) -> u32 {
let i = lane & 0x1F;
let mask = (offset & 0x1F) as u32;
Expand Down Expand Up @@ -1906,6 +1923,23 @@ impl Em {
/// Sampler descriptors (S#, 4 dwords) hold the sampler heap index in BORDER_COLOR_PTR
/// (word 3 [11:0]). Address layout with A16 (16-bit bias/coordinates/lod, 32-bit offset,
/// compare and gradients) as in AnyPS5's `componentShape` (GPL-2.0, ported 2026-11-20).
/// `float3 {t}_o{sfx}`: an MIMG texel offset (`o`, three 6-bit signed fields) in the texture
/// coordinates of mip `level` – offset / that level's size (array layers do not move).
fn texel_offset(&mut self, t: &str, dim: u64, o: &str, level: &str, sfx: &str) {
let (w, h, z, n) = (format!("{t}_w{sfx}"), format!("{t}_h{sfx}"), format!("{t}_d{sfx}"), format!("{t}_n{sfx}"));
let dims = match dim {
0 => format!("{t}_T.GetDimensions({level}, {w}, {n});"),
1 => format!("{t}_T.GetDimensions({level}, {w}, {h}, {n});"),
2 => format!("{t}_T.GetDimensions({level}, {w}, {h}, {z}, {n});"),
4 => format!("{t}_T.GetDimensions({level}, {w}, {z}, {n}); {z} = 1u;"),
_ => format!("{t}_T.GetDimensions({level}, {w}, {h}, {z}, {n}); {z} = 1u;"),
};
self.line(&format!("uint {w} = 1u, {h} = 1u, {z} = 1u, {n}; {dims}"));
self.line(&format!(
"float3 {t}_o{sfx} = float3((float)(((int)({o} << 26)) >> 26) / (float){w}, (float)(((int)({o} << 18)) >> 26) / (float){h}, (float)(((int)({o} << 10)) >> 26) / (float){z});"
));
}

fn mimg(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
if f("TFE") != 0 || f("LWE") != 0 {
Expand Down Expand Up @@ -2109,8 +2143,8 @@ impl Em {
};
let s3 = self.sreg(ssamp + 3);
// texel offsets come from a VGPR (6-bit fields); SM 6.6 takes only immediate offsets, so
// the coordinates move by offset / size of the sampled mip (exact for lz / l / gather,
// the rounded implicit LOD otherwise)
// the coordinates move by offset / size of the sampled mip (exact for lz / integer l /
// gather; an implicit LOD with a linear mip filter is sampled per mip further down)
let offset = if has_o {
if dim == 3 {
return Err("MIMG offset cube");
Expand All @@ -2120,19 +2154,9 @@ impl Em {
} else {
None
};
let coord0 = match dim {
0 => coords[0].clone(),
1 => format!("float2({}, {})", coords[0], coords[1]),
2 => format!("float3({}, {}, {})", coords[0], coords[1], coords[2]),
4 => format!("float2({}, round({}))", coords[0], coords[1]),
5 => format!("float3({}, {}, round({}))", coords[0], coords[1], coords[2]),
_ => String::new(),
};
let coords: Vec<String> = if offset.is_some() {
coords.iter().enumerate().map(|(k, c)| if (dim == 4 && k == 1) || (dim == 5 && k == 2) { c.clone() } else { format!("({c} + {t}_o[{k}])") }).collect()
} else {
coords
};
let coord0 = sample_coord(dim, &coords);
let coords_unmoved = coords.clone();
let coords: Vec<String> = if offset.is_some() { moved_coords(dim, &coords, &format!("{t}_o")) } else { coords };
let (ty, coord) = match dim {
0 => ("Texture1D<float4>", coords[0].clone()),
1 => ("Texture2D<float4>", format!("float2({}, {})", coords[0], coords[1])),
Expand All @@ -2157,17 +2181,7 @@ impl Em {
(None, _, true) => format!("(uint)max(round({t}_T.CalculateLevelOfDetail({t}_S, {coord0})), 0.0f)"),
_ => "0u".to_string(),
};
let dims = match dim {
0 => format!("{t}_T.GetDimensions({level}, {t}_w, {t}_n);"),
1 => format!("{t}_T.GetDimensions({level}, {t}_w, {t}_h, {t}_n);"),
2 => format!("{t}_T.GetDimensions({level}, {t}_w, {t}_h, {t}_d, {t}_n);"),
4 => format!("{t}_T.GetDimensions({level}, {t}_w, {t}_d, {t}_n); {t}_d = 1u;"),
_ => format!("{t}_T.GetDimensions({level}, {t}_w, {t}_h, {t}_d, {t}_n); {t}_d = 1u;"),
};
self.line(&format!("uint {t}_w = 1u, {t}_h = 1u, {t}_d = 1u, {t}_n; {dims}"));
self.line(&format!(
"float3 {t}_o = float3((float)(((int)({o} << 26)) >> 26) / (float){t}_w, (float)(((int)({o} << 18)) >> 26) / (float){t}_h, (float)(((int)({o} << 10)) >> 26) / (float){t}_d);"
));
self.texel_offset(&t, dim, o, &level, "");
}
let gather = base.starts_with("gather4");
let call = if gather {
Expand Down Expand Up @@ -2205,6 +2219,35 @@ impl Em {
(None, None, None, Some(b)) if ps => format!("{t}_T.SampleBias({t}_S, {})", tail(format!("{coord}, {b}"))),
(None, None, None, Some(b)) => format!("{t}_T.SampleLevel({t}_S, {coord}, {})", floor(b.clone())),
_ if has_lz || !ps => format!("{t}_T.SampleLevel({t}_S, {coord}, {})", floor("0.0f".into())),
// implicit LOD with an offset and a linear mip filter: the console moves each of
// the two blended mips by the offset in its own texels – sampled per mip and
// blended here. Anisotropic or point-mip samplers keep the one-mip form above.
_ if offset.is_some() => {
let o = offset.clone().unwrap_or_default();
let (w0, w2) = match self.static_ss.get(&d.pc) {
Some(w) => (format!("{}u", w[0]), format!("{}u", w[2])),
None => (self.sreg(ssamp), self.sreg(ssamp + 2)),
};
// the level a clamp past the last mip asks for is the last mip ({t}_n: the view's levels)
let lod = floor(format!("{t}_T.CalculateLevelOfDetail({t}_S, {coord0})"));
self.line(&format!("float {t}_L = min({lod}, (float)(max({t}_n, 1u) - 1u)); float {t}_l0 = floor({t}_L);"));
let l1 = format!("min((uint){t}_l0 + 1u, max({t}_n, 1u) - 1u)");
self.texel_offset(&t, dim, &o, &format!("(uint){t}_l0"), "a");
self.texel_offset(&t, dim, &o, &l1, "b");
let c0 = sample_coord(dim, &moved_coords(dim, &coords_unmoved, &format!("{t}_oa")));
let c1 = sample_coord(dim, &moved_coords(dim, &coords_unmoved, &format!("{t}_ob")));
self.line(&format!("float4 {t}_m0 = {t}_T.SampleLevel({t}_S, {c0}, {t}_l0);"));
self.line(&format!("float4 {t}_m1 = {t}_T.SampleLevel({t}_S, {c1}, (float)({l1}));"));
self.line(&format!("float4 {t}_s1 = {t}_T.Sample({t}_S, {});", tail(coord.clone())));
// S# word 2: XY_MAG_FILTER [21:20], XY_MIN_FILTER [23:22], MIP_FILTER [27:26];
// word 0: MAX_ANISO_RATIO [11:9] – anisotropic only with an aniso min / mag
// filter, as `desc::sampler_d3d12` decides. A level-0 SampleLevel filters with
// the mag filter, so mip 0 of a minified sample needs min = mag.
self.line(&format!(
"uint {t}_mag = (({w2}) >> 20) & 3u, {t}_min = (({w2}) >> 22) & 3u; bool {t}_pm = ((({w2}) >> 26) & 3u) == 2u && !(({t}_mag >= 2u || {t}_min >= 2u) && ((({w0}) >> 9) & 7u) != 0u) && ({t}_l0 >= 1.0f || (({t}_mag | ({t}_mag >> 1)) & 1u) == (({t}_min | ({t}_min >> 1)) & 1u));"
));
format!("({t}_pm ? lerp({t}_m0, {t}_m1, {t}_L - {t}_l0) : {t}_s1)")
}
_ => format!("{t}_T.Sample({t}_S, {})", tail(coord.clone())),
}
};
Expand Down
69 changes: 58 additions & 11 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,42 @@ pub fn draw_gs(
mem: &[u32],
size: u32,
clear: [f32; 4],
) -> Result<Vec<[f32; 4]>, String> {
draw_gs_views(vs, gs, ps, layout, vertices, stride, sgprs, mem, &[], &[], size, clear)
}

/// `draw` with textures and samplers in the directly indexed heaps (see `ViewTexture`).
#[allow(clippy::too_many_arguments)]
pub fn draw_views(
vs: &[u8],
ps: &[u8],
layout: &[VertexElement],
vertices: &[f32],
stride: u32,
sgprs: &[u32],
mem: &[u32],
textures: &[ViewTexture],
samplers: &[D3D12_SAMPLER_DESC],
size: u32,
clear: [f32; 4],
) -> Result<Vec<[f32; 4]>, String> {
draw_gs_views(vs, None, ps, layout, vertices, stride, sgprs, mem, textures, samplers, size, clear)
}

#[allow(clippy::too_many_arguments)]
fn draw_gs_views(
vs: &[u8],
gs: Option<&[u8]>,
ps: &[u8],
layout: &[VertexElement],
vertices: &[f32],
stride: u32,
sgprs: &[u32],
mem: &[u32],
textures: &[ViewTexture],
samplers: &[D3D12_SAMPLER_DESC],
size: u32,
clear: [f32; 4],
) -> Result<Vec<[f32; 4]>, String> {
let mut g = GPU.lock().unwrap();
let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?;
Expand Down Expand Up @@ -685,7 +721,8 @@ pub fn draw_gs(
pd.RasterizerState.DepthClipEnable = true.into();
pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT;
let pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&pd).map_err(|x| format!("CreateGraphicsPipelineState: {x}"))?;
draw_on(dev, &pso, &rs, vertices, stride, sgprs, mem, size, clear)
let draw = Draw { sgprs: sgprs.to_vec(), scissor: [0, 0, size as i32, size as i32] };
draw_on_multi(dev, &pso, &rs, vertices, stride, &[draw], mem, textures, samplers, size, clear)
}
}

Expand All @@ -710,7 +747,8 @@ pub fn draw_on(
}

/// A texture in D3D12 terms (e.g. decoded from a console T# by `gpu::desc`): SRV at
/// descriptor heap index 2·i; `data` = subresource 0, rows of `row_bytes` tightly packed.
/// descriptor heap index 2·i; `data` = the `MipLevels` levels one after the other, each in
/// tightly packed rows (`row_bytes` for level 0, its width's share for the smaller ones).
pub struct ViewTexture {
pub res: D3D12_RESOURCE_DESC,
pub srv: D3D12_SHADER_RESOURCE_VIEW_DESC,
Expand Down Expand Up @@ -751,25 +789,34 @@ unsafe fn bind_views(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, textu
}
let mut keep: Vec<windows::core::IUnknown> = vec![heap.cast().map_err(e)?, sheap.cast().map_err(e)?];
for (i, t) in textures.iter().enumerate() {
let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let (mut rows, mut total) = (0u32, 0u64);
dev.GetCopyableFootprints(&t.res, 0, 1, 0, Some(&mut fp), Some(&mut rows), None, Some(&mut total));
let levels = t.res.MipLevels.max(1) as usize;
let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels];
let (mut rows, mut total) = (vec![0u32; levels], 0u64);
dev.GetCopyableFootprints(&t.res, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), None, Some(&mut total));
let up = buffer(dev, total, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?;
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(e)?;
for y in 0..rows as usize {
if let Some(src) = t.data.get(y * t.row_bytes..(y + 1) * t.row_bytes) {
std::ptr::copy_nonoverlapping(src.as_ptr(), (p as *mut u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), t.row_bytes);
let texel = t.row_bytes / (t.res.Width as usize).max(1);
let mut offset = 0usize;
for (k, fp) in fps.iter().enumerate() {
let row_bytes = ((t.res.Width as usize) >> k).max(1) * texel;
for y in 0..rows[k] as usize {
if let Some(src) = t.data.get(offset + y * row_bytes..offset + (y + 1) * row_bytes) {
std::ptr::copy_nonoverlapping(src.as_ptr(), (p as *mut u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize), row_bytes);
}
}
offset += rows[k] as usize * row_bytes;
}
up.Unmap(0, None);
let mut r: Option<ID3D12Resource> = None;
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &t.res, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r)
.map_err(|x| format!("texture {i}: {x}"))?;
let r = r.ok_or("texture")?;
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } };
let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } };
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
for (k, fp) in fps.iter().enumerate() {
let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } };
let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } };
list.CopyTextureRegion(&dst, 0, 0, 0, &src, None);
}
list.ResourceBarrier(&[transition(&r, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)]);
dev.CreateShaderResourceView(&r, Some(&t.srv), at(&heap, 2 * i, inc));
keep.push(r.cast().map_err(e)?);
Expand Down
77 changes: 76 additions & 1 deletion crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1842,6 +1842,18 @@ fn draw_vsi() -> super::VsInterface {
/// Translated for this adapter (`runner::options`: on a GPU with 32-lane waves only, the
/// form of `upper_lanes`).
fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> Vec<[f32; 4]> {
draw_console_views(vs, ps, tris_px, &[], &[], &[])
}

/// `draw_console` with initial SGPRs and textures / samplers (see `runner::ViewTexture`).
fn draw_console_views(
vs: Option<&[u8]>,
ps: Option<&[u8]>,
tris_px: &[[f32; 2]],
sgprs: &[u32],
textures: &[runner::ViewTexture],
samplers: &[windows::Win32::Graphics::Direct3D12::D3D12_SAMPLER_DESC],
) -> Vec<[f32; 4]> {
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT};
let pass_vs = prog(&[
("V_MOV_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V + 4)], None),
Expand Down Expand Up @@ -1875,7 +1887,70 @@ fn draw_console(vs: Option<&[u8]>, ps: Option<&[u8]>, tris_px: &[[f32; 2]]) -> V
runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 },
runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 },
];
runner::draw(&vsb, &psb, &layout, &verts, 24, &[], &[], 16, [-1.0; 4]).unwrap()
runner::draw_views(&vsb, &psb, &layout, &verts, 24, sgprs, &[], textures, samplers, 16, [-1.0; 4]).unwrap()
}

/// `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;
/// u = v = pixel centre · 2^0.25 / 8 gives LOD 0.25; offset (+1, 0).
#[test]
fn gpu_ps_image_sample_offset_implicit_lod_between_mips() {
if !gpu_ready() {
return;
}
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_SAMPLE_DESC};
let scale = 2f32.powf(0.25) / 8.0;
let ps = prog(&[
("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 129)], None), // offset x +1, y 0
("V_MUL_F32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 255), ("VSRC1", 2)], Some(scale.to_bits())),
("V_MUL_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 255), ("VSRC1", 3)], Some(scale.to_bits())),
("IMAGE_SAMPLE_O", "ENC_MIMG", &[("VDATA", 8), ("VADDR", 4), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0x1), ("DIM", 1)], None),
("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 8), ("VSRC1", 8), ("VSRC2", 8), ("VSRC3", 8), ("DONE", 1), ("VM", 1)], None),
]);
let mut data = Vec::new();
for k in 0..4u32 {
let n = 8 >> k;
for _y in 0..n {
for x in 0..n {
data.extend_from_slice(&[(100 * k + x) as f32; 4].map(f32::to_le_bytes).concat());
}
}
}
let res = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 8,
Height: 8,
DepthOrArraySize: 1,
MipLevels: 4,
Format: DXGI_FORMAT_R32G32B32A32_FLOAT,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
let mut srv = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32G32B32A32_FLOAT,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
..Default::default()
};
srv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 4, ..Default::default() };
let tex = runner::ViewTexture { res, srv, data, row_bytes: 8 * 16 };
// S#: clamp u / v / w, point min / mag, MIP_FILTER linear (2), LOD 0..15.99, sampler 0
let s_sharp = [2 | 2 << 3 | 2 << 6, 0xFFF << 12, 2 << 26, 0];
let mut sgprs = vec![0u32; 32];
sgprs[16..24].copy_from_slice(&tsharp(0, 77, 9));
sgprs[24..28].copy_from_slice(&s_sharp);
let px = draw_console_views(None, Some(&ps), &[[0.0, 0.0], [0.0, 32.0], [32.0, 0.0]], &sgprs, &[tex], &[crate::gpu::desc::sampler_d3d12(&s_sharp, false)]);
for y in 0..16 {
for x in 0..16 {
let u = (x as f32 + 0.5) * scale;
let texel = |size: f32| ((u * size).floor() + 1.0).clamp(0.0, size - 1.0);
let want = 0.75 * texel(8.0) + 0.25 * (100.0 + texel(4.0));
let got = px[y * 16 + x][0];
assert!((got - want).abs() < 0.02, "pixel ({x},{y}) = {got}, expected {want}");
}
}
}

/// 48 SGPR spill slots in lanes 0..47 of v30 (`v_writelane` / `v_readlane`, as 287 retail
Expand Down