Debian Codegraph @

third_party/rust/wgpu-core/src/binding_model.rs

raw
1 use alloc::{
2 borrow::{Cow, ToOwned},
3 boxed::Box,
4 string::String,
5 sync::{Arc, Weak},
6 vec::Vec,
7 };
8 use core::{fmt, mem::ManuallyDrop, ops::Range};
9
10 use arrayvec::ArrayVec;
11 use thiserror::Error;
12
13 #[cfg(feature = "serde")]
14 use serde::Deserialize;
15 #[cfg(feature = "serde")]
16 use serde::Serialize;
17
18 use crate::{
19 device::{
20 bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures, SHADER_STAGE_COUNT,
21 },
22 id::{BindGroupLayoutId, BufferId, SamplerId, TextureViewId, TlasId},
23 init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction},
24 pipeline::{ComputePipeline, RenderPipeline},
25 resource::{
26 Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError,
27 MissingTextureUsageError, ResourceErrorIdent, Sampler, TextureView, Tlas, TrackingData,
28 },
29 resource_log,
30 snatch::{SnatchGuard, Snatchable},
31 track::{BindGroupStates, ResourceUsageCompatibilityError},
32 Label,
33 };
34
35 #[derive(Clone, Debug, Error)]
36 #[non_exhaustive]
37 pub enum BindGroupLayoutEntryError {
38 #[error("Cube dimension is not expected for texture storage")]
39 StorageTextureCube,
40 #[error("Atomic storage textures are not allowed by baseline webgpu, they require the native only feature TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES")]
41 StorageTextureAtomic,
42 #[error("Arrays of bindings unsupported for this type of binding")]
43 ArrayUnsupported,
44 #[error("Multisampled binding with sample type `TextureSampleType::Float` must have filterable set to false.")]
45 SampleTypeFloatFilterableBindingMultisampled,
46 #[error("Multisampled texture binding view dimension must be 2d, got {0:?}")]
47 Non2DMultisampled(wgt::TextureViewDimension),
48 #[error(transparent)]
49 MissingFeatures(#[from] MissingFeatures),
50 #[error(transparent)]
51 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
52 }
53
54 #[derive(Clone, Debug, Error)]
55 #[non_exhaustive]
56 pub enum CreateBindGroupLayoutError {
57 #[error(transparent)]
58 Device(#[from] DeviceError),
59 #[error("Conflicting binding at index {0}")]
60 ConflictBinding(u32),
61 #[error("Binding {binding} entry is invalid")]
62 Entry {
63 binding: u32,
64 #[source]
65 error: BindGroupLayoutEntryError,
66 },
67 #[error(transparent)]
68 TooManyBindings(BindingTypeMaxCountError),
69 #[error("Bind groups may not contain both a binding array and a dynamically offset buffer")]
70 ContainsBothBindingArrayAndDynamicOffsetArray,
71 #[error("Bind groups may not contain both a binding array and a uniform buffer")]
72 ContainsBothBindingArrayAndUniformBuffer,
73 #[error("Binding index {binding} is greater than the maximum number {maximum}")]
74 InvalidBindingIndex { binding: u32, maximum: u32 },
75 #[error("Invalid visibility {0:?}")]
76 InvalidVisibility(wgt::ShaderStages),
77 }
78
79 //TODO: refactor this to move out `enum BindingError`.
80
81 #[derive(Clone, Debug, Error)]
82 #[non_exhaustive]
83 pub enum CreateBindGroupError {
84 #[error(transparent)]
85 Device(#[from] DeviceError),
86 #[error(transparent)]
87 DestroyedResource(#[from] DestroyedResourceError),
88 #[error(
89 "Binding count declared with at most {expected} items, but {actual} items were provided"
90 )]
91 BindingArrayPartialLengthMismatch { actual: usize, expected: usize },
92 #[error(
93 "Binding count declared with exactly {expected} items, but {actual} items were provided"
94 )]
95 BindingArrayLengthMismatch { actual: usize, expected: usize },
96 #[error("Array binding provided zero elements")]
97 BindingArrayZeroLength,
98 #[error("The bound range {range:?} of {buffer} overflows its size ({size})")]
99 BindingRangeTooLarge {
100 buffer: ResourceErrorIdent,
101 range: Range<wgt::BufferAddress>,
102 size: u64,
103 },
104 #[error("Binding size {actual} of {buffer} is less than minimum {min}")]
105 BindingSizeTooSmall {
106 buffer: ResourceErrorIdent,
107 actual: u64,
108 min: u64,
109 },
110 #[error("{0} binding size is zero")]
111 BindingZeroSize(ResourceErrorIdent),
112 #[error("Number of bindings in bind group descriptor ({actual}) does not match the number of bindings defined in the bind group layout ({expected})")]
113 BindingsNumMismatch { actual: usize, expected: usize },
114 #[error("Binding {0} is used at least twice in the descriptor")]
115 DuplicateBinding(u32),
116 #[error("Unable to find a corresponding declaration for the given binding {0}")]
117 MissingBindingDeclaration(u32),
118 #[error(transparent)]
119 MissingBufferUsage(#[from] MissingBufferUsageError),
120 #[error(transparent)]
121 MissingTextureUsage(#[from] MissingTextureUsageError),
122 #[error("Binding declared as a single item, but bind group is using it as an array")]
123 SingleBindingExpected,
124 #[error("Buffer offset {0} does not respect device's requested `{1}` limit {2}")]
125 UnalignedBufferOffset(wgt::BufferAddress, &'static str, u32),
126 #[error(
127 "Buffer binding {binding} range {given} exceeds `max_*_buffer_binding_size` limit {limit}"
128 )]
129 BufferRangeTooLarge {
130 binding: u32,
131 given: u32,
132 limit: u32,
133 },
134 #[error("Binding {binding} has a different type ({actual:?}) than the one in the layout ({expected:?})")]
135 WrongBindingType {
136 // Index of the binding
137 binding: u32,
138 // The type given to the function
139 actual: wgt::BindingType,
140 // Human-readable description of expected types
141 expected: &'static str,
142 },
143 #[error("Texture binding {binding} expects multisampled = {layout_multisampled}, but given a view with samples = {view_samples}")]
144 InvalidTextureMultisample {
145 binding: u32,
146 layout_multisampled: bool,
147 view_samples: u32,
148 },
149 #[error(
150 "Texture binding {} expects sample type {:?}, but was given a view with format {:?} (sample type {:?})",
151 binding,
152 layout_sample_type,
153 view_format,
154 view_sample_type
155 )]
156 InvalidTextureSampleType {
157 binding: u32,
158 layout_sample_type: wgt::TextureSampleType,
159 view_format: wgt::TextureFormat,
160 view_sample_type: wgt::TextureSampleType,
161 },
162 #[error("Texture binding {binding} expects dimension = {layout_dimension:?}, but given a view with dimension = {view_dimension:?}")]
163 InvalidTextureDimension {
164 binding: u32,
165 layout_dimension: wgt::TextureViewDimension,
166 view_dimension: wgt::TextureViewDimension,
167 },
168 #[error("Storage texture binding {binding} expects format = {layout_format:?}, but given a view with format = {view_format:?}")]
169 InvalidStorageTextureFormat {
170 binding: u32,
171 layout_format: wgt::TextureFormat,
172 view_format: wgt::TextureFormat,
173 },
174 #[error("Storage texture bindings must have a single mip level, but given a view with mip_level_count = {mip_level_count:?} at binding {binding}")]
175 InvalidStorageTextureMipLevelCount { binding: u32, mip_level_count: u32 },
176 #[error("Sampler binding {binding} expects comparison = {layout_cmp}, but given a sampler with comparison = {sampler_cmp}")]
177 WrongSamplerComparison {
178 binding: u32,
179 layout_cmp: bool,
180 sampler_cmp: bool,
181 },
182 #[error("Sampler binding {binding} expects filtering = {layout_flt}, but given a sampler with filtering = {sampler_flt}")]
183 WrongSamplerFiltering {
184 binding: u32,
185 layout_flt: bool,
186 sampler_flt: bool,
187 },
188 #[error("TLAS binding {binding} is required to support vertex returns but is missing flag AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN")]
189 MissingTLASVertexReturn { binding: u32 },
190 #[error("Bound texture views can not have both depth and stencil aspects enabled")]
191 DepthStencilAspect,
192 #[error("The adapter does not support read access for storage textures of format {0:?}")]
193 StorageReadNotSupported(wgt::TextureFormat),
194 #[error("The adapter does not support atomics for storage textures of format {0:?}")]
195 StorageAtomicNotSupported(wgt::TextureFormat),
196 #[error("The adapter does not support write access for storage textures of format {0:?}")]
197 StorageWriteNotSupported(wgt::TextureFormat),
198 #[error("The adapter does not support read-write access for storage textures of format {0:?}")]
199 StorageReadWriteNotSupported(wgt::TextureFormat),
200 #[error(transparent)]
201 ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
202 #[error(transparent)]
203 InvalidResource(#[from] InvalidResourceError),
204 }
205
206 #[derive(Clone, Debug, Error)]
207 pub enum BindingZone {
208 #[error("Stage {0:?}")]
209 Stage(wgt::ShaderStages),
210 #[error("Whole pipeline")]
211 Pipeline,
212 }
213
214 #[derive(Clone, Debug, Error)]
215 #[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())]
216 pub struct BindingTypeMaxCountError {
217 pub kind: BindingTypeMaxCountErrorKind,
218 pub zone: BindingZone,
219 pub limit: u32,
220 pub count: u32,
221 }
222
223 #[derive(Clone, Debug)]
224 pub enum BindingTypeMaxCountErrorKind {
225 DynamicUniformBuffers,
226 DynamicStorageBuffers,
227 SampledTextures,
228 Samplers,
229 StorageBuffers,
230 StorageTextures,
231 UniformBuffers,
232 BindingArrayElements,
233 BindingArraySamplerElements,
234 }
235
236 impl BindingTypeMaxCountErrorKind {
237 fn to_config_str(&self) -> &'static str {
238 match self {
239 BindingTypeMaxCountErrorKind::DynamicUniformBuffers => {
240 "max_dynamic_uniform_buffers_per_pipeline_layout"
241 }
242 BindingTypeMaxCountErrorKind::DynamicStorageBuffers => {
243 "max_dynamic_storage_buffers_per_pipeline_layout"
244 }
245 BindingTypeMaxCountErrorKind::SampledTextures => {
246 "max_sampled_textures_per_shader_stage"
247 }
248 BindingTypeMaxCountErrorKind::Samplers => "max_samplers_per_shader_stage",
249 BindingTypeMaxCountErrorKind::StorageBuffers => "max_storage_buffers_per_shader_stage",
250 BindingTypeMaxCountErrorKind::StorageTextures => {
251 "max_storage_textures_per_shader_stage"
252 }
253 BindingTypeMaxCountErrorKind::UniformBuffers => "max_uniform_buffers_per_shader_stage",
254 BindingTypeMaxCountErrorKind::BindingArrayElements => {
255 "max_binding_array_elements_per_shader_stage"
256 }
257 BindingTypeMaxCountErrorKind::BindingArraySamplerElements => {
258 "max_binding_array_elements_per_shader_stage"
259 }
260 }
261 }
262 }
263
264 #[derive(Debug, Default)]
265 pub(crate) struct PerStageBindingTypeCounter {
266 vertex: u32,
267 fragment: u32,
268 compute: u32,
269 }
270
271 impl PerStageBindingTypeCounter {
272 pub(crate) fn add(&mut self, stage: wgt::ShaderStages, count: u32) {
273 if stage.contains(wgt::ShaderStages::VERTEX) {
274 self.vertex += count;
275 }
276 if stage.contains(wgt::ShaderStages::FRAGMENT) {
277 self.fragment += count;
278 }
279 if stage.contains(wgt::ShaderStages::COMPUTE) {
280 self.compute += count;
281 }
282 }
283
284 pub(crate) fn max(&self) -> (BindingZone, u32) {
285 let max_value = self.vertex.max(self.fragment.max(self.compute));
286 let mut stage = wgt::ShaderStages::NONE;
287 if max_value == self.vertex {
288 stage |= wgt::ShaderStages::VERTEX
289 }
290 if max_value == self.fragment {
291 stage |= wgt::ShaderStages::FRAGMENT
292 }
293 if max_value == self.compute {
294 stage |= wgt::ShaderStages::COMPUTE
295 }
296 (BindingZone::Stage(stage), max_value)
297 }
298
299 pub(crate) fn merge(&mut self, other: &Self) {
300 self.vertex = self.vertex.max(other.vertex);
301 self.fragment = self.fragment.max(other.fragment);
302 self.compute = self.compute.max(other.compute);
303 }
304
305 pub(crate) fn validate(
306 &self,
307 limit: u32,
308 kind: BindingTypeMaxCountErrorKind,
309 ) -> Result<(), BindingTypeMaxCountError> {
310 let (zone, count) = self.max();
311 if limit < count {
312 Err(BindingTypeMaxCountError {
313 kind,
314 zone,
315 limit,
316 count,
317 })
318 } else {
319 Ok(())
320 }
321 }
322 }
323
324 #[derive(Debug, Default)]
325 pub(crate) struct BindingTypeMaxCountValidator {
326 dynamic_uniform_buffers: u32,
327 dynamic_storage_buffers: u32,
328 sampled_textures: PerStageBindingTypeCounter,
329 samplers: PerStageBindingTypeCounter,
330 storage_buffers: PerStageBindingTypeCounter,
331 storage_textures: PerStageBindingTypeCounter,
332 uniform_buffers: PerStageBindingTypeCounter,
333 acceleration_structures: PerStageBindingTypeCounter,
334 binding_array_elements: PerStageBindingTypeCounter,
335 binding_array_sampler_elements: PerStageBindingTypeCounter,
336 has_bindless_array: bool,
337 }
338
339 impl BindingTypeMaxCountValidator {
340 pub(crate) fn add_binding(&mut self, binding: &wgt::BindGroupLayoutEntry) {
341 let count = binding.count.map_or(1, |count| count.get());
342
343 if binding.count.is_some() {
344 self.binding_array_elements.add(binding.visibility, count);
345 self.has_bindless_array = true;
346
347 if let wgt::BindingType::Sampler(_) = binding.ty {
348 self.binding_array_sampler_elements
349 .add(binding.visibility, count);
350 }
351 } else {
352 match binding.ty {
353 wgt::BindingType::Buffer {
354 ty: wgt::BufferBindingType::Uniform,
355 has_dynamic_offset,
356 ..
357 } => {
358 self.uniform_buffers.add(binding.visibility, count);
359 if has_dynamic_offset {
360 self.dynamic_uniform_buffers += count;
361 }
362 }
363 wgt::BindingType::Buffer {
364 ty: wgt::BufferBindingType::Storage { .. },
365 has_dynamic_offset,
366 ..
367 } => {
368 self.storage_buffers.add(binding.visibility, count);
369 if has_dynamic_offset {
370 self.dynamic_storage_buffers += count;
371 }
372 }
373 wgt::BindingType::Sampler { .. } => {
374 self.samplers.add(binding.visibility, count);
375 }
376 wgt::BindingType::Texture { .. } => {
377 self.sampled_textures.add(binding.visibility, count);
378 }
379 wgt::BindingType::StorageTexture { .. } => {
380 self.storage_textures.add(binding.visibility, count);
381 }
382 wgt::BindingType::AccelerationStructure { .. } => {
383 self.acceleration_structures.add(binding.visibility, count);
384 }
385 }
386 }
387 }
388
389 pub(crate) fn merge(&mut self, other: &Self) {
390 self.dynamic_uniform_buffers += other.dynamic_uniform_buffers;
391 self.dynamic_storage_buffers += other.dynamic_storage_buffers;
392 self.sampled_textures.merge(&other.sampled_textures);
393 self.samplers.merge(&other.samplers);
394 self.storage_buffers.merge(&other.storage_buffers);
395 self.storage_textures.merge(&other.storage_textures);
396 self.uniform_buffers.merge(&other.uniform_buffers);
397 self.acceleration_structures
398 .merge(&other.acceleration_structures);
399 self.binding_array_elements
400 .merge(&other.binding_array_elements);
401 self.binding_array_sampler_elements
402 .merge(&other.binding_array_sampler_elements);
403 }
404
405 pub(crate) fn validate(&self, limits: &wgt::Limits) -> Result<(), BindingTypeMaxCountError> {
406 if limits.max_dynamic_uniform_buffers_per_pipeline_layout < self.dynamic_uniform_buffers {
407 return Err(BindingTypeMaxCountError {
408 kind: BindingTypeMaxCountErrorKind::DynamicUniformBuffers,
409 zone: BindingZone::Pipeline,
410 limit: limits.max_dynamic_uniform_buffers_per_pipeline_layout,
411 count: self.dynamic_uniform_buffers,
412 });
413 }
414 if limits.max_dynamic_storage_buffers_per_pipeline_layout < self.dynamic_storage_buffers {
415 return Err(BindingTypeMaxCountError {
416 kind: BindingTypeMaxCountErrorKind::DynamicStorageBuffers,
417 zone: BindingZone::Pipeline,
418 limit: limits.max_dynamic_storage_buffers_per_pipeline_layout,
419 count: self.dynamic_storage_buffers,
420 });
421 }
422 self.sampled_textures.validate(
423 limits.max_sampled_textures_per_shader_stage,
424 BindingTypeMaxCountErrorKind::SampledTextures,
425 )?;
426 self.samplers.validate(
427 limits.max_samplers_per_shader_stage,
428 BindingTypeMaxCountErrorKind::Samplers,
429 )?;
430 self.storage_buffers.validate(
431 limits.max_storage_buffers_per_shader_stage,
432 BindingTypeMaxCountErrorKind::StorageBuffers,
433 )?;
434 self.storage_textures.validate(
435 limits.max_storage_textures_per_shader_stage,
436 BindingTypeMaxCountErrorKind::StorageTextures,
437 )?;
438 self.uniform_buffers.validate(
439 limits.max_uniform_buffers_per_shader_stage,
440 BindingTypeMaxCountErrorKind::UniformBuffers,
441 )?;
442 self.binding_array_elements.validate(
443 limits.max_binding_array_elements_per_shader_stage,
444 BindingTypeMaxCountErrorKind::BindingArrayElements,
445 )?;
446 self.binding_array_sampler_elements.validate(
447 limits.max_binding_array_sampler_elements_per_shader_stage,
448 BindingTypeMaxCountErrorKind::BindingArraySamplerElements,
449 )?;
450 Ok(())
451 }
452
453 /// Validate that the bind group layout does not contain both a binding array and a dynamic offset array.
454 ///
455 /// This allows us to use `UPDATE_AFTER_BIND` on vulkan for bindless arrays. Vulkan does not allow
456 /// `UPDATE_AFTER_BIND` on dynamic offset arrays. See <https://github.com/gfx-rs/wgpu/issues/6737>
457 pub(crate) fn validate_binding_arrays(&self) -> Result<(), CreateBindGroupLayoutError> {
458 let has_dynamic_offset_array =
459 self.dynamic_uniform_buffers > 0 || self.dynamic_storage_buffers > 0;
460 let has_uniform_buffer = self.uniform_buffers.max().1 > 0;
461 if self.has_bindless_array && has_dynamic_offset_array {
462 return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndDynamicOffsetArray);
463 }
464 if self.has_bindless_array && has_uniform_buffer {
465 return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndUniformBuffer);
466 }
467 Ok(())
468 }
469 }
470
471 /// Bindable resource and the slot to bind it to.
472 /// cbindgen:ignore
473 #[derive(Clone, Debug)]
474 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
475 pub struct BindGroupEntry<'a, B = BufferId, S = SamplerId, TV = TextureViewId, TLAS = TlasId>
476 where
477 [BufferBinding<B>]: ToOwned,
478 [S]: ToOwned,
479 [TV]: ToOwned,
480 <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
481 <[S] as ToOwned>::Owned: fmt::Debug,
482 <[TV] as ToOwned>::Owned: fmt::Debug,
483 {
484 /// Slot for which binding provides resource. Corresponds to an entry of the same
485 /// binding index in the [`BindGroupLayoutDescriptor`].
486 pub binding: u32,
487 #[cfg_attr(
488 feature = "serde",
489 serde(bound(deserialize = "BindingResource<'a, B, S, TV, TLAS>: Deserialize<'de>"))
490 )]
491 /// Resource to attach to the binding
492 pub resource: BindingResource<'a, B, S, TV, TLAS>,
493 }
494
495 /// cbindgen:ignore
496 pub type ResolvedBindGroupEntry<'a> =
497 BindGroupEntry<'a, Arc<Buffer>, Arc<Sampler>, Arc<TextureView>, Arc<Tlas>>;
498
499 /// Describes a group of bindings and the resources to be bound.
500 #[derive(Clone, Debug)]
501 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
502 pub struct BindGroupDescriptor<
503 'a,
504 BGL = BindGroupLayoutId,
505 B = BufferId,
506 S = SamplerId,
507 TV = TextureViewId,
508 TLAS = TlasId,
509 > where
510 [BufferBinding<B>]: ToOwned,
511 [S]: ToOwned,
512 [TV]: ToOwned,
513 <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
514 <[S] as ToOwned>::Owned: fmt::Debug,
515 <[TV] as ToOwned>::Owned: fmt::Debug,
516 [BindGroupEntry<'a, B, S, TV, TLAS>]: ToOwned,
517 <[BindGroupEntry<'a, B, S, TV, TLAS>] as ToOwned>::Owned: fmt::Debug,
518 {
519 /// Debug label of the bind group.
520 ///
521 /// This will show up in graphics debuggers for easy identification.
522 pub label: Label<'a>,
523 /// The [`BindGroupLayout`] that corresponds to this bind group.
524 pub layout: BGL,
525 #[cfg_attr(
526 feature = "serde",
527 serde(bound(
528 deserialize = "<[BindGroupEntry<'a, B, S, TV, TLAS>] as ToOwned>::Owned: Deserialize<'de>"
529 ))
530 )]
531 /// The resources to bind to this bind group.
532 pub entries: Cow<'a, [BindGroupEntry<'a, B, S, TV, TLAS>]>,
533 }
534
535 /// cbindgen:ignore
536 pub type ResolvedBindGroupDescriptor<'a> = BindGroupDescriptor<
537 'a,
538 Arc<BindGroupLayout>,
539 Arc<Buffer>,
540 Arc<Sampler>,
541 Arc<TextureView>,
542 Arc<Tlas>,
543 >;
544
545 /// Describes a [`BindGroupLayout`].
546 #[derive(Clone, Debug)]
547 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
548 pub struct BindGroupLayoutDescriptor<'a> {
549 /// Debug label of the bind group layout.
550 ///
551 /// This will show up in graphics debuggers for easy identification.
552 pub label: Label<'a>,
553 /// Array of entries in this BindGroupLayout
554 pub entries: Cow<'a, [wgt::BindGroupLayoutEntry]>,
555 }
556
557 /// Used by [`BindGroupLayout`]. It indicates whether the BGL must be
558 /// used with a specific pipeline. This constraint only happens when
559 /// the BGLs have been derived from a pipeline without a layout.
560 #[derive(Debug)]
561 pub(crate) enum ExclusivePipeline {
562 None,
563 Render(Weak<RenderPipeline>),
564 Compute(Weak<ComputePipeline>),
565 }
566
567 impl fmt::Display for ExclusivePipeline {
568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 match self {
570 ExclusivePipeline::None => f.write_str("None"),
571 ExclusivePipeline::Render(p) => {
572 if let Some(p) = p.upgrade() {
573 p.error_ident().fmt(f)
574 } else {
575 f.write_str("RenderPipeline")
576 }
577 }
578 ExclusivePipeline::Compute(p) => {
579 if let Some(p) = p.upgrade() {
580 p.error_ident().fmt(f)
581 } else {
582 f.write_str("ComputePipeline")
583 }
584 }
585 }
586 }
587 }
588
589 /// Bind group layout.
590 #[derive(Debug)]
591 pub struct BindGroupLayout {
592 pub(crate) raw: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
593 pub(crate) device: Arc<Device>,
594 pub(crate) entries: bgl::EntryMap,
595 /// It is very important that we know if the bind group comes from the BGL pool.
596 ///
597 /// If it does, then we need to remove it from the pool when we drop it.
598 ///
599 /// We cannot unconditionally remove from the pool, as BGLs that don't come from the pool
600 /// (derived BGLs) must not be removed.
601 pub(crate) origin: bgl::Origin,
602 pub(crate) exclusive_pipeline: crate::OnceCellOrLock<ExclusivePipeline>,
603 #[allow(unused)]
604 pub(crate) binding_count_validator: BindingTypeMaxCountValidator,
605 /// The `label` from the descriptor used to create the resource.
606 pub(crate) label: String,
607 }
608
609 impl Drop for BindGroupLayout {
610 fn drop(&mut self) {
611 resource_log!("Destroy raw {}", self.error_ident());
612 if matches!(self.origin, bgl::Origin::Pool) {
613 self.device.bgl_pool.remove(&self.entries);
614 }
615 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
616 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
617 unsafe {
618 self.device.raw().destroy_bind_group_layout(raw);
619 }
620 }
621 }
622
623 crate::impl_resource_type!(BindGroupLayout);
624 crate::impl_labeled!(BindGroupLayout);
625 crate::impl_parent_device!(BindGroupLayout);
626 crate::impl_storage_item!(BindGroupLayout);
627
628 impl BindGroupLayout {
629 pub(crate) fn raw(&self) -> &dyn hal::DynBindGroupLayout {
630 self.raw.as_ref()
631 }
632 }
633
634 #[derive(Clone, Debug, Error)]
635 #[non_exhaustive]
636 pub enum CreatePipelineLayoutError {
637 #[error(transparent)]
638 Device(#[from] DeviceError),
639 #[error(
640 "Push constant at index {index} has range bound {bound} not aligned to {}",
641 wgt::PUSH_CONSTANT_ALIGNMENT
642 )]
643 MisalignedPushConstantRange { index: usize, bound: u32 },
644 #[error(transparent)]
645 MissingFeatures(#[from] MissingFeatures),
646 #[error("Push constant range (index {index}) provides for stage(s) {provided:?} but there exists another range that provides stage(s) {intersected:?}. Each stage may only be provided by one range")]
647 MoreThanOnePushConstantRangePerStage {
648 index: usize,
649 provided: wgt::ShaderStages,
650 intersected: wgt::ShaderStages,
651 },
652 #[error("Push constant at index {index} has range {}..{} which exceeds device push constant size limit 0..{max}", range.start, range.end)]
653 PushConstantRangeTooLarge {
654 index: usize,
655 range: Range<u32>,
656 max: u32,
657 },
658 #[error(transparent)]
659 TooManyBindings(BindingTypeMaxCountError),
660 #[error("Bind group layout count {actual} exceeds device bind group limit {max}")]
661 TooManyGroups { actual: usize, max: usize },
662 #[error(transparent)]
663 InvalidResource(#[from] InvalidResourceError),
664 }
665
666 #[derive(Clone, Debug, Error)]
667 #[non_exhaustive]
668 pub enum PushConstantUploadError {
669 #[error("Provided push constant with indices {offset}..{end_offset} overruns matching push constant range at index {idx}, with stage(s) {:?} and indices {:?}", range.stages, range.range)]
670 TooLarge {
671 offset: u32,
672 end_offset: u32,
673 idx: usize,
674 range: wgt::PushConstantRange,
675 },
676 #[error("Provided push constant is for stage(s) {actual:?}, stage with a partial match found at index {idx} with stage(s) {matched:?}, however push constants must be complete matches")]
677 PartialRangeMatch {
678 actual: wgt::ShaderStages,
679 idx: usize,
680 matched: wgt::ShaderStages,
681 },
682 #[error("Provided push constant is for stage(s) {actual:?}, but intersects a push constant range (at index {idx}) with stage(s) {missing:?}. Push constants must provide the stages for all ranges they intersect")]
683 MissingStages {
684 actual: wgt::ShaderStages,
685 idx: usize,
686 missing: wgt::ShaderStages,
687 },
688 #[error("Provided push constant is for stage(s) {actual:?}, however the pipeline layout has no push constant range for the stage(s) {unmatched:?}")]
689 UnmatchedStages {
690 actual: wgt::ShaderStages,
691 unmatched: wgt::ShaderStages,
692 },
693 #[error("Provided push constant offset {0} does not respect `PUSH_CONSTANT_ALIGNMENT`")]
694 Unaligned(u32),
695 }
696
697 /// Describes a pipeline layout.
698 ///
699 /// A `PipelineLayoutDescriptor` can be used to create a pipeline layout.
700 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
701 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
702 #[cfg_attr(feature = "serde", serde(bound = "BGL: Serialize"))]
703 pub struct PipelineLayoutDescriptor<'a, BGL = BindGroupLayoutId>
704 where
705 [BGL]: ToOwned,
706 <[BGL] as ToOwned>::Owned: fmt::Debug,
707 {
708 /// Debug label of the pipeline layout.
709 ///
710 /// This will show up in graphics debuggers for easy identification.
711 pub label: Label<'a>,
712 /// Bind groups that this pipeline uses. The first entry will provide all the bindings for
713 /// "set = 0", second entry will provide all the bindings for "set = 1" etc.
714 #[cfg_attr(
715 feature = "serde",
716 serde(bound(deserialize = "<[BGL] as ToOwned>::Owned: Deserialize<'de>"))
717 )]
718 pub bind_group_layouts: Cow<'a, [BGL]>,
719 /// Set of push constant ranges this pipeline uses. Each shader stage that
720 /// uses push constants must define the range in push constant memory that
721 /// corresponds to its single `layout(push_constant)` uniform block.
722 ///
723 /// If this array is non-empty, the
724 /// [`Features::PUSH_CONSTANTS`](wgt::Features::PUSH_CONSTANTS) feature must
725 /// be enabled.
726 pub push_constant_ranges: Cow<'a, [wgt::PushConstantRange]>,
727 }
728
729 /// cbindgen:ignore
730 pub type ResolvedPipelineLayoutDescriptor<'a> = PipelineLayoutDescriptor<'a, Arc<BindGroupLayout>>;
731
732 #[derive(Debug)]
733 pub struct PipelineLayout {
734 pub(crate) raw: ManuallyDrop<Box<dyn hal::DynPipelineLayout>>,
735 pub(crate) device: Arc<Device>,
736 /// The `label` from the descriptor used to create the resource.
737 pub(crate) label: String,
738 pub(crate) bind_group_layouts: ArrayVec<Arc<BindGroupLayout>, { hal::MAX_BIND_GROUPS }>,
739 pub(crate) push_constant_ranges: ArrayVec<wgt::PushConstantRange, { SHADER_STAGE_COUNT }>,
740 }
741
742 impl Drop for PipelineLayout {
743 fn drop(&mut self) {
744 resource_log!("Destroy raw {}", self.error_ident());
745 // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
746 let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
747 unsafe {
748 self.device.raw().destroy_pipeline_layout(raw);
749 }
750 }
751 }
752
753 impl PipelineLayout {
754 pub(crate) fn raw(&self) -> &dyn hal::DynPipelineLayout {
755 self.raw.as_ref()
756 }
757
758 pub(crate) fn get_binding_maps(&self) -> ArrayVec<&bgl::EntryMap, { hal::MAX_BIND_GROUPS }> {
759 self.bind_group_layouts
760 .iter()
761 .map(|bgl| &bgl.entries)
762 .collect()
763 }
764
765 /// Validate push constants match up with expected ranges.
766 pub(crate) fn validate_push_constant_ranges(
767 &self,
768 stages: wgt::ShaderStages,
769 offset: u32,
770 end_offset: u32,
771 ) -> Result<(), PushConstantUploadError> {
772 // Don't need to validate size against the push constant size limit here,
773 // as push constant ranges are already validated to be within bounds,
774 // and we validate that they are within the ranges.
775
776 if offset % wgt::PUSH_CONSTANT_ALIGNMENT != 0 {
777 return Err(PushConstantUploadError::Unaligned(offset));
778 }
779
780 // Push constant validation looks very complicated on the surface, but
781 // the problem can be range-reduced pretty well.
782 //
783 // Push constants require (summarized from the vulkan spec):
784 // 1. For each byte in the range and for each shader stage in stageFlags,
785 // there must be a push constant range in the layout that includes that
786 // byte and that stage.
787 // 2. For each byte in the range and for each push constant range that overlaps that byte,
788 // `stage` must include all stages in that push constant range’s `stage`.
789 //
790 // However there are some additional constraints that help us:
791 // 3. All push constant ranges are the only range that can access that stage.
792 // i.e. if one range has VERTEX, no other range has VERTEX
793 //
794 // Therefore we can simplify the checks in the following ways:
795 // - Because 3 guarantees that the push constant range has a unique stage,
796 // when we check for 1, we can simply check that our entire updated range
797 // is within a push constant range. i.e. our range for a specific stage cannot
798 // intersect more than one push constant range.
799 let mut used_stages = wgt::ShaderStages::NONE;
800 for (idx, range) in self.push_constant_ranges.iter().enumerate() {
801 // contains not intersects due to 2
802 if stages.contains(range.stages) {
803 if !(range.range.start <= offset && end_offset <= range.range.end) {
804 return Err(PushConstantUploadError::TooLarge {
805 offset,
806 end_offset,
807 idx,
808 range: range.clone(),
809 });
810 }
811 used_stages |= range.stages;
812 } else if stages.intersects(range.stages) {
813 // Will be caught by used stages check below, but we can do this because of 1
814 // and is more helpful to the user.
815 return Err(PushConstantUploadError::PartialRangeMatch {
816 actual: stages,
817 idx,
818 matched: range.stages,
819 });
820 }
821
822 // The push constant range intersects range we are uploading
823 if offset < range.range.end && range.range.start < end_offset {
824 // But requires stages we don't provide
825 if !stages.contains(range.stages) {
826 return Err(PushConstantUploadError::MissingStages {
827 actual: stages,
828 idx,
829 missing: stages,
830 });
831 }
832 }
833 }
834 if used_stages != stages {
835 return Err(PushConstantUploadError::UnmatchedStages {
836 actual: stages,
837 unmatched: stages - used_stages,
838 });
839 }
840 Ok(())
841 }
842 }
843
844 crate::impl_resource_type!(PipelineLayout);
845 crate::impl_labeled!(PipelineLayout);
846 crate::impl_parent_device!(PipelineLayout);
847 crate::impl_storage_item!(PipelineLayout);
848
849 #[repr(C)]
850 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
851 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
852 pub struct BufferBinding<B = BufferId> {
853 pub buffer: B,
854 pub offset: wgt::BufferAddress,
855 pub size: Option<wgt::BufferSize>,
856 }
857
858 pub type ResolvedBufferBinding = BufferBinding<Arc<Buffer>>;
859
860 // Note: Duplicated in `wgpu-rs` as `BindingResource`
861 // They're different enough that it doesn't make sense to share a common type
862 #[derive(Debug, Clone)]
863 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
864 pub enum BindingResource<'a, B = BufferId, S = SamplerId, TV = TextureViewId, TLAS = TlasId>
865 where
866 [BufferBinding<B>]: ToOwned,
867 [S]: ToOwned,
868 [TV]: ToOwned,
869 <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
870 <[S] as ToOwned>::Owned: fmt::Debug,
871 <[TV] as ToOwned>::Owned: fmt::Debug,
872 {
873 Buffer(BufferBinding<B>),
874 #[cfg_attr(
875 feature = "serde",
876 serde(bound(deserialize = "<[BufferBinding<B>] as ToOwned>::Owned: Deserialize<'de>"))
877 )]
878 BufferArray(Cow<'a, [BufferBinding<B>]>),
879 Sampler(S),
880 #[cfg_attr(
881 feature = "serde",
882 serde(bound(deserialize = "<[S] as ToOwned>::Owned: Deserialize<'de>"))
883 )]
884 SamplerArray(Cow<'a, [S]>),
885 TextureView(TV),
886 #[cfg_attr(
887 feature = "serde",
888 serde(bound(deserialize = "<[TV] as ToOwned>::Owned: Deserialize<'de>"))
889 )]
890 TextureViewArray(Cow<'a, [TV]>),
891 AccelerationStructure(TLAS),
892 }
893
894 pub type ResolvedBindingResource<'a> =
895 BindingResource<'a, Arc<Buffer>, Arc<Sampler>, Arc<TextureView>, Arc<Tlas>>;
896
897 #[derive(Clone, Debug, Error)]
898 #[non_exhaustive]
899 pub enum BindError {
900 #[error(
901 "{bind_group} {group} expects {expected} dynamic offset{s0}. However {actual} dynamic offset{s1} were provided.",
902 s0 = if *.expected >= 2 { "s" } else { "" },
903 s1 = if *.actual >= 2 { "s" } else { "" },
904 )]
905 MismatchedDynamicOffsetCount {
906 bind_group: ResourceErrorIdent,
907 group: u32,
908 actual: usize,
909 expected: usize,
910 },
911 #[error(
912 "Dynamic binding index {idx} (targeting {bind_group} {group}, binding {binding}) with value {offset}, does not respect device's requested `{limit_name}` limit: {alignment}"
913 )]
914 UnalignedDynamicBinding {
915 bind_group: ResourceErrorIdent,
916 idx: usize,
917 group: u32,
918 binding: u32,
919 offset: u32,
920 alignment: u32,
921 limit_name: &'static str,
922 },
923 #[error(
924 "Dynamic binding offset index {idx} with offset {offset} would overrun the buffer bound to {bind_group} {group} -> binding {binding}. \
925 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",
926 )]
927 DynamicBindingOutOfBounds {
928 bind_group: ResourceErrorIdent,
929 idx: usize,
930 group: u32,
931 binding: u32,
932 offset: u32,
933 buffer_size: wgt::BufferAddress,
934 binding_range: Range<wgt::BufferAddress>,
935 maximum_dynamic_offset: wgt::BufferAddress,
936 },
937 }
938
939 #[derive(Debug)]
940 pub struct BindGroupDynamicBindingData {
941 /// The index of the binding.
942 ///
943 /// Used for more descriptive errors.
944 pub(crate) binding_idx: u32,
945 /// The size of the buffer.
946 ///
947 /// Used for more descriptive errors.
948 pub(crate) buffer_size: wgt::BufferAddress,
949 /// The range that the binding covers.
950 ///
951 /// Used for more descriptive errors.
952 pub(crate) binding_range: Range<wgt::BufferAddress>,
953 /// The maximum value the dynamic offset can have before running off the end of the buffer.
954 pub(crate) maximum_dynamic_offset: wgt::BufferAddress,
955 /// The binding type.
956 pub(crate) binding_type: wgt::BufferBindingType,
957 }
958
959 pub(crate) fn buffer_binding_type_alignment(
960 limits: &wgt::Limits,
961 binding_type: wgt::BufferBindingType,
962 ) -> (u32, &'static str) {
963 match binding_type {
964 wgt::BufferBindingType::Uniform => (
965 limits.min_uniform_buffer_offset_alignment,
966 "min_uniform_buffer_offset_alignment",
967 ),
968 wgt::BufferBindingType::Storage { .. } => (
969 limits.min_storage_buffer_offset_alignment,
970 "min_storage_buffer_offset_alignment",
971 ),
972 }
973 }
974
975 pub(crate) fn buffer_binding_type_bounds_check_alignment(
976 alignments: &hal::Alignments,
977 binding_type: wgt::BufferBindingType,
978 ) -> wgt::BufferAddress {
979 match binding_type {
980 wgt::BufferBindingType::Uniform => alignments.uniform_bounds_check_alignment.get(),
981 wgt::BufferBindingType::Storage { .. } => wgt::COPY_BUFFER_ALIGNMENT,
982 }
983 }
984
985 #[derive(Debug)]
986 pub struct BindGroup {
987 pub(crate) raw: Snatchable<Box<dyn hal::DynBindGroup>>,
988 pub(crate) device: Arc<Device>,
989 pub(crate) layout: Arc<BindGroupLayout>,
990 /// The `label` from the descriptor used to create the resource.
991 pub(crate) label: String,
992 pub(crate) tracking_data: TrackingData,
993 pub(crate) used: BindGroupStates,
994 pub(crate) used_buffer_ranges: Vec<BufferInitTrackerAction>,
995 pub(crate) used_texture_ranges: Vec<TextureInitTrackerAction>,
996 pub(crate) dynamic_binding_info: Vec<BindGroupDynamicBindingData>,
997 /// Actual binding sizes for buffers that don't have `min_binding_size`
998 /// specified in BGL. Listed in the order of iteration of `BGL.entries`.
999 pub(crate) late_buffer_binding_sizes: Vec<wgt::BufferSize>,
1000 }
1001
1002 impl Drop for BindGroup {
1003 fn drop(&mut self) {
1004 if let Some(raw) = self.raw.take() {
1005 resource_log!("Destroy raw {}", self.error_ident());
1006 unsafe {
1007 self.device.raw().destroy_bind_group(raw);
1008 }
1009 }
1010 }
1011 }
1012
1013 impl BindGroup {
1014 pub(crate) fn try_raw<'a>(
1015 &'a self,
1016 guard: &'a SnatchGuard,
1017 ) -> Result<&'a dyn hal::DynBindGroup, DestroyedResourceError> {
1018 // Clippy insist on writing it this way. The idea is to return None
1019 // if any of the raw buffer is not valid anymore.
1020 for buffer in &self.used_buffer_ranges {
1021 buffer.buffer.try_raw(guard)?;
1022 }
1023 for texture in &self.used_texture_ranges {
1024 texture.texture.try_raw(guard)?;
1025 }
1026
1027 self.raw
1028 .get(guard)
1029 .map(|raw| raw.as_ref())
1030 .ok_or_else(|| DestroyedResourceError(self.error_ident()))
1031 }
1032
1033 pub(crate) fn validate_dynamic_bindings(
1034 &self,
1035 bind_group_index: u32,
1036 offsets: &[wgt::DynamicOffset],
1037 ) -> Result<(), BindError> {
1038 if self.dynamic_binding_info.len() != offsets.len() {
1039 return Err(BindError::MismatchedDynamicOffsetCount {
1040 bind_group: self.error_ident(),
1041 group: bind_group_index,
1042 expected: self.dynamic_binding_info.len(),
1043 actual: offsets.len(),
1044 });
1045 }
1046
1047 for (idx, (info, &offset)) in self
1048 .dynamic_binding_info
1049 .iter()
1050 .zip(offsets.iter())
1051 .enumerate()
1052 {
1053 let (alignment, limit_name) =
1054 buffer_binding_type_alignment(&self.device.limits, info.binding_type);
1055 if offset as wgt::BufferAddress % alignment as u64 != 0 {
1056 return Err(BindError::UnalignedDynamicBinding {
1057 bind_group: self.error_ident(),
1058 group: bind_group_index,
1059 binding: info.binding_idx,
1060 idx,
1061 offset,
1062 alignment,
1063 limit_name,
1064 });
1065 }
1066
1067 if offset as wgt::BufferAddress > info.maximum_dynamic_offset {
1068 return Err(BindError::DynamicBindingOutOfBounds {
1069 bind_group: self.error_ident(),
1070 group: bind_group_index,
1071 binding: info.binding_idx,
1072 idx,
1073 offset,
1074 buffer_size: info.buffer_size,
1075 binding_range: info.binding_range.clone(),
1076 maximum_dynamic_offset: info.maximum_dynamic_offset,
1077 });
1078 }
1079 }
1080
1081 Ok(())
1082 }
1083 }
1084
1085 crate::impl_resource_type!(BindGroup);
1086 crate::impl_labeled!(BindGroup);
1087 crate::impl_parent_device!(BindGroup);
1088 crate::impl_storage_item!(BindGroup);
1089 crate::impl_trackable!(BindGroup);
1090
1091 #[derive(Clone, Debug, Error)]
1092 #[non_exhaustive]
1093 pub enum GetBindGroupLayoutError {
1094 #[error("Invalid group index {0}")]
1095 InvalidGroupIndex(u32),
1096 #[error(transparent)]
1097 InvalidResource(#[from] InvalidResourceError),
1098 }
1099
1100 #[derive(Clone, Debug, Error, Eq, PartialEq)]
1101 #[error("Buffer is bound with size {bound_size} where the shader expects {shader_size} in group[{group_index}] compact index {compact_index}")]
1102 pub struct LateMinBufferBindingSizeMismatch {
1103 pub group_index: u32,
1104 pub compact_index: usize,
1105 pub shader_size: wgt::BufferAddress,
1106 pub bound_size: wgt::BufferAddress,
1107 }