use crcbl_hal::{
BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
BufferUsage, ClearValue, ColorTargetState, ComputePipelineHandle, Device, Format,
GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, SampleType, ShaderStages, StoreOp,
check_portable_storage_buffers,
};
use crcbl_shaders::cmaa2::{ACCUM_WORDS, Cmaa2Params, PARAMS_SIZE, WORD_BYTES, WORKGROUP_SIZE};
use crcbl_shaders::{CMAA2_APPLY, CMAA2_EDGES, CMAA2_SHAPES};
use std::cell::Cell;
use std::rc::Rc;
use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline_entry, storage, uniform};
use crate::graph::{ImageId, RenderGraph};
use crate::partial::Partial;
use crate::transient::TransientBufferDesc;
const FULLSCREEN_VERTICES: u32 = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct GroupKey {
source: ImageViewHandle,
buffers: [BufferHandle; 2],
}
#[derive(Debug)]
pub(crate) struct Cmaa2 {
working_layout: BindGroupLayoutHandle,
working_pipeline_layout: PipelineLayoutHandle,
edges: ComputePipelineHandle,
shapes: ComputePipelineHandle,
apply_layout: BindGroupLayoutHandle,
apply_pipeline_layout: PipelineLayoutHandle,
apply_pipeline: GraphicsPipelineHandle,
uniforms: Vec<BufferHandle>,
working_groups: Vec<Option<(GroupKey, BindGroupHandle)>>,
apply_groups: Vec<Option<(GroupKey, BindGroupHandle)>>,
params: Cmaa2Params,
}
fn sampled_compute(binding: u32) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
}
}
impl Cmaa2 {
pub(crate) const PASSES: u32 = 3;
pub(crate) const FULLSCREEN_PASSES: u64 = 1;
pub(crate) fn new(
device: &dyn Device,
frames: usize,
target_format: Format,
build_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
PipelineLayoutHandle,
&[ColorTargetState],
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
let working_entries = [
uniform(0),
sampled_compute(1),
storage(2, false, UINT_STRIDE),
storage(3, false, UINT_STRIDE),
];
let working_desc = BindGroupLayoutDesc {
label: Some("cmaa2 working"),
entries: &working_entries,
};
let apply_entries = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: UINT_STRIDE,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::UniformBuffer { dynamic: false },
count: 1,
flags: BindingFlags::empty(),
},
];
let apply_desc = BindGroupLayoutDesc {
label: Some("cmaa2 apply"),
entries: &apply_entries,
};
check_portable_storage_buffers(Some("cmaa2"), &[&working_desc, &apply_desc])?;
let mut made = Partial::new(device);
let working_layout = made.add(device.create_bind_group_layout(&working_desc)?);
let working_set_layouts = [working_layout];
let working_pipeline_layout =
made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("cmaa2 working"),
bind_group_layouts: &working_set_layouts,
push_constants: None,
})?);
let edges = made.add(compute_pipeline_entry(
device,
"cmaa2 edges",
&CMAA2_EDGES,
"edgesMain",
working_pipeline_layout,
WORKGROUP_SIZE,
)?);
let shapes = made.add(compute_pipeline_entry(
device,
"cmaa2 shapes",
&CMAA2_SHAPES,
"shapesMain",
working_pipeline_layout,
WORKGROUP_SIZE,
)?);
let apply_layout = made.add(device.create_bind_group_layout(&apply_desc)?);
let apply_set_layouts = [apply_layout];
let apply_pipeline_layout =
made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("cmaa2 apply"),
bind_group_layouts: &apply_set_layouts,
push_constants: None,
})?);
let apply_pipeline = made.add(build_fullscreen(
device,
"cmaa2-apply",
&CMAA2_APPLY,
apply_pipeline_layout,
&[ColorTargetState::opaque(target_format)],
)?);
let mut uniforms = Vec::with_capacity(frames);
for _ in 0..frames {
uniforms.push(made.add(device.create_buffer(&BufferDesc {
label: Some("cmaa2 params"),
size: PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?));
}
made.keep();
Ok(Self {
working_layout,
working_pipeline_layout,
edges,
shapes,
apply_layout,
apply_pipeline_layout,
apply_pipeline,
uniforms,
working_groups: (0..frames).map(|_| None).collect(),
apply_groups: (0..frames).map(|_| None).collect(),
params: Cmaa2Params::default(),
})
}
pub(crate) fn begin_frame(
&mut self,
device: &dyn Device,
frame: usize,
extent: (u32, u32),
) -> Result<(), HalError> {
self.params = Cmaa2Params::for_extent(extent.0, extent.1);
device.write_buffer(self.uniforms[frame], 0, &self.params.to_bytes())
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
source: ImageId,
target: ImageId,
) {
let params = self.params;
let pixels = u64::from(params.viewport_x) * u64::from(params.viewport_y);
let edge_words = graph.create_buffer(
"cmaa2-edges",
TransientBufferDesc::storage(pixels * WORD_BYTES),
);
let accum = graph.create_buffer(
"cmaa2-accum",
TransientBufferDesc::storage(pixels * u64::from(ACCUM_WORDS) * WORD_BYTES),
);
let uniforms = self.uniforms[frame];
let working_layout = self.working_layout;
let working_pipeline_layout = self.working_pipeline_layout;
let apply_layout = self.apply_layout;
let apply_pipeline_layout = self.apply_pipeline_layout;
let apply_pipeline = self.apply_pipeline;
let (edges, shapes) = (self.edges, self.shapes);
let Self {
working_groups,
apply_groups,
..
} = self;
let working_cached = &mut working_groups[frame];
let apply_cached = &mut apply_groups[frame];
let pixel_groups = groups_for(params.viewport_x.saturating_mul(params.viewport_y));
let working: Rc<Cell<Option<BindGroupHandle>>> = Rc::new(Cell::new(None));
let build = Rc::clone(&working);
graph
.add_compute_pass("cmaa2-edges")
.use_buffer(edge_words, ResourceState::ShaderReadWrite)
.use_buffer(accum, ResourceState::ShaderReadWrite)
.read_image(source)
.execute(move |ctx| {
let view = ctx.image_view(source);
let handles = [ctx.buffer(edge_words), ctx.buffer(accum)];
let entries = [
bound(0, uniforms),
BindGroupEntry {
binding: 1,
array_index: 0,
resource: BindingResource::ImageView(view),
},
bound(2, handles[0]),
bound(3, handles[1]),
];
let Some(group) = cached_group(
working_cached,
ctx.device(),
GroupKey {
source: view,
buffers: handles,
},
"cmaa2 working",
working_layout,
&entries,
) else {
return;
};
build.set(Some(group));
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(edges);
encoder.bind_group(0, group, &[], working_pipeline_layout);
encoder.dispatch(pixel_groups, 1, 1);
});
let bind = working;
graph
.add_compute_pass("cmaa2-shapes")
.use_buffer(edge_words, ResourceState::ShaderReadWrite)
.use_buffer(accum, ResourceState::ShaderReadWrite)
.read_image(source)
.execute(move |ctx| {
let Some(group) = bind.get() else {
return;
};
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(shapes);
encoder.bind_group(0, group, &[], working_pipeline_layout);
encoder.dispatch(pixel_groups, 1, 1);
});
graph
.add_render_pass("cmaa2-apply")
.color(
target,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(source)
.read_buffer(accum)
.execute(move |ctx| {
let view = ctx.image_view(source);
let accumulation = ctx.buffer(accum);
let entries = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(view),
},
bound(1, accumulation),
bound(2, uniforms),
];
let Some(group) = cached_group(
apply_cached,
ctx.device(),
GroupKey {
source: view,
buffers: [accumulation; 2],
},
"cmaa2 apply",
apply_layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(apply_pipeline);
encoder.bind_group(0, group, &[], apply_pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
pub(crate) fn destroy(self, device: &dyn Device) {
for (_, group) in self
.working_groups
.into_iter()
.chain(self.apply_groups)
.flatten()
{
device.destroy_bind_group(group);
}
device.destroy_graphics_pipeline(self.apply_pipeline);
device.destroy_compute_pipeline(self.shapes);
device.destroy_compute_pipeline(self.edges);
device.destroy_pipeline_layout(self.apply_pipeline_layout);
device.destroy_pipeline_layout(self.working_pipeline_layout);
device.destroy_bind_group_layout(self.apply_layout);
device.destroy_bind_group_layout(self.working_layout);
for buffer in self.uniforms {
device.destroy_buffer(buffer);
}
}
}
fn groups_for(invocations: u32) -> u32 {
invocations.div_ceil(WORKGROUP_SIZE).max(1)
}
fn cached_group(
cache: &mut Option<(GroupKey, BindGroupHandle)>,
device: &dyn Device,
key: GroupKey,
label: &str,
layout: BindGroupLayoutHandle,
entries: &[BindGroupEntry],
) -> Option<BindGroupHandle> {
if let Some((cached, group)) = cache
&& *cached == key
{
return Some(*group);
}
if let Some((_, stale)) = cache.take() {
device.destroy_bind_group(stale);
}
match device.create_bind_group(&crcbl_hal::BindGroupDesc {
label: Some(label),
layout,
entries,
variable_count: None,
}) {
Ok(group) => {
*cache = Some((key, group));
Some(group)
}
Err(error) => {
crcbl_core::log::error!("graph: {label} bind group failed: {error}");
None
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn all_buffers_and_source_invalidate_and_failed_creation_retries() {
use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
use crcbl_hal::*;
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))
.unwrap();
let images: Vec<_> = (0..2)
.map(|_| {
device
.create_image(&ImageDesc {
label: Some("buffer cache source"),
image_type: ImageType::D2,
extent: Extent3d::d2(1, 1),
format: Format::Rgba8Unorm,
mip_levels: 1,
samples: 1,
usage: ImageUsage::SAMPLED,
})
.unwrap()
})
.collect();
let views: Vec<_> = images
.iter()
.map(|&image| {
device
.create_image_view(&ImageViewDesc {
label: Some("buffer cache source"),
image,
view_type: ImageViewType::D2,
format: Format::Rgba8Unorm,
range: ImageSubresourceRange::all(Format::Rgba8Unorm),
})
.unwrap()
})
.collect();
let buffers: Vec<_> = (0..4)
.map(|_| {
device
.create_buffer(&BufferDesc {
label: Some("buffer cache working"),
size: 16,
usage: BufferUsage::STORAGE,
memory: MemoryLocation::DeviceLocal,
})
.unwrap()
})
.collect();
let slots = [
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::StorageBuffer {
read_only: false,
dynamic: false,
stride: 4,
},
count: 1,
flags: BindingFlags::empty(),
},
BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::StorageBuffer {
read_only: false,
dynamic: false,
stride: 4,
},
count: 1,
flags: BindingFlags::empty(),
},
];
let layout = device
.create_bind_group_layout(&BindGroupLayoutDesc {
label: Some("buffer cache"),
entries: &slots,
})
.unwrap();
let bad_layout = device
.create_bind_group_layout(&BindGroupLayoutDesc {
label: Some("missing buffer slots"),
entries: &slots[..1],
})
.unwrap();
let mut cache = None;
let call = |cache: &mut Option<(GroupKey, BindGroupHandle)>, key: GroupKey, layout| {
let entries = [
BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(key.source),
},
BindGroupEntry {
binding: 1,
array_index: 0,
resource: BindingResource::whole_buffer(key.buffers[0]),
},
BindGroupEntry {
binding: 2,
array_index: 0,
resource: BindingResource::whole_buffer(key.buffers[1]),
},
];
cached_group(
cache,
device.as_ref(),
key,
"buffer cache",
layout,
&entries,
)
};
let initial = GroupKey {
source: views[0],
buffers: [buffers[0], buffers[1]],
};
let mut previous = call(&mut cache, initial, layout).unwrap();
assert_eq!(call(&mut cache, initial, layout), Some(previous));
recorder.assert_valid();
recorder.clear();
let first_buffer = GroupKey {
buffers: [buffers[2], buffers[1]],
..initial
};
let second_buffer = GroupKey {
buffers: [buffers[2], buffers[3]],
..initial
};
let source = GroupKey {
source: views[1],
..second_buffer
};
for (label, key) in [
("first buffer", first_buffer),
("second buffer", second_buffer),
("source view", source),
] {
let next = call(&mut cache, key, layout).unwrap();
assert_ne!(previous, next, "replacement of {label} must invalidate");
assert_eq!(cache.as_ref().unwrap().0, key);
assert_eq!(recorder.live_objects(ObjectKind::BindGroup), 1);
assert_eq!(call(&mut cache, key, layout), Some(next));
previous = next;
}
let events = recorder.events();
assert_eq!(
events
.iter()
.filter(|e| matches!(
e,
Event::Created {
kind: ObjectKind::BindGroup,
..
}
))
.count(),
3
);
assert_eq!(
events
.iter()
.filter(|e| matches!(
e,
Event::Destroyed {
kind: ObjectKind::BindGroup
}
))
.count(),
3
);
assert_eq!(call(&mut cache, initial, bad_layout), None);
assert_eq!(cache, None);
assert_eq!(recorder.live_objects(ObjectKind::BindGroup), 0);
let retry = call(&mut cache, initial, layout).unwrap();
assert_ne!(retry, previous);
recorder.assert_valid();
device.destroy_bind_group(cache.take().unwrap().1);
device.destroy_bind_group_layout(layout);
device.destroy_bind_group_layout(bad_layout);
for buffer in buffers {
device.destroy_buffer(buffer);
}
for view in views {
device.destroy_image_view(view);
}
for image in images {
device.destroy_image(image);
}
recorder.assert_valid();
assert_eq!(recorder.total_live_objects(), 0);
}
#[test]
fn a_dispatch_always_covers_at_least_one_group() {
assert_eq!(groups_for(0), 1);
assert_eq!(groups_for(1), 1);
assert_eq!(groups_for(WORKGROUP_SIZE), 1);
assert_eq!(groups_for(WORKGROUP_SIZE + 1), 2);
}
#[test]
fn every_buffer_holds_one_entry_per_pixel_of_the_block_the_shaders_read() {
let params = Cmaa2Params::for_extent(320, 240);
let pixels = u64::from(params.viewport_x) * u64::from(params.viewport_y);
assert_eq!(pixels, 320 * 240);
assert_eq!(pixels * WORD_BYTES, 320 * 240 * 4);
assert_eq!(
pixels * u64::from(ACCUM_WORDS) * WORD_BYTES,
320 * 240 * 4 * 4
);
}
}