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
2 changes: 1 addition & 1 deletion runtime/d3d12/src/device/compute_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ fn missing_literal_samplers(shader: &[u8], stage: u32, existing: &[[u32; 13]]) -
if private.iter().all(covered) { Vec::new() } else { private }
}

fn static_sampler(s: [u32; 13]) -> D3D12_STATIC_SAMPLER_DESC {
pub(super) fn static_sampler(s: [u32; 13]) -> D3D12_STATIC_SAMPLER_DESC {
D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER(s[0] as i32),
AddressU: D3D12_TEXTURE_ADDRESS_MODE(s[1] as i32),
Expand Down
64 changes: 59 additions & 5 deletions runtime/d3d12/src/device/mesh_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,31 @@ pub(super) fn reflected(
mesh: &[u8],
pixel: Option<&[u8]>,
node: u32,
) -> Result<Option<Arc<ComputeTable>>> {
build(device, original, mesh, pixel, node, &[])
}

/// The mesh table with `samplers` appended as static samplers of both the host
/// root and the root the pixel stage is translated against. Used when the
/// pixel program builds a literal sampler the title's root leaves out.
pub(super) fn reflected_with_samplers(
device: &ID3D12Device,
original: &RootSource,
mesh: &[u8],
pixel: Option<&[u8]>,
node: u32,
samplers: &[[u32; 13]],
) -> Result<Option<Arc<ComputeTable>>> {
build(device, original, mesh, pixel, node, samplers)
}

fn build(
device: &ID3D12Device,
original: &RootSource,
mesh: &[u8],
pixel: Option<&[u8]>,
node: u32,
extra: &[[u32; 13]],
) -> Result<Option<Arc<ComputeTable>>> {
let Ok(root) = parse_rts0(original.payload()) else {
return Ok(None);
Expand All @@ -37,7 +62,7 @@ pub(super) fn reflected(
_ => None,
})
.collect();
if layout.replacements.is_empty() && pixel_tables.is_empty() {
if layout.replacements.is_empty() && pixel_tables.is_empty() && extra.is_empty() {
return Ok(None);
}
let mesh_rewritten: Vec<usize> = layout.replacements.keys().copied().collect();
Expand Down Expand Up @@ -118,11 +143,39 @@ pub(super) fn reflected(
let reader = reader.ok_or(E_POINTER)?;
let mut desc = *reader.GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1)?;
let source = desc.Anonymous.Desc_1_1;
if source.NumParameters as usize != root.params.len() || source.pParameters.is_null() {
if source.NumParameters as usize != root.params.len() {
return Err(E_INVALIDARG.into());
}
let mut params = std::slice::from_raw_parts(source.pParameters, root.params.len()).to_vec();
let mut params = if root.params.is_empty() {
Vec::new()
} else {
if source.pParameters.is_null() {
return Err(E_INVALIDARG.into());
}
std::slice::from_raw_parts(source.pParameters, root.params.len()).to_vec()
};
let originals = params.clone();
// Appended static samplers join the title's own in both roots built
// below. The storage outlives both serializations.
let sampler_storage: Vec<D3D12_STATIC_SAMPLER_DESC> = if extra.is_empty() {
Vec::new()
} else {
let mut samplers = if source.NumStaticSamplers == 0 {
Vec::new()
} else {
if source.pStaticSamplers.is_null() {
return Err(E_INVALIDARG.into());
}
std::slice::from_raw_parts(source.pStaticSamplers, source.NumStaticSamplers as usize)
.to_vec()
};
samplers.extend(extra.iter().copied().map(super::compute_table::static_sampler));
samplers
};
if !sampler_storage.is_empty() {
desc.Anonymous.Desc_1_1.pStaticSamplers = sampler_storage.as_ptr();
desc.Anonymous.Desc_1_1.NumStaticSamplers = sampler_storage.len() as u32;
}
let mut range_storage = vec![Vec::new(); params.len()];
for (index, change) in layout.replacements {
let parameter = &mut params[index];
Expand Down Expand Up @@ -216,8 +269,9 @@ pub(super) fn reflected(
})
};
// The root the pixel program is translated against: the title's, with
// those tables as the program reads them.
let pixel_root = if pixel_storage.is_empty() {
// those tables as the program reads them. Appended samplers alone also
// need a pixel root: the guest root itself has none of them.
let pixel_root = if pixel_storage.is_empty() && sampler_storage.is_empty() {
None
} else {
let mut for_pixel = originals.clone();
Expand Down
34 changes: 33 additions & 1 deletion runtime/d3d12/src/device/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ unsafe fn create(
super::compute_table::capture_stage_root(pixel, root);
}
let mut rooted = [None, None];
let mut mesh_pixel_prepared = false;
// A mesh pipeline's pixel stage runs under the guest root too (its
// parameters are unchanged by the mesh table). Translate it against that
// root, as a vertex/pixel pair is, so its constant buffers and views use the
Expand All @@ -267,12 +268,43 @@ unsafe fn create(
// table carries a root that follows the program instead.
if let (Some(root), Some((pixel, _)), Some(_)) = (guest_root, original[1], original[7])
&& original[0].is_none()
&& let Some(variant) = shader_cache::raster_with_root(
{
let variant = shader_cache::raster_with_root(
pixel,
pipeline.raster_table.as_ref().and_then(|table| table.pixel_root.as_ref()).unwrap_or(root).payload(),
);
// The shader can already embed the effective root; in that case there
// is no new variant to prepare.
mesh_pixel_prepared = shader_cache::prepared(variant.as_deref().unwrap_or(pixel)).is_some();
if mesh_pixel_prepared {
rooted[1] = variant;
}
}
// A mesh pipeline's pixel program can build a literal sampler the title's
// root does not hold: the console compiles the state into the program, so
// the root can pair with a program whose words match none of its static
// samplers. The root-less fallback then reads space 32765, which no mesh
// root carries, and the driver rejects the pipeline. Rebuild the mesh
// table with the unmatched states as private static samplers, in the host
// root and in the root the pixel stage is translated against, and keep it
// only when the pixel stage then translates against that root.
if !mesh_pixel_prepared
&& let (Some((mesh, _)), Some(root), Some(field)) = (original[7], guest_root, root_record)
&& original[2..7].iter().all(Option::is_none)
&& original[0].is_none()
&& let Some((pixel, _)) = original[1]
&& let Ok(signature) = tuxbox_dxbc::rootsig::parse_rts0(root.payload())
&& let Some(unmatched) = tuxbox_dxbc::inline_sampler::unmatched(pixel, 0, &signature)
// A failed speculative root build leaves the original fallback usable.
&& let Ok(Some(table)) = super::mesh_table::reflected_with_samplers(
&device.native, root, mesh, Some(pixel), node_mask, &unmatched,
)
&& let Some(pixel_root) = &table.pixel_root
&& let Some(variant) = shader_cache::raster_with_root(pixel, pixel_root.payload())
&& shader_cache::prepared(&variant).is_some()
{
unsafe { field.write(table.native.as_raw()) };
pipeline.raster_table = Some(table);
rooted[1] = Some(variant);
}
if let Some(root) = guest_root && original[0].is_some() && original[1].is_some()
Expand Down
88 changes: 88 additions & 0 deletions runtime/dxbc/src/inline_sampler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,94 @@ fn omitted_states(
)
}

/// Each literal sampler state of the program that no static sampler visible to
/// the stage in `root` carries, as private static samplers of space 32765.
///
/// The console compiles a sampler from constant words into the program, so a
/// title can pair it with a root whose static samplers hold none of its states.
/// The translator keys a sampler by register alone, so the private registers
/// sit above every sampler register the root or the program names: one another
/// space also uses would refuse the translation ("overlaps another space").
pub fn unmatched(shader: &[u8], stage: u32, root: &crate::rootsig::RootSig) -> Option<Vec<[u32; 13]>> {
let d = Dxbc::parse(shader).ok()?;
let chunk = |tag| {
let c = d.chunk(tag)?;
shader.get(c.offset..c.offset + c.size)
};
let dxil = chunk(b"DXIL")?;
// Samplers indexed from the sampler heap need the guest's actual heap.
if !matches!(stage, 0 | 5)
|| word(dxil, 0)? >> 16 != stage
|| u64::from_le_bytes(chunk(b"SFI0")?.try_into().ok()?) & (3 << 25) != 0
{
return None;
}
let programs = xdat::programs(dxil.get(24..)?).ok()?;
let [program] = programs.as_slice() else { return None };
let resources = crate::mesh_table::shader_resources(shader)?;
let recorded: Vec<u32> =
compute_table::records(program)?.filter(|r| r[0] == 0x401).map(|r| r[2]).collect();
let visibility = if stage == 0 { 5 } else { 0 };
unmatched_states(&fssm::decode(program).ok()?.isa, root, &resources, &recorded, visibility)
}

/// The literal states of `isa` that `root` does not carry for `visibility`,
/// placed at the private registers above every sampler register the root, the
/// PSV resource list (`resources`), or the FSSM static-sampler records
/// (`recorded`) names.
fn unmatched_states(
isa: &[u8],
root: &crate::rootsig::RootSig,
resources: &[[u32; 4]],
recorded: &[u32],
visibility: u32,
) -> Option<Vec<[u32; 13]>> {
use crate::rootsig::RootParamKind;
// A root that reads the sampler heap directly has no use for static ones.
if root.flags & 0x800 != 0 {
return None;
}
let mut top = root.static_samplers.iter().map(|s| s[10]).fold(0u32, u32::max);
for param in &root.params {
let RootParamKind::Table(ranges) = &param.kind else { continue };
for range in ranges {
if range.range_type == 3 {
// An unbounded sampler table addresses every register above its base.
if range.num == u32::MAX {
return None;
}
let last = range.base_register.checked_add(range.num.checked_sub(1)?)?;
top = top.max(last);
}
}
}
for &[ty, _, low, high] in resources {
if ty == 1 {
top = top.max(low).max(high);
}
}
for &register in recorded {
top = top.max(register);
}
let states = literal_sites(isa, visibility)?.descriptors;
let visible = |s: &&[u32; 13]| s[12] == 0 || s[12] == visibility;
let missing: Vec<[u32; 13]> = states
.into_iter()
.filter(|state| !root.static_samplers.iter().filter(visible).any(|s| s[..10] == state[..10]))
.collect();
if missing.is_empty() {
return None;
}
let mut placed = Vec::with_capacity(missing.len());
for (index, mut state) in missing.into_iter().enumerate() {
state[10] = top.checked_add(1)?.checked_add(index as u32)?;
state[11] = 32765;
state[12] = visibility;
placed.push(state);
}
Some(placed)
}

#[cfg(test)]
#[path = "tests/inline_sampler.rs"]
mod tests;
Loading
Loading