use crcbl_hal::{
BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, ClearValue, Device, Format,
GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, PipelineLayoutDesc,
PipelineLayoutHandle, ResourceState, SampleType, ShaderStages, StoreOp,
check_portable_storage_buffers,
};
use crcbl_shaders::HIZ;
use crcbl_shaders::cull::OCCLUSION_MAX_LEVELS;
use crate::graph::{ImageId, ImportedImage, InitialClaim, RenderGraph};
use crate::partial::Partial;
use crate::ssao::cached_group;
use crate::transient::TransientPool;
const FULLSCREEN_VERTICES: u32 = 3;
#[must_use]
pub fn levels_for(extent: (u32, u32)) -> u32 {
let mut levels = 0;
while levels < OCCLUSION_MAX_LEVELS
&& extent.0 >> (levels + 1) >= 1
&& extent.1 >> (levels + 1) >= 1
{
levels += 1;
}
levels
}
#[must_use]
pub const fn level_extent(extent: (u32, u32), level: u32) -> (u32, u32) {
(extent.0 >> level, extent.1 >> level)
}
crcbl_console::convar! {
pub static r_occlusion_cull: bool = false;
}
crcbl_console::convar! {
pub static r_small_feature_px: f32 in 0.0 ..= 64.0 = 0.0;
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OcclusionCulling {
pub occlusion: bool,
pub small_feature_pixels: Option<f32>,
}
impl OcclusionCulling {
pub const OFF: Self = Self {
occlusion: false,
small_feature_pixels: None,
};
#[must_use]
pub const fn any(self) -> bool {
self.occlusion || self.small_feature_pixels.is_some()
}
}
impl Default for OcclusionCulling {
fn default() -> Self {
Self::OFF
}
}
#[derive(Clone, Copy, Debug)]
struct Level {
image: ImageHandle,
view: ImageViewHandle,
}
#[derive(Debug)]
struct Chain {
extent: (u32, u32),
levels: Vec<Level>,
cull_group: BindGroupHandle,
reduce_groups: Vec<BindGroupHandle>,
}
#[derive(Debug)]
pub(crate) struct OcclusionPyramid {
layout: BindGroupLayoutHandle,
pipeline_layout: PipelineLayoutHandle,
pipeline: GraphicsPipelineHandle,
chain: Option<Chain>,
first_groups: Vec<Option<(Vec<ImageViewHandle>, BindGroupHandle)>>,
history: bool,
}
impl OcclusionPyramid {
pub(crate) const PASSES: u32 = OCCLUSION_MAX_LEVELS;
pub(crate) fn new(
device: &dyn Device,
frames: usize,
build_depth_fullscreen: impl Fn(
&dyn Device,
&str,
&crcbl_shaders::Shader,
&str,
&str,
PipelineLayoutHandle,
Format,
) -> Result<GraphicsPipelineHandle, HalError>,
) -> Result<Self, HalError> {
let entries = [BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Depth,
},
count: 1,
flags: BindingFlags::empty(),
}];
let desc = BindGroupLayoutDesc {
label: Some("occlusion hiz source"),
entries: &entries,
};
check_portable_storage_buffers(Some("occlusion hiz"), &[&desc])?;
let mut made = Partial::new(device);
let layout = made.add(device.create_bind_group_layout(&desc)?);
let pipeline_layout = made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("occlusion hiz"),
bind_group_layouts: &[layout],
push_constants: None,
})?);
let pipeline = made.add(build_depth_fullscreen(
device,
"occlusion hiz",
&HIZ,
"vertexMain",
"farthestMain",
pipeline_layout,
Format::D32Float,
)?);
made.keep();
Ok(Self {
layout,
pipeline_layout,
pipeline,
chain: None,
first_groups: vec![None; frames],
history: false,
})
}
pub(crate) fn prepare(
&mut self,
device: &dyn Device,
extent: (u32, u32),
cull_layout: BindGroupLayoutHandle,
) -> Result<(), HalError> {
if self
.chain
.as_ref()
.is_some_and(|chain| chain.extent == extent)
{
return Ok(());
}
if let Some(chain) = self.chain.take() {
destroy_chain(device, chain);
}
self.history = false;
let count = levels_for(extent);
if count == 0 {
return Ok(());
}
let mut levels: Vec<Level> = Vec::with_capacity(count as usize);
let built = (|| -> Result<Chain, HalError> {
for level in 1..=count {
let (width, height) = level_extent(extent, level);
let image = device.create_image(&ImageDesc {
label: Some(&format!("occlusion pyramid {level}")),
image_type: ImageType::D2,
format: Format::D32Float,
extent: crcbl_hal::Extent3d::d2(width, height),
mip_levels: 1,
samples: 1,
usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
.union(ImageUsage::SAMPLED)
.union(ImageUsage::TRANSFER_SRC),
})?;
let view = match device.create_image_view(&ImageViewDesc {
label: Some(&format!("occlusion pyramid {level}")),
image,
view_type: ImageViewType::D2,
format: Format::D32Float,
range: ImageSubresourceRange::all(Format::D32Float),
}) {
Ok(view) => view,
Err(error) => {
device.destroy_image(image);
return Err(error);
}
};
levels.push(Level { image, view });
}
let deepest = levels[levels.len() - 1];
let cull_entries: Vec<BindGroupEntry> = (0..OCCLUSION_MAX_LEVELS)
.map(|binding| BindGroupEntry {
binding,
array_index: 0,
resource: BindingResource::ImageView(
levels.get(binding as usize).unwrap_or(&deepest).view,
),
})
.collect();
let cull_group = device.create_bind_group(&BindGroupDesc {
label: Some("occlusion pyramid"),
layout: cull_layout,
entries: &cull_entries,
variable_count: None,
})?;
let mut reduce_groups = Vec::with_capacity(levels.len().saturating_sub(1));
for source in &levels[..levels.len() - 1] {
match device.create_bind_group(&BindGroupDesc {
label: Some("occlusion hiz"),
layout: self.layout,
entries: &[BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(source.view),
}],
variable_count: None,
}) {
Ok(group) => reduce_groups.push(group),
Err(error) => {
for group in reduce_groups {
device.destroy_bind_group(group);
}
device.destroy_bind_group(cull_group);
return Err(error);
}
}
}
Ok(Chain {
extent,
levels: levels.clone(),
cull_group,
reduce_groups,
})
})();
match built {
Ok(chain) => {
self.chain = Some(chain);
Ok(())
}
Err(error) => {
for level in levels {
device.destroy_image_view(level.view);
device.destroy_image(level.image);
}
Err(error)
}
}
}
pub(crate) fn levels(&self) -> u32 {
self.chain
.as_ref()
.map_or(0, |chain| u32::try_from(chain.levels.len()).unwrap_or(0))
}
pub(crate) fn take_history(&mut self, extent: (u32, u32)) -> bool {
let history = self.history
&& self
.chain
.as_ref()
.is_some_and(|chain| chain.extent == extent);
self.history = false;
history
}
pub(crate) fn cull_group(&self) -> Option<BindGroupHandle> {
self.chain.as_ref().map(|chain| chain.cull_group)
}
pub(crate) fn import(&self, graph: &mut RenderGraph<'_>, pool: &TransientPool) -> Vec<ImageId> {
let Some(chain) = &self.chain else {
return Vec::new();
};
chain
.levels
.iter()
.enumerate()
.map(|(index, level)| {
graph.import_image(
format!("occlusion-pyramid-{}", index + 1),
ImportedImage {
image: level.image,
view: level.view,
format: Format::D32Float,
extent: level_extent(chain.extent, index as u32 + 1),
initial: pool
.imported_image_use(level.image)
.unwrap_or(ResourceState::Undefined),
claim: InitialClaim::Tracked,
final_state: ResourceState::ShaderRead,
},
)
})
.collect()
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
depth: ImageId,
levels: &[ImageId],
) {
let Some(chain) = &self.chain else {
return;
};
assert_eq!(
levels.len(),
chain.levels.len(),
"the caller imported a different pyramid than the one prepared"
);
self.history = true;
let layout = self.layout;
let pipeline_layout = self.pipeline_layout;
let pipeline = self.pipeline;
let first = &mut self.first_groups[frame];
let mut reduce = chain.reduce_groups.iter().copied();
let mut first = Some(first);
for (index, &target) in levels.iter().enumerate() {
let source = if index == 0 { depth } else { levels[index - 1] };
let pass = graph
.add_render_pass(format!("occlusion-hiz-{}", index + 1))
.depth(
target,
LoadOp::DontCare,
StoreOp::Store,
ClearValue::default(),
)
.read_image(source);
if index == 0 {
let cached = first
.take()
.unwrap_or_else(|| unreachable!("level 1 is reduced once"));
pass.execute(move |ctx| {
let view = ctx.image_view(source);
let device = ctx.device();
let entries = [BindGroupEntry {
binding: 0,
array_index: 0,
resource: BindingResource::ImageView(view),
}];
let Some(group) = cached_group(
cached,
device,
&[(0, view)],
"occlusion hiz",
layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
} else {
let group = reduce
.next()
.unwrap_or_else(|| unreachable!("a group per level below the first"));
pass.execute(move |ctx| {
let encoder = ctx.encoder();
encoder.bind_graphics_pipeline(pipeline);
encoder.bind_group(0, group, &[], pipeline_layout);
encoder.draw(0..FULLSCREEN_VERTICES, 0..1);
});
}
}
}
pub(crate) fn level_images(&self) -> Vec<(ImageHandle, ImageViewHandle, (u32, u32))> {
self.chain.as_ref().map_or_else(Vec::new, |chain| {
chain
.levels
.iter()
.zip(1..)
.map(|(level, index)| (level.image, level.view, level_extent(chain.extent, index)))
.collect()
})
}
pub(crate) fn destroy(self, device: &dyn Device) {
if let Some(chain) = self.chain {
destroy_chain(device, chain);
}
for cached in self.first_groups.into_iter().flatten() {
device.destroy_bind_group(cached.1);
}
device.destroy_graphics_pipeline(self.pipeline);
device.destroy_pipeline_layout(self.pipeline_layout);
device.destroy_bind_group_layout(self.layout);
}
}
fn destroy_chain(device: &dyn Device, chain: Chain) {
device.destroy_bind_group(chain.cull_group);
for group in chain.reduce_groups {
device.destroy_bind_group(group);
}
for level in chain.levels {
device.destroy_image_view(level.view);
device.destroy_image(level.image);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pyramid_stops_at_one_texel_or_at_the_bindings() {
assert_eq!(levels_for((1, 1)), 0, "nothing to halve");
assert_eq!(
levels_for((256, 1)),
0,
"a one-row target halves to nothing"
);
assert_eq!(levels_for((2, 2)), 1);
assert_eq!(levels_for((256, 192)), 7);
assert_eq!(level_extent((256, 192), 7), (2, 1));
assert_eq!(levels_for((97, 61)), 5);
assert_eq!(level_extent((97, 61), 5), (3, 1));
assert_eq!(levels_for((1920, 1080)), OCCLUSION_MAX_LEVELS);
assert_eq!(level_extent((1920, 1080), OCCLUSION_MAX_LEVELS), (7, 4));
}
#[test]
fn the_pyramid_costs_a_third_of_the_prepass() {
let extent = (1920, 1080);
let prepass = u64::from(extent.0) * u64::from(extent.1);
let pyramid: u64 = (1..=levels_for(extent))
.map(|level| {
let (width, height) = level_extent(extent, level);
u64::from(width) * u64::from(height)
})
.sum();
assert_eq!(pyramid * 4, 2_764_192, "2.64 MiB of level texels");
assert!(
pyramid * 3 <= prepass && pyramid * 3 + prepass / 100 >= prepass,
"a third of the prepass's {prepass} texels, to within one per cent: {pyramid}"
);
}
}