use core::ops::Range;
use crcbl_core::{Handle, Pool};
use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
use crcbl_shaders::mesh::{GpuInstance, INSTANCE_STRIDE};
#[derive(Debug)]
pub enum Instance {}
pub type InstanceHandle = Handle<Instance>;
#[derive(Debug, thiserror::Error)]
pub enum InstancePoolError {
#[error("the instance pool holds {capacity} instances and {in_use} of them are in use")]
PoolFull {
capacity: u32,
in_use: u32,
},
#[error(transparent)]
Hal(#[from] HalError),
}
impl From<InstancePoolError> for HalError {
fn from(error: InstancePoolError) -> Self {
match error {
InstancePoolError::Hal(hal) => hal,
other => Self::Backend(other.to_string()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InstancePoolDesc<'a> {
pub label: Option<&'a str>,
pub capacity: u32,
pub frames_in_flight: usize,
}
#[derive(Debug)]
pub struct InstancePool {
buffers: Vec<BufferHandle>,
dirty: Vec<DirtyRanges>,
frame: usize,
mirror: Vec<u8>,
slots: Pool<()>,
written_this_frame: Vec<u32>,
written_last_frame: Vec<u32>,
moved_mark: Vec<bool>,
capacity: u32,
high_water: u32,
revision: u64,
written_since_taken: Vec<u32>,
written_since_taken_mark: Vec<bool>,
}
impl InstancePool {
pub fn new(
device: &dyn Device,
desc: &InstancePoolDesc<'_>,
) -> Result<Self, InstancePoolError> {
assert!(
desc.frames_in_flight > 0,
"an instance pool needs at least one buffer to bind"
);
let stem = desc.label.unwrap_or("instance pool");
let size = u64::from(desc.capacity) * INSTANCE_STRIDE as u64;
let cleared = vec![0u8; desc.capacity as usize * INSTANCE_STRIDE];
let mut buffers = Vec::with_capacity(desc.frames_in_flight);
for frame in 0..desc.frames_in_flight {
let created = device
.create_buffer(&BufferDesc {
label: Some(&format!("{stem} instances {frame}")),
size,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})
.and_then(|buffer| match device.write_buffer(buffer, 0, &cleared) {
Ok(()) => Ok(buffer),
Err(error) => {
device.destroy_buffer(buffer);
Err(error)
}
});
match created {
Ok(buffer) => buffers.push(buffer),
Err(error) => {
for buffer in buffers {
device.destroy_buffer(buffer);
}
return Err(error.into());
}
}
}
Ok(Self {
buffers,
dirty: vec![DirtyRanges::default(); desc.frames_in_flight],
frame: 0,
mirror: vec![0; desc.capacity as usize * INSTANCE_STRIDE],
slots: Pool::new(),
written_this_frame: Vec::new(),
written_last_frame: Vec::new(),
moved_mark: vec![false; desc.capacity as usize],
capacity: desc.capacity,
high_water: 0,
revision: 0,
written_since_taken: Vec::new(),
written_since_taken_mark: vec![false; desc.capacity as usize],
})
}
#[must_use]
pub fn buffers(&self) -> &[BufferHandle] {
&self.buffers
}
#[must_use]
pub const fn capacity(&self) -> u32 {
self.capacity
}
#[must_use]
pub const fn len(&self) -> usize {
self.slots.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.slots.is_empty()
}
#[must_use]
pub const fn revision(&self) -> u64 {
self.revision
}
pub fn take_written(&mut self, into: &mut Vec<u32>) {
for index in self.written_since_taken.drain(..) {
self.written_since_taken_mark[index as usize] = false;
into.push(index);
}
}
#[must_use]
pub fn record(&self, index: u32) -> Option<GpuInstance> {
(index < self.high_water).then(|| self.read(index))
}
#[must_use]
pub const fn slot_count(&self) -> u32 {
self.high_water
}
pub fn insert(&mut self, instance: &GpuInstance) -> Result<InstanceHandle, InstancePoolError> {
let in_use = self.in_use();
if in_use >= self.capacity {
return Err(InstancePoolError::PoolFull {
capacity: self.capacity,
in_use,
});
}
let handle: InstanceHandle = self.slots.insert(()).cast();
self.high_water = self.high_water.max(handle.index() + 1);
self.write_live(handle.index(), instance, instance.transform);
Ok(handle)
}
pub fn set(&mut self, handle: InstanceHandle, instance: &GpuInstance) -> bool {
if !self.slots.contains(handle.cast()) {
return false;
}
let previous = self.read(handle.index()).transform;
self.write_live(handle.index(), instance, previous);
true
}
pub fn set_bases(
&mut self,
handle: InstanceHandle,
base_vertex: u32,
previous_base_vertex: u32,
) -> bool {
if !self.slots.contains(handle.cast()) {
return false;
}
let index = handle.index();
let mut record = self.read(index);
record.base_vertex = base_vertex;
record.previous_base_vertex = previous_base_vertex;
self.write(index, &record);
true
}
pub fn set_flags(&mut self, handle: InstanceHandle, flags: u32) -> bool {
if !self.slots.contains(handle.cast()) {
return false;
}
let index = handle.index();
let mut record = self.read(index);
record.flags = flags | GpuInstance::LIVE;
self.write(index, &record);
true
}
pub fn clear_flags(&mut self, bits: u32) {
let bits = bits & !GpuInstance::LIVE;
for index in 0..self.high_water {
let mut record = self.read(index);
if record.flags & GpuInstance::LIVE == 0 || record.flags & bits == 0 {
continue;
}
record.flags &= !bits;
self.write(index, &record);
}
}
#[must_use]
pub fn get(&self, handle: InstanceHandle) -> Option<GpuInstance> {
self.slots
.contains(handle.cast())
.then(|| self.read(handle.index()))
}
#[must_use]
pub fn live(&self) -> Vec<GpuInstance> {
(0..self.high_water)
.map(|index| self.read(index))
.filter(|record| record.flags & GpuInstance::LIVE != 0)
.collect()
}
#[must_use]
pub fn records(&self) -> Vec<GpuInstance> {
(0..self.high_water).map(|index| self.read(index)).collect()
}
#[must_use]
pub fn index(&self, handle: InstanceHandle) -> Option<u32> {
self.slots.contains(handle.cast()).then(|| handle.index())
}
pub fn remove(&mut self, handle: InstanceHandle) -> bool {
if self.slots.remove(handle.cast()).is_none() {
return false;
}
let index = handle.index();
let mut removed = self.read(index);
removed.flags &= !GpuInstance::LIVE;
self.write(index, &removed);
true
}
pub fn begin_frame(&mut self, device: &dyn Device) -> Result<usize, HalError> {
let slot = self.rotate();
self.flush(device)?;
Ok(slot)
}
pub fn rotate(&mut self) -> usize {
self.carry_forward();
self.frame = (self.frame + 1) % self.buffers.len();
self.frame
}
pub fn flush(&mut self, device: &dyn Device) -> Result<(), HalError> {
let slot = self.frame;
let buffer = self.buffers[slot];
let mut runs = core::mem::take(&mut self.dirty[slot].runs);
for (done, run) in runs.iter().enumerate() {
let at = run.start as usize * INSTANCE_STRIDE;
let end = run.end as usize * INSTANCE_STRIDE;
if let Err(error) = device.write_buffer(buffer, at as u64, &self.mirror[at..end]) {
runs.drain(..done);
self.dirty[slot].runs = runs;
return Err(error);
}
}
runs.clear();
self.dirty[slot].runs = runs;
Ok(())
}
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(super) fn replace_test_buffer(
&mut self,
slot: usize,
replacement: BufferHandle,
) -> BufferHandle {
core::mem::replace(&mut self.buffers[slot], replacement)
}
pub fn destroy(self, device: &dyn Device) {
for buffer in self.buffers {
device.destroy_buffer(buffer);
}
}
fn in_use(&self) -> u32 {
let used = self.slots.len() + self.slots.retired_slots();
u32::try_from(used).unwrap_or(u32::MAX)
}
fn read(&self, index: u32) -> GpuInstance {
let at = index as usize * INSTANCE_STRIDE;
let bytes: &[u8; INSTANCE_STRIDE] = self.mirror[at..at + INSTANCE_STRIDE]
.try_into()
.unwrap_or_else(|_| unreachable!("the mirror is capacity × INSTANCE_STRIDE"));
GpuInstance::from_bytes(bytes)
}
fn write_live(&mut self, index: u32, instance: &GpuInstance, previous: [f32; 16]) {
self.write(
index,
&GpuInstance {
flags: instance.flags | GpuInstance::LIVE,
previous_transform: previous,
..*instance
},
);
if !self.moved_mark[index as usize] {
self.moved_mark[index as usize] = true;
self.written_this_frame.push(index);
}
}
fn carry_forward(&mut self) {
for at in 0..self.written_last_frame.len() {
let index = self.written_last_frame[at];
if self.moved_mark[index as usize] {
continue;
}
let mut record = self.read(index);
if record.previous_transform == record.transform {
continue;
}
record.previous_transform = record.transform;
self.write(index, &record);
}
self.written_last_frame.clear();
core::mem::swap(&mut self.written_last_frame, &mut self.written_this_frame);
for index in &self.written_last_frame {
self.moved_mark[*index as usize] = false;
}
}
fn write(&mut self, index: u32, instance: &GpuInstance) {
let at = index as usize * INSTANCE_STRIDE;
self.mirror[at..at + INSTANCE_STRIDE].copy_from_slice(&instance.to_bytes());
self.revision = self.revision.wrapping_add(1);
if !self.written_since_taken_mark[index as usize] {
self.written_since_taken_mark[index as usize] = true;
self.written_since_taken.push(index);
}
for dirty in &mut self.dirty {
dirty.mark(index);
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct DirtyRanges {
runs: Vec<Range<u32>>,
}
impl DirtyRanges {
fn mark(&mut self, index: u32) {
let at = self.runs.partition_point(|run| run.end < index);
if self.runs.get(at).is_some_and(|run| run.start <= index) {
if self.runs[at].end == index {
self.runs[at].end = index + 1;
if self
.runs
.get(at + 1)
.is_some_and(|next| next.start == index + 1)
{
let end = self.runs.remove(at + 1).end;
self.runs[at].end = end;
}
}
return;
}
if self.runs.get(at).is_some_and(|run| run.start == index + 1) {
self.runs[at].start = index;
return;
}
self.runs.insert(at, index..index + 1);
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{Event, NullInstance, Recorder};
use crcbl_hal::{DeviceDesc, Instance};
const FRAMES: usize = 2;
fn open() -> (Recorder, Box<dyn Device>) {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let adapter = instance.adapters().remove(0);
let device = instance
.create_device(&DeviceDesc::for_adapter(adapter.id))
.expect("the null backend always opens");
(recorder, device)
}
fn pool(device: &dyn Device, capacity: u32) -> InstancePool {
InstancePool::new(
device,
&InstancePoolDesc {
label: Some("test"),
capacity,
frames_in_flight: FRAMES,
},
)
.expect("the null backend accepts every descriptor")
}
fn instance(n: u32) -> GpuInstance {
GpuInstance {
transform: [n as f32; 16],
previous_transform: [0.0; 16],
mesh: n,
material: n + 1,
sector: n + 2,
flags: n + 3,
base_vertex: n + 4,
previous_base_vertex: n + 5,
}
}
fn stored(n: u32) -> GpuInstance {
let caller = instance(n);
assert_eq!(
caller.flags & GpuInstance::LIVE,
0,
"instance({n}) already carries the live bit; pick another n"
);
assert_ne!(
n, 0,
"instance(0)'s transform is its own zeroed previous one"
);
GpuInstance {
flags: caller.flags | GpuInstance::LIVE,
previous_transform: caller.transform,
..caller
}
}
fn stored_after(n: u32, was: u32) -> GpuInstance {
GpuInstance {
previous_transform: instance(was).transform,
..stored(n)
}
}
fn on_device(recorder: &Recorder, pool: &InstancePool, slot: usize, index: u32) -> GpuInstance {
let bytes = recorder
.buffer_bytes(pool.buffers()[slot])
.expect("the buffer is live");
let at = index as usize * INSTANCE_STRIDE;
GpuInstance::from_bytes(
bytes[at..at + INSTANCE_STRIDE]
.try_into()
.expect("one element"),
)
}
fn writes(recorder: &Recorder) -> Vec<(u64, usize)> {
recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::BufferWritten { offset, len, .. } => Some((offset, len)),
_ => None,
})
.collect()
}
fn settle(pool: &mut InstancePool, device: &dyn Device) {
for _ in 0..FRAMES {
pool.begin_frame(device).expect("the null device writes");
}
}
fn runs(dirty: &DirtyRanges) -> Vec<(u32, u32)> {
dirty.runs.iter().map(|run| (run.start, run.end)).collect()
}
mod scratch;
#[test]
fn adjacent_marks_coalesce_and_separated_ones_do_not() {
let mut dirty = DirtyRanges::default();
for index in [3u32, 4, 5] {
dirty.mark(index);
}
assert_eq!(runs(&dirty), [(3, 6)], "3, 4 and 5 are one run of three");
let mut dirty = DirtyRanges::default();
dirty.mark(3);
dirty.mark(900);
assert_eq!(runs(&dirty), [(3, 4), (900, 901)], "a gap stays a gap");
}
#[test]
fn the_boundary_between_touching_and_separated_is_one_element() {
for (second, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
let mut dirty = DirtyRanges::default();
dirty.mark(3);
dirty.mark(second);
assert_eq!(runs(&dirty), expected, "marking 3 then {second}");
}
for (first, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
let mut dirty = DirtyRanges::default();
dirty.mark(first);
dirty.mark(3);
assert_eq!(runs(&dirty), expected, "marking {first} then 3");
}
}
#[test]
fn closing_the_gap_between_two_runs_merges_them() {
let mut dirty = DirtyRanges::default();
dirty.mark(3);
dirty.mark(5);
assert_eq!(runs(&dirty), [(3, 4), (5, 6)]);
dirty.mark(4);
assert_eq!(runs(&dirty), [(3, 6)], "one run of three, not two touching");
}
#[test]
fn coalescing_does_not_depend_on_the_order_marks_arrive_in() {
let marks = [7u32, 3, 5, 4, 900, 6];
let mut permuted = marks;
for shift in 0..marks.len() {
permuted.rotate_left(shift.min(1));
let mut dirty = DirtyRanges::default();
for index in permuted {
dirty.mark(index);
}
assert_eq!(
runs(&dirty),
[(3, 8), (900, 901)],
"the order {permuted:?} produced different runs"
);
}
}
#[test]
fn marking_the_same_element_twice_changes_nothing() {
let mut dirty = DirtyRanges::default();
dirty.mark(3);
dirty.mark(3);
assert_eq!(runs(&dirty), [(3, 4)]);
dirty.mark(4);
dirty.mark(5);
dirty.mark(4);
assert_eq!(runs(&dirty), [(3, 6)]);
}
#[test]
fn a_frame_with_no_writes_uploads_nothing() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
pool.insert(&instance(1)).expect("room");
settle(&mut pool, device.as_ref());
let before = writes(&recorder).len();
assert!(before > 0, "the insert must have reached the device at all");
for _ in 0..FRAMES * 3 {
pool.begin_frame(device.as_ref()).expect("writes");
}
assert_eq!(
writes(&recorder).len(),
before,
"six frames with nothing written must perform no seam call"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn every_write_moves_the_revision_and_a_still_frame_does_not() {
let (recorder, device) = open();
let device = device.as_ref();
let mut pool = pool(device, 16);
let start = pool.revision();
let first = pool.insert(&instance(1)).expect("room");
let inserted = pool.revision();
assert!(inserted > start, "an insert did not move the revision");
assert!(pool.set(first, &instance(2)), "the handle is live");
let written = pool.revision();
assert!(written > inserted, "a rewrite did not move the revision");
assert!(
pool.set(first, &instance(2)),
"a rewrite with the same bytes is still a write — see `InstancePool::set`"
);
let repeated = pool.revision();
assert!(
repeated > written,
"a rewrite the pool does not filter must not be filtered here either"
);
assert!(pool.set_bases(first, 4, 8), "the handle is live");
let repointed = pool.revision();
assert!(repointed > repeated, "a re-point did not move the revision");
assert!(pool.set(first, &instance(3)), "the handle is live");
let moved = pool.revision();
assert!(moved > repointed, "a move did not move the revision");
settle(&mut pool, device);
let settled = pool.revision();
assert!(
settled > moved,
"the carry-forward wrote the mirror without saying so"
);
for _ in 0..FRAMES * 3 {
pool.begin_frame(device).expect("the null device writes");
}
assert_eq!(
pool.revision(),
settled,
"a run of frames nobody wrote in moved the revision, so nothing derived from this \
array could ever be kept"
);
assert!(pool.remove(first), "the handle is live");
assert!(
pool.revision() > settled,
"a removal did not move the revision, so an instance that left the scene would go \
on casting a shadow"
);
pool.destroy(device);
recorder.assert_valid();
}
#[test]
fn every_write_names_its_element_once_and_a_still_frame_names_none() {
let (recorder, device) = open();
let device = device.as_ref();
let mut pool = pool(device, 16);
let taken = |pool: &mut InstancePool| {
let mut into = Vec::new();
pool.take_written(&mut into);
into
};
let first = pool.insert(&instance(1)).expect("room");
let second = pool.insert(&instance(2)).expect("room");
assert!(pool.set(first, &instance(3)), "the handle is live");
assert_eq!(
taken(&mut pool),
[0, 1],
"two inserts and a rewrite of the first name each element once, first write first"
);
assert!(taken(&mut pool).is_empty(), "a taken log is forgotten");
assert!(pool.set(second, &instance(2)), "the handle is live");
assert_eq!(
taken(&mut pool),
[1],
"a same-bytes rewrite is still a write"
);
assert!(pool.set_bases(first, 4, 8), "the handle is live");
assert_eq!(taken(&mut pool), [0], "a re-point is a write");
assert!(pool.set_flags(second, 1 << 8), "the handle is live");
assert_eq!(taken(&mut pool), [1], "a flag is a write");
pool.clear_flags(1 << 8);
assert_eq!(
taken(&mut pool),
[1],
"clearing a flag writes what carried it"
);
settle(&mut pool, device);
assert_eq!(
taken(&mut pool),
[0],
"the carry-forward wrote the mirror without naming the element"
);
for _ in 0..FRAMES * 3 {
pool.begin_frame(device).expect("the null device writes");
}
assert!(
taken(&mut pool).is_empty(),
"a run of frames nobody wrote in named an element"
);
assert!(pool.remove(first), "the handle is live");
assert_eq!(taken(&mut pool), [0], "a removal is a write");
let record = pool.record(0).expect("below the high-water mark");
assert_eq!(
record.flags & GpuInstance::LIVE,
0,
"a removed element reads back dead"
);
assert!(pool.record(2).is_none(), "past the high-water mark");
pool.destroy(device);
recorder.assert_valid();
}
#[test]
fn adjacent_writes_reach_the_device_as_one_call() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 1024);
let handles: Vec<_> = (0..6)
.map(|n| pool.insert(&instance(n)).expect("room"))
.collect();
settle(&mut pool, device.as_ref());
let before = writes(&recorder).len();
for handle in &handles[3..6] {
pool.set(*handle, &instance(99));
}
pool.begin_frame(device.as_ref()).expect("writes");
assert_eq!(
writes(&recorder)[before..],
[(3 * INSTANCE_STRIDE as u64, 3 * INSTANCE_STRIDE)],
"instances 3, 4 and 5 must be one write of three elements"
);
settle(&mut pool, device.as_ref());
let before = writes(&recorder).len();
pool.set(handles[0], &instance(98));
pool.set(handles[5], &instance(98));
pool.begin_frame(device.as_ref()).expect("writes");
assert_eq!(
writes(&recorder)[before..],
[
(0, INSTANCE_STRIDE),
(5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)
],
"instances 0 and 5 are not adjacent and must be two writes"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_write_reaches_every_buffer_in_the_ring() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(1)).expect("room");
settle(&mut pool, device.as_ref());
pool.set(handle, &instance(2));
let mut written_to = Vec::new();
for _ in 0..FRAMES {
let slot = pool.begin_frame(device.as_ref()).expect("writes");
written_to.push(pool.buffers()[slot]);
}
let targets: Vec<BufferHandle> = recorder
.events()
.into_iter()
.filter_map(|event| match event {
Event::BufferWritten { buffer, .. } => Some(buffer),
_ => None,
})
.collect();
for buffer in pool.buffers() {
assert!(
targets.contains(buffer),
"buffer {buffer:?} never received the instance"
);
}
assert_eq!(written_to.len(), FRAMES);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_full_pool_fails_by_name_and_takes_nothing() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 2);
let first = pool.insert(&instance(0)).expect("room");
pool.insert(&instance(1)).expect("room");
let error = pool
.insert(&instance(2))
.expect_err("two instances fill a pool of two");
assert!(
matches!(
error,
InstancePoolError::PoolFull {
capacity: 2,
in_use: 2
}
),
"got: {error:?}"
);
assert_eq!(pool.len(), 2, "a refused insert must not consume a slot");
assert!(pool.remove(first));
let reused = pool.insert(&instance(3)).expect("the freed slot");
assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
assert_eq!(pool.index(first), None, "and the old handle is retired");
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn the_slot_count_covers_every_occupied_element_and_never_shrinks() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 8);
assert_eq!(pool.slot_count(), 0, "an empty pool has nothing to walk");
let handles: Vec<InstanceHandle> = (0..3)
.map(|index| pool.insert(&instance(index)).expect("room"))
.collect();
assert_eq!(pool.slot_count(), 3);
assert!(pool.remove(handles[1]));
assert_eq!(pool.len(), 2, "two are live");
assert_eq!(
pool.slot_count(),
3,
"and the highest is still at element 2, so a walk must still reach it"
);
pool.insert(&instance(9)).expect("the freed slot");
assert_eq!(pool.slot_count(), 3);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn the_ring_is_one_buffer_per_frame_in_flight() {
let (recorder, device) = open();
let pool = pool(device.as_ref(), 16);
assert_eq!(pool.buffers().len(), FRAMES);
let mut distinct = pool.buffers().to_vec();
distinct.sort_unstable_by_key(|buffer| buffer.to_bits());
distinct.dedup();
assert_eq!(distinct.len(), FRAMES, "the slots must not share a buffer");
assert_eq!(pool.capacity(), 16);
assert!(pool.is_empty());
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn every_buffer_is_cleared_when_the_pool_is_created() {
let (recorder, device) = open();
let pool = pool(device.as_ref(), 16);
assert_eq!(
writes(&recorder),
vec![(0, 16 * INSTANCE_STRIDE); FRAMES],
"each buffer in the ring must be cleared, whole, before anything reads it"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instance_carries_where_it_was_last_frame() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(7)).expect("room");
settle(&mut pool, device.as_ref());
let index = pool.index(handle).expect("live");
let slot = pool.frame;
assert_eq!(
on_device(&recorder, &pool, slot, index).previous_transform,
instance(7).transform,
"a spawn did not travel from anywhere"
);
assert!(pool.set(handle, &instance(11)));
let slot = pool
.begin_frame(device.as_ref())
.expect("the null device writes");
let moved = on_device(&recorder, &pool, slot, index);
assert_eq!(moved.transform, instance(11).transform, "it arrived");
assert_eq!(
moved.previous_transform,
instance(7).transform,
"and it says where from"
);
let slot = pool
.begin_frame(device.as_ref())
.expect("the null device writes");
let stopped = on_device(&recorder, &pool, slot, index);
assert_eq!(
stopped.transform,
instance(11).transform,
"it has not moved"
);
assert_eq!(
stopped.previous_transform, stopped.transform,
"so it must report no motion"
);
settle(&mut pool, device.as_ref());
for slot in 0..FRAMES {
let resting = on_device(&recorder, &pool, slot, index);
assert_eq!(
resting.previous_transform, resting.transform,
"buffer {slot} still has it moving"
);
}
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instance_still_moving_is_not_put_at_rest() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(1)).expect("room");
settle(&mut pool, device.as_ref());
let index = pool.index(handle).expect("live");
for step in 2..6u32 {
assert!(pool.set(handle, &instance(step)));
let slot = pool
.begin_frame(device.as_ref())
.expect("the null device writes");
let moving = on_device(&recorder, &pool, slot, index);
assert_eq!(
(moving.previous_transform, moving.transform),
(instance(step - 1).transform, instance(step).transform),
"the frame that moved it to {step} lost one end of the move"
);
}
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn setting_the_bases_keeps_the_transform_the_record_moved_from() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(7)).expect("room");
assert!(pool.set(handle, &instance(11)), "the handle is live");
assert!(pool.set_bases(handle, 40, 41), "the handle is still live");
let repointed = GpuInstance {
base_vertex: 40,
previous_base_vertex: 41,
..stored_after(11, 7)
};
assert_eq!(
pool.get(handle),
Some(repointed),
"a re-point owes the two bases it was given and every other field the record \
already held — the previous transform above all"
);
let index = pool.index(handle).expect("live");
let slot = pool
.begin_frame(device.as_ref())
.expect("the null device writes");
assert_eq!(
on_device(&recorder, &pool, slot, index),
repointed,
"the buffer this frame draws from did not take the re-point, so a shader reads \
the bases of the frame before"
);
assert!(pool.remove(handle));
for _ in 0..FRAMES * 2 {
pool.begin_frame(device.as_ref())
.expect("the null device writes");
}
recorder.clear();
assert!(
!pool.set_bases(handle, 60, 61),
"a retired handle names no instance"
);
for _ in 0..FRAMES * 2 {
pool.begin_frame(device.as_ref())
.expect("the null device writes");
}
assert_eq!(
writes(&recorder),
[],
"a stale re-point marked a slot dirty, so it wrote into whatever took it"
);
for slot in 0..FRAMES {
let dead = on_device(&recorder, &pool, slot, index);
assert_eq!(
(dead.base_vertex, dead.previous_base_vertex),
(40, 41),
"buffer {slot} took a stale handle's bases"
);
}
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instance_at_rest_is_uploaded_once_and_then_never() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(7)).expect("room");
settle(&mut pool, device.as_ref());
assert!(pool.set(handle, &instance(11)));
settle(&mut pool, device.as_ref());
recorder.clear();
pool.begin_frame(device.as_ref())
.expect("the null device writes");
let carried = writes(&recorder).len();
assert_eq!(
carried, 1,
"the buffer that had not seen the carry-forward yet should have taken it, \
and {carried} write(s) says the carry-forward never reached the device"
);
recorder.clear();
for _ in 0..FRAMES * 2 {
pool.begin_frame(device.as_ref())
.expect("the null device writes");
}
assert_eq!(
writes(&recorder),
[],
"an instance nobody has written costs no upload"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instance_round_trips_through_the_pool() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let handle = pool.insert(&instance(7)).expect("room");
assert_eq!(pool.get(handle), Some(stored(7)));
assert!(pool.set(handle, &instance(11)));
assert_eq!(
pool.get(handle),
Some(stored_after(11, 7)),
"a rewrite keeps where the instance was"
);
assert!(pool.remove(handle));
assert_eq!(
pool.get(handle),
None,
"a removed handle resolves to nothing"
);
assert!(!pool.set(handle, &instance(12)), "and cannot be written");
assert!(!pool.remove(handle), "and cannot be removed twice");
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn removing_an_instance_clears_its_live_bit_on_the_device() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let first = pool.insert(&instance(1)).expect("room");
let second = pool.insert(&instance(3)).expect("room");
settle(&mut pool, device.as_ref());
for slot in 0..FRAMES {
assert_eq!(
on_device(&recorder, &pool, slot, 0),
stored(1),
"buffer {slot} did not receive the live instance"
);
}
assert!(pool.remove(first));
settle(&mut pool, device.as_ref());
for slot in 0..FRAMES {
let removed = on_device(&recorder, &pool, slot, 0);
assert_eq!(
removed.flags & GpuInstance::LIVE,
0,
"buffer {slot} still holds a live instance at the removed slot: {removed:?}"
);
assert_eq!(
removed,
GpuInstance {
flags: stored(1).flags & !GpuInstance::LIVE,
..stored(1)
},
"buffer {slot} rewrote more than the flags word"
);
assert_eq!(
on_device(&recorder, &pool, slot, 1),
stored(3),
"buffer {slot} disturbed the instance beside the removed one"
);
}
assert_eq!(
pool.get(second),
Some(stored(3)),
"and the other handle still resolves"
);
let before = writes(&recorder).len();
assert!(!pool.remove(first));
settle(&mut pool, device.as_ref());
assert_eq!(
writes(&recorder).len(),
before,
"removing a retired handle must upload nothing"
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_reused_slot_is_live_again_with_its_new_contents() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
let first = pool.insert(&instance(1)).expect("room");
assert!(pool.remove(first));
settle(&mut pool, device.as_ref());
let reused = pool.insert(&instance(5)).expect("the freed slot");
assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
settle(&mut pool, device.as_ref());
for slot in 0..FRAMES {
assert_eq!(
on_device(&recorder, &pool, slot, 0),
stored(5),
"buffer {slot} holds neither the new instance nor the live bit"
);
}
assert_eq!(pool.get(reused), Some(stored(5)));
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn an_instances_offset_is_its_index_times_the_stride() {
let (recorder, device) = open();
let mut pool = pool(device.as_ref(), 16);
for n in 0..5 {
pool.insert(&instance(n)).expect("room");
}
settle(&mut pool, device.as_ref());
let handle = pool.insert(&instance(5)).expect("room");
assert_eq!(pool.index(handle), Some(5));
let before = writes(&recorder).len();
pool.begin_frame(device.as_ref()).expect("writes");
assert_eq!(
writes(&recorder)[before..],
[(5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)]
);
pool.destroy(device.as_ref());
recorder.assert_valid();
}
#[test]
fn a_pool_leaks_nothing() {
let (recorder, device) = open();
let before = recorder.total_live_objects();
let mut pool = pool(device.as_ref(), 16);
pool.insert(&instance(0)).expect("room");
settle(&mut pool, device.as_ref());
assert!(recorder.total_live_objects() > before);
pool.destroy(device.as_ref());
assert_eq!(
recorder.total_live_objects(),
before,
"every buffer created must be destroyed"
);
recorder.assert_valid();
}
#[test]
fn a_pool_error_flattens_into_the_seams_without_losing_its_message() {
let full = InstancePoolError::PoolFull {
capacity: 4,
in_use: 4,
};
let message = full.to_string();
assert_eq!(HalError::from(full).to_string(), message);
let hal = InstancePoolError::Hal(HalError::OutOfDeviceMemory);
assert!(
matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
"a HalError must not be stringified on the way through"
);
}
}