use crcbl_core::Handle;
use crate::{
BackendKind, DeviceCaps, Features, Format, HalError, ImageViewHandle, ImageViewType, Limits,
SamplerHandle, ShaderEntry, ShaderStages, resource::BufferHandle,
};
#[derive(Debug)]
pub enum PipelineLayout {}
#[derive(Debug)]
pub enum BindGroupLayout {}
#[derive(Debug)]
pub enum BindGroup {}
#[derive(Debug)]
pub enum GraphicsPipeline {}
#[derive(Debug)]
pub enum ComputePipeline {}
pub type PipelineLayoutHandle = Handle<PipelineLayout>;
pub type BindGroupLayoutHandle = Handle<BindGroupLayout>;
pub type BindGroupHandle = Handle<BindGroup>;
pub type GraphicsPipelineHandle = Handle<GraphicsPipeline>;
pub type ComputePipelineHandle = Handle<ComputePipeline>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SampleType {
#[default]
Float,
UnfilterableFloat,
Depth,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BindingKind {
UniformBuffer {
dynamic: bool,
},
StorageBuffer {
read_only: bool,
dynamic: bool,
stride: u32,
},
SampledImage {
view_type: ImageViewType,
sample_type: SampleType,
},
StorageImage {
read_only: bool,
view_type: ImageViewType,
format: Format,
},
Sampler {
comparison: bool,
},
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BindingFlags: u32 {
const PARTIALLY_BOUND = 1 << 0;
const UPDATE_AFTER_BIND = 1 << 1;
const VARIABLE_COUNT = 1 << 2;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupLayoutEntry {
pub binding: u32,
pub visibility: ShaderStages,
pub kind: BindingKind,
pub count: u32,
pub flags: BindingFlags,
}
impl BindGroupLayoutEntry {
#[must_use]
pub fn resolved_count(&self, limits: &Limits) -> u32 {
if self.count == u32::MAX {
limits.max_bindless_descriptors.max(1)
} else {
self.count
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupLayoutDesc<'a> {
pub label: Option<&'a str>,
pub entries: &'a [BindGroupLayoutEntry],
}
impl BindGroupLayoutDesc<'_> {
pub fn check_entries(&self, caps: &DeviceCaps, backend: BackendKind) -> Result<(), HalError> {
let indexing = caps.features.contains(Features::DESCRIPTOR_INDEXING);
for (index, entry) in self.entries.iter().enumerate() {
entry.visibility.check_supported(caps.features, backend)?;
if entry.count == 0 {
return Err(HalError::InvalidDescriptor(format!(
"binding {} has count 0; a binding must hold at least one descriptor",
entry.binding
)));
}
if matches!(entry.kind, BindingKind::StorageBuffer { stride: 0, .. }) {
return Err(HalError::InvalidDescriptor(format!(
"binding {} is a storage buffer with a stride of 0; a storage buffer's \
stride is the byte size of one element of the array the shader declares",
entry.binding
)));
}
if self.entries[..index]
.iter()
.any(|earlier| earlier.binding == entry.binding)
{
return Err(HalError::InvalidDescriptor(format!(
"binding {} is declared twice in one bind group layout",
entry.binding
)));
}
if !entry.flags.is_empty() && !indexing {
return Err(HalError::Unsupported {
backend,
what: "descriptor-indexing flags on a device without DESCRIPTOR_INDEXING",
});
}
if entry.flags.contains(BindingFlags::VARIABLE_COUNT) {
if index + 1 != self.entries.len() {
return Err(HalError::InvalidDescriptor(format!(
"binding {} sets VARIABLE_COUNT but is not the last entry of its layout; \
every \"the variable binding is `entries.last()`\" reading in a backend \
depends on it being last",
entry.binding
)));
}
if self
.entries
.iter()
.any(|other| other.binding > entry.binding)
{
return Err(HalError::InvalidDescriptor(format!(
"binding {} sets VARIABLE_COUNT but is not the highest-numbered binding of \
its layout; a runtime-sized array is only legal on the highest-numbered \
binding of a set",
entry.binding
)));
}
}
if indexing
&& entry.count != u32::MAX
&& entry.count > 1
&& entry.count > caps.limits.max_bindless_descriptors.max(1)
{
return Err(HalError::InvalidDescriptor(format!(
"binding {} asks for {} descriptors but max_bindless_descriptors is {}",
entry.binding, entry.count, caps.limits.max_bindless_descriptors
)));
}
}
Ok(())
}
}
pub const PORTABLE_STORAGE_BUFFERS_PER_STAGE: u32 = 8;
pub fn check_portable_storage_buffers(
label: Option<&str>,
layouts: &[&BindGroupLayoutDesc<'_>],
) -> Result<(), HalError> {
for (stage, name) in [
(ShaderStages::VERTEX, "vertex"),
(ShaderStages::FRAGMENT, "fragment"),
(ShaderStages::COMPUTE, "compute"),
] {
let used = layouts
.iter()
.flat_map(|layout| layout.entries.iter())
.filter(|entry| {
matches!(entry.kind, BindingKind::StorageBuffer { .. })
&& entry.visibility.contains(stage)
})
.fold(0u32, |total, entry| total.saturating_add(entry.count));
if used > PORTABLE_STORAGE_BUFFERS_PER_STAGE {
return Err(HalError::InvalidDescriptor(format!(
"pipeline layout {} binds {used} storage buffers in the {name} stage, and a \
WebGPU device guarantees only {PORTABLE_STORAGE_BUFFERS_PER_STAGE}; the limit is \
a sum over every bind group layout in one pipeline layout, so splitting them \
across groups does not help — pack the data into fewer buffers instead",
label.unwrap_or("<unlabelled>"),
)));
}
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BindingResource {
Buffer {
buffer: BufferHandle,
offset: u64,
size: u64,
},
ImageView(ImageViewHandle),
Sampler(SamplerHandle),
}
impl BindingResource {
pub const WHOLE_BUFFER: u64 = u64::MAX;
#[must_use]
pub const fn whole_buffer(buffer: BufferHandle) -> Self {
Self::Buffer {
buffer,
offset: 0,
size: Self::WHOLE_BUFFER,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupEntry {
pub binding: u32,
pub array_index: u32,
pub resource: BindingResource,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BindGroupDesc<'a> {
pub label: Option<&'a str>,
pub layout: BindGroupLayoutHandle,
pub entries: &'a [BindGroupEntry],
pub variable_count: Option<u32>,
}
pub fn check_binding_offset_alignment(
limits: &Limits,
kind: BindingKind,
binding: u32,
offset: u64,
) -> Result<(), HalError> {
let alignment = match kind {
BindingKind::UniformBuffer { .. } => limits.min_uniform_buffer_offset_alignment,
BindingKind::StorageBuffer { .. } => limits.min_storage_buffer_offset_alignment,
_ => 1,
};
if alignment > 1 && !offset.is_multiple_of(alignment) {
return Err(HalError::InvalidDescriptor(format!(
"binding {binding}'s buffer offset {offset} is not a multiple of this device's \
{alignment}-byte alignment for {kind:?}"
)));
}
Ok(())
}
pub fn check_dynamic_offsets(
limits: &Limits,
dynamic: &[BindGroupLayoutEntry],
offsets: &[u32],
) -> Result<(), HalError> {
if offsets.len() != dynamic.len() {
return Err(HalError::InvalidDescriptor(format!(
"bind_group was given {} dynamic offset(s) but the layout declares {} \
dynamic-offset binding(s)",
offsets.len(),
dynamic.len()
)));
}
for (entry, offset) in dynamic.iter().zip(offsets) {
let alignment = match entry.kind {
BindingKind::UniformBuffer { .. } => limits.min_uniform_buffer_offset_alignment,
_ => limits.min_storage_buffer_offset_alignment,
};
if alignment > 1 && !u64::from(*offset).is_multiple_of(alignment) {
return Err(HalError::InvalidDescriptor(format!(
"dynamic offset {offset} for binding {} is not a multiple of this device's \
{alignment}-byte alignment",
entry.binding
)));
}
}
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PushConstantRange {
pub stages: ShaderStages,
pub offset: u32,
pub size: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PipelineLayoutDesc<'a> {
pub label: Option<&'a str>,
pub bind_group_layouts: &'a [BindGroupLayoutHandle],
pub push_constants: Option<PushConstantRange>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PrimitiveTopology {
PointList,
LineList,
LineStrip,
#[default]
TriangleList,
TriangleStrip,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FrontFace {
#[default]
Ccw,
Cw,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CullMode {
#[default]
None,
Front,
Back,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PolygonMode {
#[default]
Fill,
Line,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct PrimitiveState {
pub topology: PrimitiveTopology,
pub front_face: FrontFace,
pub cull_mode: CullMode,
pub polygon_mode: PolygonMode,
pub depth_clamp: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CompareOp {
Never,
Less,
Equal,
LessOrEqual,
#[default]
Greater,
NotEqual,
GreaterOrEqual,
Always,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StencilOp {
#[default]
Keep,
Zero,
Replace,
Invert,
IncrementClamp,
DecrementClamp,
IncrementWrap,
DecrementWrap,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct StencilFaceState {
pub compare: CompareOp,
pub fail_op: StencilOp,
pub depth_fail_op: StencilOp,
pub pass_op: StencilOp,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct StencilState {
pub front: StencilFaceState,
pub back: StencilFaceState,
pub read_mask: u32,
pub write_mask: u32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct DepthBias {
pub constant: i32,
pub slope_scale: f32,
pub clamp: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DepthStencilState {
pub format: Format,
pub depth_write: bool,
pub depth_compare: CompareOp,
pub stencil: Option<StencilState>,
pub bias: DepthBias,
}
impl Default for DepthStencilState {
fn default() -> Self {
Self {
format: Format::D32Float,
depth_write: true,
depth_compare: CompareOp::Greater,
stencil: None,
bias: DepthBias::default(),
}
}
}
impl DepthStencilState {
#[must_use]
pub fn equal_depth_read_only(format: Format) -> Self {
Self {
format,
depth_write: false,
depth_compare: CompareOp::GreaterOrEqual,
stencil: None,
bias: DepthBias::default(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MultisampleState {
pub samples: u32,
pub alpha_to_coverage: bool,
}
impl Default for MultisampleState {
fn default() -> Self {
Self {
samples: 1,
alpha_to_coverage: false,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlendFactor {
Zero,
One,
Src,
OneMinusSrc,
SrcAlpha,
OneMinusSrcAlpha,
Dst,
OneMinusDst,
DstAlpha,
OneMinusDstAlpha,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BlendOp {
#[default]
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BlendState {
pub color_src: BlendFactor,
pub color_dst: BlendFactor,
pub color_op: BlendOp,
pub alpha_src: BlendFactor,
pub alpha_dst: BlendFactor,
pub alpha_op: BlendOp,
}
impl BlendState {
#[must_use]
pub const fn alpha() -> Self {
Self {
color_src: BlendFactor::SrcAlpha,
color_dst: BlendFactor::OneMinusSrcAlpha,
color_op: BlendOp::Add,
alpha_src: BlendFactor::One,
alpha_dst: BlendFactor::OneMinusSrcAlpha,
alpha_op: BlendOp::Add,
}
}
#[must_use]
pub const fn premultiplied() -> Self {
Self {
color_src: BlendFactor::One,
color_dst: BlendFactor::OneMinusSrcAlpha,
color_op: BlendOp::Add,
alpha_src: BlendFactor::One,
alpha_dst: BlendFactor::OneMinusSrcAlpha,
alpha_op: BlendOp::Add,
}
}
#[must_use]
pub const fn additive() -> Self {
Self {
color_src: BlendFactor::One,
color_dst: BlendFactor::One,
color_op: BlendOp::Add,
alpha_src: BlendFactor::One,
alpha_dst: BlendFactor::One,
alpha_op: BlendOp::Add,
}
}
}
bitflags::bitflags! {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ColorWrites: u32 {
const R = 1 << 0;
const G = 1 << 1;
const B = 1 << 2;
const A = 1 << 3;
const ALL = Self::R.bits() | Self::G.bits() | Self::B.bits() | Self::A.bits();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColorTargetState {
pub format: Format,
pub blend: Option<BlendState>,
pub write_mask: ColorWrites,
}
impl ColorTargetState {
#[must_use]
pub const fn opaque(format: Format) -> Self {
Self {
format,
blend: None,
write_mask: ColorWrites::ALL,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Viewport {
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
pub depth_min: f32,
pub depth_max: f32,
}
impl Viewport {
#[must_use]
pub fn from_size(width: u32, height: u32) -> Self {
Self {
x: 0.0,
y: 0.0,
width: width as f32,
height: height as f32,
depth_min: 0.0,
depth_max: 1.0,
}
}
}
impl Default for Viewport {
fn default() -> Self {
Self::from_size(0, 0)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphicsPipelineDesc<'a> {
pub label: Option<&'a str>,
pub layout: PipelineLayoutHandle,
pub vertex: ShaderEntry<'a>,
pub fragment: Option<ShaderEntry<'a>>,
pub primitive: PrimitiveState,
pub depth_stencil: Option<DepthStencilState>,
pub multisample: MultisampleState,
pub color_targets: &'a [ColorTargetState],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshPipelineDesc<'a> {
pub label: Option<&'a str>,
pub layout: PipelineLayoutHandle,
pub task: Option<ShaderEntry<'a>>,
pub task_workgroup_size: [u32; 3],
pub mesh: ShaderEntry<'a>,
pub mesh_workgroup_size: [u32; 3],
pub fragment: Option<ShaderEntry<'a>>,
pub primitive: PrimitiveState,
pub depth_stencil: Option<DepthStencilState>,
pub multisample: MultisampleState,
pub color_targets: &'a [ColorTargetState],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ComputePipelineDesc<'a> {
pub label: Option<&'a str>,
pub layout: PipelineLayoutHandle,
pub compute: ShaderEntry<'a>,
pub workgroup_size: [u32; 3],
}
impl MeshPipelineDesc<'_> {
pub fn check_workgroup_sizes(&self) -> Result<(), HalError> {
workgroup_invocations(self.mesh_workgroup_size, "mesh_workgroup_size")?;
if self.task.is_some() {
workgroup_invocations(self.task_workgroup_size, "task_workgroup_size")?;
}
Ok(())
}
}
fn workgroup_invocations(size: [u32; 3], what: &str) -> Result<u32, HalError> {
for (axis, extent) in size.into_iter().enumerate() {
if extent == 0 {
return Err(HalError::InvalidDescriptor(format!(
"{what} {size:?} is zero in dimension {axis}: a workgroup with no invocations runs \
nothing, and no shader declares one"
)));
}
}
size[0]
.checked_mul(size[1])
.and_then(|product| product.checked_mul(size[2]))
.ok_or_else(|| {
HalError::InvalidDescriptor(format!(
"{what} {size:?} overflows a u32 when multiplied out"
))
})
}
impl ComputePipelineDesc<'_> {
pub fn check_workgroup_size(&self, limits: &Limits) -> Result<(), HalError> {
let size = self.workgroup_size;
let invocations = workgroup_invocations(size, "workgroup_size")?;
for (axis, (extent, max)) in size
.into_iter()
.zip(limits.max_compute_workgroup_size)
.enumerate()
{
if extent > max {
return Err(HalError::InvalidDescriptor(format!(
"workgroup_size {size:?} exceeds this device's \
max_compute_workgroup_size {:?} in dimension {axis}",
limits.max_compute_workgroup_size
)));
}
}
if invocations > limits.max_compute_invocations_per_workgroup {
return Err(HalError::InvalidDescriptor(format!(
"workgroup_size {size:?} is {invocations} invocations, over this device's \
max_compute_invocations_per_workgroup {}",
limits.max_compute_invocations_per_workgroup
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::depth;
#[test]
fn depth_defaults_are_reversed_z() {
let state = DepthStencilState::default();
assert_eq!(state.depth_compare, CompareOp::Greater);
assert_eq!(state.format, Format::D32Float);
assert!(state.depth_write);
assert_eq!(CompareOp::default(), CompareOp::Greater);
}
#[test]
fn equal_depth_pass_uses_greater_or_equal_with_writes_off() {
let state = DepthStencilState::equal_depth_read_only(Format::D32Float);
assert_eq!(state.depth_compare, CompareOp::GreaterOrEqual);
assert!(!state.depth_write);
}
#[test]
fn viewport_depth_range_is_not_inverted() {
let viewport = Viewport::from_size(1920, 1080);
assert_eq!(viewport.depth_min, 0.0);
assert_eq!(viewport.depth_max, 1.0);
assert!(viewport.depth_min < viewport.depth_max);
assert_eq!(Viewport::default().depth_min, 0.0);
}
#[test]
fn clear_depth_agrees_with_the_default_compare_op() {
assert_eq!(depth::CLEAR, 0.0);
assert_eq!(depth::NEAR, 1.0);
let state = DepthStencilState::default();
assert_eq!(state.depth_compare, CompareOp::Greater);
const {
assert!(
depth::NEAR > depth::CLEAR,
"geometry at the near plane must beat the cleared far value"
);
}
}
#[test]
fn a_pipeline_layout_over_the_portable_storage_budget_is_refused() {
let storage = |binding: u32, visibility: ShaderStages| BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: 4,
},
count: 1,
flags: BindingFlags::empty(),
};
let compute: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE)
.map(|binding| storage(binding, ShaderStages::COMPUTE))
.collect();
let at_the_floor = BindGroupLayoutDesc {
label: Some("at the floor"),
entries: &compute,
};
check_portable_storage_buffers(at_the_floor.label, &[&at_the_floor])
.expect("exactly the guaranteed number is legal");
let mut over = compute.clone();
over.push(storage(
PORTABLE_STORAGE_BUFFERS_PER_STAGE,
ShaderStages::COMPUTE,
));
let over = BindGroupLayoutDesc {
label: Some("one over"),
entries: &over,
};
let error = check_portable_storage_buffers(over.label, &[&over]).expect_err("one over");
assert!(error.to_string().contains("one over"), "{error}");
assert!(error.to_string().contains("compute"), "{error}");
let (first, second) = compute.split_at(4);
let mut tail = second.to_vec();
tail.push(storage(
PORTABLE_STORAGE_BUFFERS_PER_STAGE,
ShaderStages::COMPUTE,
));
let first = BindGroupLayoutDesc {
label: Some("split"),
entries: first,
};
let second = BindGroupLayoutDesc {
label: Some("split"),
entries: &tail,
};
check_portable_storage_buffers(Some("split"), &[&first, &second])
.expect_err("the limit sums over every bind group layout in the pipeline layout");
let graphics: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE)
.map(|binding| storage(binding, ShaderStages::VERTEX))
.chain((0..PORTABLE_STORAGE_BUFFERS_PER_STAGE).map(|binding| {
storage(
binding + PORTABLE_STORAGE_BUFFERS_PER_STAGE,
ShaderStages::FRAGMENT,
)
}))
.collect();
let graphics = BindGroupLayoutDesc {
label: Some("both stages"),
entries: &graphics,
};
check_portable_storage_buffers(graphics.label, &[&graphics])
.expect("the budget is per stage");
}
#[test]
fn the_mesh_stages_are_outside_the_webgpu_budget_and_the_fragment_stage_is_not() {
let storage = |binding: u32, visibility: ShaderStages| BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: 4,
},
count: 1,
flags: BindingFlags::empty(),
};
let mesh_only: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE * 2)
.map(|binding| storage(binding, ShaderStages::MESH.union(ShaderStages::TASK)))
.collect();
let mesh_only = BindGroupLayoutDesc {
label: Some("mesh path"),
entries: &mesh_only,
};
check_portable_storage_buffers(mesh_only.label, &[&mesh_only])
.expect("a mesh pipeline is never a WebGPU pipeline");
let shared: Vec<BindGroupLayoutEntry> = (0..PORTABLE_STORAGE_BUFFERS_PER_STAGE + 1)
.map(|binding| storage(binding, ShaderStages::MESH.union(ShaderStages::FRAGMENT)))
.collect();
let shared = BindGroupLayoutDesc {
label: Some("shared with the fragment stage"),
entries: &shared,
};
let error = check_portable_storage_buffers(shared.label, &[&shared])
.expect_err("the fragment half is still a WebGPU stage");
assert!(error.to_string().contains("fragment"), "{error}");
}
#[test]
fn an_array_of_storage_buffers_spends_its_whole_count() {
let entries = [BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: 4,
},
count: PORTABLE_STORAGE_BUFFERS_PER_STAGE + 1,
flags: BindingFlags::empty(),
}];
let desc = BindGroupLayoutDesc {
label: Some("an array"),
entries: &entries,
};
check_portable_storage_buffers(desc.label, &[&desc]).expect_err("nine descriptors");
}
#[test]
fn blend_presets_differ_only_where_they_should() {
let alpha = BlendState::alpha();
let premul = BlendState::premultiplied();
assert_eq!(alpha.color_src, BlendFactor::SrcAlpha);
assert_eq!(premul.color_src, BlendFactor::One);
assert_eq!(alpha.color_dst, premul.color_dst);
assert_eq!(BlendState::additive().color_dst, BlendFactor::One);
}
#[test]
fn color_writes_all_covers_four_channels() {
assert_eq!(ColorWrites::ALL.bits().count_ones(), 4);
assert!(ColorWrites::ALL.contains(ColorWrites::A));
}
#[test]
fn opaque_target_has_no_blending() {
let target = ColorTargetState::opaque(Format::Rgba16Float);
assert!(target.blend.is_none());
assert_eq!(target.write_mask, ColorWrites::ALL);
assert!(target.format.is_hdr_capable(), "P1 renders to RGBA16F");
}
#[test]
fn primitive_defaults_are_the_common_case() {
let primitive = PrimitiveState::default();
assert_eq!(primitive.topology, PrimitiveTopology::TriangleList);
assert_eq!(primitive.polygon_mode, PolygonMode::Fill);
assert_eq!(
primitive.cull_mode,
CullMode::None,
"culling must be asked for: the default cannot know the winding of \
imported geometry"
);
}
#[test]
fn a_workgroup_size_the_device_cannot_launch_is_refused_by_dimension() {
let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
let layout: PipelineLayoutHandle = pool.insert(0).cast();
let module: crate::ShaderModuleHandle = pool.insert(0).cast();
let desc = |workgroup_size| ComputePipelineDesc {
label: Some("guard"),
layout,
compute: ShaderEntry {
module,
entry_point: "computeMain",
},
workgroup_size,
};
let limits = Limits::minimum();
let zero = desc([0, 1, 1])
.check_workgroup_size(&limits)
.expect_err("a workgroup of no invocations");
assert!(zero.to_string().contains("zero in dimension 0"), "{zero}");
let wide = desc([limits.max_compute_workgroup_size[0] + 1, 1, 1])
.check_workgroup_size(&limits)
.expect_err("over the per-dimension limit");
assert!(
wide.to_string().contains("dimension 0"),
"the dimension must be named: {wide}"
);
let deep = [8, 8, limits.max_compute_workgroup_size[2]];
assert!(
deep.iter()
.zip(limits.max_compute_workgroup_size)
.all(|(extent, max)| *extent <= max),
"this case must be legal on every axis or it proves nothing"
);
let total = desc(deep)
.check_workgroup_size(&limits)
.expect_err("over the invocation total");
assert!(
total.to_string().contains("invocations"),
"the total must be named: {total}"
);
desc([64, 1, 1])
.check_workgroup_size(&limits)
.expect("the size every compute shader in this workspace declares");
}
fn caps(features: Features) -> DeviceCaps {
DeviceCaps {
features,
limits: Limits::desktop(),
}
}
fn binding(binding: u32, flags: BindingFlags, count: u32) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility: ShaderStages::VERTEX,
kind: BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: 4,
},
count,
flags,
}
}
fn check(entries: &[BindGroupLayoutEntry], caps: &DeviceCaps) -> Result<(), HalError> {
BindGroupLayoutDesc {
label: Some("guard"),
entries,
}
.check_entries(caps, BackendKind::Null)
}
#[test]
fn the_vertex_pulling_layout_is_legal_on_both_tiers() {
let entries = [binding(0, BindingFlags::empty(), 1)];
check(&entries, &caps(Features::GPU_DRIVEN)).expect("Tier A");
check(&entries, &caps(Features::empty())).expect("Tier B too");
let bindless = [
binding(0, BindingFlags::empty(), 1),
BindGroupLayoutEntry {
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::Float,
},
..binding(
1,
BindingFlags::VARIABLE_COUNT
| BindingFlags::PARTIALLY_BOUND
| BindingFlags::UPDATE_AFTER_BIND,
u32::MAX,
)
},
];
check(&bindless, &caps(Features::GPU_DRIVEN))
.expect("u32::MAX is a request to clamp, not an over-large request");
}
#[test]
fn a_zero_count_is_refused_by_binding_number() {
let error = check(
&[binding(3, BindingFlags::empty(), 0)],
&caps(Features::GPU_DRIVEN),
)
.expect_err("a binding holding nothing");
assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
let text = error.to_string();
for expected in ["binding 3", "count 0"] {
assert!(text.contains(expected), "{expected:?} missing from {text}");
}
}
#[test]
fn a_duplicated_binding_number_is_refused() {
let entries = [
binding(3, BindingFlags::empty(), 1),
binding(3, BindingFlags::empty(), 1),
];
let error = check(&entries, &caps(Features::GPU_DRIVEN)).expect_err("binding 3 twice");
assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
assert!(error.to_string().contains("twice"), "{error}");
}
#[test]
fn a_device_without_descriptor_indexing_refuses_the_flags_rather_than_ignoring_them() {
for flag in [
BindingFlags::PARTIALLY_BOUND,
BindingFlags::UPDATE_AFTER_BIND,
BindingFlags::VARIABLE_COUNT,
] {
assert!(!flag.is_empty(), "{flag:?} would prove nothing");
let entries = [binding(0, flag, 4)];
let error = check(&entries, &caps(Features::empty()))
.expect_err("a device without the feature");
assert!(
matches!(error, HalError::Unsupported { backend, .. } if backend == BackendKind::Null),
"{flag:?}: {error:?}"
);
check(&entries, &caps(Features::GPU_DRIVEN))
.unwrap_or_else(|error| panic!("{flag:?} on a device reporting it: {error}"));
}
}
#[test]
fn a_mesh_visible_binding_needs_the_matching_capability() {
for (stage, feature) in [
(ShaderStages::MESH, Features::MESH_SHADER),
(ShaderStages::TASK, Features::TASK_SHADER),
] {
let entries = [BindGroupLayoutEntry {
visibility: stage,
..binding(0, BindingFlags::empty(), 1)
}];
let error = check(&entries, &caps(Features::GPU_DRIVEN))
.expect_err("GPU_DRIVEN carries neither mesh flag");
assert!(
matches!(error, HalError::Unsupported { .. }),
"{stage:?}: {error}"
);
check(&entries, &caps(Features::GPU_DRIVEN | feature))
.unwrap_or_else(|error| panic!("{stage:?} on a device reporting it: {error}"));
}
}
#[test]
fn variable_count_must_be_both_last_and_highest_numbered() {
let tier_a = caps(Features::GPU_DRIVEN);
let entries = [
binding(7, BindingFlags::VARIABLE_COUNT, 8),
binding(2, BindingFlags::empty(), 1),
];
let error = check(&entries, &tier_a).expect_err("not the last entry");
assert!(
error.to_string().contains("not the last entry"),
"the half that failed must be named: {error}"
);
let entries = [
binding(7, BindingFlags::empty(), 1),
binding(2, BindingFlags::VARIABLE_COUNT, 8),
];
let error = check(&entries, &tier_a).expect_err("not the highest binding number");
assert!(
error
.to_string()
.contains("not the highest-numbered binding"),
"the half that failed must be named: {error}"
);
let entries = [
binding(2, BindingFlags::empty(), 1),
binding(7, BindingFlags::VARIABLE_COUNT, 8),
];
check(&entries, &tier_a).expect("last and highest");
}
#[test]
fn the_count_ceiling_exempts_the_sentinel_and_nothing_else() {
let tier_a = caps(Features::GPU_DRIVEN);
let ceiling = tier_a.limits.max_bindless_descriptors;
assert!(ceiling > 1, "a ceiling of {ceiling} would prove nothing");
check(&[binding(0, BindingFlags::empty(), u32::MAX)], &tier_a)
.expect("the sentinel is a request to clamp");
check(&[binding(0, BindingFlags::empty(), ceiling)], &tier_a).expect("exactly the ceiling");
let error = check(&[binding(0, BindingFlags::empty(), ceiling + 1)], &tier_a)
.expect_err("one past the ceiling is not a sentinel");
assert!(
error.to_string().contains("max_bindless_descriptors"),
"the limit must be named: {error}"
);
}
#[test]
fn the_sentinel_resolves_to_the_devices_own_ceiling() {
let desktop = Limits::desktop();
assert!(desktop.max_bindless_descriptors > 1);
assert_eq!(
binding(0, BindingFlags::VARIABLE_COUNT, u32::MAX).resolved_count(&desktop),
desktop.max_bindless_descriptors
);
assert_eq!(
binding(0, BindingFlags::empty(), 16).resolved_count(&desktop),
16,
"an explicit count is left alone"
);
let minimum = Limits::minimum();
assert_eq!(minimum.max_bindless_descriptors, 0);
assert_eq!(
binding(0, BindingFlags::empty(), u32::MAX).resolved_count(&minimum),
1,
"a device with no bindless ceiling still owes a creatable binding"
);
}
fn dynamic_slot(binding: u32, uniform: bool) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility: ShaderStages::ALL,
kind: if uniform {
BindingKind::UniformBuffer { dynamic: true }
} else {
BindingKind::StorageBuffer {
read_only: true,
dynamic: true,
stride: 4,
}
},
count: 1,
flags: BindingFlags::empty(),
}
}
#[test]
fn a_binding_offset_is_checked_against_its_own_kinds_alignment() {
let limits = Limits::desktop();
assert_eq!(limits.min_uniform_buffer_offset_alignment, 64);
assert_eq!(limits.min_storage_buffer_offset_alignment, 16);
let uniform = BindingKind::UniformBuffer { dynamic: false };
let storage = BindingKind::StorageBuffer {
read_only: true,
dynamic: false,
stride: 4,
};
check_binding_offset_alignment(&limits, uniform, 0, 128).expect("128 is a multiple of 64");
check_binding_offset_alignment(&limits, storage, 1, 32).expect("32 is a multiple of 16");
let error = check_binding_offset_alignment(&limits, uniform, 0, 32)
.expect_err("32 is not a multiple of 64");
let text = error.to_string();
assert!(text.contains("binding 0"), "{text}");
assert!(text.contains("64-byte"), "{text}");
let error = check_binding_offset_alignment(&limits, storage, 1, 8)
.expect_err("8 is not a multiple of 16");
assert!(error.to_string().contains("binding 1"), "{error}");
}
#[test]
fn an_alignment_of_one_and_a_slotless_kind_accept_every_offset() {
let limits = Limits::desktop();
let sampler = BindingKind::Sampler { comparison: false };
check_binding_offset_alignment(&limits, sampler, 0, 3)
.expect("a sampler slot takes no offset");
let mut unaligned = limits;
unaligned.min_uniform_buffer_offset_alignment = 1;
unaligned.min_storage_buffer_offset_alignment = 1;
for kind in [
BindingKind::UniformBuffer { dynamic: false },
BindingKind::StorageBuffer {
read_only: false,
dynamic: false,
stride: 4,
},
] {
check_binding_offset_alignment(&unaligned, kind, 7, 3)
.expect("an alignment of 1 accepts every offset");
}
}
#[test]
fn dynamic_offsets_are_checked_against_the_right_alignment() {
let limits = Limits::desktop();
let slots = [dynamic_slot(0, true), dynamic_slot(1, false)];
check_dynamic_offsets(&limits, &slots, &[128, 32]).expect("both are aligned");
let error = check_dynamic_offsets(&limits, &slots, &[32, 32])
.expect_err("32 is not a multiple of 64");
assert!(error.to_string().contains("binding 0"), "{error}");
let error = check_dynamic_offsets(&limits, &slots, &[128, 8])
.expect_err("8 is not a multiple of 16");
assert!(error.to_string().contains("binding 1"), "{error}");
let mut unaligned = limits;
unaligned.min_uniform_buffer_offset_alignment = 1;
unaligned.min_storage_buffer_offset_alignment = 1;
check_dynamic_offsets(&unaligned, &slots, &[3, 7])
.expect("an alignment of 1 accepts every offset");
}
#[test]
fn the_offset_count_must_match_the_layouts_dynamic_bindings() {
let limits = Limits::desktop();
let slots = [dynamic_slot(0, true)];
assert!(check_dynamic_offsets(&limits, &slots, &[]).is_err());
assert!(check_dynamic_offsets(&limits, &slots, &[0, 0]).is_err());
check_dynamic_offsets(&limits, &[], &[]).expect("no dynamic bindings, no offsets");
check_dynamic_offsets(&limits, &slots, &[0]).expect("one binding, one aligned offset");
}
#[test]
fn whole_buffer_binding_uses_the_sentinel() {
let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
let buffer: BufferHandle = pool.insert(0).cast();
let BindingResource::Buffer { offset, size, .. } = BindingResource::whole_buffer(buffer)
else {
panic!("wrong variant");
};
assert_eq!(offset, 0);
assert_eq!(size, BindingResource::WHOLE_BUFFER);
}
}