use std::sync::atomic::{AtomicU32, Ordering};
use crcbl_hal::{
Barriers, BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc,
BindGroupLayoutEntry, BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource,
BufferBarrier, BufferCopy, BufferDesc, BufferHandle, BufferUsage, CommandEncoderDesc,
ComputePipelineDesc, ComputePipelineHandle, Device, HalError, ImageViewType, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, QueueHandle, ResourceState, SampleType, ShaderEntry,
ShaderModuleDesc, ShaderStages, SubmitInfo, check_portable_storage_buffers,
};
use crcbl_shaders::draw_gen::DrawMode;
use crcbl_shaders::{
CLEAR_COUNTERS, CULL, DRAW_GEN, Stage, clear_counters, cull as cull_shader, draw_gen,
};
use glam::Mat4;
use crate::cull::{FacePlanes, Frustum};
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
const _: () = assert!(
draw_gen::STARTS_WORKGROUP_SIZE
<= crcbl_hal::Limits::minimum().max_compute_invocations_per_workgroup
&& draw_gen::STARTS_WORKGROUP_SIZE
<= crcbl_hal::Limits::minimum().max_compute_workgroup_size[0]
);
#[derive(Clone, Copy, Debug)]
pub struct DrawGenDesc<'a> {
pub label: Option<&'a str>,
pub instances: &'a [BufferHandle],
pub mesh_table: BufferHandle,
pub bucket_meshes: &'a [u32],
pub bucket_modes: &'a [u32],
pub bucket_clusters: &'a [u32],
pub bucket_cluster_bases: &'a [u32],
pub mesh_levels: &'a [crcbl_shaders::level_select::MeshLevels],
pub level_groups: &'a [crcbl_shaders::level_select::LevelGroup],
pub level_meshes: &'a [u32],
pub instance_capacity: u32,
pub hidden_view: u32,
pub mode: DrawMode,
pub task_lanes: u32,
}
const SMALL_FEATURE_ONLY: u32 = 3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Selection {
pub camera_position: [f32; 3],
pub lod_params: [f32; 3],
}
#[derive(Clone, Copy, Debug)]
pub enum FrameCull<'a> {
Plain,
Faces(&'a FacePlanes),
Occlusion(OcclusionFrame),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OcclusionFrame {
pub view_projection: Mat4,
pub previous_view_projection: Mat4,
pub target: (u32, u32),
pub pyramid_levels: u32,
pub occlusion: bool,
pub history: bool,
pub small_feature_pixels: Option<f32>,
}
#[derive(Clone, Copy, Debug)]
pub struct PyramidInputs<'p> {
pub levels: &'p [ImageId],
pub group: BindGroupHandle,
}
#[derive(Clone, Copy, Debug)]
pub struct GeneratedDraws {
pub args: BufferHandle,
pub args_id: BufferId,
pub counts: BufferHandle,
pub counts_id: BufferId,
pub flat_args_offset: u64,
pub runs_id: BufferId,
pub group_state_id: BufferId,
pub visible_count_id: BufferId,
}
#[derive(Debug)]
pub struct DrawGen {
tables: BufferHandle,
table_offsets: draw_gen::TableOffsets,
clear_params: BufferHandle,
group_state: BufferHandle,
group_stride: u32,
gen_params: Vec<BufferHandle>,
cull_params: Vec<BufferHandle>,
visible_count: Vec<BufferHandle>,
runs: Vec<BufferHandle>,
args: Vec<BufferHandle>,
counts: Vec<BufferHandle>,
clear_groups: Vec<BindGroupHandle>,
cull_groups: Vec<BindGroupHandle>,
gen_groups: Vec<BindGroupHandle>,
clear_layout: BindGroupLayoutHandle,
clear_pipeline_layout: PipelineLayoutHandle,
clear_pipeline: ComputePipelineHandle,
cull_layout: BindGroupLayoutHandle,
cull_pipeline_layout: PipelineLayoutHandle,
cull_pipeline: ComputePipelineHandle,
gen_layout: BindGroupLayoutHandle,
gen_pipeline_layout: PipelineLayoutHandle,
bin_pipeline: ComputePipelineHandle,
starts_pipeline: ComputePipelineHandle,
scatter_pipeline: ComputePipelineHandle,
bucket_count: u32,
capacity: u32,
runs_words: u32,
hidden_view: u32,
task_lanes: u32,
mode: DrawMode,
frame_modes: Vec<AtomicU32>,
occlusion: Option<OcclusionPipelines>,
}
#[derive(Debug)]
struct OcclusionPipelines {
pyramid_layout: BindGroupLayoutHandle,
cull_pipeline_layout: PipelineLayoutHandle,
early: ComputePipelineHandle,
late: ComputePipelineHandle,
late_scatter: ComputePipelineHandle,
late_finish: ComputePipelineHandle,
}
impl DrawGen {
pub fn new(
device: &dyn Device,
queue: QueueHandle,
desc: &DrawGenDesc<'_>,
) -> Result<Self, HalError> {
assert!(
!desc.instances.is_empty(),
"draw generation needs at least one instance buffer to cull"
);
assert!(
!desc.bucket_meshes.is_empty(),
"draw generation with no buckets would generate no draws"
);
assert_eq!(
desc.bucket_modes.len(),
desc.bucket_meshes.len(),
"one material mode per bucket: a shorter table would key a bucket on a mode that \
belongs to another bucket, or to nothing, and the instances meant for it would \
scatter nowhere and never be drawn"
);
assert_eq!(
desc.bucket_clusters.len(),
desc.bucket_meshes.len(),
"one cluster count per bucket: a shorter table would leave a bucket's mesh dispatch \
reading a cluster count that belongs to another bucket, or to nothing"
);
assert_eq!(
desc.bucket_cluster_bases.len(),
desc.bucket_meshes.len(),
"one cluster base per bucket: a shorter table would leave a range of buckets drawn \
in one call reading a cluster base that belongs to another bucket, or to nothing"
);
let mut rollback = Rollback::default();
match Self::build(device, queue, desc, &mut rollback) {
Ok(built) => Ok(built),
Err(error) => {
rollback.run(device);
Err(error)
}
}
}
fn build(
device: &dyn Device,
queue: QueueHandle,
desc: &DrawGenDesc<'_>,
rollback: &mut Rollback,
) -> Result<Self, HalError> {
let stem = desc.label.unwrap_or("draw generation");
let bucket_count = u32::try_from(desc.bucket_meshes.len())
.map_err(|_| HalError::InvalidDescriptor("more buckets than a u32".to_string()))?;
let capacity = desc.instance_capacity;
if capacity > cull_shader::ENTRY_INDEX_MASK + 1 {
return Err(HalError::InvalidDescriptor(format!(
"{capacity} instances do not fit the {} a survivor entry indexes below its tags",
cull_shader::ENTRY_INDEX_MASK + 1
)));
}
let draw_regions = desc.mode.regions();
let runs_words = draw_gen::runs_words(capacity, bucket_count, desc.mode == DrawMode::Faces)
.ok_or_else(|| {
HalError::InvalidDescriptor(format!(
"{capacity} instances and {bucket_count} buckets lay out more survivor and run \
words than a u32 addresses"
))
})?;
let mut buffer = |label: &str, size: u64, usage, memory| -> Result<_, HalError> {
let handle = device.create_buffer(&BufferDesc {
label: Some(&format!("{stem} {label}")),
size,
usage,
memory,
})?;
rollback.buffers.push(handle);
Ok(handle)
};
let packed = draw_gen::pack_tables(
desc.bucket_meshes,
desc.bucket_modes,
desc.bucket_clusters,
desc.bucket_cluster_bases,
desc.mesh_levels,
desc.level_groups,
desc.level_meshes,
)
.ok_or_else(|| {
HalError::InvalidDescriptor("more table words than a u32 addresses".to_string())
})?;
let tables = buffer(
"tables",
packed.bytes.len() as u64,
BufferUsage::STORAGE,
MemoryLocation::HostUpload,
)?;
device.write_buffer(tables, 0, &packed.bytes)?;
let table_offsets = packed.offsets;
let group_stride = u32::try_from(desc.level_groups.len())
.map_err(|_| HalError::InvalidDescriptor("more groups than a u32".to_string()))?
.max(1);
let group_state_bytes = u64::from(capacity) * u64::from(group_stride) * 4;
let group_state = buffer(
"lod group state",
group_state_bytes,
BufferUsage::STORAGE | BufferUsage::TRANSFER_DST,
MemoryLocation::DeviceLocal,
)?;
fill_at_start_up(
device,
queue,
&format!("{stem} lod group state"),
group_state,
&vec![
0u8;
usize::try_from(group_state_bytes).map_err(|_| HalError::InvalidDescriptor(
format!(
"the lod group state is {group_state_bytes} bytes, which does not \
fit this host's address space"
)
))?
],
ResourceState::ShaderReadWrite,
)?;
let clear_params = buffer(
"clear params",
clear_counters::PARAMS_SIZE as u64,
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
)?;
let args_words = draw_regions * bucket_count * draw_gen::DRAW_ARGS_WORDS as u32;
let counts_words = draw_gen::flat_args_word(bucket_count, draw_regions, draw_regions, 0, 0);
device.write_buffer(
clear_params,
0,
&clear_counters::Params {
args_words,
counts_words: bucket_count,
stats_words: cull_shader::STATS_WORDS,
mesh_args_words: counts_words - bucket_count,
}
.to_bytes(),
)?;
let frames = desc.instances.len();
let mut gen_params = Vec::with_capacity(frames);
let mut cull_params = Vec::with_capacity(frames);
let mut visible_count = Vec::with_capacity(frames);
let mut runs = Vec::with_capacity(frames);
let mut args = Vec::with_capacity(frames);
let mut counts = Vec::with_capacity(frames);
for frame in 0..frames {
let params = buffer(
&format!("params {frame}"),
draw_gen::PARAMS_SIZE as u64,
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
)?;
device.write_buffer(
params,
0,
&draw_gen::Params {
bucket_count,
visible_capacity: capacity,
group_stride,
bucket_modes_at: table_offsets.bucket_modes_at,
bucket_clusters_at: table_offsets.bucket_clusters_at,
mesh_levels_at: table_offsets.mesh_levels_at,
level_groups_at: table_offsets.level_groups_at,
level_meshes_at: table_offsets.level_meshes_at,
bucket_lookup_at: table_offsets.bucket_lookup_at,
task_lanes: desc.task_lanes,
flat_segments_at: table_offsets.flat_segments_at,
..draw_gen::Params::default()
}
.to_bytes(),
)?;
gen_params.push(params);
cull_params.push(buffer(
&format!("cull params {frame}"),
cull_shader::PARAMS_SIZE as u64,
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
)?);
visible_count.push(buffer(
&format!("cull stats {frame}"),
u64::from(cull_shader::STATS_WORDS) * 4,
BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC | BufferUsage::TRANSFER_DST,
MemoryLocation::DeviceLocal,
)?);
runs.push(buffer(
&format!("visible and bucket runs {frame}"),
u64::from(runs_words) * 4,
BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
MemoryLocation::DeviceLocal,
)?);
args.push(buffer(
&format!("draw args {frame}"),
u64::from(draw_regions) * u64::from(bucket_count) * draw_gen::DRAW_ARGS_SIZE as u64,
BufferUsage::STORAGE
| BufferUsage::INDIRECT
| BufferUsage::TRANSFER_SRC
| BufferUsage::TRANSFER_DST,
MemoryLocation::DeviceLocal,
)?);
counts.push(buffer(
&format!("draw counts and mesh dispatch args {frame}"),
u64::from(counts_words) * 4,
BufferUsage::STORAGE
| BufferUsage::INDIRECT
| BufferUsage::TRANSFER_SRC
| BufferUsage::TRANSFER_DST,
MemoryLocation::DeviceLocal,
)?);
}
let clear_entries = [
uniform(0),
storage(1, false, UINT_STRIDE),
storage(2, false, UINT_STRIDE),
storage(3, false, UINT_STRIDE),
];
let clear_desc = BindGroupLayoutDesc {
label: Some("clear counters"),
entries: &clear_entries,
};
check_portable_storage_buffers(clear_desc.label, &[&clear_desc])?;
let clear_layout = device.create_bind_group_layout(&clear_desc)?;
rollback.bind_group_layouts.push(clear_layout);
let clear_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("clear counters"),
bind_group_layouts: &[clear_layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(clear_pipeline_layout);
let clear_pipeline = compute_pipeline(
device,
"clear counters",
&CLEAR_COUNTERS,
clear_pipeline_layout,
clear_counters::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(clear_pipeline);
let cull_entries = [
uniform(0),
storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
storage(3, false, UINT_STRIDE),
storage(4, false, UINT_STRIDE),
];
let cull_desc = BindGroupLayoutDesc {
label: Some("cull"),
entries: &cull_entries,
};
check_portable_storage_buffers(cull_desc.label, &[&cull_desc])?;
let cull_layout = device.create_bind_group_layout(&cull_desc)?;
rollback.bind_group_layouts.push(cull_layout);
let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("cull"),
bind_group_layouts: &[cull_layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(cull_pipeline_layout);
let cull_pipeline = compute_pipeline_entry(
device,
"cull",
&CULL,
"computeMain",
cull_pipeline_layout,
cull_shader::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(cull_pipeline);
let gen_entries = [
uniform(0),
storage(1, true, crcbl_shaders::mesh::INSTANCE_STRIDE as u32),
storage(2, true, crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32),
storage(3, true, UINT_STRIDE),
storage(4, true, UINT_STRIDE),
storage(5, false, UINT_STRIDE),
storage(6, false, UINT_STRIDE),
storage(7, false, UINT_STRIDE),
storage(8, false, UINT_STRIDE),
];
let gen_desc = BindGroupLayoutDesc {
label: Some("draw args"),
entries: &gen_entries,
};
check_portable_storage_buffers(gen_desc.label, &[&gen_desc])?;
let gen_layout = device.create_bind_group_layout(&gen_desc)?;
rollback.bind_group_layouts.push(gen_layout);
let gen_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("draw args"),
bind_group_layouts: &[gen_layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(gen_pipeline_layout);
let bin_pipeline = compute_pipeline_entry(
device,
"draw args bin",
&DRAW_GEN,
"binMain",
gen_pipeline_layout,
draw_gen::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(bin_pipeline);
let starts_pipeline = compute_pipeline_entry(
device,
"draw args starts",
&DRAW_GEN,
"startsMain",
gen_pipeline_layout,
draw_gen::STARTS_WORKGROUP_SIZE,
)?;
rollback.pipelines.push(starts_pipeline);
let scatter_pipeline = compute_pipeline_entry(
device,
"draw args scatter",
&DRAW_GEN,
"scatterMain",
gen_pipeline_layout,
draw_gen::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(scatter_pipeline);
let occlusion = if desc.mode == DrawMode::Occlusion {
Some(Self::build_occlusion(
device,
rollback,
cull_layout,
gen_pipeline_layout,
)?)
} else {
None
};
let mut clear_groups = Vec::with_capacity(frames);
let mut cull_groups = Vec::with_capacity(frames);
let mut gen_groups = Vec::with_capacity(frames);
for frame in 0..frames {
let group = device.create_bind_group(&BindGroupDesc {
label: Some("clear counters"),
layout: clear_layout,
entries: &[
bound(0, clear_params),
bound(1, visible_count[frame]),
bound(2, args[frame]),
bound(3, counts[frame]),
],
variable_count: None,
})?;
rollback.bind_groups.push(group);
clear_groups.push(group);
let group = device.create_bind_group(&BindGroupDesc {
label: Some("cull"),
layout: cull_layout,
entries: &[
bound(0, cull_params[frame]),
bound(1, desc.instances[frame]),
bound(2, desc.mesh_table),
bound(3, runs[frame]),
bound(4, visible_count[frame]),
],
variable_count: None,
})?;
rollback.bind_groups.push(group);
cull_groups.push(group);
let group = device.create_bind_group(&BindGroupDesc {
label: Some("draw args"),
layout: gen_layout,
entries: &[
bound(0, gen_params[frame]),
bound(1, desc.instances[frame]),
bound(2, desc.mesh_table),
bound(3, visible_count[frame]),
bound(4, tables),
bound(5, runs[frame]),
bound(6, args[frame]),
bound(7, counts[frame]),
bound(8, group_state),
],
variable_count: None,
})?;
rollback.bind_groups.push(group);
gen_groups.push(group);
}
rollback.disarm();
Ok(Self {
tables,
table_offsets,
clear_params,
group_state,
group_stride,
gen_params,
cull_params,
visible_count,
runs,
args,
counts,
clear_groups,
cull_groups,
gen_groups,
clear_layout,
clear_pipeline_layout,
clear_pipeline,
cull_layout,
cull_pipeline_layout,
cull_pipeline,
gen_layout,
gen_pipeline_layout,
bin_pipeline,
starts_pipeline,
scatter_pipeline,
bucket_count,
capacity,
runs_words,
hidden_view: desc.hidden_view,
task_lanes: desc.task_lanes,
mode: desc.mode,
frame_modes: (0..frames).map(|_| AtomicU32::new(0)).collect(),
occlusion,
})
}
fn build_occlusion(
device: &dyn Device,
rollback: &mut Rollback,
cull_layout: BindGroupLayoutHandle,
gen_pipeline_layout: PipelineLayoutHandle,
) -> Result<OcclusionPipelines, HalError> {
let entries: Vec<BindGroupLayoutEntry> = (0..cull_shader::OCCLUSION_MAX_LEVELS)
.map(|binding| BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Depth,
},
count: 1,
flags: BindingFlags::empty(),
})
.collect();
let pyramid_desc = BindGroupLayoutDesc {
label: Some("occlusion pyramid"),
entries: &entries,
};
check_portable_storage_buffers(pyramid_desc.label, &[&pyramid_desc])?;
let pyramid_layout = device.create_bind_group_layout(&pyramid_desc)?;
rollback.bind_group_layouts.push(pyramid_layout);
let cull_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("occlusion cull"),
bind_group_layouts: &[cull_layout, pyramid_layout],
push_constants: None,
})?;
rollback.pipeline_layouts.push(cull_pipeline_layout);
let early = compute_pipeline_entry(
device,
"occlusion early cull",
&CULL,
"occlusionMain",
cull_pipeline_layout,
cull_shader::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(early);
let late = compute_pipeline_entry(
device,
"occlusion late cull",
&CULL,
"lateMain",
cull_pipeline_layout,
cull_shader::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(late);
let late_scatter = compute_pipeline_entry(
device,
"draw args late scatter",
&DRAW_GEN,
"lateScatterMain",
gen_pipeline_layout,
draw_gen::WORKGROUP_SIZE,
)?;
rollback.pipelines.push(late_scatter);
let late_finish = compute_pipeline_entry(
device,
"draw args late finish",
&DRAW_GEN,
"lateFinishMain",
gen_pipeline_layout,
draw_gen::STARTS_WORKGROUP_SIZE,
)?;
rollback.pipelines.push(late_finish);
Ok(OcclusionPipelines {
pyramid_layout,
cull_pipeline_layout,
early,
late,
late_scatter,
late_finish,
})
}
#[must_use]
pub const fn bucket_count(&self) -> u32 {
self.bucket_count
}
#[must_use]
pub const fn visible_capacity(&self) -> u32 {
self.capacity
}
#[must_use]
pub const fn bucket_start_word(&self, bucket: u32) -> u32 {
draw_gen::run_start_word(self.capacity, self.bucket_count, 0, bucket)
}
#[must_use]
pub const fn region_start_word(&self, region: u32, bucket: u32) -> u32 {
draw_gen::run_start_word(self.capacity, self.bucket_count, region, bucket)
}
#[must_use]
pub const fn chunk_start_word(&self, region: u32, bucket: u32) -> u32 {
draw_gen::chunk_start_word(self.capacity, self.bucket_count, region, bucket)
}
#[must_use]
pub const fn flat_args_offset(&self, region: u32, segment: u32) -> u64 {
draw_gen::flat_args_word(self.bucket_count, self.mode.regions(), region, segment, 0) as u64
* 4
}
#[must_use]
pub const fn bucket_mesh_word(&self, bucket: u32) -> u32 {
draw_gen::bucket_mesh_word(self.capacity, self.bucket_count, bucket)
}
#[must_use]
pub const fn args_region_offset(&self, region: u32) -> u64 {
region as u64 * self.bucket_count as u64 * draw_gen::DRAW_ARGS_SIZE as u64
}
#[must_use]
pub const fn counts_region_offset(&self, region: u32) -> u64 {
region as u64 * self.bucket_count as u64 * (4 + draw_gen::MESH_ARGS_SIZE as u64)
}
#[must_use]
pub const fn mode(&self) -> DrawMode {
self.mode
}
#[must_use]
pub fn occlusion_layout(&self) -> Option<BindGroupLayoutHandle> {
self.occlusion
.as_ref()
.map(|pipelines| pipelines.pyramid_layout)
}
#[must_use]
pub fn frame_mode(&self, frame: usize) -> DrawMode {
match self.frame_modes[frame].load(Ordering::Relaxed) {
SMALL_FEATURE_ONLY => DrawMode::Plain,
word if word == DrawMode::Occlusion.word() => DrawMode::Occlusion,
word if word == DrawMode::Faces.word() => DrawMode::Faces,
_ => DrawMode::Plain,
}
}
#[must_use]
pub fn uses_occlusion_entry(&self, frame: usize) -> bool {
let word = self.frame_modes[frame].load(Ordering::Relaxed);
word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY
}
#[must_use]
pub const fn runs_at(&self) -> u32 {
draw_gen::runs_at(self.capacity)
}
#[must_use]
pub const fn runs_size(&self) -> u64 {
self.runs_words as u64 * 4
}
#[must_use]
pub const fn args_offset(&self, bucket: u32) -> u64 {
bucket as u64 * draw_gen::DRAW_ARGS_SIZE as u64
}
#[must_use]
pub const fn count_offset(&self, bucket: u32) -> u64 {
bucket as u64 * 4
}
#[must_use]
pub const fn mesh_args_offset(&self, bucket: u32) -> u64 {
self.bucket_count as u64 * 4 + bucket as u64 * draw_gen::MESH_ARGS_SIZE as u64
}
#[must_use]
pub fn runs(&self, frame: usize) -> BufferHandle {
self.runs[frame]
}
#[must_use]
pub fn cull_params(&self, frame: usize) -> BufferHandle {
self.cull_params[frame]
}
#[must_use]
pub fn visible(&self, frame: usize) -> BufferHandle {
self.runs[frame]
}
#[must_use]
pub fn visible_count(&self, frame: usize) -> BufferHandle {
self.visible_count[frame]
}
#[must_use]
pub fn args(&self, frame: usize) -> BufferHandle {
self.args[frame]
}
#[must_use]
pub fn counts(&self, frame: usize) -> BufferHandle {
self.counts[frame]
}
#[must_use]
pub fn tables(&self) -> BufferHandle {
self.tables
}
#[must_use]
pub const fn table_offsets(&self) -> draw_gen::TableOffsets {
self.table_offsets
}
#[must_use]
pub fn mesh_args(&self, frame: usize) -> BufferHandle {
self.counts[frame]
}
#[must_use]
pub fn group_state(&self) -> BufferHandle {
self.group_state
}
#[must_use]
pub const fn group_stride(&self) -> u32 {
self.group_stride
}
pub fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
frustum: &Frustum,
instance_count: u32,
camera_position: [f32; 3],
lod_params: [f32; 3],
) -> Result<(), HalError> {
self.begin_frame_with(
device,
frame,
frustum,
instance_count,
Selection {
camera_position,
lod_params,
},
&FrameCull::Plain,
)
}
pub fn begin_frame_with(
&self,
device: &dyn Device,
frame: usize,
frustum: &Frustum,
instance_count: u32,
selection: Selection,
cull: &FrameCull<'_>,
) -> Result<(), HalError> {
let Selection {
camera_position,
lod_params,
} = selection;
let mut params = cull_shader::Params {
planes: frustum.planes.map(|plane| plane.to_array()),
instance_count,
capacity: self.capacity,
hidden_view: self.hidden_view,
..cull_shader::Params::default()
};
let mode = match cull {
FrameCull::Plain => DrawMode::Plain,
FrameCull::Faces(faces) => {
assert_eq!(
self.mode,
DrawMode::Faces,
"a point light's face culls need a generator built with its face regions"
);
params.features = cull_shader::Features::FACES;
for (face, planes) in faces.iter().enumerate() {
for (plane, value) in planes.iter().enumerate() {
params.face_planes[face * cull_shader::FACE_PLANES + plane] =
value.to_array();
}
}
DrawMode::Faces
}
FrameCull::Occlusion(occlusion) => {
assert_eq!(
self.mode,
DrawMode::Occlusion,
"the occlusion culls need a generator built with the occlusion regions"
);
let mut features = cull_shader::Features::NONE;
if occlusion.occlusion && occlusion.history {
features = features.union(cull_shader::Features::OCCLUSION_HISTORY);
}
if occlusion.small_feature_pixels.is_some() {
features = features.union(cull_shader::Features::SMALL_FEATURE);
}
params.features = features;
params.view_proj = occlusion.view_projection.to_cols_array();
params.previous_view_proj = occlusion.previous_view_projection.to_cols_array();
params.target_extent = [occlusion.target.0, occlusion.target.1];
params.pyramid_levels = occlusion
.pyramid_levels
.min(cull_shader::OCCLUSION_MAX_LEVELS);
params.small_feature_pixels = occlusion.small_feature_pixels.unwrap_or(0.0);
if occlusion.occlusion {
DrawMode::Occlusion
} else {
DrawMode::Plain
}
}
};
device.write_buffer(
self.gen_params[frame],
0,
&draw_gen::Params {
bucket_count: self.bucket_count,
visible_capacity: self.capacity,
group_stride: self.group_stride,
bucket_modes_at: self.table_offsets.bucket_modes_at,
bucket_clusters_at: self.table_offsets.bucket_clusters_at,
mesh_levels_at: self.table_offsets.mesh_levels_at,
level_groups_at: self.table_offsets.level_groups_at,
level_meshes_at: self.table_offsets.level_meshes_at,
camera_position,
lod_params,
mode,
draw_regions: self.mode.regions(),
face_runs_at: draw_gen::face_runs_at(self.capacity, self.bucket_count),
bucket_lookup_at: self.table_offsets.bucket_lookup_at,
task_lanes: self.task_lanes,
flat_segments_at: self.table_offsets.flat_segments_at,
}
.to_bytes(),
)?;
device.write_buffer(self.cull_params[frame], 0, ¶ms.to_bytes())?;
let cull_word = match cull {
FrameCull::Occlusion(occlusion)
if !occlusion.occlusion && occlusion.small_feature_pixels.is_some() =>
{
SMALL_FEATURE_ONLY
}
_ => mode.word(),
};
self.frame_modes[frame].store(cull_word, Ordering::Relaxed);
Ok(())
}
pub const MAX_PASSES: u32 = 5;
pub const DISPATCHES: u32 = 5;
pub const LATE_PASSES: u32 = 3;
pub fn add_passes(
&self,
graph: &mut RenderGraph<'_>,
frame: usize,
instance_count: u32,
) -> GeneratedDraws {
let word = self.frame_modes[frame].load(Ordering::Relaxed);
assert!(
word != DrawMode::Occlusion.word() && word != SMALL_FEATURE_ONLY,
"frame {frame} was begun with the occlusion culls, whose passes are \
`add_occlusion_passes`"
);
self.record_passes(graph, frame, instance_count, None)
}
pub fn add_occlusion_passes(
&self,
graph: &mut RenderGraph<'_>,
frame: usize,
instance_count: u32,
pyramid: &PyramidInputs<'_>,
) -> GeneratedDraws {
let word = self.frame_modes[frame].load(Ordering::Relaxed);
assert!(
word == DrawMode::Occlusion.word() || word == SMALL_FEATURE_ONLY,
"frame {frame} was not begun with the occlusion culls"
);
let occlusion = self
.occlusion
.as_ref()
.unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
self.record_passes(
graph,
frame,
instance_count,
Some((occlusion.early, occlusion.cull_pipeline_layout, pyramid)),
)
}
pub fn add_late_passes(
&self,
graph: &mut RenderGraph<'_>,
frame: usize,
instance_count: u32,
draws: &GeneratedDraws,
pyramid: &PyramidInputs<'_>,
) {
assert_eq!(
self.frame_modes[frame].load(Ordering::Relaxed),
DrawMode::Occlusion.word(),
"frame {frame} was not begun with the occlusion culls on"
);
let occlusion = self
.occlusion
.as_ref()
.unwrap_or_else(|| unreachable!("begin_frame_with checked the generator's mode"));
let groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
if groups != 0 {
let cull_group = self.cull_groups[frame];
let pyramid_group = pyramid.group;
let layout = occlusion.cull_pipeline_layout;
let pipeline = occlusion.late;
let mut pass = graph
.add_compute_pass("occlusion-late")
.use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite);
for &level in pyramid.levels {
pass = pass.read_image(level);
}
pass.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
encoder.bind_group(0, cull_group, &[], layout);
encoder.bind_group(1, pyramid_group, &[], layout);
encoder.dispatch(groups, 1, 1);
});
}
let gen_layout = self.gen_pipeline_layout;
let gen_group = self.gen_groups[frame];
for (label, pipeline, groups) in [
(
"draw-late-scatter",
occlusion.late_scatter,
instance_count.div_ceil(draw_gen::WORKGROUP_SIZE),
),
("draw-late-finish", occlusion.late_finish, 1),
] {
if groups == 0 {
continue;
}
graph
.add_compute_pass(label)
.read_buffer(draws.visible_count_id)
.use_buffer(draws.runs_id, ResourceState::ShaderReadWrite)
.use_buffer(draws.args_id, ResourceState::ShaderReadWrite)
.use_buffer(draws.counts_id, ResourceState::ShaderReadWrite)
.use_buffer(draws.group_state_id, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
encoder.bind_group(0, gen_group, &[], gen_layout);
encoder.dispatch(groups, 1, 1);
});
}
}
fn record_passes(
&self,
graph: &mut RenderGraph<'_>,
frame: usize,
instance_count: u32,
occlusion: Option<(
ComputePipelineHandle,
PipelineLayoutHandle,
&PyramidInputs<'_>,
)>,
) -> GeneratedDraws {
let import = |graph: &mut RenderGraph<'_>, label: &str, buffer, state| {
graph.import_buffer(
label,
ImportedBuffer {
buffer,
initial: state,
final_state: state,
},
)
};
let visible_count = import(
graph,
"cull-count",
self.visible_count[frame],
ResourceState::ShaderRead,
);
let runs = import(
graph,
"visible-and-bucket-runs",
self.runs[frame],
ResourceState::ShaderRead,
);
let args = import(
graph,
"draw-args",
self.args[frame],
ResourceState::IndirectArgument,
);
let counts = import(
graph,
"draw-counts-and-mesh-dispatch-args",
self.counts[frame],
ResourceState::IndirectArgument,
);
let group_state = import(
graph,
"lod-group-state",
self.group_state,
ResourceState::ShaderReadWrite,
);
let clear_pipeline = self.clear_pipeline;
let clear_layout = self.clear_pipeline_layout;
let clear_group = self.clear_groups[frame];
let regions = self.mode.regions();
let clear_groups = (regions * self.bucket_count * draw_gen::DRAW_ARGS_WORDS as u32)
.max(draw_gen::flat_args_word(
self.bucket_count,
regions,
regions,
0,
0,
))
.div_ceil(clear_counters::WORKGROUP_SIZE);
graph
.add_compute_pass("clear-counters")
.use_buffer(visible_count, ResourceState::ShaderReadWrite)
.use_buffer(args, ResourceState::ShaderReadWrite)
.use_buffer(counts, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(clear_pipeline);
encoder.bind_group(0, clear_group, &[], clear_layout);
encoder.dispatch(clear_groups, 1, 1);
});
let (cull_pipeline, cull_layout, pyramid_group) = match occlusion {
Some((pipeline, layout, pyramid)) => (pipeline, layout, Some(pyramid.group)),
None => (self.cull_pipeline, self.cull_pipeline_layout, None),
};
let cull_group = self.cull_groups[frame];
let cull_groups = instance_count.div_ceil(cull_shader::WORKGROUP_SIZE);
if cull_groups != 0 {
let mut pass = graph
.add_compute_pass("cull")
.use_buffer(runs, ResourceState::ShaderReadWrite)
.use_buffer(visible_count, ResourceState::ShaderReadWrite);
for &level in occlusion.map_or(&[][..], |(_, _, pyramid)| pyramid.levels) {
pass = pass.read_image(level);
}
pass.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(cull_pipeline);
encoder.bind_group(0, cull_group, &[], cull_layout);
if let Some(group) = pyramid_group {
encoder.bind_group(1, group, &[], cull_layout);
}
encoder.dispatch(cull_groups, 1, 1);
});
}
let gen_layout = self.gen_pipeline_layout;
let gen_group = self.gen_groups[frame];
let bin_groups = instance_count
.max(self.bucket_count)
.div_ceil(draw_gen::WORKGROUP_SIZE);
let scatter_groups = instance_count.div_ceil(draw_gen::WORKGROUP_SIZE);
let passes = [
("draw-args", self.bin_pipeline, bin_groups),
("draw-starts", self.starts_pipeline, 1),
("draw-scatter", self.scatter_pipeline, scatter_groups),
];
for (label, pipeline, groups) in passes {
if groups == 0 {
continue;
}
graph
.add_compute_pass(label)
.read_buffer(visible_count)
.use_buffer(runs, ResourceState::ShaderReadWrite)
.use_buffer(args, ResourceState::ShaderReadWrite)
.use_buffer(counts, ResourceState::ShaderReadWrite)
.use_buffer(group_state, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(pipeline);
encoder.bind_group(0, gen_group, &[], gen_layout);
encoder.dispatch(groups, 1, 1);
});
}
GeneratedDraws {
args: self.args[frame],
args_id: args,
counts: self.counts[frame],
counts_id: counts,
flat_args_offset: self.flat_args_offset(0, 0),
runs_id: runs,
group_state_id: group_state,
visible_count_id: visible_count,
}
}
pub fn destroy(self, device: &dyn Device) {
if let Some(occlusion) = self.occlusion {
for pipeline in [
occlusion.early,
occlusion.late,
occlusion.late_scatter,
occlusion.late_finish,
] {
device.destroy_compute_pipeline(pipeline);
}
device.destroy_pipeline_layout(occlusion.cull_pipeline_layout);
device.destroy_bind_group_layout(occlusion.pyramid_layout);
}
device.destroy_compute_pipeline(self.scatter_pipeline);
device.destroy_compute_pipeline(self.starts_pipeline);
device.destroy_compute_pipeline(self.bin_pipeline);
device.destroy_pipeline_layout(self.gen_pipeline_layout);
device.destroy_compute_pipeline(self.cull_pipeline);
device.destroy_pipeline_layout(self.cull_pipeline_layout);
device.destroy_compute_pipeline(self.clear_pipeline);
device.destroy_pipeline_layout(self.clear_pipeline_layout);
for group in self
.gen_groups
.into_iter()
.chain(self.cull_groups)
.chain(self.clear_groups)
{
device.destroy_bind_group(group);
}
device.destroy_bind_group_layout(self.gen_layout);
device.destroy_bind_group_layout(self.cull_layout);
device.destroy_bind_group_layout(self.clear_layout);
for buffer in [self.tables, self.clear_params, self.group_state]
.into_iter()
.chain(self.gen_params)
.chain(self.cull_params)
.chain(self.visible_count)
.chain(self.runs)
.chain(self.args)
.chain(self.counts)
{
device.destroy_buffer(buffer);
}
}
}
pub(crate) const fn uniform(binding: u32) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
}
}
pub(crate) const UINT_STRIDE: u32 = size_of::<u32>() as u32;
pub(crate) const fn storage(binding: u32, read_only: bool, stride: u32) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::StorageBuffer {
read_only,
dynamic: false,
stride,
},
count: 1,
flags: BindingFlags::empty(),
}
}
pub(crate) const fn bound(binding: u32, buffer: BufferHandle) -> BindGroupEntry {
BindGroupEntry {
binding,
array_index: 0,
resource: BindingResource::whole_buffer(buffer),
}
}
pub(crate) fn compute_pipeline(
device: &dyn Device,
label: &str,
shader: &crcbl_shaders::Shader,
layout: PipelineLayoutHandle,
workgroup_size: u32,
) -> Result<ComputePipelineHandle, HalError> {
let entry_point = shader.entry_point(Stage::Compute).ok_or_else(|| {
HalError::ShaderCompilation(format!(
"{}.slang exposes no unambiguous compute entry point; the committed SPIR-V and its \
manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
shader.name()
))
})?;
compute_pipeline_entry(device, label, shader, entry_point, layout, workgroup_size)
}
pub(crate) fn compute_pipeline_entry(
device: &dyn Device,
label: &str,
shader: &crcbl_shaders::Shader,
entry_point: &str,
layout: PipelineLayoutHandle,
workgroup_size: u32,
) -> Result<ComputePipelineHandle, HalError> {
compute_pipeline_entry_with_workgroup(
device,
label,
shader,
entry_point,
layout,
[workgroup_size, 1, 1],
)
}
pub(crate) fn compute_pipeline_entry_with_workgroup(
device: &dyn Device,
label: &str,
shader: &crcbl_shaders::Shader,
entry_point: &str,
layout: PipelineLayoutHandle,
workgroup_size: [u32; 3],
) -> Result<ComputePipelineHandle, HalError> {
let module = device.create_shader_module(&ShaderModuleDesc {
label: Some(shader.name()),
spirv: shader.spirv(),
wgsl: shader.wgsl(),
msl: shader.msl(),
dxil: &shader.dxil_containers(),
})?;
let pipeline = device.create_compute_pipeline(&ComputePipelineDesc {
label: Some(label),
layout,
compute: ShaderEntry {
module,
entry_point,
},
workgroup_size,
});
device.destroy_shader_module(module);
pipeline
}
pub(crate) fn fill_at_start_up(
device: &dyn Device,
queue: QueueHandle,
label: &str,
buffer: BufferHandle,
contents: &[u8],
final_state: ResourceState,
) -> Result<(), HalError> {
let size = u64::try_from(contents.len()).map_err(|_| {
HalError::InvalidDescriptor(format!(
"{label} is {} bytes, which does not fit a buffer size",
contents.len()
))
})?;
let staging = device.create_buffer(&BufferDesc {
label: Some(&format!("{label} staging")),
size,
usage: BufferUsage::TRANSFER_SRC,
memory: MemoryLocation::HostUpload,
})?;
let filled = record_fill(device, queue, label, buffer, staging, contents, final_state);
device.destroy_buffer(staging);
filled
}
fn record_fill(
device: &dyn Device,
queue: QueueHandle,
label: &str,
buffer: BufferHandle,
staging: BufferHandle,
contents: &[u8],
final_state: ResourceState,
) -> Result<(), HalError> {
device.write_buffer(staging, 0, contents)?;
let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
label: Some(&format!("{label} zero")),
queue,
});
encoder.pipeline_barrier(&Barriers {
buffers: &[BufferBarrier::new(
buffer,
ResourceState::Undefined,
ResourceState::TransferDst,
)],
..Barriers::default()
});
encoder.copy_buffer_to_buffer(&BufferCopy {
src: staging,
src_offset: 0,
dst: buffer,
dst_offset: 0,
size: contents.len() as u64,
});
encoder.pipeline_barrier(&Barriers {
buffers: &[BufferBarrier::new(
buffer,
ResourceState::TransferDst,
final_state,
)],
..Barriers::default()
});
let commands = encoder.finish()?;
let submitted = device
.submit(queue, &SubmitInfo::new(&[commands]))
.and_then(|()| device.wait_idle());
device.destroy_command_buffer(commands);
submitted
}
#[derive(Debug, Default)]
struct Rollback {
buffers: Vec<BufferHandle>,
bind_groups: Vec<BindGroupHandle>,
bind_group_layouts: Vec<BindGroupLayoutHandle>,
pipeline_layouts: Vec<PipelineLayoutHandle>,
pipelines: Vec<ComputePipelineHandle>,
}
impl Rollback {
fn disarm(&mut self) {
*self = Self::default();
}
fn run(self, device: &dyn Device) {
for handle in self.pipelines {
device.destroy_compute_pipeline(handle);
}
for handle in self.pipeline_layouts {
device.destroy_pipeline_layout(handle);
}
for handle in self.bind_groups {
device.destroy_bind_group(handle);
}
for handle in self.bind_group_layouts {
device.destroy_bind_group_layout(handle);
}
for handle in self.buffers {
device.destroy_buffer(handle);
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crcbl_hal::null::{NullInstance, Recorder};
use crcbl_hal::{DeviceDesc, Instance, QueueKind};
use crcbl_shaders::level_select::MeshLevels;
fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
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");
let queue = device.queue(QueueKind::Graphics).expect("always present");
(recorder, device, queue)
}
fn generator(device: &dyn Device, queue: QueueHandle, capacity: u32, buckets: u32) -> DrawGen {
generator_in(device, queue, capacity, buckets, DrawMode::Plain)
}
fn generator_in(
device: &dyn Device,
queue: QueueHandle,
capacity: u32,
buckets: u32,
mode: DrawMode,
) -> DrawGen {
let storage = |label: &str, size: u64| {
device
.create_buffer(&BufferDesc {
label: Some(label),
size,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::HostUpload,
})
.expect("a storage buffer")
};
let instances = [storage("instances", 4)];
let mesh_table = storage("mesh table", 4);
let bucket_meshes: Vec<u32> = (0..buckets).collect();
let zeroes = vec![0u32; bucket_meshes.len()];
let mesh_levels: Vec<MeshLevels> = bucket_meshes
.iter()
.map(|mesh| MeshLevels {
first_level: *mesh,
..MeshLevels::FLAT
})
.collect();
DrawGen::new(
device,
queue,
&DrawGenDesc {
label: Some("draw gen test"),
instances: &instances,
mesh_table,
bucket_meshes: &bucket_meshes,
bucket_modes: &zeroes,
bucket_clusters: &zeroes,
bucket_cluster_bases: &zeroes,
mesh_levels: &mesh_levels,
level_groups: &[],
level_meshes: &bucket_meshes,
instance_capacity: capacity,
hidden_view: 0,
mode,
task_lanes: 0,
},
)
.expect("the null backend builds a generator")
}
#[test]
fn the_runs_buffer_grows_by_a_word_per_bucket() {
const CAPACITY: u32 = 1000;
let (recorder, device, queue) = open();
let device = device.as_ref();
let few = generator(device, queue, CAPACITY, 1);
let many = generator(device, queue, CAPACITY, 64);
let size = |draws: &DrawGen| {
recorder
.buffer_size(draws.runs(0))
.expect("the runs buffer is live")
};
let regions = u64::from(draw_gen::DRAW_REGIONS);
assert_eq!(
size(&many) - size(&few),
u64::from(many.bucket_count() - few.bucket_count()) * (2 * regions + 1) * 4,
"sixty-three more buckets cost sixty-three more words of run start and of chunk \
start a region, and of mesh, and nothing else"
);
assert_eq!(
size(&few),
(3 * u64::from(CAPACITY) + regions + 1 + 2 * regions) * 4,
"one bucket's generator holds the survivors, their routes, one capacity of runs, \
one start per region, its mesh, and its chunk start and the region's end per region"
);
for draws in [&few, &many] {
assert_eq!(
draws.runs_size(),
size(draws),
"and the accessor a reader sizes a copy by is the size that was allocated"
);
}
few.destroy(device);
many.destroy(device);
recorder.assert_valid();
}
#[test]
fn every_bucket_start_is_a_word_of_its_own_behind_the_runs() {
const CAPACITY: u32 = 100;
let (recorder, device, queue) = open();
let device = device.as_ref();
let draws = generator(device, queue, CAPACITY, 5);
assert_eq!(
draws.runs_at(),
2 * CAPACITY,
"past the survivors and their routes"
);
let starts: Vec<u32> = (0..draws.bucket_count())
.map(|bucket| draws.bucket_start_word(bucket))
.collect();
assert_eq!(
starts,
(0..5)
.map(|bucket| 3 * CAPACITY + bucket)
.collect::<Vec<_>>(),
"one word per bucket, in bucket order, behind one capacity of runs"
);
assert_eq!(
draws.region_start_word(1, 0),
starts[starts.len() - 1] + 1,
"region 1's starts directly behind region 0's"
);
assert_eq!(
draws.bucket_mesh_word(0),
draws.region_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count() - 1) + 1,
"the buckets' meshes directly behind the last region's starts"
);
assert_eq!(
draws.chunk_start_word(0, 0),
draws.bucket_mesh_word(draws.bucket_count() - 1) + 1,
"the chunk starts directly behind the last bucket's mesh"
);
assert_eq!(
draws.chunk_start_word(1, 0),
draws.chunk_start_word(0, draws.bucket_count()) + 1,
"each region's chunk starts, its end word included, directly behind the one before"
);
assert_eq!(
u64::from(draws.chunk_start_word(draw_gen::DRAW_REGIONS - 1, draws.bucket_count()) + 1)
* 4,
draws.runs_size(),
"and the last region's chunk end is the buffer's last word"
);
draws.destroy(device);
recorder.assert_valid();
}
#[test]
fn the_measured_scene_pays_a_word_per_bucket_rather_than_a_capacity() {
const CAPACITY: u32 = 17219;
const BUCKETS: u32 = 938;
let per_bucket_runs = u64::from(CAPACITY) * (1 + u64::from(BUCKETS)) * 4;
let shared_runs = u64::from(
draw_gen::runs_words(CAPACITY, BUCKETS, false).expect("the scene's layout addresses"),
) * 4;
assert_eq!(
per_bucket_runs, 64_674_564,
"61.7 MiB a buffer, as measured"
);
assert_eq!(
shared_runs, 262_936,
"256.8 KiB a buffer, with a run start and a chunk start per bucket for every draw \
region, a chunk end per region, and a mesh word per bucket"
);
}
#[test]
fn the_regions_cost_what_their_layout_says_in_the_measured_scene() {
const CAPACITY: u32 = 17219;
const BUCKETS: u32 = 938;
let (recorder, device, queue) = open();
let device = device.as_ref();
let size = |buffer| recorder.buffer_size(buffer).expect("live");
let per_frame = |mode| {
let draws = generator_in(device, queue, CAPACITY, BUCKETS, mode);
let bytes = size(draws.runs(0)) + size(draws.args(0)) + size(draws.counts(0));
draws.destroy(device);
bytes
};
let [plain, occlusion, faces] =
[DrawMode::Plain, DrawMode::Occlusion, DrawMode::Faces].map(per_frame);
assert_eq!(
plain, 296_776,
"runs, one region of arguments and one of counts, and its flat dispatches"
);
assert_eq!(
occlusion, 364_456,
"three regions of arguments, counts and flat dispatches"
);
assert_eq!(
faces, 913_076,
"seven regions and six capacities of face runs"
);
let before = (3 * u64::from(CAPACITY) + u64::from(BUCKETS)) * 4
+ u64::from(BUCKETS) * (draw_gen::DRAW_ARGS_SIZE as u64 + 16);
assert_eq!(before, 244_148);
let cascades = crate::shadow::CASCADES as u64;
let slots = crate::shadow::LIGHT_SLOTS as u64;
let renderer_before = before * (1 + cascades + slots);
let renderer_after = occlusion + plain * cascades + faces * slots;
assert_eq!(renderer_before, 1_709_036);
assert_eq!(
renderer_after, 4_610_312,
"4.40 MiB a frame in flight, against 1.63 MiB before"
);
recorder.assert_valid();
}
}