diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md index 82880973..7f034dfa 100644 --- a/docs/ENVIRONMENT.md +++ b/docs/ENVIRONMENT.md @@ -99,6 +99,7 @@ The launcher sets these for a Proton or Wine launch. A value you set yourself is | `TUXBOX_REFERENCE_CBV` | `1` applies the constant-buffer layer to a provider TuxBox didn't build | | `TUXBOX_RASTER_ROOT_FALLBACK` | Try an unsupported raster root signature unchanged | | `TUXBOX_DESCRIPTOR_HEAP_LIMIT` | Cap shader-visible descriptor heaps to force paging. Without it a heap over 1,000,000 descriptors gets what the driver allows, at most the 1,048,575 slots the heap bitmaps name | +| `TUXBOX_CONSOLE_BUILT` | With `TUXBOX_CONSOLE_STRUCTURES`, which of the structures the title builds while it runs are written for the walks. By default those in packed positions, which are final in title memory when the build is called. `0` writes none. `late` also writes those in float positions, at the call and once more when the GPU is past that frame, for a host whose GPU works in the title's own memory. `all` also writes those in float positions as the CPU reads them at the call, which is wrong for a mesh the GPU writes afterwards. For comparing pictures | | `TUXBOX_CONSOLE_WALKS` | With `TUXBOX_CONSOLE_STRUCTURES`, give the buffer only to the walk programs whose source digest begins with one of these comma-separated prefixes. The others keep their empty scenes. For finding which walk a fault or a wrong picture comes from, and for a title whose walks cannot all be given the buffer yet: in ProjectScarlett only the four distant-shadow walks can (`a902033a,bd054a51,65f82768,3b375136`); with the others the hit-resolve programs they feed do not return and the device is lost | | `TUXBOX_PLACEMENT_LAZY_FLUSH` | `1` looks for written placed textures only on the first `D3DFlushEntireCpuCache` after a submission. Later flushes leave their uploads to the next submission, which a batch already waiting behind a label can then precede | | `TUXBOX_PLACEMENT_WATCH` | `0` checks every placed texture against the title's memory before each batch, instead of only those XMem's write watch saw written or cannot track | diff --git a/runtime/d3d12/src/commands/build_raytracing.rs b/runtime/d3d12/src/commands/build_raytracing.rs index e1359b84..d579832d 100644 --- a/runtime/d3d12/src/commands/build_raytracing.rs +++ b/runtime/d3d12/src/commands/build_raytracing.rs @@ -10,7 +10,9 @@ use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::System::{Diagnostics::Debug::ReadProcessMemory, Threading::GetCurrentProcess}; use windows::core::{GUID, IUnknown, Result}; +mod box_tree; mod console; +mod console_structure; pub(super) mod guest_addresses; mod meshlet_indices; mod packed_positions; diff --git a/runtime/d3d12/src/commands/build_raytracing/box_tree.rs b/runtime/d3d12/src/commands/build_raytracing/box_tree.rs new file mode 100644 index 00000000..ad4b0fc9 --- /dev/null +++ b/runtime/d3d12/src/commands/build_raytracing/box_tree.rs @@ -0,0 +1,123 @@ +//! A four-way tree of boxes over things that each have a box. +//! +//! The console's structures are such trees: a box node holds up to four +//! children with the box of each. This builds one over leaves given by their +//! boxes, for the structures the provider writes itself (`console_scene`, +//! `console_structure`). It is not the console builder's tree: any tree whose +//! boxes hold their children gives a walk the same hits. A node's leaves are +//! halved at the median of their box centres along the axis the centres +//! spread widest on, and each half again. +// Not called outside the tests until the structures are placed for the walks. +#![cfg_attr(not(test), allow(dead_code))] + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Bounds { + pub(super) min: [f32; 3], + pub(super) max: [f32; 3], +} + +impl Bounds { + /// The box nothing is inside, as the console keeps an empty slot. + pub(super) const NONE: Self = Self { min: [f32::MAX; 3], max: [f32::MIN; 3] }; + + pub(super) fn add(&mut self, other: &Bounds) { + for axis in 0..3 { + self.min[axis] = self.min[axis].min(other.min[axis]); + self.max[axis] = self.max[axis].max(other.max[axis]); + } + } + + pub(super) fn of(points: &[[f32; 3]]) -> Self { + let mut bounds = Self::NONE; + for point in points { + bounds.add(&Bounds { min: *point, max: *point }); + } + bounds + } + + /// Whether the box holds something a ray can reach: every bound is a + /// finite number and none is missing. + pub(super) fn finite(&self) -> bool { + (0..3).all(|axis| self.min[axis].is_finite() && self.max[axis].is_finite() && self.min[axis] <= self.max[axis]) + } + + /// The six floats a box node keeps: the low corner, then the high one. + pub(super) fn words(&self) -> [u32; 6] { + core::array::from_fn(|at| if at < 3 { self.min[at] } else { self.max[at - 3] }.to_bits()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Child { + Leaf(usize), + Node(usize), +} + +/// The nodes, the root first and every node before the nodes below it, and +/// the box of each. +pub(super) struct Tree { + pub(super) nodes: Vec>, + pub(super) bounds: Vec, +} + +fn halve<'a>(leaves: &'a mut [usize], boxes: &[Bounds]) -> (&'a mut [usize], &'a mut [usize]) { + let centre = |leaf: usize, axis: usize| boxes[leaf].min[axis] + boxes[leaf].max[axis]; + let spread = |axis: usize| { + let (low, high) = leaves.iter().fold((f32::MAX, f32::MIN), |(low, high), &leaf| { + (low.min(centre(leaf, axis)), high.max(centre(leaf, axis))) + }); + high - low + }; + let axis = (0..3).max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or(0); + leaves.sort_unstable_by(|&a, &b| centre(a, axis).total_cmp(¢re(b, axis)).then(a.cmp(&b))); + leaves.split_at_mut(leaves.len() / 2) +} + +fn node(leaves: &mut [usize], boxes: &[Bounds], nodes: &mut Vec>) -> usize { + let me = nodes.len(); + nodes.push(Vec::new()); + let groups: Vec<&mut [usize]> = if leaves.len() <= 4 { + leaves.chunks_mut(1).collect() + } else { + let (low, high) = halve(leaves, boxes); + let (a, b) = halve(low, boxes); + let (c, d) = halve(high, boxes); + vec![a, b, c, d] + }; + let mut children = Vec::with_capacity(4); + for group in groups { + match group.len() { + 0 => {} + 1 => children.push(Child::Leaf(group[0])), + _ => children.push(Child::Node(node(group, boxes, nodes))), + } + } + nodes[me] = children; + me +} + +/// The tree over leaves with these boxes. With no leaf it has no node; with +/// any, its root is a node, of one child for a single leaf. +pub(super) fn tree(boxes: &[Bounds]) -> Tree { + let mut nodes = Vec::new(); + if !boxes.is_empty() { + let mut leaves: Vec = (0..boxes.len()).collect(); + node(&mut leaves, boxes, &mut nodes); + } + // A node's children come after it, so the last node's box is known first. + let mut bounds = vec![Bounds::NONE; nodes.len()]; + for (index, children) in nodes.iter().enumerate().rev() { + for child in children { + let below = match *child { + Child::Leaf(leaf) => boxes[leaf], + Child::Node(below) => bounds[below], + }; + bounds[index].add(&below); + } + } + Tree { nodes, bounds } +} + +#[cfg(test)] +#[path = "../../tests/commands/box_tree.rs"] +mod tests; diff --git a/runtime/d3d12/src/commands/build_raytracing/console.rs b/runtime/d3d12/src/commands/build_raytracing/console.rs index ba32175c..d0399cf4 100644 --- a/runtime/d3d12/src/commands/build_raytracing/console.rs +++ b/runtime/d3d12/src/commands/build_raytracing/console.rs @@ -9,15 +9,19 @@ //! places it names. A walk dispatched later finds it by the address the //! title binds. //! -//! Structures the title builds from geometry while it runs are not placed -//! yet: their instances are left out of the scene. -use super::{Entry, packed_structure, title_geometry}; -use crate::device::console_heap::{self, Placed}; +//! - A bottom-level build is written from the geometry it names +//! (`console_structure`) when that geometry is final in title memory at the +//! call: packed positions, which the title streams in. A mesh in float +//! positions is mostly one the GPU writes after the call, so its structure +//! is left out and its instances stay out of the scene +//! (`TUXBOX_CONSOLE_BUILT`). +use super::{Entry, console_structure, packed_structure, title_geometry}; +use crate::device::console_heap::{self, ConsoleHeap, Placed, Reread}; use crate::device::{blas, ray_build}; use crate::diagnostics::log; use std::sync::atomic::{AtomicU64, Ordering}; use tuxbox_bvh_layout::{Bounds, Instance, Structure, header, write_scene}; -use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::{Direct3D12::*, Dxgi::Common::*}; use windows::core::IUnknown; type Build = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC; @@ -26,6 +30,8 @@ type Build = D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC; const INSTANCE: usize = Instance::BYTES; /// More instances than this are not read: no scene of the title comes near. const LIMIT: usize = 1 << 20; +/// A scene of this many instances or more is one of the world's. +const LARGE: usize = 1024; /// Whether the `count`-th of something is worth a line in the log. fn told(count: u64) -> bool { @@ -112,9 +118,20 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * for (index, build) in builds.iter().enumerate() { // SAFETY: `addresses` is not null here and holds an entry for each build (`# Safety`). let alias = if addresses.is_null() { 0 } else { unsafe { addresses.add(index).read_unaligned() } }; + // What the title had built at these addresses is gone: so is its second reading. + heap.begun(build.DestAccelerationStructureData); + heap.begun(alias); // SAFETY: as this function's. let why = match unsafe { expanded(build, alias) } { - Ok(bytes) if heap.structure(device, &[build.DestAccelerationStructureData, alias], &bytes) => { + // The expansion is what the title has there, byte for byte: so is its length. + Ok(bytes) + if heap.structure( + device, + &[build.DestAccelerationStructureData, alias], + &bytes, + bytes.len() as u64, + ) => + { placed += 1; continue; } @@ -142,19 +159,221 @@ pub(super) unsafe fn rehydrated(owner: &IUnknown, builds: &[Build], addresses: * } } -/// The bottom-level builds of a build call. A structure the title builds -/// from geometry while it runs is not written yet, so whatever was placed -/// under its address is no longer what the title has there. +/// Which of the structures a title builds while it runs are written. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Built { + /// None: their instances stay out of the scenes. + None, + /// Those whose geometry is final at the call. + Settled, + /// Those, and the others read at the call and once more when the GPU is + /// past the frame: for a host whose GPU works in the title's own memory. + Late, + /// Every one the CPU can read at the call, right or not: for comparing pictures. + All, +} + +/// What `TUXBOX_CONSOLE_BUILT` asks for. +fn built_from(asked: Option<&str>) -> Built { + match asked.map(str::trim) { + Some("0") => Built::None, + Some("late") => Built::Late, + Some("all") => Built::All, + _ => Built::Settled, + } +} + +fn built_mode() -> Built { + static MODE: std::sync::LazyLock = std::sync::LazyLock::new(|| { + let mode = built_from(std::env::var("TUXBOX_CONSOLE_BUILT").ok().as_deref()); + if mode != Built::Settled { + log(&format!("TUXBOX_CONSOLE_BUILT: of the structures the title builds, written are {mode:?}")); + } + mode + }); + *MODE +} + +/// Why a build in float positions is left out. +const UNSETTLED: &str = "float positions, which the GPU may write after the call"; + +/// Whether title memory holds a geometry's final positions when its build is +/// called. Packed positions are streamed in with the mesh and stay as they +/// are. Float positions are what a skinned or simulated mesh is written in, +/// by the GPU, after the title has recorded the build: read at the call they +/// are an earlier frame's, or not positions at all. +fn settled(format: DXGI_FORMAT) -> bool { + format == DXGI_FORMAT_R32G32_FLOAT +} + +/// The geometry descriptions of one bottom-level build, copied: what is +/// needed to read its triangles after the call as well. /// /// # Safety -/// `owner` is the list's controlling guest device. +/// `build` is the title's description, live for the call. +unsafe fn descriptions(build: &Build) -> Result, &'static str> { + let inputs = &build.Inputs; + // SAFETY: the title supplies the descriptions for the duration of the call. + if !unsafe { ray_build::valid(inputs) } { + return Err("inputs that are not valid"); + } + let mut out = Vec::new(); + for index in 0..inputs.NumDescs as usize { + // SAFETY: `ray_build::valid` checked the layout and every pointer. + let description = + unsafe { title_geometry::description(inputs, index) }.ok_or("a missing geometry description")?; + if description.Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES { + return Err("a geometry that is not triangles"); + } + out.push(description); + } + Ok(out) +} + +/// The vertex format of a triangle geometry. +fn format(description: &D3D12_RAYTRACING_GEOMETRY_DESC) -> DXGI_FORMAT { + // SAFETY: `descriptions` keeps triangle geometries only: the discriminant selects Triangles. + unsafe { description.Anonymous.Triangles.VertexFormat } +} + +/// The structure over the triangles the descriptions name, as title memory +/// holds them now. +fn structure_from(descriptions: &[D3D12_RAYTRACING_GEOMETRY_DESC]) -> Result, &'static str> { + let mut geometry = Vec::new(); + for description in descriptions { + // SAFETY: as in `format`. + geometry.push(title_geometry::triangles_of(unsafe { &description.Anonymous.Triangles })?); + } + let parts: Vec<(&title_geometry::Geometry, u32)> = geometry + .iter() + .zip(descriptions) + .map(|(geometry, description)| (geometry, description.Flags.0.cast_unsigned())) + .collect(); + console_structure::build(&parts) +} + +/// The bytes of title memory the console's own structure is sure to cover +/// for a structure this writer made: its header, and half a leaf for each +/// triangle, since a console leaf holds two at most. The console's builder +/// writes more than that, never less. +fn least_extent(bytes: &[u8]) -> u64 { + let leaves = bytes.get(12..16).map_or(0, |word| u32::from_le_bytes(core::array::from_fn(|byte| word[byte]))); + 64 + 32 * u64::from(leaves) +} + +/// A digest of a structure's bytes, never 0. +fn digest(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)) + | 1 +} + +/// The builds whose second reading is due: each is read again and, when the +/// GPU has changed its positions since the call, written anew. A reading +/// whose build is no longer the last one at its address, or was built over, +/// places nothing: the buffer checks that as it places (`structure_if_current`). +fn look_again(heap: &ConsoleHeap, device: &ID3D12Device) { + static READ: AtomicU64 = AtomicU64::new(0); + static CHANGED: AtomicU64 = AtomicU64::new(0); + static UNREADABLE: AtomicU64 = AtomicU64::new(0); + for (destination, look) in heap.due() { + match structure_from(&look.geometry) { + Ok(bytes) if digest(&bytes) == look.digest => {} + Ok(bytes) => { + let placed = + heap.structure_if_current(device, destination, look.generation, &bytes, least_extent(&bytes)); + if placed == Some(true) { + CHANGED.fetch_add(1, Ordering::Relaxed); + } + } + Err(_) => { + UNREADABLE.fetch_add(1, Ordering::Relaxed); + } + } + let read = READ.fetch_add(1, Ordering::Relaxed) + 1; + if told(read) { + log(&format!( + "console structures: {read} builds in float positions read again once the GPU was past their frame: {} had changed and were written anew, {} could not be read", + CHANGED.load(Ordering::Relaxed), + UNREADABLE.load(Ordering::Relaxed) + )); + } + } +} + +/// The bottom-level builds of a build call: each structure the title asks +/// the builder for is written from the geometry the build names, when that +/// geometry is final at the call (`settled`). An update is written anew. A +/// structure that is not written leaves nothing under its address: whatever +/// was placed there is no longer what the title has. +/// +/// # Safety +/// `owner` is the list's controlling guest device, and `entries` holds the +/// title's descriptions for the call. pub(super) unsafe fn built(owner: Option<&IUnknown>, entries: &[Entry]) { let Some(owner) = owner.filter(|_| console_heap::enabled()) else { return }; + static WRITTEN: AtomicU64 = AtomicU64::new(0); + static UNSETTLED_LEFT: AtomicU64 = AtomicU64::new(0); + static LEFT: AtomicU64 = AtomicU64::new(0); // SAFETY: as this function's. - let (heap, _) = unsafe { blas::console(owner) }; + let (heap, device) = unsafe { blas::console(owner) }; + let mode = built_mode(); + if mode == Built::Late { + look_again(heap, device); + } for entry in entries { - if entry.build.Inputs.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL { - heap.forget(entry.build.DestAccelerationStructureData); + let build = &entry.build; + if build.Inputs.Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL { + continue; + } + let destination = build.DestAccelerationStructureData; + let generation = heap.begun(destination); + if mode == Built::None { + heap.forget(destination); + continue; + } + // SAFETY: as this function's. + let described = unsafe { descriptions(build) }; + let floats = described.as_ref().is_ok_and(|descriptions| !descriptions.iter().all(|one| settled(format(one)))); + let bytes = match described.as_deref() { + Ok(_) if floats && mode == Built::Settled => Err(UNSETTLED), + Ok(descriptions) => structure_from(descriptions), + Err(why) => Err(*why), + }; + if floats + && mode == Built::Late + && let Ok(geometry) = described + { + let digest = bytes.as_deref().map_or(0, digest); + heap.read_again(destination, Reread { generation, due: console_heap::presents() + 1, digest, geometry }); + } + let why = match bytes { + Ok(bytes) if heap.structure(device, &[destination], &bytes, least_extent(&bytes)) => { + let written = WRITTEN.fetch_add(1, Ordering::Relaxed) + 1; + if told(written) { + let (_, _, used) = heap.totals(); + log(&format!( + "console structures: {written} structures written from the geometry of their builds; left out: {} in float positions, {} for another reason; {} given up under later structures ({} MiB used)", + UNSETTLED_LEFT.load(Ordering::Relaxed), + LEFT.load(Ordering::Relaxed), + heap.overlapped(), + used >> 20 + )); + } + continue; + } + Ok(_) => "the buffer has no room", + Err(why) => why, + }; + heap.forget(destination); + if why == UNSETTLED { + UNSETTLED_LEFT.fetch_add(1, Ordering::Relaxed); + continue; + } + let left = LEFT.fetch_add(1, Ordering::Relaxed) + 1; + if told(left) { + log(&format!( + "console structures: the structure built at {destination:#x} is not written: {why} (#{left})" + )); } } } @@ -181,6 +400,7 @@ fn structure(placed: &Placed) -> Structure { pub(super) unsafe fn scenes(owner: Option<&IUnknown>, entries: &[Entry]) { let Some(owner) = owner.filter(|_| console_heap::enabled()) else { return }; static SCENES: AtomicU64 = AtomicU64::new(0); + static LARGE_SCENES: AtomicU64 = AtomicU64::new(0); // SAFETY: as this function's. let (heap, device) = unsafe { blas::console(owner) }; for entry in entries { @@ -190,6 +410,10 @@ pub(super) unsafe fn scenes(owner: Option<&IUnknown>, entries: &[Entry]) { } let number = SCENES.fetch_add(1, Ordering::Relaxed) + 1; let (destination, count) = (build.DestAccelerationStructureData, build.Inputs.NumDescs as usize); + // The scenes of a few instances outnumber the others: the large ones + // are counted apart, so that the log follows them through a run. + let large = if count >= LARGE { LARGE_SCENES.fetch_add(1, Ordering::Relaxed) + 1 } else { 0 }; + let told = |number: u64| told(number) || (large != 0 && told(large)); let indirect = build.Inputs.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS; // SAFETY: a top-level build's inputs hold the address of its instances. let address = unsafe { build.Inputs.Anonymous.InstanceDescs }; diff --git a/runtime/d3d12/src/commands/build_raytracing/console_structure.rs b/runtime/d3d12/src/commands/build_raytracing/console_structure.rs new file mode 100644 index 00000000..d9775520 --- /dev/null +++ b/runtime/d3d12/src/commands/build_raytracing/console_structure.rs @@ -0,0 +1,153 @@ +//! Bottom-level structures written in the console's form from triangles. +//! +//! A title builds most of its bottom-level structures while it runs, from +//! geometry it names by address. On the console the builder library answers +//! with a structure in the console's own form, which the title's ray-walk +//! shaders then read through the scenes that name it. `build` writes that +//! form. Its parts are those of the public traversal source +//! (`XboxBvh4Header`, `XboxBvh4Leaf` and `XboxBvh4Node32` in +//! `XDXRStandaloneTraverseShortStackCPU.hlsli`), laid out as the title's own +//! packed structures are once expanded (`packed_structure`): +//! +//! - the 64-byte header, with the bottom-level flag and a leaf frame that +//! leaves positions as they are; +//! - the parent table, one word per 64 bytes from the first leaf; +//! - one 64-byte leaf per triangle: its corners, its geometry's index and +//! flags, its place among the geometry's triangles, no second triangle, +//! and the vertex order of a triangle whose corners keep their places; +//! - box nodes of 128 bytes, the root among them even over a single leaf. +//! +//! The console's builder pairs triangles in a leaf and picks its tree by +//! other rules. A walk only needs boxes that hold what is below them, so the +//! tree is `box_tree`'s and a leaf holds one triangle. + +use super::box_tree::{Bounds, Child, tree}; +use super::title_geometry::Geometry; + +const UNIT: usize = 64; +const WIDE: usize = 128; +const VERSION: u32 = 6; +const BOTTOM_LEVEL: u32 = 0x8000_0000; +const TRIANGLE: u32 = 0; +const BOX32: u32 = 5; +const NO_NODE: u32 = u32::MAX; +const PLAIN_FRAME: u32 = 0x007f_7f7f; +/// The vertex order of a triangle whose corners keep their places. +const KEPT: u32 = 0x9; +/// The geometry flags a leaf carries: opaque, and no second any-hit call. +const LEAF_FLAGS: u32 = 3; +/// A structure of more triangles is refused rather than built. +pub(super) const LIMIT: usize = 4 << 20; +/// No geometry reaches this far from its origin on an axis. Bytes that say +/// so are not positions: a vertex buffer the GPU fills, a skinned mesh for +/// one, does not hold its positions in title memory when the build is called. +/// A structure written from them has corners up to the largest float, and +/// every ray of a walk then meets it. +pub(super) const REACH: f32 = 1.0e5; + +/// A count or a byte offset within one structure, as the word that holds it. +fn to_word(value: usize) -> u32 { + u32::try_from(value).expect("LIMIT triangles keep a structure under 4 GiB") +} + +fn pointer(at: usize, kind: u32) -> u32 { + to_word(at / 8) | kind +} + +fn put(out: &mut [u8], at: usize, words: &[u32]) { + for (index, word) in words.iter().enumerate() { + out[at + 4 * index..at + 4 * index + 4].copy_from_slice(&word.to_le_bytes()); + } +} + +/// The structure over the triangles of `parts`: each geometry of the build, +/// in the build's order, with its flags. A triangle that names a vertex its +/// geometry lacks, or has a corner that is not a finite number, gets no leaf: +/// no ray could hit it. With no leaf the structure is a header alone, whose +/// root pointer is no node. +pub(super) fn build(parts: &[(&Geometry, u32)]) -> Result, &'static str> { + if parts.len() > 1 << 24 { + return Err("more geometries than a leaf can name"); + } + if parts + .iter() + .try_fold(0usize, |sum, (geometry, _)| sum.checked_add(geometry.triangles())) + .is_none_or(|sum| sum > LIMIT) + { + return Err("more triangles than a structure is built for"); + } + let mut leaves = Vec::new(); + let mut boxes = Vec::new(); + for (index, (geometry, flags)) in parts.iter().enumerate() { + for primitive in 0..to_word(geometry.triangles()) { + let Some(corners) = geometry.triangle(primitive) else { continue }; + if !corners.iter().flatten().all(|value| value.is_finite()) { + continue; + } + if corners.iter().flatten().any(|value| value.abs() > REACH) { + return Err("a corner lies farther than any geometry reaches: the bytes read are not positions"); + } + leaves.push((to_word(index) << 8 | flags & LEAF_FLAGS, primitive, corners)); + boxes.push(Bounds::of(&corners)); + } + } + let built = tree(&boxes); + let mut header = vec![BOTTOM_LEVEL | VERSION, 0, 0, to_word(leaves.len())]; + if leaves.is_empty() { + header.extend([0; 6]); + header.extend([to_word(UNIT), 0, NO_NODE, to_word(UNIT), to_word(UNIT), PLAIN_FRAME]); + let mut bytes = vec![0u8; UNIT]; + put(&mut bytes, 0, &header); + return Ok(bytes); + } + + let units = leaves.len() + built.nodes.len() * WIDE / UNIT; + let parents_at = UNIT; + let leaves_at = parents_at + (4 * units).next_multiple_of(UNIT); + let nodes_at = leaves_at + leaves.len() * UNIT; + let mut bytes = vec![0u8; nodes_at + built.nodes.len() * WIDE]; + let parent_entry = |at: usize| parents_at + 4 * ((at - leaves_at) / UNIT); + for unit in 0..units { + put(&mut bytes, parents_at + 4 * unit, &[NO_NODE]); + } + for (slot, (geometry, primitive, corners)) in leaves.iter().enumerate() { + let at = leaves_at + slot * UNIT; + let mut words: Vec = corners.iter().flatten().map(|value| value.to_bits()).collect(); + // The corner a second triangle would add. + words.extend([f32::NAN.to_bits(); 3]); + words.extend([*geometry, *primitive, NO_NODE, KEPT]); + put(&mut bytes, at, &words); + } + for (index, children) in built.nodes.iter().enumerate() { + let at = nodes_at + index * WIDE; + let me = pointer(at, BOX32); + for slot in 0..4 { + let (child, bounds) = match children.get(slot) { + Some(&Child::Leaf(leaf)) => (pointer(leaves_at + leaf * UNIT, TRIANGLE), boxes[leaf]), + Some(&Child::Node(below)) => (pointer(nodes_at + below * WIDE, BOX32), built.bounds[below]), + None => (NO_NODE, Bounds::NONE), + }; + if child != NO_NODE { + put(&mut bytes, parent_entry((child >> 3) as usize * UNIT), &[me]); + } + put(&mut bytes, at + 4 * slot, &[child]); + put(&mut bytes, at + 16 + 24 * slot, &bounds.words()); + } + } + header[1] = to_word(bytes.len() / UNIT - 1); + header.extend(built.bounds[0].words()); + header.extend([ + to_word(nodes_at), + 0, + pointer(nodes_at, BOX32), + to_word(leaves_at), + to_word(parents_at), + PLAIN_FRAME, + ]); + put(&mut bytes, 0, &header); + Ok(bytes) +} + +#[cfg(test)] +#[path = "../../tests/commands/console_structure.rs"] +mod tests; diff --git a/runtime/d3d12/src/commands/build_raytracing/title_geometry.rs b/runtime/d3d12/src/commands/build_raytracing/title_geometry.rs index f0a0e8b0..42f949b2 100644 --- a/runtime/d3d12/src/commands/build_raytracing/title_geometry.rs +++ b/runtime/d3d12/src/commands/build_raytracing/title_geometry.rs @@ -25,6 +25,11 @@ pub(super) struct Geometry { } impl Geometry { + /// How many triangles the geometry holds. + pub(super) fn triangles(&self) -> usize { + self.indices.as_ref().map_or(self.positions.len(), Vec::len) / 3 + } + /// The corners of triangle `primitive` in index order, as the buffers /// hold them: before the transform. pub(super) fn corners(&self, primitive: u32) -> Option { @@ -39,6 +44,17 @@ impl Geometry { } Some(corners) } + + /// The corners of triangle `primitive` in index order, transformed. + pub(super) fn triangle(&self, primitive: u32) -> Option { + let corners = self.corners(primitive)?; + Some(match &self.transform { + Some(m) => corners.map(|[x, y, z]| { + core::array::from_fn(|row| m[4 * row] * x + m[4 * row + 1] * y + m[4 * row + 2] * z + m[4 * row + 3]) + }), + None => corners, + }) + } } /// Triangle `primitive` of geometry `index`, before that geometry's diff --git a/runtime/d3d12/src/device/console_heap.rs b/runtime/d3d12/src/device/console_heap.rs index 73209620..bad548f8 100644 --- a/runtime/d3d12/src/device/console_heap.rs +++ b/runtime/d3d12/src/device/console_heap.rs @@ -152,12 +152,12 @@ pub(crate) fn presented() { } /// Presents so far: when a place is given up. -fn presents() -> u64 { +pub(crate) fn presents() -> u64 { clock().presents } /// The last present the GPU is past: what places given up have rested to. -fn finished() -> u64 { +pub(crate) fn finished() -> u64 { clock().finished(reached) } @@ -382,11 +382,33 @@ struct Scene { structures: Vec, } +/// A build whose geometry is read once more, after the GPU has had the frame +/// it was recorded in. +pub(crate) struct Reread { + /// Which of the builds at its address it is for (`Book::begun`). + pub(crate) generation: u64, + /// The present the GPU must be past. + pub(crate) due: u64, + /// Of the structure written at the call, 0 when none was. + pub(crate) digest: u64, + pub(crate) geometry: Vec, +} + /// What the buffer holds and under which names: the part that needs no /// device. struct Book { places: Places, structures: HashMap, + /// For each address a structure is named at, the bytes of title memory + /// that structure is sure to cover from there. + extents: BTreeMap, + /// Structures given up because the title built another over them. + overlapped: u64, + /// For each address the title has built or rehydrated at, how many times: + /// a reading taken for one build is of no use once another came there. + generations: BTreeMap, + /// The builds whose geometry is read once more, by their address. + pending: BTreeMap, /// For each structure's place, its size and how many hold it: the /// addresses that name it and the scenes whose instance records do. named: HashMap, @@ -408,6 +430,10 @@ impl Book { Self { places: Places::new(bytes), structures: HashMap::new(), + extents: BTreeMap::new(), + overlapped: 0, + generations: BTreeMap::new(), + pending: BTreeMap::new(), named: HashMap::new(), scenes: HashMap::new(), offsets: None, @@ -441,13 +467,92 @@ impl Book { } } + /// The title has a structure of at least `extent` bytes at each of + /// `addresses`. A structure named at an address inside those bytes, or + /// whose own bytes reach one of the addresses, is one the title has + /// written over: nothing else says that it dropped it. A reading pending + /// for a build at an address inside those bytes is for memory the title + /// has written over too, whether that build placed a structure or not. + fn claim(&mut self, addresses: &[u64], extent: u64, now: u64) { + for &address in addresses.iter().filter(|address| **address != 0) { + let inside = address.checked_add(extent).filter(|_| extent > 1).map(|end| address + 1..end); + let mut gone: Vec = + inside.clone().map_or_else(Vec::new, |inside| self.extents.range(inside).map(|(at, _)| *at).collect()); + let waiting: Vec = + inside.map_or_else(Vec::new, |inside| self.generations.range(inside).map(|(at, _)| *at).collect()); + if let Some((&before, &reach)) = self.extents.range(..address).next_back() + && before.saturating_add(reach) > address + { + gone.push(before); + } + for at in gone.into_iter().filter(|at| !addresses.contains(at)) { + self.forget(at, now); + self.stale(at); + self.overlapped += 1; + } + for at in waiting.into_iter().filter(|at| !addresses.contains(at)) { + self.stale(at); + } + self.extents.insert(address, extent); + } + } + + /// What was read, or waits to be read, for the last build at `address` + /// is no longer wanted. + fn stale(&mut self, address: u64) { + self.pending.remove(&address); + if let Some(generation) = self.generations.get_mut(&address) { + *generation += 1; + } + } + + /// The title builds or rehydrates at `address`: the number of this + /// build there. A reading pending for an earlier one is dropped. + fn begun(&mut self, address: u64) -> u64 { + self.pending.remove(&address); + let generation = self.generations.entry(address).or_insert(0); + *generation += 1; + *generation + } + + /// Whether build `generation` at `address` is still the last one there + /// and nothing was built over it. + fn current(&self, address: u64, generation: u64) -> bool { + self.generations.get(&address) == Some(&generation) + } + + /// The geometry of a build at `address` is read once more later, unless + /// that build is already not the last one there. + fn read_again(&mut self, address: u64, pending: Reread) { + if self.current(address, pending.generation) { + self.pending.insert(address, pending); + } + } + + /// The pending readings the GPU is far enough for, taken out. + fn take_due(&mut self, finished: u64) -> Vec<(u64, Reread)> { + let due: Vec = + self.pending.iter().filter(|(_, pending)| pending.due <= finished).map(|(at, _)| *at).collect(); + due.into_iter().filter_map(|at| self.pending.remove(&at).map(|pending| (at, pending))).collect() + } + /// What `address` named is no longer the title's structure. fn forget(&mut self, address: u64, now: u64) { + self.extents.remove(&address); if let Some(old) = self.structures.remove(&address) { self.unname(old.offset, now); } } + /// The title now has a structure of at least `extent` bytes at + /// `addresses`, placed here or not. What it was built over is given up + /// either way: the title has written over it whether or not the new + /// structure found room in the buffer. + fn built_over(&mut self, addresses: &[u64], placed: Option, bytes: u64, extent: u64, now: u64) -> bool { + self.claim(addresses, extent, now); + self.structure(addresses, placed, bytes, now) + } + /// The structure of `bytes` bytes the title has at `addresses` is at /// `placed`, or it found no place: then what those addresses named is no /// longer the title's structure, and they name nothing. @@ -592,13 +697,63 @@ impl ConsoleHeap { /// Places an expanded bottom-level structure and names it by the /// addresses the title knows it at. False when it could not be placed: /// those addresses then name nothing. - pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8]) -> bool { + /// + /// `extent` is how many bytes of title memory the title's own structure + /// is sure to cover from each address: what was named inside them is + /// given up (`Book::claim`), whether or not this structure finds room. + /// 0 claims nothing. + pub(crate) fn structure(&self, device: &ID3D12Device, addresses: &[u64], bytes: &[u8], extent: u64) -> bool { + let mut inner = self.lock(); + let placed = bytes + .get(..64) + .and_then(|header| <[u8; 64]>::try_from(header).ok()) + .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header })); + inner.book.built_over(addresses, placed, bytes.len() as u64, extent, presents()) + } + + /// The title builds or rehydrates at `address` (`Book::begun`). 0 names nothing. + pub(crate) fn begun(&self, address: u64) -> u64 { + if address == 0 { 0 } else { self.lock().book.begun(address) } + } + + /// Reads the geometry of a build at `address` once more later (`Book::read_again`). + pub(crate) fn read_again(&self, address: u64, pending: Reread) { + self.lock().book.read_again(address, pending); + } + + /// The readings that are due: the GPU is past the present each waited for. + pub(crate) fn due(&self) -> Vec<(u64, Reread)> { + self.lock().book.take_due(finished()) + } + + /// `structure` for a reading taken out by `due`: None, and nothing + /// placed, when build `generation` is no longer the last one at + /// `address` or was built over since. The check and the placing are one + /// step under the buffer's lock, so a build recorded meanwhile on another + /// list either comes first and makes this reading stale, or comes after + /// and replaces what it placed. + pub(crate) fn structure_if_current( + &self, + device: &ID3D12Device, + address: u64, + generation: u64, + bytes: &[u8], + extent: u64, + ) -> Option { let mut inner = self.lock(); + if !inner.book.current(address, generation) { + return None; + } let placed = bytes .get(..64) .and_then(|header| <[u8; 64]>::try_from(header).ok()) .and_then(|header| Some(Placed { offset: inner.write(device, bytes)?, header })); - inner.book.structure(addresses, placed, bytes.len() as u64, presents()) + Some(inner.book.built_over(&[address], placed, bytes.len() as u64, extent, presents())) + } + + /// Structures given up so far because the title built another over them. + pub(crate) fn overlapped(&self) -> u64 { + self.lock().book.overlapped } /// Names a structure without placing bytes, for tests of what reads the names. diff --git a/runtime/d3d12/src/tests/commands/box_tree.rs b/runtime/d3d12/src/tests/commands/box_tree.rs new file mode 100644 index 00000000..0be943d6 --- /dev/null +++ b/runtime/d3d12/src/tests/commands/box_tree.rs @@ -0,0 +1,82 @@ +use super::*; + +fn boxes(count: usize) -> Vec { + // Points along a bent line, so that each axis takes its turn as the widest. + (0..count) + .map(|index| { + let at = index as f32; + let low = [at * 3.0, (at * 0.37).sin() * 20.0, (index % 7) as f32]; + Bounds { min: low, max: [low[0] + 1.0, low[1] + 2.0, low[2] + 0.5] } + }) + .collect() +} + +#[test] +fn no_leaf_gives_no_node_and_one_leaf_a_root_of_one_child() { + assert!(tree(&[]).nodes.is_empty()); + let one = tree(&boxes(1)); + assert_eq!(one.nodes, [vec![Child::Leaf(0)]]); + assert_eq!(one.bounds, boxes(1)); +} + +#[test] +fn up_to_four_leaves_hang_from_the_root() { + let four = tree(&boxes(4)); + assert_eq!(four.nodes.len(), 1); + assert_eq!(four.nodes[0].len(), 4); + let five = tree(&boxes(5)); + assert!(five.nodes.len() > 1 && five.nodes[0].len() == 4); +} + +#[test] +fn every_leaf_is_under_the_root_once_and_every_box_holds_what_is_below() { + for count in [1usize, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 63, 64, 65, if cfg!(miri) { 66 } else { 1000 }] { + let leaves = boxes(count); + let built = tree(&leaves); + let mut seen = vec![0u32; count]; + let mut reached = vec![0u32; built.nodes.len()]; + reached[0] = 1; + for (index, children) in built.nodes.iter().enumerate() { + assert!((1..=4).contains(&children.len()), "{count} leaves"); + let mut around = Bounds::NONE; + for child in children { + match *child { + Child::Leaf(leaf) => { + seen[leaf] += 1; + around.add(&leaves[leaf]); + } + Child::Node(below) => { + // A node comes before the nodes below it. + assert!(below > index); + reached[below] += 1; + around.add(&built.bounds[below]); + } + } + } + assert_eq!(around, built.bounds[index]); + } + assert!(seen.iter().all(|times| *times == 1), "{count} leaves: {seen:?}"); + assert!(reached.iter().all(|times| *times == 1), "{count} leaves: {reached:?}"); + // Four children a node: a tree of n leaves is at most about log4 deep, + // so it has far fewer nodes than leaves. + assert!(built.nodes.len() <= count.max(1)); + } +} + +#[test] +fn the_same_leaves_give_the_same_tree() { + let leaves = boxes(300); + assert_eq!(tree(&leaves).nodes, tree(&leaves).nodes); +} + +#[test] +fn a_box_of_points_and_its_words() { + let bounds = Bounds::of(&[[1.0, 5.0, -2.0], [3.0, 4.0, 0.0]]); + assert_eq!(bounds, Bounds { min: [1.0, 4.0, -2.0], max: [3.0, 5.0, 0.0] }); + assert_eq!(bounds.words(), [1.0f32, 4.0, -2.0, 3.0, 5.0, 0.0].map(f32::to_bits)); + assert!( + bounds.finite() + && !Bounds::of(&[[f32::NAN, 0.0, 0.0]]).finite() + && !Bounds::of(&[[f32::INFINITY, 0.0, 0.0]]).finite() + ); +} diff --git a/runtime/d3d12/src/tests/commands/console.rs b/runtime/d3d12/src/tests/commands/console.rs index a9593bd4..364a7f56 100644 --- a/runtime/d3d12/src/tests/commands/console.rs +++ b/runtime/d3d12/src/tests/commands/console.rs @@ -40,3 +40,28 @@ fn a_scene_names_a_placed_structure_by_what_its_header_holds() { assert_eq!(scene.words[at + record::ROOT] & 0x1fff_ffff, 0x45); assert_eq!(scene.words[at + record::COMPRESSION], 0x807e_8180); } + +#[test] +fn only_packed_positions_are_final_at_the_call() { + assert!(settled(DXGI_FORMAT_R32G32_FLOAT)); + assert!(!settled(DXGI_FORMAT_R32G32B32_FLOAT)); + assert!(!settled(DXGI_FORMAT_R32G32B32A32_FLOAT)); + assert!(!settled(DXGI_FORMAT_UNKNOWN)); +} + +#[test] +fn the_built_structures_written_are_the_settled_ones_unless_asked_otherwise() { + assert_eq!(built_from(None), Built::Settled); + assert_eq!(built_from(Some("1")), Built::Settled); + assert_eq!(built_from(Some("0")), Built::None); + assert_eq!(built_from(Some(" all ")), Built::All); + assert_eq!(built_from(Some("late")), Built::Late); + assert_eq!(built_from(Some("")), Built::Settled); +} + +#[test] +fn a_digest_tells_two_structures_apart_and_is_never_the_mark_of_none() { + assert_ne!(digest(&[1, 2, 3]), digest(&[1, 2, 4])); + assert_eq!(digest(&[7; 64]), digest(&[7; 64])); + assert_ne!(digest(&[]), 0); +} diff --git a/runtime/d3d12/src/tests/commands/console_structure.rs b/runtime/d3d12/src/tests/commands/console_structure.rs new file mode 100644 index 00000000..9911cb59 --- /dev/null +++ b/runtime/d3d12/src/tests/commands/console_structure.rs @@ -0,0 +1,212 @@ +use super::*; + +#[path = "console_walk.rs"] +mod walker; +use walker::*; + +type Triangle = [[f32; 3]; 3]; + +/// A geometry whose every three positions are a triangle. +fn soup(triangles: &[Triangle]) -> Geometry { + Geometry { positions: triangles.iter().flatten().copied().collect(), indices: None, transform: None } +} + +fn words(bytes: &[u8], at: usize, count: usize) -> Vec { + (0..count).map(|index| word(bytes, at + 4 * index)).collect() +} + +/// What each leaf names: its geometry and flags word, and its primitive. +fn named(bytes: &[u8]) -> Vec<(u32, u32)> { + let leaves_at = word(bytes, 52) as usize; + (0..word(bytes, 12) as usize) + .map(|slot| (word(bytes, leaves_at + UNIT * slot + 48), word(bytes, leaves_at + UNIT * slot + 52))) + .collect() +} + +const FLAT: Triangle = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + +#[test] +fn one_triangle_is_a_header_a_parent_table_a_leaf_and_a_root_box() { + let triangle = [[1.0, 2.0, 3.0], [4.0, 2.0, 3.0], [1.0, 6.0, 5.0]]; + let bytes = build(&[(&soup(&[triangle]), 1)]).unwrap(); + assert_eq!(bytes.len(), 64 + 64 + 64 + 128); + let header = words(&bytes, 0, 16); + assert_eq!(header[..4], [0x8000_0006, 4, 0, 1]); + assert_eq!(header[4..10], [1.0f32, 2.0, 3.0, 4.0, 6.0, 5.0].map(f32::to_bits)); + assert_eq!(header[10..], [192, 0, (192 / 8) | 5, 128, 64, 0x007f_7f7f]); + + let leaf = words(&bytes, 128, 16); + assert_eq!(leaf[..9], [1.0f32, 2.0, 3.0, 4.0, 2.0, 3.0, 1.0, 6.0, 5.0].map(f32::to_bits)); + assert!(leaf[9..12].iter().all(|bits| f32::from_bits(*bits).is_nan())); + assert_eq!(leaf[12..], [1, 0, NO_NODE, 9]); + + assert_eq!(words(&bytes, 192, 4), [128 / 8, NO_NODE, NO_NODE, NO_NODE]); + assert_eq!(words(&bytes, 192 + 16, 6), header[4..10]); + // An empty slot holds no point. + assert_eq!( + words(&bytes, 192 + 16 + 24, 6), + [f32::MAX, f32::MAX, f32::MAX, f32::MIN, f32::MIN, f32::MIN].map(f32::to_bits) + ); + // The leaf's unit names the node; the node, being the root, names none. + assert_eq!(words(&bytes, 64, 3), [(192 / 8) | 5, NO_NODE, NO_NODE]); +} + +#[test] +fn a_leaf_names_its_geometry_its_flags_and_its_place_in_the_geometry() { + let first = soup(&[FLAT, FLAT.map(|corner| corner.map(|value| value + 10.0))]); + let second = Geometry { + positions: vec![[0.0, 0.0, 5.0], [1.0, 0.0, 5.0], [0.0, 1.0, 5.0], [1.0, 1.0, 5.0]], + indices: Some(vec![0, 1, 2, 2, 1, 3]), + transform: None, + }; + // Only the two flags a walk reads are kept. + let bytes = build(&[(&first, 0), (&second, 0xff)]).unwrap(); + assert_eq!(named(&bytes), [(0, 0), (0, 1), (0x103, 0), (0x103, 1)]); +} + +#[test] +fn a_geometry_transform_moves_the_corners_a_leaf_keeps() { + let mut moved = soup(&[FLAT]); + moved.transform = Some([1.0, 0.0, 0.0, 7.0, 0.0, 1.0, 0.0, 8.0, 0.0, 0.0, 1.0, 9.0]); + let bytes = build(&[(&moved, 1)]).unwrap(); + assert_eq!(words(&bytes, 128, 9), [7.0f32, 8.0, 9.0, 8.0, 8.0, 9.0, 7.0, 9.0, 9.0].map(f32::to_bits)); +} + +#[test] +fn a_triangle_no_ray_could_hit_gets_no_leaf() { + let unreal = [[f32::NAN, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + let endless = [[f32::INFINITY, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + // Its second triangle names a vertex the geometry lacks. + let lacking = Geometry { positions: FLAT.to_vec(), indices: Some(vec![0, 1, 2, 0, 1, 3]), transform: None }; + let bytes = build(&[(&soup(&[unreal, FLAT, endless]), 1), (&lacking, 1)]).unwrap(); + assert_eq!(named(&bytes), [(1, 1), (0x101, 0)]); + + let empty = build(&[(&soup(&[unreal]), 1)]).unwrap(); + assert_eq!(empty.len(), 64); + assert_eq!([word(&empty, 0), word(&empty, 4), word(&empty, 12), word(&empty, 48)], [0x8000_0006, 0, 0, NO_NODE]); + assert_eq!(build(&[]).unwrap(), empty); +} + +#[test] +fn a_corner_out_of_reach_refuses_the_whole_structure() { + // What a build gave in a run: bytes that are not positions, read as floats. + let fine = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + for wrong in [2.384_498_4e38, -6.074_149_6e29, -7.238_293e15, REACH * 1.01] { + for (corner, axis) in [(0, 0), (1, 2), (2, 1)] { + let mut far = fine; + far[corner][axis] = wrong; + assert!(build(&[(&soup(&[fine, far]), 1)]).is_err(), "{wrong} at corner {corner}, axis {axis}"); + } + } + // A geometry's transform is applied first: it can bring a corner out of reach. + let mut moved = soup(&[fine]); + moved.transform = Some([1.0, 0.0, 0.0, REACH, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]); + assert!(build(&[(&moved, 1)]).is_err()); + // The reach itself is still geometry. + let edge = [[REACH, 0.0, 0.0], [REACH - 1.0, 0.0, 0.0], [REACH - 1.0, -REACH, 0.0]]; + assert_eq!(build(&[(&soup(&[fine, edge]), 1)]).map(|bytes| words(&bytes, 0, 4)[3]), Ok(2)); +} + +fn scattered(count: usize, random: &mut Random) -> Vec { + (0..count) + .map(|_| { + let corner = random.point(20.0); + [ + corner, + core::array::from_fn(|axis| corner[axis] + random.between(-2.0, 2.0)), + core::array::from_fn(|axis| corner[axis] + random.between(-2.0, 2.0)), + ] + }) + .collect() +} + +#[test] +fn a_walk_of_the_structure_finds_what_every_triangle_gives() { + // Miri runs these loops hundreds of times slower: it gets the small + // structures and fewer rays. + let sizes: &[(usize, u64)] = if cfg!(miri) { + &[(1, 3), (2, 4), (4, 5), (5, 6), (17, 7)] + } else { + &[(1, 3), (2, 4), (4, 5), (5, 6), (100, 7), (3000, 8)] + }; + let rays: usize = if cfg!(miri) { 40 } else { 1000 }; + for &(count, seed) in sizes { + let mut random = Random(seed); + let triangles = scattered(count, &mut random); + let bytes = build(&[(&soup(&triangles), 1)]).unwrap(); + let root = word(&bytes, 48); + assert!(root as i32 > 0); + let mut hits = 0; + for ray in 0..rays { + let origin = random.point(30.0); + // Half of the rays aim inside a triangle, so that hits are common. + let direction: [f32; 3] = if ray % 2 == 0 { + let triangle = &triangles[ray / 2 % count]; + let (u, v) = (random.between(0.1, 0.4), random.between(0.1, 0.4)); + core::array::from_fn(|axis| { + triangle[0][axis] + + u * (triangle[1][axis] - triangle[0][axis]) + + v * (triangle[2][axis] - triangle[0][axis]) + - origin[axis] + }) + } else { + random.point(1.0) + }; + let (origin, direction) = (origin.map(f64::from), direction.map(f64::from)); + let mut expected = None::<(f64, u32)>; + for (primitive, triangle) in triangles.iter().enumerate() { + let corners = triangle.map(|corner| corner.map(f64::from)); + if let Some((distance, _)) = meets(&corners, origin, direction) + && expected.is_none_or(|(nearest, _)| distance < nearest) + { + expected = Some((distance, primitive as u32)); + } + } + // The same corners through the same arithmetic: the same answer. + let found = walk_structure(&bytes, 0, root, origin, direction, f64::MAX).map( + |(distance, geometry, primitive, _)| { + assert_eq!(geometry, 0); + (distance, primitive) + }, + ); + assert_eq!(found, expected, "ray {ray} of {count} triangles"); + hits += usize::from(found.is_some()); + } + assert!(hits >= rays * 9 / 20, "{count} triangles: {hits} hits"); + } +} + +#[test] +fn every_leaf_is_under_the_root_once_and_every_parent_is_named() { + for count in [1usize, 2, 4, 5, 6, 16, 17, 64, 65, if cfg!(miri) { 66 } else { 1000 }] { + let bytes = build(&[(&soup(&scattered(count, &mut Random(77))), 1)]).unwrap(); + let (leaves_at, parents_at, nodes_at, root) = + (word(&bytes, 52) as usize, word(&bytes, 56) as usize, word(&bytes, 40) as usize, word(&bytes, 48)); + let parent = |pointer: u32| word(&bytes, parents_at + 4 * ((target(pointer) - leaves_at) / UNIT)); + assert_eq!(parent(root), NO_NODE); + assert_eq!(target(root), nodes_at); + let mut seen = vec![0u32; count]; + let mut nodes = 0; + let mut stack = vec![root]; + while let Some(pointer) = stack.pop() { + assert_eq!(pointer & 7, BOX32); + nodes += 1; + for child in words(&bytes, target(pointer), 4) { + if child == NO_NODE { + continue; + } + assert_eq!(parent(child), pointer, "{count} triangles"); + match child & 7 { + BOX32 => stack.push(child), + TRIANGLE => seen[(target(child) - leaves_at) / UNIT] += 1, + kind => panic!("a child of kind {kind}"), + } + } + } + assert!(seen.iter().all(|times| *times == 1), "{count} triangles: {seen:?}"); + assert_eq!(bytes.len(), nodes_at + nodes * WIDE); + assert_eq!(nodes_at, leaves_at + count * UNIT); + assert_eq!(word(&bytes, 4) as usize, bytes.len() / UNIT - 1); + assert!(leaves_at - parents_at >= 4 * (count + 2 * nodes)); + } +} diff --git a/runtime/d3d12/src/tests/commands/console_walk.rs b/runtime/d3d12/src/tests/commands/console_walk.rs new file mode 100644 index 00000000..f0f77d86 --- /dev/null +++ b/runtime/d3d12/src/tests/commands/console_walk.rs @@ -0,0 +1,232 @@ +#![allow(dead_code)] +//! A walk of console structures on the CPU, for checking what the provider +//! writes against every triangle tried in turn. It reads what the public +//! traversal source reads: node pointers from the structure's start, the +//! root in the header, an instance's record as a walk enters it. + +const UNIT: usize = 64; +const NO_NODE: u32 = u32::MAX; +const IDENTITY_ROWS: u32 = 0x8000_0000; +const ROOT: u32 = 0x3fff_ffff; + +pub(super) fn word(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) +} + +pub(super) fn vector(bytes: &[u8], at: usize) -> [f64; 3] { + core::array::from_fn(|axis| f64::from(f32::from_bits(word(bytes, at + 4 * axis)))) +} + +pub(super) fn target(pointer: u32) -> usize { + (pointer >> 3) as usize * UNIT +} + +fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn dot(a: [f64; 3], b: [f64; 3]) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// How far along the ray it meets the triangle, and how close to an edge. +pub(super) fn meets(corners: &[[f64; 3]; 3], origin: [f64; 3], direction: [f64; 3]) -> Option<(f64, f64)> { + let (first, second) = (sub(corners[1], corners[0]), sub(corners[2], corners[0])); + let p = cross(direction, second); + let determinant = dot(first, p); + if determinant.abs() < 1e-18 { + return None; + } + let from = sub(origin, corners[0]); + let u = dot(from, p) / determinant; + let q = cross(from, first); + let v = dot(direction, q) / determinant; + let distance = dot(second, q) / determinant; + (u >= 0.0 && v >= 0.0 && u + v <= 1.0 && distance > 0.0).then_some((distance, u.min(v).min(1.0 - u - v))) +} + +/// A half-precision float. +fn half(bits: u32) -> f64 { + let (sign, exponent, fraction) = (bits >> 15 & 1, (bits >> 10 & 0x1f) as i32, f64::from(bits & 0x3ff)); + let magnitude = match exponent { + 0 => fraction * 2f64.powi(-24), + 31 if fraction == 0.0 => f64::INFINITY, + 31 => f64::NAN, + _ => (1.0 + fraction / 1024.0) * 2f64.powi(exponent - 15), + }; + if sign == 0 { magnitude } else { -magnitude } +} + +/// The box of slot `slot` of the 64-byte box node at `at`: six halves. +fn narrow_box(bytes: &[u8], at: usize, slot: usize) -> ([f64; 3], [f64; 3]) { + let value = |index: usize| half(word(bytes, at + 16 + 12 * slot + 4 * (index / 2)) >> (16 * (index % 2)) & 0xffff); + ([value(0), value(1), value(2)], [value(3), value(4), value(5)]) +} + +/// Whether the ray passes through the box at `at` before `limit`, with a +/// little room: a walk may test boxes more generously than exactly. +fn enters(bytes: &[u8], at: usize, origin: [f64; 3], direction: [f64; 3], limit: f64) -> bool { + passes((vector(bytes, at), vector(bytes, at + 12)), origin, direction, limit) +} + +fn passes((low, high): ([f64; 3], [f64; 3]), origin: [f64; 3], direction: [f64; 3], limit: f64) -> bool { + let (mut near, mut far) = (0.0f64, limit); + for axis in 0..3 { + let (a, b) = ((low[axis] - origin[axis]) / direction[axis], (high[axis] - origin[axis]) / direction[axis]); + near = near.max(a.min(b)); + far = far.min(a.max(b)); + } + near <= far + 1e-6 * far.abs().max(1.0) +} + +/// The nearest triangle of the bottom-level structure at `base`: its +/// distance, geometry index, primitive and closeness to an edge. A leaf is +/// read through a pointer of kind 0: its first triangle in slots 0, 1 and 2 +/// and, when its flags say it holds two, the second in slots 1, 3 and 2. Box +/// nodes are of kind 4 (64 bytes, halves) or 5 (128 bytes, floats). +pub(super) fn walk_structure( + heap: &[u8], + base: usize, + root: u32, + origin: [f64; 3], + direction: [f64; 3], + limit: f64, +) -> Option<(f64, u32, u32, f64)> { + let mut nearest = None; + let mut reach = limit; + let mut stack = vec![root]; + while let Some(pointer) = stack.pop() { + let at = base + target(pointer); + match pointer & 7 { + 0 => { + let named = word(heap, at + 48); + let slot = |slot: usize| vector(heap, at + 12 * slot); + let mut triangles = vec![([slot(0), slot(1), slot(2)], word(heap, at + 52))]; + if named & 0x80 != 0 { + triangles.push(([slot(1), slot(3), slot(2)], word(heap, at + 56))); + } + for (corners, primitive) in triangles { + if let Some((distance, edge)) = meets(&corners, origin, direction) + && distance < reach + { + reach = distance; + nearest = Some((distance, named >> 8, primitive, edge)); + } + } + } + 4 => { + for slot in 0..4 { + let child = word(heap, at + 4 * slot); + if child != NO_NODE && passes(narrow_box(heap, at, slot), origin, direction, reach) { + stack.push(child); + } + } + } + 5 => { + for slot in 0..4 { + let child = word(heap, at + 4 * slot); + if child != NO_NODE && enters(heap, at + 16 + 24 * slot, origin, direction, reach) { + stack.push(child); + } + } + } + kind => panic!("a bottom-level node of kind {kind}"), + } + } + nearest +} + +/// The nearest hit of the scene at `scene` in `heap`, entering instances as +/// the traversal source does: distance, the instance's place in the title's +/// array, geometry index, primitive and closeness to an edge. +pub(super) fn walk( + heap: &[u8], + scene: usize, + origin: [f32; 3], + direction: [f32; 3], +) -> Option<(f64, u32, u32, u32, f64)> { + let root = word(heap, scene + 48); + if root as i32 <= 0 { + return None; + } + let (origin, direction) = (origin.map(f64::from), direction.map(f64::from)); + let mut nearest = None; + let mut reach = f64::MAX; + let mut stack = vec![root]; + while let Some(pointer) = stack.pop() { + let at = scene + target(pointer); + match pointer & 7 { + 5 => { + for slot in 0..4 { + let child = word(heap, at + 4 * slot); + if child != NO_NODE && enters(heap, at + 16 + 24 * slot, origin, direction, reach) { + stack.push(child); + } + } + } + 6 => { + let (rooted, page) = (word(heap, at + 56), word(heap, at + 60)); + let moved = vector(heap, at + 64); + let rows = [vector(heap, at + 76), vector(heap, at + 88), vector(heap, at + 100)]; + let (mut from, mut along) = (origin, direction); + if rooted & IDENTITY_ROWS == 0 { + from = rows.map(|row| dot(row, origin)); + along = rows.map(|row| dot(row, direction)); + } + for axis in 0..3 { + from[axis] += moved[axis]; + } + let root = rooted & ROOT; + assert_ne!(root, ROOT); + if let Some((distance, geometry, primitive, edge)) = + walk_structure(heap, (page as usize) << 8, root, from, along, reach) + { + reach = distance; + nearest = Some((distance, word(heap, at + 112), geometry, primitive, edge)); + } + } + kind => panic!("a scene node of kind {kind}"), + } + } + nearest +} + +/// A generator of the same numbers every run. +use core::f32::consts::TAU; + +pub(super) struct Random(pub(super) u64); + +impl Random { + pub(super) fn next(&mut self) -> f32 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 >> 40) as f32 / (1u64 << 24) as f32 + } + + pub(super) fn between(&mut self, low: f32, high: f32) -> f32 { + low + (high - low) * self.next() + } + + pub(super) fn point(&mut self, reach: f32) -> [f32; 3] { + core::array::from_fn(|_| self.between(-reach, reach)) + } + + /// A turn, an uneven scale and a move. + pub(super) fn transform(&mut self) -> [f32; 12] { + let (a, b, c) = (self.between(0.0, TAU), self.between(0.0, TAU), self.between(0.0, TAU)); + let (sa, ca, sb, cb, sc, cc) = (a.sin(), a.cos(), b.sin(), b.cos(), c.sin(), c.cos()); + let turn = [ + [cb * cc, sa * sb * cc - ca * sc, ca * sb * cc + sa * sc], + [cb * sc, sa * sb * sc + ca * cc, ca * sb * sc - sa * cc], + [-sb, sa * cb, ca * cb], + ]; + let scale = [self.between(0.5, 2.0), self.between(0.5, 2.0), self.between(0.5, 2.0)]; + let moved = self.point(40.0); + core::array::from_fn(|at| if at % 4 == 3 { moved[at / 4] } else { turn[at / 4][at % 4] * scale[at % 4] }) + } +} diff --git a/runtime/d3d12/src/tests/device/console_heap.rs b/runtime/d3d12/src/tests/device/console_heap.rs index 85bf604a..a96b86a1 100644 --- a/runtime/d3d12/src/tests/device/console_heap.rs +++ b/runtime/d3d12/src/tests/device/console_heap.rs @@ -360,3 +360,110 @@ fn a_structure_is_found_by_each_address_it_is_named_at() { heap.forget(0x1000); assert!(heap.placed(0x1000).is_none() && heap.placed(0x2000).is_some()); } + +/// Names a structure of 600 bytes at `address`, sure to cover `extent` bytes there. +fn built(book: &mut Book, address: u64, extent: u64) { + let at = book.places.take(600, 0).unwrap(); + book.claim(&[address], extent, 0); + book.name(&[address], placed(at), 600, 0); +} + +#[test] +fn a_structure_built_inside_another_gives_the_other_up() { + let mut book = Book::new(1 << 20); + built(&mut book, 0x1000, 0x800); + built(&mut book, 0x1400, 0x100); + assert!(!book.structures.contains_key(&0x1000)); + assert!(book.structures.contains_key(&0x1400)); + assert_eq!((book.overlapped, book.named.len(), book.extents.len()), (1, 1, 1)); +} + +#[test] +fn a_structure_that_reaches_a_later_address_gives_that_one_up() { + let mut book = Book::new(1 << 20); + built(&mut book, 0x1400, 0x100); + built(&mut book, 0x17ff, 0x100); + built(&mut book, 0x1000, 0x800); + assert!(book.structures.contains_key(&0x1000)); + assert!(!book.structures.contains_key(&0x1400) && !book.structures.contains_key(&0x17ff)); + assert_eq!((book.overlapped, book.named.len()), (2, 1)); +} + +#[test] +fn structures_side_by_side_are_both_kept() { + let mut book = Book::new(1 << 20); + built(&mut book, 0x1000, 0x400); + built(&mut book, 0x1400, 0x400); + built(&mut book, 0xc00, 0x400); + assert_eq!((book.overlapped, book.structures.len(), book.extents.len()), (0, 3, 3)); +} + +#[test] +fn a_structure_keeps_the_other_address_it_is_named_at_and_claims_nothing_without_an_extent() { + let mut book = Book::new(1 << 20); + let at = book.places.take(600, 0).unwrap(); + book.claim(&[0x1000, 0x1200], 0x400, 0); + book.name(&[0x1000, 0x1200], placed(at), 600, 0); + assert_eq!((book.overlapped, book.structures.len()), (0, 2)); + // No extent: nothing is given up, even an address one byte further. + let other = book.places.take(600, 0).unwrap(); + book.claim(&[0xfff], 0, 0); + book.name(&[0xfff], placed(other), 600, 0); + assert_eq!((book.overlapped, book.structures.len()), (0, 3)); +} + +#[test] +fn a_structure_forgotten_no_longer_claims_its_bytes() { + let mut book = Book::new(1 << 20); + built(&mut book, 0x1000, 0x800); + book.forget(0x1000, 0); + built(&mut book, 0x1400, 0x100); + assert_eq!((book.overlapped, book.structures.len(), book.extents.len()), (0, 1, 1)); +} + +#[test] +fn a_structure_that_finds_no_place_still_gives_up_what_the_title_built_over() { + let mut book = Book::new(1 << 20); + built(&mut book, 0x1400, 0x100); + assert!(!book.built_over(&[0x1000], None, 600, 0x800, 0)); + assert!(!book.structures.contains_key(&0x1400) && !book.structures.contains_key(&0x1000)); + assert_eq!((book.overlapped, book.named.len(), book.extents.len()), (1, 0, 0)); +} + +fn pending(generation: u64) -> Reread { + Reread { generation, due: 0, digest: 0, geometry: Vec::new() } +} + +#[test] +fn a_reading_pending_at_an_address_a_later_structure_covers_is_dropped() { + let mut book = Book::new(1 << 20); + // Its first reading failed, so it placed nothing and holds no bytes. + let generation = book.begun(0x1400); + book.read_again(0x1400, pending(generation)); + built(&mut book, 0x1000, 0x800); + assert!(book.take_due(u64::MAX).is_empty()); + assert!(!book.current(0x1400, generation)); +} + +#[test] +fn a_reading_taken_before_the_title_builds_there_again_is_no_longer_current() { + let mut book = Book::new(1 << 20); + let generation = book.begun(0x1000); + book.read_again(0x1000, pending(generation)); + assert_eq!(book.take_due(u64::MAX).len(), 1); + assert!(book.current(0x1000, generation)); + let again = book.begun(0x1000); + assert!(!book.current(0x1000, generation) && book.current(0x1000, again)); +} + +#[test] +fn a_reading_waits_in_its_own_buffer_only_and_only_for_the_last_build_at_its_address() { + let (mut one, mut other) = (Book::new(1 << 20), Book::new(1 << 20)); + let generation = one.begun(0x1000); + one.read_again(0x1000, pending(generation)); + assert!(other.take_due(u64::MAX).is_empty()); + let earlier = one.begun(0x2000); + one.begun(0x2000); + one.read_again(0x2000, pending(earlier)); + assert_eq!(one.take_due(u64::MAX).iter().map(|(at, _)| *at).collect::>(), [0x1000]); +}