Files
6gbvram---16gb-ram/crates/victory-gpu/src/resource.rs
T

1165 lines
35 KiB
Rust
Raw Normal View History

//! Heaps, committed and placed resources, and resource sizes.
//!
//! shortcut: heaps and resources are plain host memory and a resource's
//! GPU address is its CPU address, as on the console. Rewrite them on host
//! D3D12 heaps and resources once the command-stream decoder needs the host
//! GPU to see them (TODO.md, GPU).
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::{Layout, alloc_zeroed, dealloc};
use std::ffi::c_void;
use std::ptr::NonNull;
use crate::object::{
self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
guid,
};
/// The interfaces every device child also answers for.
pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [
guid(
0x63ee58fb,
0x1268,
0x4835,
[0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6],
),
guid(
0x905db94b,
0xa00c,
0x4140,
[0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57],
),
guid(
0xc4fec28f,
0x7966,
0x4e95,
[0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8],
),
];
const HEAP_IIDS: [Iid; 4] = [
guid(
0x6b3b2502,
0x6e51,
0x45b3,
[0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3],
),
PAGEABLE_IIDS[0],
PAGEABLE_IIDS[1],
PAGEABLE_IIDS[2],
];
const RESOURCE_IIDS: [Iid; 4] = [
guid(
0x696442be,
0xa72e,
0x4059,
[0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
),
PAGEABLE_IIDS[0],
PAGEABLE_IIDS[1],
PAGEABLE_IIDS[2],
];
const KIB_64: u64 = 64 << 10;
const MIB_4: u64 = 4 << 20;
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct HeapProperties {
kind: u32,
cpu_pages: u32,
pool: u32,
creation_nodes: u32,
visible_nodes: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct HeapDesc {
size: u64,
properties: HeapProperties,
alignment: u64,
flags: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub(crate) struct ResourceDesc {
dimension: u32,
alignment: u64,
width: u64,
height: u32,
depth_or_array_size: u16,
mip_levels: u16,
format: u32,
sample_count: u32,
sample_quality: u32,
layout: u32,
flags: u32,
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AllocationInfo {
size: u64,
alignment: u64,
}
const _: () = assert!(size_of::<HeapProperties>() == 20);
const _: () = assert!(size_of::<HeapDesc>() == 48);
const _: () = assert!(size_of::<ResourceDesc>() == 56);
const BUFFER: u32 = 1;
const TEXTURE_3D: u32 = 4;
/// Bytes per element and the element's width in texels (4 for block
/// compression), by DXGI format number. `None` for 1-bit, video and
/// console-only formats.
fn element(format: u32) -> Option<(u64, u64)> {
Some(match format {
1..=4 => (16, 1),
5..=8 => (12, 1),
9..=22 => (8, 1),
23..=47 | 67 | 87..=93 => (4, 1),
48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
60..=65 => (1, 1),
70..=72 | 79..=81 => (8, 4),
73..=78 | 82..=84 | 94..=99 => (16, 4),
_ => return None,
})
}
/// Bytes and alignment a resource takes in our layout: every mip of every
/// array slice and sample, packed, rounded up to 64 KiB.
///
/// shortcut: an unpadded bound, not the console's tiled layout. Titles that
/// write console-tiled data straight into memory may need more; revisit with
/// the texture layouts (TODO.md, formats).
fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
let bytes = if desc.dimension == BUFFER {
desc.width
} else {
let (element, block) = element(desc.format)?;
let (depth, slices) = if desc.dimension == TEXTURE_3D {
(u64::from(desc.depth_or_array_size), 1)
} else {
(1, u64::from(desc.depth_or_array_size))
};
let height = u64::from(desc.height);
let mips = mip_count(desc);
let mut chain = 0u64;
for mip in 0..mips.min(64) {
let w = (desc.width >> mip).max(1).div_ceil(block);
let h = (height >> mip).max(1).div_ceil(block);
let d = (depth >> mip).max(1);
chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?;
}
chain
.checked_mul(slices)?
.checked_mul(u64::from(desc.sample_count.max(1)))?
};
if bytes == 0 {
return None;
}
let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 };
let alignment = desc.alignment.max(minimum);
if !alignment.is_power_of_two() {
return None;
}
Some(AllocationInfo {
size: bytes.checked_next_multiple_of(KIB_64)?,
alignment,
})
}
/// Mip levels, the full chain for 0.
fn mip_count(desc: &ResourceDesc) -> u32 {
let depth = if desc.dimension == TEXTURE_3D {
u64::from(desc.depth_or_array_size)
} else {
1
};
match desc.mip_levels {
0 => {
64 - desc
.width
.max(u64::from(desc.height))
.max(depth)
.max(1)
.leading_zeros()
}
n => u32::from(n),
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct PlacedFootprint {
pub(crate) offset: u64,
format: u32,
width: u32,
height: u32,
depth: u32,
row_pitch: u32,
}
impl PlacedFootprint {
/// The bytes it spans in a buffer: every row pitched but the last.
pub(crate) fn bytes(&self) -> Option<u64> {
let (element, block) = element(self.format)?;
let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth);
let last = u64::from(self.width).div_ceil(block) * element;
Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last)
}
}
const _: () = assert!(size_of::<PlacedFootprint>() == 32);
const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
offset: u64::MAX,
format: 0,
width: 0,
height: 0,
depth: 0,
row_pitch: 0,
};
/// One subresource's size in an upload buffer: footprint (offset 0), rows
/// and bytes per row. Planes of depth-stencil formats are not told apart.
fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
const PITCH: u64 = 256;
if desc.dimension == BUFFER {
let footprint = PlacedFootprint {
offset: 0,
format: 0,
width: u32::try_from(desc.width).ok()?,
height: 1,
depth: 1,
row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?,
};
return (index == 0).then_some((footprint, 1, desc.width));
}
let mips = mip_count(desc);
let slices = if desc.dimension == TEXTURE_3D {
1
} else {
u32::from(desc.depth_or_array_size).max(1)
};
let (mip, slice) = (index % mips, index / mips);
if slice >= slices {
return None;
}
let (element, block) = element(desc.format)?;
let width = (desc.width >> mip).max(1).next_multiple_of(block);
let height = (u64::from(desc.height) >> mip)
.max(1)
.next_multiple_of(block);
let depth = if desc.dimension == TEXTURE_3D {
(u32::from(desc.depth_or_array_size) >> mip).max(1)
} else {
1
};
let row_size = width / block * element;
let footprint = PlacedFootprint {
offset: 0,
format: desc.format,
width: u32::try_from(width).ok()?,
height: u32::try_from(height).ok()?,
depth,
row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?,
};
Some((footprint, u32::try_from(height / block).ok()?, row_size))
}
/// Device method: where each subresource goes in an upload buffer, rows
/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give
/// the documented all-ones values.
pub(crate) extern "system" fn copyable_footprints(
_: This,
desc: *const ResourceDesc,
first: u32,
count: u32,
base: u64,
layouts: *mut PlacedFootprint,
rows: *mut u32,
row_sizes: *mut u64,
total: *mut u64,
) {
const PLACEMENT: u64 = 512;
// SAFETY: the title passes a description (null is tolerated).
let desc = unsafe { desc.as_ref() };
let mut end = base;
let mut known = desc.is_some();
for i in 0..count {
let one = desc.and_then(|d| subresource(d, first + i));
let (layout, row_count, row_size) = match one {
Some((mut footprint, row_count, row_size)) => {
footprint.offset = end.next_multiple_of(PLACEMENT);
let pitch = u64::from(footprint.row_pitch);
let lines = u64::from(row_count) * u64::from(footprint.depth);
end = footprint.offset + pitch * lines.saturating_sub(1) + row_size;
(footprint, row_count, row_size)
}
None => {
known = false;
(NO_FOOTPRINT, u32::MAX, u64::MAX)
}
};
let i = i as usize;
// SAFETY: each output is null or holds `count` entries.
unsafe {
if !layouts.is_null() {
layouts.add(i).write(layout);
}
if !rows.is_null() {
rows.add(i).write(row_count);
}
if !row_sizes.is_null() {
row_sizes.add(i).write(row_size);
}
}
}
if !known {
tracing::warn!(?desc, "no footprint for this resource");
}
if !total.is_null() {
// SAFETY: checked non-null.
unsafe { total.write(if known { end - base } else { u64::MAX }) };
}
}
/// Device method: the footprint of resources placed one after another.
/// Returns a 16-byte value, through a hidden first argument. Invalid input
/// gives the documented size `u64::MAX`.
pub(crate) extern "system" fn allocation_info(
out: *mut AllocationInfo,
_: This,
_visible: u32,
count: u32,
descs: *const ResourceDesc,
) -> *mut AllocationInfo {
let descs = if descs.is_null() {
&[][..]
} else {
// SAFETY: the title passes `count` descriptions.
unsafe { std::slice::from_raw_parts(descs, count as usize) }
};
let mut total = AllocationInfo {
size: 0,
alignment: KIB_64,
};
for desc in descs {
let Some(one) = footprint(desc) else {
tracing::warn!(?desc, "no size for this resource");
total = AllocationInfo {
size: u64::MAX,
alignment: 0,
};
break;
};
total.size = total.size.next_multiple_of(one.alignment) + one.size;
total.alignment = total.alignment.max(one.alignment);
}
// SAFETY: the caller passes room for the value.
unsafe { out.write(total) };
out
}
/// Zeroed host memory standing in for GPU memory.
pub(crate) struct Memory {
ptr: NonNull<u8>,
layout: Layout,
}
impl Memory {
/// `size` zeroed bytes aligned to `alignment` (a power of two).
pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
Memory::new(AllocationInfo { size, alignment })
}
pub(crate) fn address(&self) -> u64 {
self.ptr.as_ptr() as u64
}
fn new(info: AllocationInfo) -> Result<Memory, HRESULT> {
let layout = usize::try_from(info.size)
.ok()
.zip(usize::try_from(info.alignment).ok())
.filter(|&(size, _)| size > 0)
.and_then(|(size, align)| Layout::from_size_align(size, align).ok())
.ok_or(E_INVALIDARG)?;
// SAFETY: the size is non-zero.
let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?;
Ok(Memory { ptr, layout })
}
}
impl Drop for Memory {
fn drop(&mut self) {
// SAFETY: allocated in `new` with this layout.
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
}
}
#[repr(C)]
struct Heap {
object: Object,
desc: HeapDesc,
memory: Memory,
}
pub(crate) extern "system" fn create_heap(
_: This,
desc: *const HeapDesc,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes a description (null is tolerated).
let Some(&desc) = (unsafe { desc.as_ref() }) else {
return E_INVALIDARG;
};
tracing::debug!(
size = desc.size,
kind = desc.properties.kind,
flags = format_args!("{:#x}", desc.flags),
"heap"
);
if desc.alignment != 0 && !desc.alignment.is_power_of_two() {
return E_INVALIDARG;
}
let info = AllocationInfo {
size: desc.size,
alignment: desc.alignment.max(KIB_64),
};
let memory = match Memory::new(info) {
Ok(memory) => memory,
Err(hr) => return hr,
};
let heap = Box::new(Heap {
object: Object::new(&HEAP_FUNCTIONS),
desc,
memory,
});
object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out)
}
extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out)
}
extern "system" fn heap_release(this: This) -> u32 {
object::release_boxed::<Heap>(this)
}
extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
if !out.is_null() {
// SAFETY: `this` is a heap; the title passes room for a description.
unsafe { out.write((*this.cast::<Heap>()).desc) };
}
}
/// A resource's memory: its own, or a range of a heap it holds a reference
/// to.
enum Backing {
Committed(Memory),
Placed { heap: This, offset: u64 },
}
impl Drop for Backing {
fn drop(&mut self) {
if let Backing::Placed { heap, .. } = *self {
heap_release(heap);
}
}
}
#[repr(C)]
struct Resource {
object: Object,
desc: ResourceDesc,
heap: HeapProperties,
heap_flags: u32,
backing: Backing,
/// Textures also live on the host GPU (decision 0007); buffers do not
/// yet.
#[cfg(windows)]
host: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>,
/// The state the host texture is in. The title's barriers name console
/// states (looser than the host's), so we transition from this one.
#[cfg(windows)]
host_state: std::sync::atomic::AtomicU32,
}
/// Moves the host texture to `wanted` (a host texture state); the host
/// resource and the state it leaves, if that is a change.
#[cfg(windows)]
pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> {
use windows::core::Interface;
let r = resource(this);
let host = r.host.as_ref()?;
let before = r
.host_state
.swap(wanted, std::sync::atomic::Ordering::Relaxed);
(before != wanted).then(|| (host.as_raw(), before))
}
/// The host GPU's copy of a title resource, if it has one.
#[cfg(windows)]
pub(crate) fn host_resource<'a>(
this: This,
) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
if this.is_null() {
return None;
}
resource(this).host.as_ref()
}
/// A host texture like the title's: same description, in GPU memory,
/// without the console's layout and flags.
#[cfg(windows)]
fn host_texture(
desc: &ResourceDesc,
state: u32,
clear: *const c_void,
) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
use windows::Win32::Graphics::Direct3D12::*;
const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
if desc.dimension == BUFFER {
return None;
}
let host = crate::host::host()?;
let mut d = *desc;
d.layout = 0;
d.alignment = 0;
d.flags &= PC_FLAGS;
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let mut texture: Option<ID3D12Resource> = None;
// SAFETY: the description has the host layout (checked size, same
// fields); the out pointer is ours.
let made = unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
(&raw const d).cast(),
D3D12_RESOURCE_STATES(crate::host::texture_state(state) as i32),
// The same layout: format, then color or depth and stencil.
(!clear.is_null()).then_some(clear.cast()),
&mut texture,
)
};
if let Err(e) = made {
tracing::warn!(error = %e, desc = ?d, "no host texture");
}
texture
}
/// A buffer's host memory and size; `None` for textures.
pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> {
if this.is_null() {
return None;
}
let r = resource(this);
(r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width))
}
impl Resource {
fn data(&self) -> *mut u8 {
match self.backing {
Backing::Committed(ref memory) => memory.ptr.as_ptr(),
// SAFETY: placement checked the range lies inside the heap.
Backing::Placed { heap, offset } => unsafe {
(*heap.cast::<Heap>())
.memory
.ptr
.as_ptr()
.add(offset as usize)
},
}
}
}
fn resource<'a>(this: This) -> &'a Resource {
// SAFETY: called from resource methods only.
unsafe { &*this.cast::<Resource>() }
}
// The creation methods' own arguments, passed on.
#[allow(clippy::too_many_arguments)]
fn hand_out_resource(
desc: ResourceDesc,
heap: HeapProperties,
heap_flags: u32,
backing: Backing,
state: u32,
clear: *const c_void,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
#[cfg(not(windows))]
let _ = (state, clear);
let resource = Box::new(Resource {
object: Object::new(&RESOURCE_FUNCTIONS),
desc,
heap,
heap_flags,
backing,
#[cfg(windows)]
host: host_texture(&desc, state, clear),
#[cfg(windows)]
host_state: crate::host::texture_state(state).into(),
});
object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
}
pub(crate) extern "system" fn create_committed(
_: This,
heap: *const HeapProperties,
heap_flags: u32,
desc: *const ResourceDesc,
state: u32,
clear: *const c_void,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes both descriptions (null is tolerated).
let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else {
return E_INVALIDARG;
};
let Some(info) = footprint(&desc) else {
tracing::warn!(?desc, "no size for this resource");
return E_INVALIDARG;
};
tracing::debug!(
dimension = desc.dimension,
size = info.size,
heap = heap.kind,
"committed resource"
);
let memory = match Memory::new(info) {
Ok(memory) => memory,
Err(hr) => return hr,
};
hand_out_resource(
desc,
heap,
heap_flags,
Backing::Committed(memory),
state,
clear,
iid,
out,
)
}
pub(crate) extern "system" fn create_placed(
_: This,
heap: This,
offset: u64,
desc: *const ResourceDesc,
state: u32,
clear: *const c_void,
iid: *const Iid,
out: *mut This,
) -> HRESULT {
// SAFETY: the title passes a description (null is tolerated).
let Some(&desc) = (unsafe { desc.as_ref() }) else {
return E_INVALIDARG;
};
if heap.is_null() {
return E_INVALIDARG;
}
// SAFETY: the title passes one of our heaps.
let h = unsafe { &*heap.cast::<Heap>() };
let fits = footprint(&desc).is_some_and(|info| {
offset.is_multiple_of(info.alignment)
&& offset
.checked_add(info.size)
.is_some_and(|end| end <= h.desc.size)
});
if !fits {
tracing::warn!(
?desc,
offset,
heap = h.desc.size,
"placed resource does not fit"
);
return E_INVALIDARG;
}
object::add_ref(heap);
let backing = Backing::Placed { heap, offset };
hand_out_resource(
desc,
h.desc.properties,
h.desc.flags,
backing,
state,
clear,
iid,
out,
)
}
extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
object::answer(
RESOURCE,
iid,
object::is(iid, &RESOURCE_IIDS).then_some(this),
out,
)
}
extern "system" fn resource_release(this: This) -> u32 {
object::release_boxed::<Resource>(this)
}
/// Memory is always mapped (subresources are not told apart yet); a null
/// `out` only asks for residency.
extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT {
if !out.is_null() {
// SAFETY: checked non-null; the title passes room for a pointer.
unsafe { out.write(resource(this).data()) };
}
S_OK
}
extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {}
extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
if !out.is_null() {
// SAFETY: checked non-null; the title passes room for a description.
unsafe { out.write(resource(this).desc) };
}
}
extern "system" fn gpu_address(this: This) -> u64 {
resource(this).data() as u64
}
extern "system" fn heap_properties(
this: This,
properties: *mut HeapProperties,
flags: *mut u32,
) -> HRESULT {
let r = resource(this);
// SAFETY: either pointer may be null; otherwise the title passes room.
unsafe {
if let Some(p) = properties.as_mut() {
*p = r.heap;
}
if let Some(f) = flags.as_mut() {
*f = r.heap_flags;
}
}
S_OK
}
/// IUnknown 3, object 4, device child 1, heap 1.
static HEAP_FUNCTIONS: Table<9> = {
let mut f = object::d3d12_object(object::missing_table::<HEAP, 9>());
f[0] = heap_query as *const ();
f[2] = heap_release as *const ();
f[7] = object::parent_device as *const (); // 0x38
f[8] = heap_desc as *const (); // 0x40
Table(f)
};
/// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3
/// console ones).
static RESOURCE_FUNCTIONS: Table<18> = {
let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 18>());
f[0] = resource_query as *const ();
f[2] = resource_release as *const ();
f[7] = object::parent_device as *const (); // 0x38
f[8] = map as *const (); // 0x40
f[9] = unmap as *const (); // 0x48
f[10] = resource_desc as *const (); // 0x50
f[11] = gpu_address as *const (); // 0x58
f[14] = heap_properties as *const (); // 0x70
Table(f)
};
#[cfg(test)]
mod tests {
use super::*;
use crate::object::slot;
type Release = extern "system" fn(This) -> u32;
type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
type Address = extern "system" fn(This) -> u64;
const PROPERTIES: HeapProperties = HeapProperties {
kind: 1,
cpu_pages: 0,
pool: 0,
creation_nodes: 0,
visible_nodes: 0,
};
fn buffer(width: u64) -> ResourceDesc {
ResourceDesc {
dimension: BUFFER,
alignment: 0,
width,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format: 0,
sample_count: 1,
sample_quality: 0,
layout: 1,
flags: 0,
}
}
fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc {
ResourceDesc {
dimension: 3,
width,
height,
format,
mip_levels: mips,
layout: 0,
..buffer(0)
}
}
fn heap(size: u64) -> This {
let desc = HeapDesc {
size,
properties: PROPERTIES,
alignment: 0,
flags: 0,
};
let mut heap = std::ptr::null();
assert_eq!(
create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap),
S_OK
);
heap
}
#[test]
fn heaps_are_zeroed_aligned_memory() {
let heap = heap(1 << 20);
// SAFETY: a heap we just made.
let memory = unsafe { &(*heap.cast::<Heap>()).memory };
assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0);
let mut back = std::mem::MaybeUninit::<HeapDesc>::uninit();
slot::<extern "system" fn(This, *mut HeapDesc)>(heap, 0x40)(heap, back.as_mut_ptr());
// SAFETY: written above.
assert_eq!(unsafe { back.assume_init() }.size, 1 << 20);
assert_eq!(slot::<Release>(heap, 0x10)(heap), 0);
let bad = HeapDesc {
size: 1 << 20,
properties: PROPERTIES,
alignment: 3,
flags: 0,
};
let mut out = std::ptr::null();
assert_eq!(
create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out),
E_INVALIDARG
);
}
#[test]
fn sizes_cover_every_mip() {
let size = |d: &ResourceDesc| footprint(d).map(|i| i.size);
assert_eq!(size(&buffer(256)), Some(KIB_64));
// 256x256 RGBA8, full chain: 4/3 of 256 KiB, rounded up.
assert_eq!(size(&texture(256, 256, 28, 0)), Some(384 << 10));
// BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB.
assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10));
assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format");
let mut info = AllocationInfo {
size: 0,
alignment: 0,
};
let descs = [buffer(100), texture(256, 256, 28, 0)];
allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr());
assert_eq!(
info,
AllocationInfo {
size: (64 + 384) << 10,
alignment: KIB_64
}
);
allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1));
assert_eq!(info.size, u64::MAX);
}
#[test]
fn upload_footprints_follow_the_pc_rules() {
let null = std::ptr::null();
let mut layouts = [NO_FOOTPRINT; 2];
let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0);
let mut footprints = |desc: &ResourceDesc, first, count| {
let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr());
copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total);
(layouts, rows, sizes, total)
};
// 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512.
let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2);
assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400));
// Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one
// packed row, rounded up to 512.
assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512));
assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30));
assert_eq!(t, l[1].offset + 256 * 29 + 200);
// BC1: rows of 4x4 blocks, 8 bytes each.
let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1);
assert_eq!((r[0], s[0]), (16, 128));
let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1);
assert_eq!(t, u64::MAX, "no second subresource");
}
/// A 4x4 texture filled from a title buffer through our list and queue,
/// then read back from the host GPU.
#[cfg(windows)]
#[test]
fn buffer_data_reaches_the_host_texture() {
use windows::Win32::Graphics::Direct3D12::*;
let Some(host) = crate::host::host() else {
return; // no host GPU here
};
let null = std::ptr::null();
let iid = &RESOURCE_IIDS[0];
const COPY_DEST: u32 = 0x400;
let (mut image, mut source) = (null, null);
let rgba = texture(4, 4, 28, 1);
assert_eq!(
create_committed(
null,
&PROPERTIES,
0,
&rgba,
COPY_DEST,
null.cast(),
iid,
&mut image
),
S_OK
);
assert_eq!(
create_committed(
null,
&PROPERTIES,
0,
&buffer(1024),
0,
null.cast(),
iid,
&mut source
),
S_OK
);
let (data, _) = buffer_bytes(source).unwrap();
// SAFETY: the buffer holds 1024 bytes.
let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) };
for (i, b) in bytes.iter_mut().enumerate() {
*b = (i % 251) as u8;
}
let queue_iid = guid(
0x0ec870a6,
0x5d7e,
0x4c22,
[0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
);
let allocator_iid = guid(
0x6102dee4,
0xaf59,
0x4b09,
[0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
);
let list_iid = guid(
0x5b160d0f,
0xac1b,
0x4185,
[0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
);
let (mut queue, mut allocator, mut list) = (null, null, null);
let queue_desc = [0u32; 4];
assert_eq!(
crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue),
S_OK
);
assert_eq!(
crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator),
S_OK
);
assert_eq!(
crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list),
S_OK
);
#[repr(C)]
struct Location {
resource: This,
kind: u32,
footprint: PlacedFootprint,
}
let rows = PlacedFootprint {
offset: 0,
format: 28,
width: 4,
height: 4,
depth: 1,
row_pitch: 256,
};
let to = Location {
resource: image,
kind: 0,
footprint: PlacedFootprint { offset: 0, ..rows },
};
let from = Location {
resource: source,
kind: 1,
footprint: rows,
};
type Copy =
extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8);
slot::<Copy>(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast());
slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list);
slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
// Read the host texture back into a readback buffer.
let readback_heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_READBACK,
..Default::default()
};
let readback_desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 1024,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut readback: Option<ID3D12Resource> = None;
// SAFETY: plain creation of a readback buffer.
unsafe {
host.device
.CreateCommittedResource(
&readback_heap,
D3D12_HEAP_FLAG_NONE,
&readback_desc,
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut readback,
)
.unwrap();
}
let readback = readback.unwrap();
let host_image = host_resource(image).unwrap();
let back = host.new_list().unwrap();
let (_, before) = host_transition(image, 0x800).unwrap();
use windows::core::Interface;
let out_to = Location {
resource: readback.as_raw().cast_const().cast(),
kind: 1,
footprint: rows,
};
let out_from = Location {
resource: host_image.as_raw().cast_const().cast(),
kind: 0,
footprint: to.footprint,
};
// SAFETY: an open list, live resources, locations in the host layout.
unsafe {
back.list.ResourceBarrier(&[crate::host::transition(
host_image,
D3D12_RESOURCE_STATES(before as i32),
D3D12_RESOURCE_STATE_COPY_SOURCE,
)]);
back.list.CopyTextureRegion(
(&raw const out_to).cast(),
0,
0,
0,
(&raw const out_from).cast(),
None,
);
}
back.close();
host.execute(&[&back]);
let mut mapped = std::ptr::null_mut();
// SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
let read = unsafe {
readback
.Map(
0,
Some(&D3D12_RANGE {
Begin: 0,
End: 1024,
}),
Some(&mut mapped),
)
.unwrap();
std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
};
for row in 0..4 {
let at = row * 256;
assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}");
}
}
#[test]
fn committed_and_placed_resources_map_at_their_gpu_address() {
let null = std::ptr::null();
let mut committed = null;
let hr = create_committed(
null,
&PROPERTIES,
0,
&buffer(256),
0,
null.cast(),
&RESOURCE_IIDS[0],
&mut committed,
);
assert_eq!(hr, S_OK);
let mut data = std::ptr::null_mut();
assert_eq!(
slot::<Map>(committed, 0x40)(committed, 0, null.cast(), &mut data),
S_OK
);
assert_eq!(slot::<Address>(committed, 0x58)(committed), data as u64);
// SAFETY: the buffer is at least 256 zeroed bytes.
assert_eq!(unsafe { *data.add(255) }, 0);
assert_eq!(slot::<Release>(committed, 0x10)(committed), 0);
let heap = heap(4 * KIB_64);
let place = |offset, desc: &ResourceDesc, out: &mut This| {
create_placed(
null,
heap,
offset,
desc,
0,
null.cast(),
&RESOURCE_IIDS[0],
out,
)
};
let mut placed = null;
assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK);
// SAFETY: a heap we made.
let base = unsafe { (*heap.cast::<Heap>()).memory.ptr.as_ptr() } as u64;
assert_eq!(slot::<Address>(placed, 0x58)(placed), base + KIB_64);
let mut other = null;
assert_eq!(
place(4 * KIB_64, &buffer(1), &mut other),
E_INVALIDARG,
"past the end"
);
assert_eq!(
place(100, &buffer(1), &mut other),
E_INVALIDARG,
"misaligned"
);
// The resource keeps the heap alive.
assert_eq!(slot::<Release>(heap, 0x10)(heap), 1);
assert_eq!(slot::<Release>(placed, 0x10)(placed), 0);
}
}