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
89 changes: 89 additions & 0 deletions crates/victory-formats/examples/texture_layout_bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//! Run with `cargo run --release -p victory-formats --example texture_layout_bench`.
use std::hint::black_box;
use std::time::Instant;

use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc};

fn main() {
const CALLS: u64 = 50_000;
let base = TextureDesc {
dimension: Dimension::Tex2d,
width: 512,
height: 512,
depth_or_array: 1,
mips: 0,
format: 98, // BC7
samples: 1,
swizzle: Swizzle::SW_64KB_D,
};
let cases = [
("BC7 64KB_D", base),
(
"BC1 64KB_S",
TextureDesc {
format: 71,
swizzle: Swizzle::SW_64KB_S,
..base
},
),
(
"RGBA8 4KB_D",
TextureDesc {
format: 28,
swizzle: Swizzle::SW_4KB_D,
..base
},
),
(
"R8 64KB_S",
TextureDesc {
format: 61,
swizzle: Swizzle::SW_64KB_S,
..base
},
),
(
"RGBA8 volume 64KB_S",
TextureDesc {
dimension: Dimension::Tex3d,
width: 128,
height: 128,
depth_or_array: 64,
format: 28,
swizzle: Swizzle::SW_64KB_S,
..base
},
),
(
"RGBA8 linear",
TextureDesc {
format: 28,
swizzle: Swizzle::LINEAR,
..base
},
),
];

for (name, desc) in cases {
let mut samples = [0.0; 7];
black_box(Texture::new(black_box(&desc)).unwrap());
let mut checksum = 0u64;
for sample in &mut samples {
let start = Instant::now();
for i in 0..CALLS {
let desc = TextureDesc {
width: desc.width + (i % 32) as u32,
..desc
};
let texture = black_box(Texture::new(black_box(&desc)).unwrap());
let layout = &texture.planes[0].layout;
checksum =
checksum.wrapping_add(texture.size + layout.offset(0, 7, 11, 0).unwrap());
}
*sample = start.elapsed().as_secs_f64() * 1e9 / CALLS as f64;
}
samples.sort_by(f64::total_cmp);
println!("{name:22} {:8.1} ns/layout {checksum}", samples[3]);
}
}
92 changes: 84 additions & 8 deletions crates/victory-formats/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
//! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//! EXPRESS OR IMPLIED.

use std::sync::OnceLock;

/// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Swizzle(pub u32);
Expand Down Expand Up @@ -174,11 +176,14 @@ pub struct Layout {
/// The first mip in the tail; `mips.len()` without one.
pub first_tail_mip: u32,
pub mips: Vec<Mip>,
/// Byte offsets inside a block of each element coordinate bit, per
/// axis; empty for linear and unsupported modes.
pattern: [Vec<u32>; 3],
/// Byte offsets inside a block for each coordinate, per axis.
/// Empty for linear and unsupported modes.
pattern: &'static SwizzlePattern,
}

type SwizzlePattern = [Vec<u32>; 3];
static EMPTY_PATTERN: SwizzlePattern = [const { Vec::new() }; 3];

/// Micro tile (256 bytes) patterns by log2 of the element size: for each
/// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...),
/// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S`
Expand Down Expand Up @@ -247,6 +252,18 @@ fn spread(bits: &[u32]) -> Vec<u32> {
.collect()
}

/// Tables depend only on the micro-tile kind, block size and element size.
/// Texture extents, mip placement and array slices only affect the base
/// address, so layouts with the same key can share these immutable tables.
fn shared_pattern(kind: usize, element_log2: u32, block_log2: u32) -> &'static SwizzlePattern {
// Indexed by MICRO kind, block size (256 B, 4 KiB, 64 KiB), then element size.
static PATTERNS: [[[OnceLock<SwizzlePattern>; 5]; 3]; 3] =
[const { [const { [const { OnceLock::new() }; 5] }; 3] }; 3];
let block_index = ((block_log2 - 8) / 4) as usize;
PATTERNS[kind][block_index][element_log2 as usize]
.get_or_init(|| pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)))
}

const MAX_MIPS: u32 = 16;

/// The largest width, height and depth (or array size) accepted, in texels.
Expand Down Expand Up @@ -322,7 +339,7 @@ impl Layout {
alignment: 256,
first_tail_mip: d.mips,
mips,
pattern: Default::default(),
pattern: &EMPTY_PATTERN,
}
}

Expand Down Expand Up @@ -498,9 +515,9 @@ impl Layout {
} else {
usize::from(d.swizzle.display())
};
pattern(kind, element_log2, block_log2).map(|bits| spread(&bits))
shared_pattern(kind, element_log2, block_log2)
} else {
Default::default()
&EMPTY_PATTERN
};
Layout {
desc: d,
Expand Down Expand Up @@ -744,6 +761,13 @@ impl Layout {
}
runs.push((first_tiled, first_linear, bytes - first_linear));
}
// A mip can end partway through the last run. Check the other runs
// once so each row can copy them with a compile-time length.
let (body, last) = runs.split_at(runs.len().saturating_sub(1));
let run_len = body
.first()
.map(|run| run.2)
.filter(|&len| body.iter().all(|run| run.2 == len));
for z in 0..depth {
let (s, inner) = self.split(first + z);
let base = u64::from(s) * self.slice_size + m.offset;
Expand All @@ -754,16 +778,33 @@ impl Layout {
copy(tiled_row as usize, linear_row, bytes);
} else {
let tiled_row = (base + self.row(m, y, inner)) as usize;
for &(tiled, linear, len) in &runs {
copy(tiled_row + tiled, linear_row + linear, len);
match run_len {
Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy),
Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy),
Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy),
_ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy),
}
copy_runs::<0>(last, tiled_row, linear_row, &mut copy);
}
}
}
Ok(())
}
}

/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0.
fn copy_runs<const N: usize>(
runs: &[(usize, usize, usize)],
tiled_row: usize,
linear_row: usize,
copy: &mut impl FnMut(usize, usize, usize),
) {
for &(tiled, linear, len) in runs {
let len = if N == 0 { len } else { N };
copy(tiled_row + tiled, linear_row + linear, len);
}
}

/// What a DXGI format stores per element: bytes, texels per element side
/// (4 for block compression), and whether its stencil is a second plane
/// (the GPU keeps depth and stencil apart).
Expand Down Expand Up @@ -1131,6 +1172,41 @@ mod tests {
assert_eq!(l.offset(0, 0, 16, 0), Ok(8192));
}

#[test]
fn layouts_share_identical_swizzle_tables() {
for (swizzle, kind, dimension, block_log2) in [
(Swizzle::SW_256B_S, 0, Dimension::Tex2d, 8),
(Swizzle::SW_256B_D, 1, Dimension::Tex2d, 8),
(Swizzle::SW_4KB_S, 0, Dimension::Tex2d, 12),
(Swizzle::SW_4KB_D, 1, Dimension::Tex2d, 12),
(Swizzle::SW_64KB_S, 0, Dimension::Tex2d, 16),
(Swizzle::SW_64KB_D, 1, Dimension::Tex2d, 16),
(Swizzle::SW_4KB_S, 2, Dimension::Tex3d, 12),
(Swizzle::SW_64KB_S, 2, Dimension::Tex3d, 16),
] {
for element_log2 in 0..5 {
let d = Desc {
dimension,
depth: 8,
..desc(128, 96, 7, 1 << element_log2, swizzle)
};
let first = Layout::new(&d).unwrap();
let second = Layout::new(&Desc {
width: 32,
height: 24,
mips: 3,
depth: 1,
..d
})
.unwrap();
let expected = pattern(kind, element_log2, block_log2).map(|bits| spread(&bits));
assert_eq!(first.pattern, &expected);
assert!(std::ptr::eq(first.pattern, second.pattern));
assert!(std::ptr::eq(first.pattern, first.clone().pattern));
}
}
}

/// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8,
/// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail.
#[test]
Expand Down
103 changes: 103 additions & 0 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,22 @@ impl HostHeap {
};
}

/// Makes slot `index` (a dynamic one) a shader resource view of `resource`.
pub(crate) fn srv_at(
&self,
index: u32,
resource: &ID3D12Resource,
desc: &D3D12_SHADER_RESOURCE_VIEW_DESC,
) {
let Some(host) = host() else { return };
// SAFETY: a live resource and a slot of our heap.
unsafe {
host.device
.CreateShaderResourceView(resource, Some(desc), self.cpu(index))
};
self.keep(index, Some(resource.clone()));
}

fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
D3D12_CPU_DESCRIPTOR_HANDLE {
ptr: self.cpu + index as usize * self.step as usize,
Expand Down Expand Up @@ -722,6 +738,55 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
))
}

/// If `view` is a buffer SRV whose offset in its shadow buffer is not a
/// multiple of its element stride (so `FirstElement` cannot address it on the
/// shared shadow buffer), returns `(title_src, byte_len, element_stride, desc)`
/// so the caller can copy the elements into an element-aligned scratch buffer.
pub(crate) fn unaligned_srv(
view: &View,
) -> Option<(u64, u64, u64, D3D12_SHADER_RESOURCE_VIEW_DESC)> {
let (address, len, words): (u64, u64, &[u32; 10]) = match view {
View::Shader(r, Some(words)) => {
if crate::resource::host_resource(*r as crate::object::This).is_some() {
return None;
}
let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?;
(data as u64, len, words)
}
View::Placed(false, resource, desc) if resource[0] == 1 => (
u64::from(desc[10]) | u64::from(desc[11]) << 32,
u64::from(resource[4]) | u64::from(resource[5]) << 32,
desc[..10].try_into().ok()?,
),
_ => return None,
};
let mut desc = srv_desc(words);
if desc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER {
return None;
}
let element = element_size(&desc);
if element == 0 {
return None;
}
let shadow = crate::shadow::find(address, len)?;
if shadow.offset(address) % element == 0 {
return None;
}
// SAFETY: checked ViewDimension == BUFFER.
let buffer = unsafe { &mut desc.Anonymous.Buffer };
let first_bytes = buffer.FirstElement.checked_mul(element)?;
let avail = len.saturating_sub(first_bytes);
let max_elems = (avail / element).min(u64::from(u32::MAX)) as u32;
if buffer.NumElements > max_elems {
buffer.NumElements = max_elems;
}
let bytes = u64::from(buffer.NumElements) * element;
if bytes == 0 {
return None;
}
Some((address + first_bytes, bytes, element, desc))
}

/// The host resource a slot made by [`make`] views, if any.
type Kept = Option<ID3D12Resource>;

Expand Down Expand Up @@ -1237,4 +1302,42 @@ mod tests {
assert_eq!(heap.dynamic(50), Some(4));
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
}

/// A placed structured buffer SRV whose offset in its shadow buffer is not
/// a multiple of its stride is flagged for element-aligned copying.
#[test]
fn unaligned_buffer_srv_is_detected() {
if host().is_none() {
return; // no host GPU
}
let start = 0x7000_0000u64;
let resource_id = 0xDEAD_BEEF_usize;
crate::shadow::register(resource_id, start, 4096);

let placed = |addr: u64, num_elements: u32, stride: u32| {
let mut res = [0u32; 14];
res[0] = 1; // BUFFER
res[4] = num_elements * stride;
let mut desc = [0u32; 16];
desc[1] = 1; // D3D12_SRV_DIMENSION_BUFFER
desc[2] = 5768; // default component mapping
desc[6] = num_elements;
desc[7] = stride;
desc[10] = addr as u32;
desc[11] = (addr >> 32) as u32;
View::Placed(false, res, desc)
};

// Offset 112 is a multiple of stride 56 -> aligned on the shadow buffer.
assert!(unaligned_srv(&placed(start + 112, 2, 56)).is_none());

// Offset 16 is not a multiple of stride 56 -> must be copied aligned.
let (src, bytes, align, desc) =
unaligned_srv(&placed(start + 16, 2, 56)).expect("unaligned");
assert_eq!((src, bytes, align), (start + 16, 112, 56));
// SAFETY: checked BUFFER dimension.
assert_eq!(unsafe { desc.Anonymous.Buffer.NumElements }, 2);

crate::shadow::unregister(resource_id, start);
}
}
Loading
Loading