use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crcbl_hal::{
BufferCopy, BufferDesc, BufferHandle, BufferUsage, Device, MemoryLocation, ReadbackDesc,
ReadbackHandle, ReadbackState, ResourceState,
};
use crcbl_shaders::cull;
use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
const SLOT_BYTES: u64 = cull::STATS_WORDS as u64 * 4;
const POLL_DEADLINE: u64 = 120;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ClusterCull {
pub survivors: u64,
pub frustum_rejects: u64,
pub cone_rejects: u64,
}
impl ClusterCull {
#[must_use]
pub const fn tested(&self) -> u64 {
self.survivors + self.frustum_rejects + self.cone_rejects
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OcclusionCull {
pub early_rejects: u64,
pub late_rejects: u64,
pub small_feature_rejects: u64,
}
impl OcclusionCull {
#[must_use]
pub const fn rescued(&self) -> u64 {
self.early_rejects.saturating_sub(self.late_rejects)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CullStats {
pub instances: u64,
pub clusters: Option<ClusterCull>,
pub occlusion: OcclusionCull,
pub frame: u64,
}
#[derive(Debug)]
enum SlotState {
Idle,
Recording,
Polling {
frame: u64,
since: u64,
readback: ReadbackHandle,
},
}
#[derive(Debug)]
struct Slot {
buffer: BufferHandle,
imported: ResourceState,
state: SlotState,
}
#[derive(Debug)]
pub struct CullStatsRing {
slots: Vec<Slot>,
next: usize,
recorded: Arc<AtomicU64>,
counts_clusters: bool,
frames: u64,
latest: Option<CullStats>,
off: bool,
}
impl CullStatsRing {
#[must_use]
pub fn new(
device: &dyn Device,
frames_in_flight: usize,
counts_clusters: bool,
) -> Option<Self> {
let count = frames_in_flight.max(1) + 1;
let mut slots = Vec::with_capacity(count);
for index in 0..count {
match device.create_buffer(&BufferDesc {
label: Some("cull stats readback"),
size: SLOT_BYTES,
usage: BufferUsage::TRANSFER_DST,
memory: MemoryLocation::HostReadback,
}) {
Ok(buffer) => slots.push(Slot {
buffer,
imported: ResourceState::Undefined,
state: SlotState::Idle,
}),
Err(error) => {
crcbl_core::log::debug!(
"cull stats: readback buffer {index} refused ({error}); the culling \
counters stay on the GPU"
);
for slot in &slots {
device.destroy_buffer(slot.buffer);
}
return None;
}
}
}
Some(Self {
slots,
next: 0,
recorded: Arc::new(AtomicU64::new(0)),
counts_clusters,
frames: 0,
latest: None,
off: false,
})
}
#[must_use]
pub const fn latest(&self) -> Option<CullStats> {
self.latest
}
pub fn begin_frame(&mut self, device: &dyn Device) {
if self.off {
return;
}
self.frames += 1;
self.request_recorded(device);
self.poll_outstanding(device);
}
fn request_recorded(&mut self, device: &dyn Device) {
let recorded = self.recorded.swap(0, Ordering::Relaxed);
let Some(index) = self
.slots
.iter()
.position(|slot| matches!(slot.state, SlotState::Recording))
else {
return;
};
if recorded == 0 {
self.slots[index].state = SlotState::Idle;
return;
}
let since = self.frames;
let request = device.request_readback(&ReadbackDesc {
label: Some("cull stats"),
buffer: self.slots[index].buffer,
offset: 0,
size: SLOT_BYTES,
after: None,
});
match request {
Ok(readback) => {
self.slots[index].state = SlotState::Polling {
frame: recorded,
since,
readback,
};
}
Err(error) => {
self.slots[index].state = SlotState::Idle;
self.give_up(device, &format!("request failed ({error})"));
}
}
}
fn poll_outstanding(&mut self, device: &dyn Device) {
let mut bytes = [0u8; SLOT_BYTES as usize];
for index in 0..self.slots.len() {
let SlotState::Polling {
frame,
since,
readback,
} = self.slots[index].state
else {
continue;
};
if since >= self.frames {
continue;
}
match device.poll_readback(readback, &mut bytes) {
Ok(ReadbackState::Ready) => {
device.destroy_readback(readback);
self.slots[index].state = SlotState::Idle;
self.report(frame, &bytes);
}
Ok(ReadbackState::Pending) if self.frames - since >= POLL_DEADLINE => {
device.destroy_readback(readback);
self.slots[index].state = SlotState::Idle;
crcbl_core::log::debug!(
"cull stats: frame {frame} was never answered; its slot is back in the ring"
);
}
Ok(ReadbackState::Pending) => {}
Err(error) => {
self.give_up(device, &format!("poll failed ({error})"));
return;
}
}
}
}
fn report(&mut self, frame: u64, bytes: &[u8; SLOT_BYTES as usize]) {
if self.latest.is_some_and(|latest| latest.frame >= frame) {
return;
}
let stats = CullStats {
instances: u64::from(word(bytes, cull::INSTANCE_SURVIVOR_WORD)),
clusters: self.counts_clusters.then(|| ClusterCull {
survivors: u64::from(word(bytes, cull::CLUSTER_SURVIVOR_WORD)),
frustum_rejects: u64::from(word(bytes, cull::CLUSTER_FRUSTUM_REJECT_WORD)),
cone_rejects: u64::from(word(bytes, cull::CLUSTER_CONE_REJECT_WORD)),
}),
occlusion: OcclusionCull {
early_rejects: u64::from(word(bytes, cull::OCCLUSION_EARLY_REJECT_WORD)),
late_rejects: u64::from(word(bytes, cull::OCCLUSION_LATE_REJECT_WORD)),
small_feature_rejects: u64::from(word(bytes, cull::SMALL_FEATURE_REJECT_WORD)),
},
frame,
};
crcbl_core::log::trace!(
"cull stats: frame {frame} kept {} instances, and its cluster cull did {:?}",
stats.instances,
stats.clusters,
);
self.latest = Some(stats);
}
fn take_slot(&mut self) -> Option<usize> {
let len = self.slots.len();
if let Some(index) = self
.slots
.iter()
.position(|slot| matches!(slot.state, SlotState::Recording))
{
return Some(index);
}
let index = (0..len)
.map(|step| (self.next + step) % len)
.find(|&index| matches!(self.slots[index].state, SlotState::Idle))?;
self.slots[index].state = SlotState::Recording;
self.next = (index + 1) % len;
Some(index)
}
pub fn add_copy_pass(&mut self, graph: &mut RenderGraph<'_>, stats: BufferId) {
if self.off {
return;
}
let Some(index) = self.take_slot() else {
return;
};
let frame = self.frames;
let recorded = Arc::clone(&self.recorded);
let slot = &mut self.slots[index];
let handle = slot.buffer;
let dst = graph.import_buffer(
"cull-stats-slot",
ImportedBuffer {
buffer: handle,
initial: slot.imported,
final_state: ResourceState::TransferDst,
},
);
slot.imported = ResourceState::TransferDst;
graph
.add_copy_pass("cull-stats-readback")
.use_buffer(stats, ResourceState::TransferSrc)
.use_buffer(dst, ResourceState::TransferDst)
.execute(move |ctx| {
let src = ctx.buffer(stats);
let dst = ctx.buffer(dst);
ctx.encoder().copy_buffer_to_buffer(&BufferCopy {
src,
src_offset: 0,
dst,
dst_offset: 0,
size: SLOT_BYTES,
});
recorded.store(frame, Ordering::Relaxed);
});
}
fn give_up(&mut self, device: &dyn Device, why: &str) {
self.off = true;
self.latest = None;
crcbl_core::log::warn!("cull stats: {why}; the culling counters are off (said once)");
for slot in &mut self.slots {
if let SlotState::Polling { readback, .. } = slot.state {
device.destroy_readback(readback);
}
slot.state = SlotState::Idle;
}
}
pub fn destroy(self, device: &dyn Device) {
for slot in &self.slots {
if let SlotState::Polling { readback, .. } = slot.state {
device.destroy_readback(readback);
}
device.destroy_buffer(slot.buffer);
}
}
}
fn word(bytes: &[u8; SLOT_BYTES as usize], index: u32) -> u32 {
let start = index as usize * 4;
u32::from_le_bytes([
bytes[start],
bytes[start + 1],
bytes[start + 2],
bytes[start + 3],
])
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{Command, NullInstance, Recorder};
use crcbl_hal::{
AdapterId, CommandEncoderDesc, DeviceDesc, Instance, QueueHandle, QueueKind, SubmitInfo,
};
use crate::graph::ImportedBuffer;
use crate::transient::TransientPool;
const FRAMES_IN_FLIGHT: usize = 2;
const BOUND: u64 = 16;
struct Harness {
recorder: Recorder,
device: Box<dyn Device>,
queue: QueueHandle,
stats: BufferHandle,
pool: TransientPool,
}
impl Harness {
fn open() -> Self {
let recorder = Recorder::new();
let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
let device = instance
.create_device(&DeviceDesc::for_adapter(AdapterId(0)))
.expect("the gpu_driven preset opens");
let queue = device.queue(QueueKind::Graphics).expect("always present");
let stats = device
.create_buffer(&BufferDesc {
label: Some("cull stats"),
size: SLOT_BYTES,
usage: BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::DeviceLocal,
})
.expect("a device-local counter buffer");
Self {
recorder,
device,
queue,
stats,
pool: TransientPool::new(),
}
}
fn frame(&mut self, ring: &mut CullStatsRing) {
let device = self.device.as_ref();
ring.begin_frame(device);
let mut graph = RenderGraph::new(self.queue);
let stats = graph.import_buffer(
"cull-count",
ImportedBuffer {
buffer: self.stats,
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
ring.add_copy_pass(&mut graph, stats);
let compiled = graph.compile(&self.pool).expect("a legal frame");
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some("cull stats frame"),
queue: self.queue,
});
compiled
.execute(device, &mut self.pool, encoder.as_mut(), None)
.expect("the graph executed");
let commands = encoder.finish().expect("recording succeeded");
device
.submit(self.queue, &SubmitInfo::new(&[commands]))
.expect("submitted");
device.destroy_command_buffer(commands);
}
fn ring(&self, counts_clusters: bool) -> CullStatsRing {
CullStatsRing::new(self.device.as_ref(), FRAMES_IN_FLIGHT, counts_clusters)
.expect("the null backend gives out readback buffers")
}
fn finish(self, ring: CullStatsRing) {
ring.destroy(self.device.as_ref());
self.device.destroy_buffer(self.stats);
}
}
#[test]
fn a_counter_is_read_from_its_own_word() {
let bytes = stats_bytes();
assert_eq!(word(&bytes, cull::INSTANCE_SURVIVOR_WORD), 7);
assert_eq!(word(&bytes, cull::CLUSTER_SURVIVOR_WORD), 9);
assert_eq!(word(&bytes, cull::CLUSTER_FRUSTUM_REJECT_WORD), 13);
assert_eq!(word(&bytes, cull::CLUSTER_CONE_REJECT_WORD), 17);
}
fn stats_bytes() -> [u8; SLOT_BYTES as usize] {
let mut bytes = [0u8; SLOT_BYTES as usize];
for (index, value) in [
(cull::INSTANCE_SURVIVOR_WORD, 7u32),
(cull::CLUSTER_SURVIVOR_WORD, 9),
(crcbl_shaders::light::CLUSTER_OVERFLOW_WORD, 11),
(cull::CLUSTER_FRUSTUM_REJECT_WORD, 13),
(cull::CLUSTER_CONE_REJECT_WORD, 17),
(cull::OCCLUSION_EARLY_REJECT_WORD, 19),
(cull::OCCLUSION_LATE_REJECT_WORD, 23),
(cull::SMALL_FEATURE_REJECT_WORD, 29),
] {
let at = index as usize * 4;
bytes[at..at + 4].copy_from_slice(&value.to_le_bytes());
}
bytes
}
#[test]
fn each_cluster_counter_reaches_the_field_that_names_it() {
let harness = Harness::open();
let mut ring = harness.ring(true);
ring.report(3, &stats_bytes());
assert_eq!(
ring.latest(),
Some(CullStats {
instances: 7,
clusters: Some(ClusterCull {
survivors: 9,
frustum_rejects: 13,
cone_rejects: 17,
}),
occlusion: OcclusionCull {
early_rejects: 19,
late_rejects: 23,
small_feature_rejects: 29,
},
frame: 3,
}),
);
harness.finish(ring);
}
#[test]
fn the_copy_is_recorded_and_sits_outside_every_pass() {
let mut harness = Harness::open();
let mut ring = harness.ring(false);
harness.frame(&mut ring);
let copies: Vec<BufferCopy> = harness
.recorder
.commands()
.into_iter()
.filter_map(|command| match command {
Command::CopyBufferToBuffer(copy) => Some(copy),
_ => None,
})
.collect();
assert_eq!(copies.len(), 1, "one copy per frame, no more and no less");
assert_eq!(copies[0].src, harness.stats);
assert_eq!(copies[0].size, SLOT_BYTES);
assert!(
ring.slots.iter().any(|slot| slot.buffer == copies[0].dst),
"the copy must land in this ring's own slot",
);
harness.recorder.assert_valid();
harness.finish(ring);
}
#[test]
fn the_graph_moves_the_counter_buffer_through_transfer_src_and_back() {
let mut harness = Harness::open();
let mut ring = harness.ring(false);
harness.frame(&mut ring);
let transitions: Vec<(ResourceState, ResourceState)> = harness
.recorder
.commands()
.into_iter()
.filter_map(|command| match command {
Command::Barrier { buffers, .. } => Some(buffers),
_ => None,
})
.flatten()
.filter(|barrier| barrier.buffer == harness.stats)
.map(|barrier| (barrier.from, barrier.to))
.collect();
assert_eq!(
transitions,
[
(ResourceState::ShaderRead, ResourceState::TransferSrc),
(ResourceState::TransferSrc, ResourceState::ShaderRead),
],
);
harness.finish(ring);
}
#[test]
fn a_reused_slot_barriers_against_the_frame_that_wrote_it_last() {
let mut harness = Harness::open();
let mut ring = harness.ring(false);
harness.frame(&mut ring);
let slot = recording_slot(&ring);
assert_eq!(
barrier_before_the_copy_into(&harness.recorder, slot),
Some((ResourceState::Undefined, ResourceState::TransferDst)),
"a slot nothing has written orders against nothing, and says so",
);
for _ in 1..ring.slots.len() {
harness.recorder.clear();
harness.frame(&mut ring);
assert_ne!(
recording_slot(&ring),
slot,
"the ring must hand out a different slot until it has turned over",
);
}
harness.recorder.clear();
harness.frame(&mut ring);
assert_eq!(
recording_slot(&ring),
slot,
"the ring has come round and this frame reuses the first slot",
);
assert_eq!(
barrier_before_the_copy_into(&harness.recorder, slot),
Some((ResourceState::TransferDst, ResourceState::TransferDst)),
"the copy into a reused slot must be ordered against the copy that wrote it last, \
and a source of `Undefined` would carry no scope to order against",
);
harness.finish(ring);
}
fn barrier_before_the_copy_into(
recorder: &Recorder,
buffer: BufferHandle,
) -> Option<(ResourceState, ResourceState)> {
let mut transition = None;
for command in recorder.commands() {
match command {
Command::Barrier { buffers, .. } => {
if let Some(found) = buffers.iter().find(|barrier| barrier.buffer == buffer) {
transition = Some((found.from, found.to));
}
}
Command::CopyBufferToBuffer(copy) if copy.dst == buffer => return transition,
_ => {}
}
}
None
}
fn recording_slot(ring: &CullStatsRing) -> BufferHandle {
let index = ring
.slots
.iter()
.position(|slot| matches!(slot.state, SlotState::Recording))
.expect("a frame that recorded its copy left exactly one slot recording");
ring.slots[index].buffer
}
fn stats_copies(recorder: &Recorder) -> usize {
recorder
.commands()
.iter()
.filter(|command| {
matches!(command, Command::CopyBufferToBuffer(copy) if copy.size == SLOT_BYTES)
})
.count()
}
fn run_until_reported(
harness: &mut Harness,
ring: &mut CullStatsRing,
bound: u64,
) -> CullStats {
for _ in 0..bound {
harness.frame(ring);
if let Some(stats) = ring.latest() {
return stats;
}
}
panic!("nothing was reported in {bound} frames");
}
#[test]
fn nothing_is_reported_until_a_readback_has_answered() {
let mut harness = Harness::open();
let mut ring = harness.ring(false);
assert_eq!(ring.latest(), None, "nothing has been recorded yet");
harness.frame(&mut ring);
assert_eq!(ring.latest(), None, "frame 1 has only recorded its copy");
harness.frame(&mut ring);
assert_eq!(
ring.latest(),
None,
"frame 2 made the request; polling it here would ask about a frame still being \
recorded",
);
harness.frame(&mut ring);
let stats = ring.latest().expect("the first request has answered");
assert_eq!(
stats.frame, 1,
"the report names the frame whose copy it is, not the frame it landed on",
);
harness.frame(&mut ring);
assert_eq!(
ring.latest().expect("and the ring keeps turning").frame,
2,
"each further frame advances the report by one",
);
harness.finish(ring);
}
#[test]
fn a_first_poll_that_answers_pending_still_reports() {
for pending_polls in 1..=4u32 {
let mut harness = Harness::open();
harness.recorder.set_readback_latency(pending_polls);
let mut ring = harness.ring(false);
let bound = 2 * (2 + u64::from(pending_polls) + ring.slots.len() as u64);
let first = run_until_reported(&mut harness, &mut ring, bound);
assert_eq!(
first.frame, 1,
"the first frame's copy is the first thing to answer, {pending_polls} pending \
polls or not",
);
let mut later = first;
for _ in 0..bound {
harness.frame(&mut ring);
later = ring.latest().expect("a report never goes back to nothing");
if later.frame > first.frame {
break;
}
}
assert!(
later.frame > first.frame,
"the ring stopped reporting after its first answer: {later:?}",
);
harness.finish(ring);
}
}
#[test]
fn a_readback_that_never_completes_reports_nothing() {
let mut harness = Harness::open();
harness.recorder.set_readback_latency(1_000);
let mut ring = harness.ring(false);
for _ in 0..(ring.slots.len() * 3) {
harness.frame(&mut ring);
assert_eq!(ring.latest(), None, "a pending slot has nothing to report");
}
harness.finish(ring);
}
#[test]
fn a_device_that_stops_answering_neither_leaks_slots_nor_wedges_the_ring() {
let mut harness = Harness::open();
harness.recorder.set_readback_latency(u32::MAX);
let mut ring = harness.ring(false);
for _ in 0..=ring.slots.len() {
harness.frame(&mut ring);
}
let live = harness.recorder.total_live_objects();
for _ in 0..(POLL_DEADLINE / 2) {
harness.recorder.clear();
harness.frame(&mut ring);
assert_eq!(
stats_copies(&harness.recorder),
0,
"a frame with no free slot must record no copy",
);
assert!(
harness.recorder.total_live_objects() <= live,
"the ring must not accumulate requests a device never answers",
);
}
let mut copies = 0;
for _ in 0..(2 * POLL_DEADLINE) {
harness.recorder.clear();
harness.frame(&mut ring);
copies += stats_copies(&harness.recorder);
assert!(
harness.recorder.total_live_objects() <= live,
"the ring must not accumulate requests a device never answers",
);
}
assert!(
copies > 0,
"the deadline must hand the slots back, so the ring records copies again",
);
assert_eq!(
ring.latest(),
None,
"and still reports nothing it never read"
);
harness.finish(ring);
}
#[test]
fn a_device_that_refuses_the_readback_reports_nothing_rather_than_zero() {
let mut harness = Harness::open();
let mut ring = harness.ring(false);
run_until_reported(&mut harness, &mut ring, BOUND);
assert!(ring.latest().is_some(), "the ring was working");
harness.recorder.lose_device("the test lost the device");
ring.begin_frame(harness.device.as_ref());
assert_eq!(ring.latest(), None, "a refused readback is not a zero");
ring.begin_frame(harness.device.as_ref());
assert_eq!(ring.latest(), None);
harness.finish(ring);
}
#[test]
fn the_cluster_word_is_unknown_where_no_stage_counts_it() {
for (counts_clusters, expected) in [(false, None), (true, Some(ClusterCull::default()))] {
let mut harness = Harness::open();
let mut ring = harness.ring(counts_clusters);
let stats = run_until_reported(&mut harness, &mut ring, BOUND);
assert_eq!(stats.clusters, expected);
harness.finish(ring);
}
}
#[test]
fn a_graph_that_was_dropped_rather_than_executed_stamps_nothing() {
let harness = Harness::open();
let mut ring = harness.ring(false);
for _ in 0..BOUND {
ring.begin_frame(harness.device.as_ref());
let mut graph = RenderGraph::new(harness.queue);
let stats = graph.import_buffer(
"cull-count",
ImportedBuffer {
buffer: harness.stats,
initial: ResourceState::ShaderRead,
final_state: ResourceState::ShaderRead,
},
);
ring.add_copy_pass(&mut graph, stats);
drop(graph);
assert_eq!(ring.latest(), None, "no copy ran, so there is nothing back");
}
harness.finish(ring);
}
#[test]
fn the_ring_leaks_nothing() {
let mut harness = Harness::open();
let before = harness.recorder.total_live_objects();
let mut ring = harness.ring(false);
assert!(harness.recorder.total_live_objects() > before);
harness.frame(&mut ring);
harness.frame(&mut ring);
ring.destroy(harness.device.as_ref());
assert_eq!(
harness.recorder.total_live_objects(),
before,
"every slot and every live readback must be released",
);
harness.device.destroy_buffer(harness.stats);
}
}