Skip to main content

wgpu_core/
binding_model.rs

1use alloc::{
2    borrow::{Cow, ToOwned},
3    boxed::Box,
4    string::String,
5    sync::{Arc, Weak},
6    vec::Vec,
7};
8use core::{
9    fmt,
10    mem::ManuallyDrop,
11    num::{NonZeroU32, Saturating},
12    ops::Range,
13};
14
15use arrayvec::ArrayVec;
16use thiserror::Error;
17
18#[cfg(feature = "serde")]
19use serde::Deserialize;
20#[cfg(feature = "serde")]
21use serde::Serialize;
22
23use wgpu_sync::OnceCell;
24use wgt::error::{ErrorType, WebGpuError};
25
26use crate::{
27    api_log,
28    device::{bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
29    init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction},
30    pipeline::{ComputePipeline, RenderPipeline},
31    ray_tracing_pipeline::RayTracingPipeline,
32    resource::{
33        Buffer, DestroyedResourceError, ExternalTexture, InvalidOrDestroyedResourceError,
34        InvalidResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError,
35        RawResourceAccess, ResourceErrorIdent, ResourceState, Sampler, TextureView, Tlas,
36        TrackingData,
37    },
38    resource_log,
39    snatch::{SnatchGuard, Snatchable},
40    track::{BindGroupStates, ResourceUsageCompatibilityError},
41    Label,
42};
43
44#[derive(Clone, Debug, Error)]
45#[non_exhaustive]
46pub enum BindGroupLayoutEntryError {
47    #[error("Multiple binding types provided, expected exactly one")]
48    MultipleBindingTypesProvided,
49    #[error("No binding types provided, expected exactly one")]
50    NoBindingTypesProvided,
51    #[error("Cube dimension is not expected for texture storage")]
52    StorageTextureCube,
53    #[error("Atomic storage textures are not allowed by baseline webgpu, they require the native only feature TEXTURE_ATOMIC")]
54    StorageTextureAtomic,
55    #[error("Arrays of bindings unsupported for this type of binding")]
56    ArrayUnsupported,
57    #[error("Multisampled binding with sample type `TextureSampleType::Float` must have filterable set to false.")]
58    SampleTypeFloatFilterableBindingMultisampled,
59    #[error("Multisampled texture binding view dimension must be 2d, got {0:?}")]
60    Non2DMultisampled(wgt::TextureViewDimension),
61    #[error(transparent)]
62    MissingFeatures(#[from] MissingFeatures),
63    #[error(transparent)]
64    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
65}
66
67#[derive(Clone, Debug, Error)]
68#[non_exhaustive]
69pub enum CreateBindGroupLayoutError {
70    #[error(transparent)]
71    Device(#[from] DeviceError),
72    #[error("Conflicting binding at index {0}")]
73    ConflictBinding(u32),
74    #[error("Binding {binding} entry is invalid")]
75    Entry {
76        binding: u32,
77        #[source]
78        error: BindGroupLayoutEntryError,
79    },
80    #[error(transparent)]
81    TooManyBindings(BindingTypeMaxCountError),
82    #[error("Bind groups may not contain both a binding array and a dynamically offset buffer")]
83    ContainsBothBindingArrayAndDynamicOffsetArray,
84    #[error("Bind groups may not contain both a binding array and a uniform buffer")]
85    ContainsBothBindingArrayAndUniformBuffer,
86    #[error("Binding index {binding} is greater than the maximum number {maximum}")]
87    InvalidBindingIndex { binding: u32, maximum: u32 },
88    #[error("Invalid visibility {0:?}")]
89    InvalidVisibility(wgt::ShaderStages),
90    #[error("Binding index {binding}: {access:?} access to storage textures with format {format:?} is not supported")]
91    UnsupportedStorageTextureAccess {
92        binding: u32,
93        access: wgt::StorageTextureAccess,
94        format: wgt::TextureFormat,
95    },
96}
97
98impl WebGpuError for CreateBindGroupLayoutError {
99    fn webgpu_error_type(&self) -> ErrorType {
100        match self {
101            Self::Device(e) => e.webgpu_error_type(),
102
103            Self::ConflictBinding(_)
104            | Self::Entry { .. }
105            | Self::TooManyBindings(_)
106            | Self::InvalidBindingIndex { .. }
107            | Self::InvalidVisibility(_)
108            | Self::ContainsBothBindingArrayAndDynamicOffsetArray
109            | Self::ContainsBothBindingArrayAndUniformBuffer
110            | Self::UnsupportedStorageTextureAccess { .. } => ErrorType::Validation,
111        }
112    }
113}
114
115#[derive(Clone, Debug, Error)]
116#[non_exhaustive]
117pub enum BindingError {
118    #[error(transparent)]
119    DestroyedResource(#[from] DestroyedResourceError),
120    #[error("Buffer {buffer}: Binding with size {binding_size} at offset {offset} would overflow buffer size of {buffer_size}")]
121    BindingRangeTooLarge {
122        buffer: ResourceErrorIdent,
123        offset: wgt::BufferAddress,
124        binding_size: u64,
125        buffer_size: u64,
126    },
127    #[error("Buffer {buffer}: Binding offset {offset} is greater than buffer size {buffer_size}")]
128    BindingOffsetTooLarge {
129        buffer: ResourceErrorIdent,
130        offset: wgt::BufferAddress,
131        buffer_size: u64,
132    },
133    /// The supplied binding offset was equal to the buffer size.
134    ///
135    /// A binding offset equal to the buffer size is legal for vertex and index buffer
136    /// bindings, but not for storage/uniform buffer bindings, thus this error should only
137    /// be raised for the latter.
138    #[error("Buffer {buffer}: Binding offset {offset} must be strictly less than buffer size {buffer_size}")]
139    BindingOffsetEqualsSize {
140        buffer: ResourceErrorIdent,
141        offset: wgt::BufferAddress,
142        buffer_size: u64,
143    },
144    #[error("Unbinding vertex buffer at slot {slot} expects offset to be 0. However an offset of {offset} was provided.")]
145    UnbindingVertexBufferOffsetNotZero { slot: u32, offset: u64 },
146    #[error("Unbinding vertex buffer at slot {slot} expects size to be 0. However a size of {size} was provided.")]
147    UnbindingVertexBufferSizeNotZero { slot: u32, size: u64 },
148}
149
150impl WebGpuError for BindingError {
151    fn webgpu_error_type(&self) -> ErrorType {
152        match self {
153            Self::DestroyedResource(e) => e.webgpu_error_type(),
154            Self::BindingRangeTooLarge { .. }
155            | Self::BindingOffsetTooLarge { .. }
156            | Self::BindingOffsetEqualsSize { .. }
157            | BindingError::UnbindingVertexBufferOffsetNotZero { .. }
158            | BindingError::UnbindingVertexBufferSizeNotZero { .. } => ErrorType::Validation,
159        }
160    }
161}
162
163// TODO: there may be additional variants here that can be extracted into
164// `BindingError`.
165#[derive(Clone, Debug, Error)]
166#[non_exhaustive]
167pub enum CreateBindGroupError {
168    #[error(transparent)]
169    Device(#[from] DeviceError),
170    #[error(transparent)]
171    DestroyedResource(#[from] DestroyedResourceError),
172    #[error(transparent)]
173    BindingError(#[from] BindingError),
174    #[error(
175        "Binding count declared with at most {expected} items, but {actual} items were provided"
176    )]
177    BindingArrayPartialLengthMismatch { actual: usize, expected: usize },
178    #[error(
179        "Binding count declared with exactly {expected} items, but {actual} items were provided"
180    )]
181    BindingArrayLengthMismatch { actual: usize, expected: usize },
182    #[error("Array binding provided zero elements")]
183    BindingArrayZeroLength,
184    #[error("Binding size {actual} of {buffer} is less than minimum {min}")]
185    BindingSizeTooSmall {
186        buffer: ResourceErrorIdent,
187        actual: u64,
188        min: u64,
189    },
190    #[error("{0} binding size is zero")]
191    BindingZeroSize(ResourceErrorIdent),
192    #[error("Number of bindings in bind group descriptor ({actual}) does not match the number of bindings defined in the bind group layout ({expected})")]
193    BindingsNumMismatch { actual: usize, expected: usize },
194    #[error("Binding {0} is used at least twice in the descriptor")]
195    DuplicateBinding(u32),
196    #[error("Unable to find a corresponding declaration for the given binding {0}")]
197    MissingBindingDeclaration(u32),
198    #[error(transparent)]
199    MissingBufferUsage(#[from] MissingBufferUsageError),
200    #[error(transparent)]
201    MissingTextureUsage(#[from] MissingTextureUsageError),
202    #[error("Binding declared as a single item, but bind group is using it as an array")]
203    SingleBindingExpected,
204    #[error("Effective buffer binding size {size} for storage buffers is expected to align to {alignment}, but size is {size}")]
205    UnalignedEffectiveBufferBindingSizeForStorage { alignment: u32, size: u64 },
206    #[error("Buffer offset {0} does not respect device's requested `{1}` limit {2}")]
207    UnalignedBufferOffset(wgt::BufferAddress, &'static str, u32),
208    #[error(
209        "Buffer binding {binding} range {given} exceeds `max_*_buffer_binding_size` limit {limit}"
210    )]
211    BufferRangeTooLarge {
212        binding: u32,
213        given: u64,
214        limit: u64,
215    },
216    #[error("Binding {binding} has a different type ({actual:?}) than the one in the layout ({expected:?})")]
217    WrongBindingType {
218        // Index of the binding
219        binding: u32,
220        // The type given to the function
221        actual: wgt::BindingType,
222        // Human-readable description of expected types
223        expected: &'static str,
224    },
225    #[error("Texture binding {binding} expects multisampled = {layout_multisampled}, but given a view with samples = {view_samples}")]
226    InvalidTextureMultisample {
227        binding: u32,
228        layout_multisampled: bool,
229        view_samples: u32,
230    },
231    #[error(
232        "Texture binding {} expects sample type {:?}, but was given a view with format {:?} (sample type {:?})",
233        binding,
234        layout_sample_type,
235        view_format,
236        view_sample_type
237    )]
238    InvalidTextureSampleType {
239        binding: u32,
240        layout_sample_type: wgt::TextureSampleType,
241        view_format: wgt::TextureFormat,
242        view_sample_type: wgt::TextureSampleType,
243    },
244    #[error("Texture binding {binding} expects dimension = {layout_dimension:?}, but given a view with dimension = {view_dimension:?}")]
245    InvalidTextureDimension {
246        binding: u32,
247        layout_dimension: wgt::TextureViewDimension,
248        view_dimension: wgt::TextureViewDimension,
249    },
250    #[error("Texture binding {binding} is given a view with dimension = {view_dimension:?}, but the texture was created with texture_binding_view_dimension = {texture_binding_view_dimension:?}")]
251    InvalidTextureBindingViewDimension {
252        binding: u32,
253        view_dimension: wgt::TextureViewDimension,
254        texture_binding_view_dimension: wgt::TextureViewDimension,
255    },
256    #[error("Storage texture binding {binding} expects format = {layout_format:?}, but given a view with format = {view_format:?}")]
257    InvalidStorageTextureFormat {
258        binding: u32,
259        layout_format: wgt::TextureFormat,
260        view_format: wgt::TextureFormat,
261    },
262    #[error("Storage texture bindings must have a single mip level, but given a view with mip_level_count = {mip_level_count:?} at binding {binding}")]
263    InvalidStorageTextureMipLevelCount { binding: u32, mip_level_count: u32 },
264    #[error("Storage texture bindings must have an identity swizzle, but given a view with swizzle = {swizzle:?}")]
265    InvalidStorageTextureSwizzle {
266        swizzle: wgt::TextureComponentSwizzle,
267    },
268    #[error("External texture bindings must have a single mip level, but given a view with mip_level_count = {mip_level_count:?} at binding {binding}")]
269    InvalidExternalTextureMipLevelCount { binding: u32, mip_level_count: u32 },
270    #[error("External texture bindings must have a format of `rgba8unorm`, `bgra8unorm`, or `rgba16float, but given a view with format = {format:?} at binding {binding}")]
271    InvalidExternalTextureFormat {
272        binding: u32,
273        format: wgt::TextureFormat,
274    },
275    #[error("Sampler binding {binding} expects comparison = {layout_cmp}, but given a sampler with comparison = {sampler_cmp}")]
276    WrongSamplerComparison {
277        binding: u32,
278        layout_cmp: bool,
279        sampler_cmp: bool,
280    },
281    #[error("Sampler binding {binding} expects filtering = {layout_flt}, but given a sampler with filtering = {sampler_flt}")]
282    WrongSamplerFiltering {
283        binding: u32,
284        layout_flt: bool,
285        sampler_flt: bool,
286    },
287    #[error("TLAS binding {binding} is required to support vertex returns but is missing flag AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN")]
288    MissingTLASVertexReturn { binding: u32 },
289    #[error("Bound texture views can not have both depth and stencil aspects enabled")]
290    DepthStencilAspect,
291    #[error(transparent)]
292    ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
293    #[error(transparent)]
294    InvalidResource(#[from] InvalidResourceError),
295}
296
297impl WebGpuError for CreateBindGroupError {
298    fn webgpu_error_type(&self) -> ErrorType {
299        match self {
300            Self::Device(e) => e.webgpu_error_type(),
301            Self::DestroyedResource(e) => e.webgpu_error_type(),
302            Self::BindingError(e) => e.webgpu_error_type(),
303            Self::MissingBufferUsage(e) => e.webgpu_error_type(),
304            Self::MissingTextureUsage(e) => e.webgpu_error_type(),
305            Self::ResourceUsageCompatibility(e) => e.webgpu_error_type(),
306            Self::InvalidResource(e) => e.webgpu_error_type(),
307            Self::BindingArrayPartialLengthMismatch { .. }
308            | Self::BindingArrayLengthMismatch { .. }
309            | Self::BindingArrayZeroLength
310            | Self::BindingSizeTooSmall { .. }
311            | Self::BindingsNumMismatch { .. }
312            | Self::BindingZeroSize(_)
313            | Self::DuplicateBinding(_)
314            | Self::MissingBindingDeclaration(_)
315            | Self::SingleBindingExpected
316            | Self::UnalignedEffectiveBufferBindingSizeForStorage { .. }
317            | Self::UnalignedBufferOffset(_, _, _)
318            | Self::BufferRangeTooLarge { .. }
319            | Self::WrongBindingType { .. }
320            | Self::InvalidTextureMultisample { .. }
321            | Self::InvalidTextureSampleType { .. }
322            | Self::InvalidTextureDimension { .. }
323            | Self::InvalidStorageTextureFormat { .. }
324            | Self::InvalidStorageTextureMipLevelCount { .. }
325            | Self::InvalidStorageTextureSwizzle { .. }
326            | Self::WrongSamplerComparison { .. }
327            | Self::WrongSamplerFiltering { .. }
328            | Self::DepthStencilAspect
329            | Self::MissingTLASVertexReturn { .. }
330            | Self::InvalidExternalTextureMipLevelCount { .. }
331            | Self::InvalidExternalTextureFormat { .. }
332            | Self::InvalidTextureBindingViewDimension { .. } => ErrorType::Validation,
333        }
334    }
335}
336
337#[derive(Clone, Debug, Error)]
338pub enum BindingZone {
339    #[error("Stage {0:?}")]
340    Stage(wgt::ShaderStages),
341    #[error("Whole pipeline")]
342    Pipeline,
343}
344
345#[derive(Clone, Debug, Error)]
346#[error("Too many bindings of type {kind:?} in {zone}, limit is {limit}, count was {count}. Check the limit `{}` passed to `Adapter::request_device`", .kind.to_config_str())]
347pub struct BindingTypeMaxCountError {
348    pub kind: BindingTypeMaxCountErrorKind,
349    pub zone: BindingZone,
350    pub limit: u32,
351    pub count: u32,
352}
353
354impl WebGpuError for BindingTypeMaxCountError {
355    fn webgpu_error_type(&self) -> ErrorType {
356        ErrorType::Validation
357    }
358}
359
360#[derive(Clone, Debug)]
361pub enum BindingTypeMaxCountErrorKind {
362    DynamicUniformBuffers,
363    DynamicStorageBuffers,
364    SampledTextures,
365    Samplers,
366    StorageBuffers,
367    StorageTextures,
368    UniformBuffers,
369    BindingArrayElements,
370    BindingArraySamplerElements,
371    BindingArrayAccelerationStructureElements,
372    AccelerationStructures,
373    BuffersAndAccelerationStructures,
374}
375
376impl BindingTypeMaxCountErrorKind {
377    fn to_config_str(&self) -> &'static str {
378        match self {
379            BindingTypeMaxCountErrorKind::DynamicUniformBuffers => {
380                "max_dynamic_uniform_buffers_per_pipeline_layout"
381            }
382            BindingTypeMaxCountErrorKind::DynamicStorageBuffers => {
383                "max_dynamic_storage_buffers_per_pipeline_layout"
384            }
385            BindingTypeMaxCountErrorKind::SampledTextures => {
386                "max_sampled_textures_per_shader_stage"
387            }
388            BindingTypeMaxCountErrorKind::Samplers => "max_samplers_per_shader_stage",
389            BindingTypeMaxCountErrorKind::StorageBuffers => "max_storage_buffers_per_shader_stage",
390            BindingTypeMaxCountErrorKind::StorageTextures => {
391                "max_storage_textures_per_shader_stage"
392            }
393            BindingTypeMaxCountErrorKind::UniformBuffers => "max_uniform_buffers_per_shader_stage",
394            BindingTypeMaxCountErrorKind::BindingArrayElements => {
395                "max_binding_array_elements_per_shader_stage"
396            }
397            BindingTypeMaxCountErrorKind::BindingArraySamplerElements => {
398                "max_binding_array_sampler_elements_per_shader_stage"
399            }
400            BindingTypeMaxCountErrorKind::BindingArrayAccelerationStructureElements => {
401                "max_binding_array_acceleration_structure_elements_per_shader_stage"
402            }
403            BindingTypeMaxCountErrorKind::AccelerationStructures => {
404                "max_acceleration_structures_per_shader_stage"
405            }
406            BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures => {
407                "max_buffers_and_acceleration_structures_per_shader_stage"
408            }
409        }
410    }
411}
412
413#[derive(Debug, Default)]
414pub(crate) struct PerStageBindingTypeCounter {
415    vertex: Saturating<u32>,
416    fragment: Saturating<u32>,
417    compute: Saturating<u32>,
418    ray_generation: Saturating<u32>,
419    miss: Saturating<u32>,
420    any_hit: Saturating<u32>,
421    closest_hit: Saturating<u32>,
422}
423
424impl PerStageBindingTypeCounter {
425    pub(crate) fn add(&mut self, stage: wgt::ShaderStages, count: u32) {
426        if stage.contains(wgt::ShaderStages::VERTEX) {
427            self.vertex += count;
428        }
429        if stage.contains(wgt::ShaderStages::FRAGMENT) {
430            self.fragment += count;
431        }
432        if stage.contains(wgt::ShaderStages::COMPUTE) {
433            self.compute += count;
434        }
435        if stage.contains(wgt::ShaderStages::RAY_GENERATION) {
436            self.ray_generation += count;
437        }
438        if stage.contains(wgt::ShaderStages::MISS) {
439            self.miss += count;
440        }
441        if stage.contains(wgt::ShaderStages::ANY_HIT) {
442            self.any_hit += count;
443        }
444        if stage.contains(wgt::ShaderStages::CLOSEST_HIT) {
445            self.closest_hit += count;
446        }
447    }
448
449    pub(crate) fn max(&self) -> (BindingZone, u32) {
450        let max_value = self.vertex.max(
451            self.fragment.max(
452                self.compute.max(
453                    self.ray_generation
454                        .max(self.miss.max(self.any_hit.max(self.closest_hit))),
455                ),
456            ),
457        );
458        let mut stage = wgt::ShaderStages::NONE;
459        if max_value == self.vertex {
460            stage |= wgt::ShaderStages::VERTEX
461        }
462        if max_value == self.fragment {
463            stage |= wgt::ShaderStages::FRAGMENT
464        }
465        if max_value == self.compute {
466            stage |= wgt::ShaderStages::COMPUTE
467        }
468        if max_value == self.ray_generation {
469            stage |= wgt::ShaderStages::RAY_GENERATION
470        }
471        if max_value == self.miss {
472            stage |= wgt::ShaderStages::MISS
473        }
474        if max_value == self.any_hit {
475            stage |= wgt::ShaderStages::ANY_HIT
476        }
477        if max_value == self.closest_hit {
478            stage |= wgt::ShaderStages::CLOSEST_HIT
479        }
480        (BindingZone::Stage(stage), max_value.0)
481    }
482
483    pub(crate) fn merge(&mut self, other: &Self) {
484        self.vertex += other.vertex;
485        self.fragment += other.fragment;
486        self.compute += other.compute;
487    }
488
489    pub(crate) fn validate(
490        &self,
491        limit: u32,
492        kind: BindingTypeMaxCountErrorKind,
493    ) -> Result<(), BindingTypeMaxCountError> {
494        let (zone, count) = self.max();
495        if limit < count {
496            Err(BindingTypeMaxCountError {
497                kind,
498                zone,
499                limit,
500                count,
501            })
502        } else {
503            Ok(())
504        }
505    }
506}
507
508#[derive(Debug, Default)]
509pub(crate) struct BindingTypeMaxCountValidator {
510    dynamic_uniform_buffers: u32,
511    dynamic_storage_buffers: u32,
512    sampled_textures: PerStageBindingTypeCounter,
513    samplers: PerStageBindingTypeCounter,
514    storage_buffers: PerStageBindingTypeCounter,
515    storage_textures: PerStageBindingTypeCounter,
516    uniform_buffers: PerStageBindingTypeCounter,
517    acceleration_structures: PerStageBindingTypeCounter,
518    binding_array_elements: PerStageBindingTypeCounter,
519    binding_array_sampler_elements: PerStageBindingTypeCounter,
520    binding_array_acceleration_structure_elements: PerStageBindingTypeCounter,
521    has_bindless_array: bool,
522}
523
524impl BindingTypeMaxCountValidator {
525    pub(crate) fn add_binding(&mut self, binding: &wgt::BindGroupLayoutEntry) {
526        let count = binding.count.map_or(1, |count| count.get());
527
528        if binding.count.is_some() {
529            self.binding_array_elements.add(binding.visibility, count);
530            self.has_bindless_array = true;
531
532            match binding.ty {
533                wgt::BindingType::Sampler(_) => {
534                    self.binding_array_sampler_elements
535                        .add(binding.visibility, count);
536                }
537                wgt::BindingType::AccelerationStructure { .. } => {
538                    self.binding_array_acceleration_structure_elements
539                        .add(binding.visibility, count);
540                }
541                _ => {}
542            }
543        } else {
544            match binding.ty {
545                wgt::BindingType::Buffer {
546                    ty: wgt::BufferBindingType::Uniform,
547                    has_dynamic_offset,
548                    ..
549                } => {
550                    self.uniform_buffers.add(binding.visibility, count);
551                    if has_dynamic_offset {
552                        self.dynamic_uniform_buffers += count;
553                    }
554                }
555                wgt::BindingType::Buffer {
556                    ty: wgt::BufferBindingType::Storage { .. },
557                    has_dynamic_offset,
558                    ..
559                } => {
560                    self.storage_buffers.add(binding.visibility, count);
561                    if has_dynamic_offset {
562                        self.dynamic_storage_buffers += count;
563                    }
564                }
565                wgt::BindingType::Sampler { .. } => {
566                    self.samplers.add(binding.visibility, count);
567                }
568                wgt::BindingType::Texture { .. } => {
569                    self.sampled_textures.add(binding.visibility, count);
570                }
571                wgt::BindingType::StorageTexture { .. } => {
572                    self.storage_textures.add(binding.visibility, count);
573                }
574                wgt::BindingType::AccelerationStructure { .. } => {
575                    self.acceleration_structures.add(binding.visibility, count);
576                }
577                wgt::BindingType::ExternalTexture => {
578                    // https://www.w3.org/TR/webgpu/#gpuexternaltexture
579                    // In order to account for many possible representations,
580                    // the binding conservatively uses the following, for each
581                    // external texture:
582                    // * Three sampled textures for up to 3 planes
583                    // * One additional sampled texture for a 3D LUT
584                    // * One sampler to sample the LUT
585                    // * One uniform buffer for metadata
586                    self.sampled_textures.add(binding.visibility, count * 4);
587                    self.samplers.add(binding.visibility, count);
588                    self.uniform_buffers.add(binding.visibility, count);
589                }
590            }
591        }
592    }
593
594    pub(crate) fn merge(&mut self, other: &Self) {
595        self.dynamic_uniform_buffers += other.dynamic_uniform_buffers;
596        self.dynamic_storage_buffers += other.dynamic_storage_buffers;
597        self.sampled_textures.merge(&other.sampled_textures);
598        self.samplers.merge(&other.samplers);
599        self.storage_buffers.merge(&other.storage_buffers);
600        self.storage_textures.merge(&other.storage_textures);
601        self.uniform_buffers.merge(&other.uniform_buffers);
602        self.acceleration_structures
603            .merge(&other.acceleration_structures);
604        self.binding_array_elements
605            .merge(&other.binding_array_elements);
606        self.binding_array_sampler_elements
607            .merge(&other.binding_array_sampler_elements);
608        self.binding_array_acceleration_structure_elements
609            .merge(&other.binding_array_acceleration_structure_elements);
610    }
611
612    pub(crate) fn validate(
613        &self,
614        limits: &wgt::Limits,
615        instance_flags: wgt::InstanceFlags,
616    ) -> Result<(), BindingTypeMaxCountError> {
617        if limits.max_dynamic_uniform_buffers_per_pipeline_layout < self.dynamic_uniform_buffers {
618            return Err(BindingTypeMaxCountError {
619                kind: BindingTypeMaxCountErrorKind::DynamicUniformBuffers,
620                zone: BindingZone::Pipeline,
621                limit: limits.max_dynamic_uniform_buffers_per_pipeline_layout,
622                count: self.dynamic_uniform_buffers,
623            });
624        }
625        if limits.max_dynamic_storage_buffers_per_pipeline_layout < self.dynamic_storage_buffers {
626            return Err(BindingTypeMaxCountError {
627                kind: BindingTypeMaxCountErrorKind::DynamicStorageBuffers,
628                zone: BindingZone::Pipeline,
629                limit: limits.max_dynamic_storage_buffers_per_pipeline_layout,
630                count: self.dynamic_storage_buffers,
631            });
632        }
633        self.sampled_textures.validate(
634            limits.max_sampled_textures_per_shader_stage,
635            BindingTypeMaxCountErrorKind::SampledTextures,
636        )?;
637        self.samplers.validate(
638            limits.max_samplers_per_shader_stage,
639            BindingTypeMaxCountErrorKind::Samplers,
640        )?;
641        self.storage_buffers.validate(
642            limits.max_storage_buffers_per_shader_stage,
643            BindingTypeMaxCountErrorKind::StorageBuffers,
644        )?;
645        // NOTE: We don't explicitly check `max_storage_buffers_in_vertex_stage` or
646        // `max_storage_buffers_in_fragment_stage` because we don't assign different values between
647        // those and `max_storage_buffers_per_shader_stage`. If this changes, this needs to be
648        // fixed!
649        self.storage_textures.validate(
650            limits.max_storage_textures_per_shader_stage,
651            BindingTypeMaxCountErrorKind::StorageTextures,
652        )?;
653        // NOTE: We don't explicitly check `max_storage_textures_in_vertex_stage` or
654        // `max_storage_textures_in_fragment_stage` because we don't assign different values between
655        // those and `max_storage_textures_per_shader_stage`. If this changes, this needs to be
656        // fixed!
657        self.uniform_buffers.validate(
658            limits.max_uniform_buffers_per_shader_stage,
659            BindingTypeMaxCountErrorKind::UniformBuffers,
660        )?;
661        self.binding_array_elements.validate(
662            limits.max_binding_array_elements_per_shader_stage,
663            BindingTypeMaxCountErrorKind::BindingArrayElements,
664        )?;
665        self.binding_array_sampler_elements.validate(
666            limits.max_binding_array_sampler_elements_per_shader_stage,
667            BindingTypeMaxCountErrorKind::BindingArraySamplerElements,
668        )?;
669        self.binding_array_acceleration_structure_elements
670            .validate(
671                limits.max_binding_array_acceleration_structure_elements_per_shader_stage,
672                BindingTypeMaxCountErrorKind::BindingArrayAccelerationStructureElements,
673            )?;
674        self.acceleration_structures.validate(
675            limits.max_acceleration_structures_per_shader_stage,
676            BindingTypeMaxCountErrorKind::AccelerationStructures,
677        )?;
678
679        if !instance_flags.contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) {
680            self.buffers_and_acceleration_structures().validate(
681                limits.max_buffers_and_acceleration_structures_per_shader_stage,
682                BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures,
683            )?;
684        }
685
686        Ok(())
687    }
688
689    fn buffers_and_acceleration_structures(&self) -> PerStageBindingTypeCounter {
690        let mut buffers_and_acceleration_structures = PerStageBindingTypeCounter::default();
691        buffers_and_acceleration_structures.merge(&self.uniform_buffers);
692        buffers_and_acceleration_structures.merge(&self.storage_buffers);
693        buffers_and_acceleration_structures.merge(&self.acceleration_structures);
694        buffers_and_acceleration_structures
695    }
696
697    pub(crate) fn buffers_and_acceleration_structures_in_vertex_stage(&self) -> u32 {
698        self.buffers_and_acceleration_structures().vertex.0
699    }
700
701    /// Validate that the bind group layout does not contain both a binding array and a dynamic offset array.
702    ///
703    /// This allows us to use `UPDATE_AFTER_BIND` on vulkan for bindless arrays. Vulkan does not allow
704    /// `UPDATE_AFTER_BIND` on dynamic offset arrays. See <https://github.com/gfx-rs/wgpu/issues/6737>
705    pub(crate) fn validate_binding_arrays(&self) -> Result<(), CreateBindGroupLayoutError> {
706        let has_dynamic_offset_array =
707            self.dynamic_uniform_buffers > 0 || self.dynamic_storage_buffers > 0;
708        let has_uniform_buffer = self.uniform_buffers.max().1 > 0;
709        if self.has_bindless_array && has_dynamic_offset_array {
710            return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndDynamicOffsetArray);
711        }
712        if self.has_bindless_array && has_uniform_buffer {
713            return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndUniformBuffer);
714        }
715        Ok(())
716    }
717}
718
719/// Bindable resource and the slot to bind it to.
720/// cbindgen:ignore
721#[derive(Clone, Debug)]
722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
723pub struct BindGroupEntry<
724    'a,
725    B = Arc<Buffer>,
726    S = Arc<Sampler>,
727    TV = Arc<TextureView>,
728    TLAS = Arc<Tlas>,
729    ET = Arc<ExternalTexture>,
730> where
731    [BufferBinding<B>]: ToOwned,
732    [S]: ToOwned,
733    [TV]: ToOwned,
734    [TLAS]: ToOwned,
735    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
736    <[S] as ToOwned>::Owned: fmt::Debug,
737    <[TV] as ToOwned>::Owned: fmt::Debug,
738    <[TLAS] as ToOwned>::Owned: fmt::Debug,
739{
740    /// Slot for which binding provides resource. Corresponds to an entry of the same
741    /// binding index in the [`BindGroupLayoutDescriptor`].
742    pub binding: u32,
743    #[cfg_attr(
744        feature = "serde",
745        serde(bound(deserialize = "BindingResource<'a, B, S, TV, TLAS, ET>: Deserialize<'de>"))
746    )]
747    /// Resource to attach to the binding
748    pub resource: BindingResource<'a, B, S, TV, TLAS, ET>,
749}
750
751/// Describes a group of bindings and the resources to be bound.
752#[derive(Clone, Debug)]
753#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
754/// cbindgen:ignore
755pub struct BindGroupDescriptor<
756    'a,
757    BGL = Arc<BindGroupLayout>,
758    B = Arc<Buffer>,
759    S = Arc<Sampler>,
760    TV = Arc<TextureView>,
761    TLAS = Arc<Tlas>,
762    ET = Arc<ExternalTexture>,
763> where
764    [BufferBinding<B>]: ToOwned,
765    [S]: ToOwned,
766    [TV]: ToOwned,
767    [TLAS]: ToOwned,
768    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
769    <[S] as ToOwned>::Owned: fmt::Debug,
770    <[TV] as ToOwned>::Owned: fmt::Debug,
771    <[TLAS] as ToOwned>::Owned: fmt::Debug,
772    [BindGroupEntry<'a, B, S, TV, TLAS, ET>]: ToOwned,
773    <[BindGroupEntry<'a, B, S, TV, TLAS, ET>] as ToOwned>::Owned: fmt::Debug,
774{
775    /// Debug label of the bind group.
776    ///
777    /// This will show up in graphics debuggers for easy identification.
778    pub label: Label<'a>,
779    /// The [`BindGroupLayout`] that corresponds to this bind group.
780    pub layout: BGL,
781    #[cfg_attr(
782        feature = "serde",
783        serde(bound(
784            deserialize = "<[BindGroupEntry<'a, B, S, TV, TLAS, ET>] as ToOwned>::Owned: Deserialize<'de>"
785        ))
786    )]
787    /// The resources to bind to this bind group.
788    #[allow(clippy::type_complexity)]
789    pub entries: Cow<'a, [BindGroupEntry<'a, B, S, TV, TLAS, ET>]>,
790}
791
792/// A buffer binding.
793///
794/// Corresponds to [WebGPU `GPUBufferBindingLayout`](
795/// https://gpuweb.github.io/gpuweb/#dictdef-gpubufferbindinglayout).
796#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
797#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
798pub struct BufferBindingLayout {
799    /// Sub-type of the buffer binding.
800    pub ty: wgt::BufferBindingType,
801
802    /// Indicates that the binding has a dynamic offset.
803    ///
804    /// One offset must be passed to [`RenderPass::set_bind_group`](crate::command::RenderPass::set_bind_group)
805    /// for each dynamic binding in increasing order of binding number.
806    ///
807    #[cfg_attr(feature = "serde", serde(default))]
808    pub has_dynamic_offset: bool,
809
810    /// The minimum size for a [`BufferBinding`] matching this entry, in bytes.
811    ///
812    /// If this is `Some(size)`:
813    ///
814    /// - When calling [`Device::create_bind_group`], the resource at this bind point
815    ///   must be a [`BindingResource::Buffer`] whose effective size is at
816    ///   least `size`.
817    ///
818    /// - When calling [`Device::create_render_pipeline`] or [`Device::create_compute_pipeline`],
819    ///   `size` must be at least the [minimum buffer binding size] for the
820    ///   shader module global at this bind point: large enough to hold the
821    ///   global's value, along with one element of a trailing runtime-sized
822    ///   array, if present.
823    ///
824    /// If this is `None`:
825    ///
826    /// - Each draw or dispatch command checks that the buffer range at this
827    ///   bind point satisfies the [minimum buffer binding size].
828    ///
829    /// [minimum buffer binding size]: https://www.w3.org/TR/webgpu/#minimum-buffer-binding-size
830    #[cfg_attr(feature = "serde", serde(default))]
831    pub min_binding_size: Option<wgt::BufferSize>,
832}
833
834/// A sampler that can be used to sample a texture.
835///
836/// Example WGSL syntax:
837/// ```rust,ignore
838/// @group(0) @binding(0)
839/// var s: sampler;
840/// ```
841///
842/// Example GLSL syntax:
843/// ```cpp,ignore
844/// layout(binding = 0)
845/// uniform sampler s;
846/// ```
847///
848/// Corresponds to [WebGPU `GPUSamplerBindingLayout`](
849/// https://gpuweb.github.io/gpuweb/#dictdef-gpusamplerbindinglayout).
850#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
851#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
852pub struct SamplerBindingLayout {
853    /// Type of a sampler binding.
854    pub ty: wgt::SamplerBindingType,
855}
856
857/// A texture binding.
858///
859/// Example WGSL syntax:
860/// ```rust,ignore
861/// @group(0) @binding(0)
862/// var t: texture_2d<f32>;
863/// ```
864///
865/// Example GLSL syntax:
866/// ```cpp,ignore
867/// layout(binding = 0)
868/// uniform texture2D t;
869/// ```
870///
871/// Corresponds to [WebGPU `GPUTextureBindingLayout`](
872/// https://gpuweb.github.io/gpuweb/#dictdef-gputexturebindinglayout).
873#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
875pub struct TextureBindingLayout {
876    /// Sample type of the texture binding.
877    pub sample_type: wgt::TextureSampleType,
878    /// Dimension of the texture view that is going to be sampled.
879    pub view_dimension: wgt::TextureViewDimension,
880    /// True if the texture has a sample count greater than 1. If this is true,
881    /// the texture must be declared as `texture_multisampled_2d` or
882    /// `texture_depth_multisampled_2d` in the shader, and read using `textureLoad`.
883    pub multisampled: bool,
884}
885
886/// A storage texture.
887///
888/// Example WGSL syntax:
889/// ```rust,ignore
890/// @group(0) @binding(0)
891/// var my_storage_image: texture_storage_2d<r32float, write>;
892/// ```
893///
894/// Example GLSL syntax:
895/// ```cpp,ignore
896/// layout(set=0, binding=0, r32f) writeonly uniform image2D myStorageImage;
897/// ```
898/// Note that the texture format must be specified in the shader, along with the
899/// access mode. For WGSL, the format must be one of the enumerants in the list
900/// of [storage texel formats](https://gpuweb.github.io/gpuweb/wgsl/#storage-texel-formats).
901///
902/// Corresponds to [WebGPU `GPUStorageTextureBindingLayout`](
903/// https://gpuweb.github.io/gpuweb/#dictdef-gpustoragetexturebindinglayout).
904#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
905#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
906pub struct StorageTextureBindingLayout {
907    /// Allowed access to this texture.
908    pub access: wgt::StorageTextureAccess,
909    /// Format of the texture.
910    pub format: wgt::TextureFormat,
911    /// Dimension of the texture view that is going to be sampled.
912    pub view_dimension: wgt::TextureViewDimension,
913}
914
915/// A ray-tracing acceleration structure binding.
916///
917/// Example WGSL syntax:
918/// ```rust,ignore
919/// @group(0) @binding(0)
920/// var as: acceleration_structure;
921/// ```
922///
923/// or with vertex return enabled
924/// ```rust,ignore
925/// @group(0) @binding(0)
926/// var as: acceleration_structure<vertex_return>;
927/// ```
928///
929/// Example GLSL syntax:
930/// ```cpp,ignore
931/// layout(binding = 0)
932/// uniform accelerationStructureEXT as;
933/// ```
934#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
935#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
936pub struct AccelerationStructureBindingLayout {
937    /// Whether this acceleration structure can be used to
938    /// create a ray query that has flag vertex return in the shader
939    ///
940    /// If enabled requires [`wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN`]
941    pub vertex_return: bool,
942}
943
944/// An external texture binding.
945///
946/// Example WGSL syntax:
947/// ```rust,ignore
948/// @group(0) @binding(0)
949/// var t: texture_external;
950/// ```
951///
952/// Corresponds to [WebGPU `GPUExternalTextureBindingLayout`](
953/// https://gpuweb.github.io/gpuweb/#dictdef-gpuexternaltexturebindinglayout).
954///
955/// Requires [`wgt::Features::EXTERNAL_TEXTURE`]
956#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
957#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
958pub struct ExternalTextureBindingLayout;
959
960/// Describes a single binding inside a bind group.
961///
962/// Corresponds to [WebGPU `GPUBindGroupLayoutEntry`](
963/// https://gpuweb.github.io/gpuweb/#dictdef-gpubindgrouplayoutentry).
964#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
965#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
966pub struct BindGroupLayoutEntry {
967    /// Binding index. Must match shader index and be unique inside a `BindGroupLayout`. A binding
968    /// of index 1, would be described as `@group(0) @binding(1)` in shaders.
969    pub binding: u32,
970    /// Which shader stages can see this binding.
971    pub visibility: wgt::ShaderStages,
972
973    // type of binding
974    #[cfg_attr(feature = "serde", serde(default))]
975    pub buffer: Option<BufferBindingLayout>,
976    #[cfg_attr(feature = "serde", serde(default))]
977    pub sampler: Option<SamplerBindingLayout>,
978    #[cfg_attr(feature = "serde", serde(default))]
979    pub texture: Option<TextureBindingLayout>,
980    #[cfg_attr(feature = "serde", serde(default))]
981    pub storage_texture: Option<StorageTextureBindingLayout>,
982    #[cfg_attr(feature = "serde", serde(default))]
983    pub external_texture: Option<ExternalTextureBindingLayout>,
984    #[cfg_attr(feature = "serde", serde(default))]
985    pub acceleration_structure: Option<AccelerationStructureBindingLayout>,
986
987    /// If the binding is an array of multiple resources. Corresponds to `binding_array<T>` in the shader.
988    ///
989    /// When this is `Some` the following validation applies:
990    /// - Count must be of value 1 or greater, this corresponds to the length of the array of resources that will be bound.
991    /// - When `ty == BindingType::Texture`, [`wgt::Features::TEXTURE_BINDING_ARRAY`] must be supported.
992    /// - When `ty == BindingType::Sampler`, [`wgt::Features::TEXTURE_BINDING_ARRAY`] must be supported.
993    /// - When `ty == BindingType::Buffer`, [`wgt::Features::BUFFER_BINDING_ARRAY`] must be supported.
994    /// - When `ty == BindingType::Buffer` and `ty.ty == BufferBindingType::Storage`, [`wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
995    /// - When `ty == BindingType::StorageTexture`, [`wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
996    /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `has_dynamic_offset == true`
997    /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `ty.ty == BufferBindingType::Uniform`.
998    /// - If [`wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY`] is enabled, the specified count becomes the upper bound instead.
999    ///
1000    #[cfg_attr(feature = "serde", serde(default))]
1001    pub count: Option<NonZeroU32>,
1002}
1003
1004impl From<core::convert::Infallible> for CreateBindGroupLayoutError {
1005    fn from(_: core::convert::Infallible) -> Self {
1006        unreachable!()
1007    }
1008}
1009
1010impl From<wgt::BindGroupLayoutEntry> for BindGroupLayoutEntry {
1011    fn from(val: wgt::BindGroupLayoutEntry) -> Self {
1012        let wgt::BindGroupLayoutEntry {
1013            binding,
1014            visibility,
1015            ty,
1016            count,
1017        } = val;
1018        BindGroupLayoutEntry {
1019            binding,
1020            visibility,
1021            buffer: if let wgt::BindingType::Buffer {
1022                ty,
1023                has_dynamic_offset,
1024                min_binding_size,
1025            } = ty
1026            {
1027                Some(BufferBindingLayout {
1028                    ty,
1029                    has_dynamic_offset,
1030                    min_binding_size,
1031                })
1032            } else {
1033                None
1034            },
1035            sampler: if let wgt::BindingType::Sampler(ty) = ty {
1036                Some(SamplerBindingLayout { ty })
1037            } else {
1038                None
1039            },
1040            texture: if let wgt::BindingType::Texture {
1041                sample_type,
1042                view_dimension,
1043                multisampled,
1044            } = ty
1045            {
1046                Some(TextureBindingLayout {
1047                    sample_type,
1048                    view_dimension,
1049                    multisampled,
1050                })
1051            } else {
1052                None
1053            },
1054            storage_texture: if let wgt::BindingType::StorageTexture {
1055                access,
1056                format,
1057                view_dimension,
1058            } = ty
1059            {
1060                Some(StorageTextureBindingLayout {
1061                    access,
1062                    format,
1063                    view_dimension,
1064                })
1065            } else {
1066                None
1067            },
1068            external_texture: if let wgt::BindingType::ExternalTexture = ty {
1069                Some(ExternalTextureBindingLayout {})
1070            } else {
1071                None
1072            },
1073            acceleration_structure: if let wgt::BindingType::AccelerationStructure {
1074                vertex_return,
1075            } = ty
1076            {
1077                Some(AccelerationStructureBindingLayout { vertex_return })
1078            } else {
1079                None
1080            },
1081            count,
1082        }
1083    }
1084}
1085
1086impl TryInto<wgt::BindGroupLayoutEntry> for BindGroupLayoutEntry {
1087    type Error = CreateBindGroupLayoutError;
1088
1089    fn try_into(self) -> Result<wgt::BindGroupLayoutEntry, Self::Error> {
1090        let BindGroupLayoutEntry {
1091            binding,
1092            visibility,
1093            buffer,
1094            sampler,
1095            texture,
1096            storage_texture,
1097            external_texture,
1098            acceleration_structure,
1099            count,
1100        } = self;
1101        let mut binding_ty: Option<wgt::BindingType> = None;
1102        if let Some(BufferBindingLayout {
1103            ty,
1104            has_dynamic_offset,
1105            min_binding_size,
1106        }) = buffer
1107        {
1108            binding_ty = Some(wgt::BindingType::Buffer {
1109                ty,
1110                has_dynamic_offset,
1111                min_binding_size,
1112            });
1113        }
1114        if let Some(SamplerBindingLayout { ty }) = sampler {
1115            if binding_ty.is_some() {
1116                return Err(CreateBindGroupLayoutError::Entry {
1117                    binding,
1118                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
1119                });
1120            }
1121            binding_ty = Some(wgt::BindingType::Sampler(ty))
1122        }
1123        if let Some(TextureBindingLayout {
1124            sample_type,
1125            view_dimension,
1126            multisampled,
1127        }) = texture
1128        {
1129            if binding_ty.is_some() {
1130                return Err(CreateBindGroupLayoutError::Entry {
1131                    binding,
1132                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
1133                });
1134            }
1135            binding_ty = Some(wgt::BindingType::Texture {
1136                sample_type,
1137                view_dimension,
1138                multisampled,
1139            })
1140        }
1141        if let Some(StorageTextureBindingLayout {
1142            access,
1143            format,
1144            view_dimension,
1145        }) = storage_texture
1146        {
1147            if binding_ty.is_some() {
1148                return Err(CreateBindGroupLayoutError::Entry {
1149                    binding,
1150                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
1151                });
1152            }
1153            binding_ty = Some(wgt::BindingType::StorageTexture {
1154                access,
1155                format,
1156                view_dimension,
1157            })
1158        }
1159        if let Some(ExternalTextureBindingLayout) = external_texture {
1160            if binding_ty.is_some() {
1161                return Err(CreateBindGroupLayoutError::Entry {
1162                    binding,
1163                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
1164                });
1165            }
1166            binding_ty = Some(wgt::BindingType::ExternalTexture)
1167        }
1168        if let Some(AccelerationStructureBindingLayout { vertex_return }) = acceleration_structure {
1169            if binding_ty.is_some() {
1170                return Err(CreateBindGroupLayoutError::Entry {
1171                    binding,
1172                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
1173                });
1174            }
1175            binding_ty = Some(wgt::BindingType::AccelerationStructure { vertex_return })
1176        }
1177        Ok(wgt::BindGroupLayoutEntry {
1178            binding,
1179            visibility,
1180            ty: binding_ty.ok_or(CreateBindGroupLayoutError::Entry {
1181                binding,
1182                error: BindGroupLayoutEntryError::NoBindingTypesProvided,
1183            })?,
1184            count,
1185        })
1186    }
1187}
1188
1189/// Describes a [`BindGroupLayout`].
1190#[derive(Clone, Debug)]
1191#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1192pub struct BindGroupLayoutDescriptor<'a, BGLE: Copy> {
1193    /// Debug label of the bind group layout.
1194    ///
1195    /// This will show up in graphics debuggers for easy identification.
1196    pub label: Label<'a>,
1197    /// Array of entries in this BindGroupLayout
1198    pub entries: Cow<'a, [BGLE]>,
1199}
1200
1201/// Used by [`BindGroupLayout`]. It indicates whether the BGL must be
1202/// used with a specific pipeline. This constraint only happens when
1203/// the BGLs have been derived from a pipeline without a layout.
1204#[derive(Clone, Debug)]
1205pub(crate) enum ExclusivePipeline {
1206    None,
1207    Render(Weak<RenderPipeline>),
1208    Compute(Weak<ComputePipeline>),
1209    RayTracing(Weak<RayTracingPipeline>),
1210}
1211
1212impl From<&Arc<RenderPipeline>> for ExclusivePipeline {
1213    fn from(pipeline: &Arc<RenderPipeline>) -> Self {
1214        Self::Render(Arc::downgrade(pipeline))
1215    }
1216}
1217
1218impl From<&Arc<ComputePipeline>> for ExclusivePipeline {
1219    fn from(pipeline: &Arc<ComputePipeline>) -> Self {
1220        Self::Compute(Arc::downgrade(pipeline))
1221    }
1222}
1223
1224impl From<&Arc<RayTracingPipeline>> for ExclusivePipeline {
1225    fn from(pipeline: &Arc<RayTracingPipeline>) -> Self {
1226        Self::RayTracing(Arc::downgrade(pipeline))
1227    }
1228}
1229
1230impl fmt::Display for ExclusivePipeline {
1231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1232        match self {
1233            ExclusivePipeline::None => f.write_str("None"),
1234            ExclusivePipeline::Render(p) => {
1235                if let Some(p) = p.upgrade() {
1236                    p.error_ident().fmt(f)
1237                } else {
1238                    f.write_str("RenderPipeline")
1239                }
1240            }
1241            ExclusivePipeline::Compute(p) => {
1242                if let Some(p) = p.upgrade() {
1243                    p.error_ident().fmt(f)
1244                } else {
1245                    f.write_str("ComputePipeline")
1246                }
1247            }
1248            ExclusivePipeline::RayTracing(p) => {
1249                if let Some(p) = p.upgrade() {
1250                    p.error_ident().fmt(f)
1251                } else {
1252                    f.write_str("RayTracingPipeline")
1253                }
1254            }
1255        }
1256    }
1257}
1258
1259#[derive(Debug)]
1260pub enum RawBindGroupLayout {
1261    Owning(ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>),
1262    /// The empty BGL was created by the device and will be destroyed by the device.
1263    RefDeviceEmptyBGL,
1264}
1265
1266#[derive(Debug)]
1267pub(crate) struct BindGroupLayoutState {
1268    pub(crate) raw: RawBindGroupLayout,
1269    /// It is very important that we know if the bind group comes from the BGL pool.
1270    ///
1271    /// If it does, then we need to remove it from the pool when we drop it.
1272    ///
1273    /// We cannot unconditionally remove from the pool, as BGLs that don't come from the pool
1274    /// (derived BGLs) must not be removed.
1275    pub(crate) origin: bgl::Origin,
1276    pub(crate) binding_count_validator: BindingTypeMaxCountValidator,
1277}
1278
1279/// Bind group layout.
1280#[derive(Debug)]
1281pub struct BindGroupLayout {
1282    pub(crate) state: ResourceState<BindGroupLayoutState>,
1283    pub(crate) device: Arc<Device>,
1284    pub(crate) entries: bgl::EntryMap,
1285    /// Bindings of buffer entries without `min_binding_size`. Their sizes are checked against
1286    /// the shader at draw or dispatch time.
1287    pub(crate) late_sized_bindings: Vec<u32>,
1288    pub(crate) exclusive_pipeline: OnceCell<ExclusivePipeline>,
1289    /// The `label` from the descriptor used to create the resource.
1290    pub(crate) label: String,
1291}
1292
1293impl Drop for BindGroupLayout {
1294    #[allow(trivial_casts)]
1295    fn drop(&mut self) {
1296        profiling::scope!("BindGroupLayout::drop");
1297        api_log!("BindGroupLayout::drop {:?}", self as *const _);
1298        #[cfg(feature = "trace")]
1299        {
1300            let mut t = self.device.trace.lock();
1301            if let Some(t) = t.as_mut() {
1302                use crate::device::trace;
1303
1304                // SAFETY: All bind group layouts are constructed in Arc => are heap allocated
1305                t.add(trace::Action::DropBindGroupLayout(unsafe {
1306                    trace::to_trace(self)
1307                }));
1308            }
1309        }
1310        resource_log!("Destroy raw {}", self.error_ident());
1311        let ResourceState::Valid(state) = &mut self.state else {
1312            return;
1313        };
1314        if matches!(state.origin, bgl::Origin::Pool) {
1315            self.device.bgl_pool.remove(&self.entries);
1316        }
1317        match state.raw {
1318            RawBindGroupLayout::Owning(ref mut raw) => {
1319                // SAFETY: We are in the Drop impl and we don't use state.raw anymore after this point.
1320                let raw = unsafe { ManuallyDrop::take(raw) };
1321                unsafe {
1322                    self.device.raw().destroy_bind_group_layout(raw);
1323                }
1324            }
1325            RawBindGroupLayout::RefDeviceEmptyBGL => {}
1326        }
1327    }
1328}
1329
1330crate::impl_resource_type!(BindGroupLayout);
1331crate::impl_labeled!(BindGroupLayout);
1332crate::impl_parent_device!(BindGroupLayout);
1333crate::impl_storage_item!(BindGroupLayout);
1334
1335impl BindGroupLayout {
1336    pub(crate) fn try_raw(&self) -> Result<&dyn hal::DynBindGroupLayout, InvalidResourceError> {
1337        let ResourceState::Valid(state) = &self.state else {
1338            return Err(InvalidResourceError(self.error_ident()));
1339        };
1340        match &state.raw {
1341            RawBindGroupLayout::Owning(raw) => Ok(raw.as_ref()),
1342            RawBindGroupLayout::RefDeviceEmptyBGL => Ok(self.device.empty_bgl.as_ref()),
1343        }
1344    }
1345
1346    pub(crate) fn state(&self) -> Result<&BindGroupLayoutState, InvalidResourceError> {
1347        let ResourceState::Valid(state) = &self.state else {
1348            return Err(InvalidResourceError(self.error_ident()));
1349        };
1350        Ok(state)
1351    }
1352
1353    pub(crate) fn check_is_valid(self: &Arc<Self>) -> Result<(), InvalidResourceError> {
1354        let ResourceState::Valid(_) = &self.state else {
1355            return Err(InvalidResourceError(self.error_ident()));
1356        };
1357        Ok(())
1358    }
1359
1360    fn empty(device: &Arc<Device>, exclusive_pipeline: ExclusivePipeline) -> Arc<Self> {
1361        Arc::new(Self {
1362            state: ResourceState::Valid(BindGroupLayoutState {
1363                raw: RawBindGroupLayout::RefDeviceEmptyBGL,
1364                origin: bgl::Origin::Derived,
1365                binding_count_validator: BindingTypeMaxCountValidator::default(),
1366            }),
1367            device: device.clone(),
1368            entries: bgl::EntryMap::default(),
1369            late_sized_bindings: Vec::new(),
1370            exclusive_pipeline: OnceCell::from(exclusive_pipeline),
1371            label: String::new(),
1372        })
1373    }
1374
1375    pub fn invalid(device: &Arc<Device>, label: String) -> Arc<Self> {
1376        Arc::new(Self {
1377            state: ResourceState::Invalid,
1378            device: device.clone(),
1379            entries: bgl::EntryMap::default(),
1380            late_sized_bindings: Vec::new(),
1381            exclusive_pipeline: OnceCell::from(ExclusivePipeline::None),
1382            label,
1383        })
1384    }
1385}
1386
1387#[derive(Clone, Debug, Error)]
1388#[non_exhaustive]
1389pub enum CreatePipelineLayoutError {
1390    #[error(transparent)]
1391    Device(#[from] DeviceError),
1392    #[error(
1393        "Immediate data has range bound {size} which is not aligned to IMMEDIATE_DATA_ALIGNMENT ({})",
1394        wgt::IMMEDIATE_DATA_ALIGNMENT
1395    )]
1396    MisalignedImmediateSize { size: u32 },
1397    #[error(transparent)]
1398    MissingFeatures(#[from] MissingFeatures),
1399    #[error(
1400        "Immediate data has size {size} which exceeds device immediate data size limit 0..{max}"
1401    )]
1402    ImmediateRangeTooLarge { size: u32, max: u32 },
1403    #[error(transparent)]
1404    TooManyBindings(BindingTypeMaxCountError),
1405    #[error("Bind group layout count {actual} exceeds device bind group limit {max}")]
1406    TooManyGroups { actual: usize, max: usize },
1407    #[error(transparent)]
1408    InvalidResource(#[from] InvalidResourceError),
1409    #[error("Bind group layout at index {index} has an exclusive pipeline: {pipeline}")]
1410    BglHasExclusivePipeline { index: usize, pipeline: String },
1411}
1412
1413impl WebGpuError for CreatePipelineLayoutError {
1414    fn webgpu_error_type(&self) -> ErrorType {
1415        match self {
1416            Self::Device(e) => e.webgpu_error_type(),
1417            Self::MissingFeatures(e) => e.webgpu_error_type(),
1418            Self::InvalidResource(e) => e.webgpu_error_type(),
1419            Self::TooManyBindings(e) => e.webgpu_error_type(),
1420            Self::MisalignedImmediateSize { .. }
1421            | Self::ImmediateRangeTooLarge { .. }
1422            | Self::TooManyGroups { .. }
1423            | Self::BglHasExclusivePipeline { .. } => ErrorType::Validation,
1424        }
1425    }
1426}
1427
1428#[derive(Clone, Debug, Error)]
1429#[non_exhaustive]
1430pub enum ImmediateUploadError {
1431    #[error(
1432        "Provided immediate data start offset {start_offset} overruns the range with a size of {immediate_size}"
1433    )]
1434    StartOffsetOverrun {
1435        start_offset: u32,
1436        immediate_size: u32,
1437    },
1438    #[error(
1439        "Provided immediate data start offset {0} does not respect \
1440        `IMMEDIATE_DATA_ALIGNMENT` ({ida})",
1441        ida = wgt::IMMEDIATE_DATA_ALIGNMENT
1442    )]
1443    StartOffsetUnaligned(u32),
1444    #[error(
1445        "Provided immediate data byte size {0} does not respect \
1446        `IMMEDIATE_DATA_ALIGNMENT` ({ida})",
1447        ida = wgt::IMMEDIATE_DATA_ALIGNMENT
1448    )]
1449    SizeUnaligned(usize),
1450    #[error(
1451        "Provided immediate data start offset {} + size {} overruns `max_immediate_size` {}",
1452        start_offset,
1453        size_bytes,
1454        limit
1455    )]
1456    EndOffsetBeyondLimit {
1457        start_offset: u32,
1458        size_bytes: usize,
1459        limit: u32,
1460    },
1461}
1462
1463impl WebGpuError for ImmediateUploadError {
1464    fn webgpu_error_type(&self) -> ErrorType {
1465        ErrorType::Validation
1466    }
1467}
1468
1469/// Describes a pipeline layout.
1470///
1471/// A `PipelineLayoutDescriptor` can be used to create a pipeline layout.
1472#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1473#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1474#[cfg_attr(feature = "serde", serde(bound = "BGL: Serialize"))]
1475/// cbindgen:ignore
1476pub struct PipelineLayoutDescriptor<'a, BGL = Arc<BindGroupLayout>>
1477where
1478    [Option<BGL>]: ToOwned,
1479    <[Option<BGL>] as ToOwned>::Owned: fmt::Debug,
1480{
1481    /// Debug label of the pipeline layout.
1482    ///
1483    /// This will show up in graphics debuggers for easy identification.
1484    pub label: Label<'a>,
1485    /// Bind groups that this pipeline uses. The first entry will provide all the bindings for
1486    /// "set = 0", second entry will provide all the bindings for "set = 1" etc.
1487    #[cfg_attr(
1488        feature = "serde",
1489        serde(bound(deserialize = "<[Option<BGL>] as ToOwned>::Owned: Deserialize<'de>"))
1490    )]
1491    pub bind_group_layouts: Cow<'a, [Option<BGL>]>,
1492    /// The number of bytes of immediate data that are allocated for use
1493    /// in the shader. The `var<immediate>`s in the shader attached to
1494    /// this pipeline must be equal or smaller than this size.
1495    ///
1496    /// If this value is non-zero, [`wgt::Features::IMMEDIATES`] must be enabled.
1497    pub immediate_size: u32,
1498}
1499
1500#[derive(Debug)]
1501pub struct PipelineLayout {
1502    pub(crate) raw: ResourceState<Box<dyn hal::DynPipelineLayout>>,
1503    pub(crate) device: Arc<Device>,
1504    /// The `label` from the descriptor used to create the resource.
1505    pub(crate) label: String,
1506    pub(crate) bind_group_layouts: ArrayVec<Option<Arc<BindGroupLayout>>, { hal::MAX_BIND_GROUPS }>,
1507    pub(crate) immediate_size: u32,
1508    pub(crate) buffers_and_acceleration_structures_in_vertex_stage: u32,
1509}
1510
1511impl Drop for PipelineLayout {
1512    #[allow(trivial_casts)]
1513    fn drop(&mut self) {
1514        profiling::scope!("PipelineLayout::drop");
1515        api_log!("PipelineLayout::drop {:?}", self as *const _);
1516        resource_log!("Destroy raw {}", self.error_ident());
1517        if let ResourceState::Valid(raw) = core::mem::replace(&mut self.raw, ResourceState::Invalid)
1518        {
1519            unsafe {
1520                self.device.raw().destroy_pipeline_layout(raw);
1521            }
1522        }
1523        #[cfg(feature = "trace")]
1524        {
1525            if let Some(t) = self.device.trace.lock().as_mut() {
1526                t.add(crate::device::trace::Action::DropPipelineLayout(unsafe {
1527                    crate::device::trace::to_trace(self)
1528                }));
1529            }
1530        }
1531    }
1532}
1533
1534impl PipelineLayout {
1535    pub(crate) fn raw(&self) -> Result<&dyn hal::DynPipelineLayout, InvalidResourceError> {
1536        self.raw
1537            .as_ref()
1538            .valid()
1539            .map(|r| r.as_ref())
1540            .ok_or_else(|| InvalidResourceError(self.error_ident()))
1541    }
1542
1543    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
1544        self.raw
1545            .as_ref()
1546            .valid()
1547            .map(|_| ())
1548            .ok_or_else(|| InvalidResourceError(self.error_ident()))
1549    }
1550
1551    pub(crate) fn get_bind_group_layout(
1552        self: &Arc<Self>,
1553        index: u32,
1554        exclusive_pipeline_for_empty_bgl: ExclusivePipeline,
1555    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
1556        let max_bind_groups = self.device.limits.max_bind_groups;
1557        if index >= max_bind_groups {
1558            return Err(GetBindGroupLayoutError::IndexOutOfRange {
1559                index,
1560                max: max_bind_groups,
1561            });
1562        }
1563        Ok(self
1564            .bind_group_layouts
1565            .get(index as usize)
1566            .cloned()
1567            .flatten()
1568            .unwrap_or_else(|| {
1569                BindGroupLayout::empty(&self.device, exclusive_pipeline_for_empty_bgl)
1570            }))
1571    }
1572
1573    pub(crate) fn get_bgl_entry(
1574        &self,
1575        group: u32,
1576        binding: u32,
1577    ) -> Option<&wgt::BindGroupLayoutEntry> {
1578        let bgl = self.bind_group_layouts.get(group as usize)?;
1579        let bgl = bgl.as_ref()?;
1580        bgl.entries.get(binding)
1581    }
1582
1583    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
1584        Arc::new(Self {
1585            raw: ResourceState::Invalid,
1586            device,
1587            label,
1588            bind_group_layouts: ArrayVec::new(),
1589            immediate_size: 0,
1590            buffers_and_acceleration_structures_in_vertex_stage: 0,
1591        })
1592    }
1593}
1594
1595crate::impl_resource_type!(PipelineLayout);
1596crate::impl_labeled!(PipelineLayout);
1597crate::impl_parent_device!(PipelineLayout);
1598crate::impl_storage_item!(PipelineLayout);
1599
1600#[repr(C)]
1601#[derive(Clone, Debug, Hash, Eq, PartialEq)]
1602#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1603pub struct BufferBinding<B = Arc<Buffer>> {
1604    pub buffer: B,
1605    pub offset: wgt::BufferAddress,
1606
1607    /// Size of the binding. If `None`, the binding spans from `offset` to the
1608    /// end of the buffer.
1609    ///
1610    /// We use `BufferAddress` to allow a size of zero on this `wgpu_core` type,
1611    /// because JavaScript bindings cannot readily express `Option<NonZeroU64>`.
1612    /// The `wgpu` API uses `Option<BufferSize>` (i.e. `NonZeroU64`) for this
1613    /// field.
1614    pub size: Option<wgt::BufferAddress>,
1615}
1616
1617// Note: Duplicated in `wgpu-rs` as `BindingResource`
1618// They're different enough that it doesn't make sense to share a common type
1619#[derive(Debug, Clone)]
1620#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1621pub enum BindingResource<
1622    'a,
1623    B = Arc<Buffer>,
1624    S = Arc<Sampler>,
1625    TV = Arc<TextureView>,
1626    TLAS = Arc<Tlas>,
1627    ET = Arc<ExternalTexture>,
1628> where
1629    [BufferBinding<B>]: ToOwned,
1630    [S]: ToOwned,
1631    [TV]: ToOwned,
1632    [TLAS]: ToOwned,
1633    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
1634    <[S] as ToOwned>::Owned: fmt::Debug,
1635    <[TV] as ToOwned>::Owned: fmt::Debug,
1636    <[TLAS] as ToOwned>::Owned: fmt::Debug,
1637{
1638    Buffer(BufferBinding<B>),
1639    #[cfg_attr(
1640        feature = "serde",
1641        serde(bound(deserialize = "<[BufferBinding<B>] as ToOwned>::Owned: Deserialize<'de>"))
1642    )]
1643    BufferArray(Cow<'a, [BufferBinding<B>]>),
1644    Sampler(S),
1645    #[cfg_attr(
1646        feature = "serde",
1647        serde(bound(deserialize = "<[S] as ToOwned>::Owned: Deserialize<'de>"))
1648    )]
1649    SamplerArray(Cow<'a, [S]>),
1650    TextureView(TV),
1651    #[cfg_attr(
1652        feature = "serde",
1653        serde(bound(deserialize = "<[TV] as ToOwned>::Owned: Deserialize<'de>"))
1654    )]
1655    TextureViewArray(Cow<'a, [TV]>),
1656    AccelerationStructure(TLAS),
1657    #[cfg_attr(
1658        feature = "serde",
1659        serde(bound(deserialize = "<[TLAS] as ToOwned>::Owned: Deserialize<'de>"))
1660    )]
1661    AccelerationStructureArray(Cow<'a, [TLAS]>),
1662    ExternalTexture(ET),
1663}
1664
1665#[derive(Clone, Debug, Error)]
1666#[non_exhaustive]
1667pub enum BindError {
1668    #[error(
1669        "Dynamic offsets not expected with null bind group at index {group}. However {actual} dynamic offset{s1} were provided.",
1670        s1 = if *.actual >= 2 { "s" } else { "" },
1671    )]
1672    DynamicOffsetCountNotZero { group: u32, actual: usize },
1673    #[error(
1674        "{bind_group} at index {group} expects {expected} dynamic offset{s0}, but {actual} dynamic offset{s1} {to_be} provided",
1675        s0 = if *.expected >= 2 { "s" } else { "" },
1676        s1 = if *.actual >= 2 { "s" } else { "" },
1677        to_be = if *.actual == 1 { "was" } else { "were" },
1678    )]
1679    MismatchedDynamicOffsetCount {
1680        bind_group: ResourceErrorIdent,
1681        group: u32,
1682        actual: usize,
1683        expected: usize,
1684    },
1685    #[error(
1686        "Dynamic binding index {idx} (targeting {bind_group} {group}, binding {binding}) with value {offset}, does not respect device's requested `{limit_name}` limit: {alignment}"
1687    )]
1688    UnalignedDynamicBinding {
1689        bind_group: ResourceErrorIdent,
1690        idx: usize,
1691        group: u32,
1692        binding: u32,
1693        offset: u32,
1694        alignment: u32,
1695        limit_name: &'static str,
1696    },
1697    #[error(
1698        "Dynamic binding offset index {idx} with offset {offset} would overrun the buffer bound to {bind_group} {group} -> binding {binding}. \
1699         Buffer size is {buffer_size} bytes, the binding binds bytes {binding_range:?}, meaning the maximum the binding can be offset is {maximum_dynamic_offset} bytes",
1700    )]
1701    DynamicBindingOutOfBounds {
1702        bind_group: ResourceErrorIdent,
1703        idx: usize,
1704        group: u32,
1705        binding: u32,
1706        offset: u32,
1707        buffer_size: wgt::BufferAddress,
1708        binding_range: Range<wgt::BufferAddress>,
1709        maximum_dynamic_offset: wgt::BufferAddress,
1710    },
1711}
1712
1713impl WebGpuError for BindError {
1714    fn webgpu_error_type(&self) -> ErrorType {
1715        ErrorType::Validation
1716    }
1717}
1718
1719#[derive(Debug)]
1720pub struct BindGroupDynamicBindingData {
1721    /// The index of the binding.
1722    ///
1723    /// Used for more descriptive errors.
1724    pub(crate) binding_idx: u32,
1725    /// The size of the buffer.
1726    ///
1727    /// Used for more descriptive errors.
1728    pub(crate) buffer_size: wgt::BufferAddress,
1729    /// The range that the binding covers.
1730    ///
1731    /// Used for more descriptive errors.
1732    pub(crate) binding_range: Range<wgt::BufferAddress>,
1733    /// The maximum value the dynamic offset can have before running off the end of the buffer.
1734    pub(crate) maximum_dynamic_offset: wgt::BufferAddress,
1735    /// The binding type.
1736    pub(crate) binding_type: wgt::BufferBindingType,
1737}
1738
1739pub(crate) fn buffer_binding_type_alignment(
1740    limits: &wgt::Limits,
1741    binding_type: wgt::BufferBindingType,
1742) -> (u32, &'static str) {
1743    match binding_type {
1744        wgt::BufferBindingType::Uniform => (
1745            limits.min_uniform_buffer_offset_alignment,
1746            "min_uniform_buffer_offset_alignment",
1747        ),
1748        wgt::BufferBindingType::Storage { .. } => (
1749            limits.min_storage_buffer_offset_alignment,
1750            "min_storage_buffer_offset_alignment",
1751        ),
1752    }
1753}
1754
1755pub(crate) fn buffer_binding_type_bounds_check_alignment(
1756    alignments: &hal::Alignments,
1757    binding_type: wgt::BufferBindingType,
1758) -> wgt::BufferAddress {
1759    match binding_type {
1760        wgt::BufferBindingType::Uniform => alignments.uniform_bounds_check_alignment.get(),
1761        wgt::BufferBindingType::Storage { .. } => wgt::COPY_BUFFER_ALIGNMENT,
1762    }
1763}
1764
1765#[derive(Debug)]
1766pub(crate) struct BindGroupState {
1767    pub(crate) raw: Snatchable<Box<dyn hal::DynBindGroup>>,
1768}
1769
1770#[derive(Debug)]
1771pub struct BindGroup {
1772    pub(crate) state: ResourceState<BindGroupState>,
1773    pub(crate) device: Arc<Device>,
1774    pub(crate) layout: Arc<BindGroupLayout>,
1775    /// The `label` from the descriptor used to create the resource.
1776    pub(crate) label: String,
1777    pub(crate) tracking_data: TrackingData,
1778    pub(crate) used: BindGroupStates,
1779    pub(crate) buffer_init_actions: Vec<BufferInitTrackerAction>,
1780    pub(crate) texture_init_actions: Vec<TextureInitTrackerAction>,
1781    /// INVARIANT: Sorted by binding index order.
1782    pub(crate) dynamic_binding_info: Vec<BindGroupDynamicBindingData>,
1783    /// Bound sizes of `layout.late_sized_bindings`, in the same order.
1784    pub(crate) late_buffer_binding_sizes: Vec<wgt::BufferSize>,
1785}
1786
1787impl Drop for BindGroup {
1788    #[allow(trivial_casts)]
1789    fn drop(&mut self) {
1790        profiling::scope!("BindGroup::drop");
1791        api_log!("BindGroup::drop {:?}", self as *const _);
1792        #[cfg(feature = "trace")]
1793        if let Some(t) = self.device.trace.lock().as_mut() {
1794            use crate::device::trace::{to_trace, Action};
1795            t.add(Action::DropBindGroup(unsafe { to_trace(self) }));
1796        }
1797        let ResourceState::Valid(state) = &mut self.state else {
1798            return;
1799        };
1800        if let Some(raw) = state.raw.take() {
1801            resource_log!("Destroy raw {}", self.error_ident());
1802            unsafe {
1803                self.device.raw().destroy_bind_group(raw);
1804            }
1805        }
1806    }
1807}
1808
1809impl BindGroup {
1810    pub(crate) fn try_raw<'a>(
1811        &'a self,
1812        guard: &'a SnatchGuard,
1813    ) -> Result<&'a dyn hal::DynBindGroup, InvalidOrDestroyedResourceError> {
1814        for buffer in self.used.buffers.used_resources() {
1815            buffer.try_raw(guard)?;
1816        }
1817        for texture in self.used.views.used_textures() {
1818            texture.try_raw(guard)?;
1819        }
1820
1821        self.state()?
1822            .raw
1823            .get(guard)
1824            .map(|raw| raw.as_ref())
1825            .ok_or_else(|| DestroyedResourceError(self.error_ident()).into())
1826    }
1827
1828    pub(crate) fn state(&self) -> Result<&BindGroupState, InvalidResourceError> {
1829        let ResourceState::Valid(state) = &self.state else {
1830            return Err(InvalidResourceError(self.error_ident()));
1831        };
1832        Ok(state)
1833    }
1834
1835    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
1836        self.state().map(|_| ())
1837    }
1838
1839    pub(crate) fn invalid(
1840        device: Arc<Device>,
1841        label: String,
1842        layout: Arc<BindGroupLayout>,
1843    ) -> Arc<Self> {
1844        Arc::new(Self {
1845            state: ResourceState::Invalid,
1846            layout,
1847            label,
1848            tracking_data: TrackingData::new(device.tracker_indices.bind_groups.clone()),
1849            used: BindGroupStates::new(),
1850            buffer_init_actions: Vec::new(),
1851            texture_init_actions: Vec::new(),
1852            dynamic_binding_info: Vec::new(),
1853            late_buffer_binding_sizes: Vec::new(),
1854            device,
1855        })
1856    }
1857
1858    pub(crate) fn validate_dynamic_bindings(
1859        &self,
1860        bind_group_index: u32,
1861        offsets: &[wgt::DynamicOffset],
1862    ) -> Result<(), BindError> {
1863        if self.dynamic_binding_info.len() != offsets.len() {
1864            return Err(BindError::MismatchedDynamicOffsetCount {
1865                bind_group: self.error_ident(),
1866                group: bind_group_index,
1867                expected: self.dynamic_binding_info.len(),
1868                actual: offsets.len(),
1869            });
1870        }
1871
1872        for (idx, (info, &offset)) in self
1873            .dynamic_binding_info
1874            .iter()
1875            .zip(offsets.iter())
1876            .enumerate()
1877        {
1878            let (alignment, limit_name) =
1879                buffer_binding_type_alignment(&self.device.limits, info.binding_type);
1880            if !(offset as wgt::BufferAddress).is_multiple_of(alignment as u64) {
1881                return Err(BindError::UnalignedDynamicBinding {
1882                    bind_group: self.error_ident(),
1883                    group: bind_group_index,
1884                    binding: info.binding_idx,
1885                    idx,
1886                    offset,
1887                    alignment,
1888                    limit_name,
1889                });
1890            }
1891
1892            if offset as wgt::BufferAddress > info.maximum_dynamic_offset {
1893                return Err(BindError::DynamicBindingOutOfBounds {
1894                    bind_group: self.error_ident(),
1895                    group: bind_group_index,
1896                    binding: info.binding_idx,
1897                    idx,
1898                    offset,
1899                    buffer_size: info.buffer_size,
1900                    binding_range: info.binding_range.clone(),
1901                    maximum_dynamic_offset: info.maximum_dynamic_offset,
1902                });
1903            }
1904        }
1905
1906        Ok(())
1907    }
1908}
1909
1910crate::impl_resource_type!(BindGroup);
1911crate::impl_labeled!(BindGroup);
1912crate::impl_parent_device!(BindGroup);
1913crate::impl_storage_item!(BindGroup);
1914crate::impl_trackable!(BindGroup);
1915
1916#[derive(Clone, Debug, Error)]
1917#[non_exhaustive]
1918pub enum GetBindGroupLayoutError {
1919    #[error("Bind group layout index {index} is greater than the device's configured `max_bind_groups` limit {max}")]
1920    IndexOutOfRange { index: u32, max: u32 },
1921    #[error(transparent)]
1922    InvalidResource(#[from] InvalidResourceError),
1923}
1924
1925impl WebGpuError for GetBindGroupLayoutError {
1926    fn webgpu_error_type(&self) -> ErrorType {
1927        match self {
1928            Self::IndexOutOfRange { .. } => ErrorType::Validation,
1929            Self::InvalidResource(e) => e.webgpu_error_type(),
1930        }
1931    }
1932}
1933
1934#[derive(Clone, Debug, Error, Eq, PartialEq)]
1935#[error(
1936    "In bind group index {group_index}, the buffer bound at binding index {binding_index} \
1937     is bound with size {bound_size} where the shader expects {shader_size}."
1938)]
1939pub struct LateMinBufferBindingSizeMismatch {
1940    pub group_index: u32,
1941    pub binding_index: u32,
1942    pub shader_size: wgt::BufferAddress,
1943    pub bound_size: wgt::BufferAddress,
1944}