1use alloc::{
2 boxed::Box,
3 string::{String, ToString as _},
4 sync::Arc,
5 vec::Vec,
6};
7use core::{fmt, num::NonZeroU32};
8
9use arrayvec::ArrayVec;
10use hashbrown::hash_map::Entry;
11use shader_io_deductions::{display_deductions_as_optional_list, MaxVertexShaderOutputDeduction};
12use thiserror::Error;
13use wgt::{
14 error::{ErrorType, WebGpuError},
15 BindGroupLayoutEntry, BindingType,
16};
17
18use crate::{
19 command::ColorAttachmentError, device::bgl, pipeline::ColorStateError,
20 resource::InvalidResourceError,
21 validation::shader_io_deductions::MaxFragmentShaderInputDeduction, FastHashMap, FastHashSet,
22};
23
24pub mod shader_io_deductions;
25
26#[derive(Debug)]
27enum ResourceType {
28 Buffer {
29 minimum_binding_size: wgt::BufferSize,
30 },
31 Texture {
32 dim: naga::ImageDimension,
33 arrayed: bool,
34 class: naga::ImageClass,
35 },
36 Sampler {
37 comparison: bool,
38 },
39 AccelerationStructure {
40 vertex_return: bool,
41 },
42}
43
44#[derive(Clone, Debug)]
45pub enum BindingTypeName {
46 Buffer,
47 Texture,
48 Sampler,
49 AccelerationStructure,
50 ExternalTexture,
51}
52
53impl From<&ResourceType> for BindingTypeName {
54 fn from(ty: &ResourceType) -> BindingTypeName {
55 match ty {
56 ResourceType::Buffer { .. } => BindingTypeName::Buffer,
57 ResourceType::Texture {
58 class: naga::ImageClass::External,
59 ..
60 } => BindingTypeName::ExternalTexture,
61 ResourceType::Texture { .. } => BindingTypeName::Texture,
62 ResourceType::Sampler { .. } => BindingTypeName::Sampler,
63 ResourceType::AccelerationStructure { .. } => BindingTypeName::AccelerationStructure,
64 }
65 }
66}
67
68impl From<&BindingType> for BindingTypeName {
69 fn from(ty: &BindingType) -> BindingTypeName {
70 match ty {
71 BindingType::Buffer { .. } => BindingTypeName::Buffer,
72 BindingType::Texture { .. } => BindingTypeName::Texture,
73 BindingType::StorageTexture { .. } => BindingTypeName::Texture,
74 BindingType::Sampler { .. } => BindingTypeName::Sampler,
75 BindingType::AccelerationStructure { .. } => BindingTypeName::AccelerationStructure,
76 BindingType::ExternalTexture => BindingTypeName::ExternalTexture,
77 }
78 }
79}
80
81#[derive(Debug)]
82struct Resource {
83 #[allow(unused)]
84 name: Option<String>,
85 bind: naga::ResourceBinding,
86 ty: ResourceType,
87 class: naga::AddressSpace,
88}
89
90#[derive(Clone, Copy, Debug, Eq, PartialEq)]
91enum NumericDimension {
92 Scalar,
93 Vector(naga::VectorSize),
94 Matrix(naga::VectorSize, naga::VectorSize),
95}
96
97impl fmt::Display for NumericDimension {
98 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99 match *self {
100 Self::Scalar => write!(f, ""),
101 Self::Vector(size) => write!(f, "x{}", size as u8),
102 Self::Matrix(columns, rows) => write!(f, "x{}{}", columns as u8, rows as u8),
103 }
104 }
105}
106
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub struct NumericType {
109 dim: NumericDimension,
110 scalar: naga::Scalar,
111}
112
113impl fmt::Display for NumericType {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
115 write!(
116 f,
117 "{:?}{}{}",
118 self.scalar.kind,
119 self.scalar.width * 8,
120 self.dim
121 )
122 }
123}
124
125#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct InterfaceVar {
127 pub ty: NumericType,
128 interpolation: Option<naga::Interpolation>,
129 sampling: Option<naga::Sampling>,
130 per_primitive: bool,
131}
132
133impl InterfaceVar {
134 pub fn vertex_attribute(format: wgt::VertexFormat) -> Self {
135 InterfaceVar {
136 ty: NumericType::from_vertex_format(format),
137 interpolation: None,
138 sampling: None,
139 per_primitive: false,
140 }
141 }
142}
143
144impl fmt::Display for InterfaceVar {
145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146 write!(
147 f,
148 "{} interpolated as {:?} with sampling {:?}",
149 self.ty, self.interpolation, self.sampling
150 )
151 }
152}
153
154#[derive(Debug, Eq, PartialEq)]
161enum Varying {
162 UserDefined { location: u32, iv: InterfaceVar },
169
170 BuiltIn(BuiltIn),
176}
177
178#[derive(Clone, Debug, Eq, PartialEq)]
179enum BuiltIn {
180 Position { invariant: bool },
181 ViewIndex,
182 BaseInstance,
183 BaseVertex,
184 ClipDistances { array_size: u32 },
185 CullDistance,
186 InstanceIndex,
187 PointSize,
188 VertexIndex,
189 DrawIndex,
190 FragDepth,
191 PointCoord,
192 FrontFacing,
193 PrimitiveIndex,
194 Barycentric { perspective: bool },
195 SampleIndex,
196 SampleMask,
197 GlobalInvocationId,
198 LocalInvocationId,
199 LocalInvocationIndex,
200 WorkGroupId,
201 WorkGroupSize,
202 NumWorkGroups,
203 NumSubgroups,
204 SubgroupId,
205 SubgroupSize,
206 SubgroupInvocationId,
207 MeshTaskSize,
208 CullPrimitive,
209 PointIndex,
210 LineIndices,
211 TriangleIndices,
212 VertexCount,
213 Vertices,
214 PrimitiveCount,
215 Primitives,
216 RayInvocationId,
217 NumRayInvocations,
218 InstanceCustomData,
219 GeometryIndex,
220 WorldRayOrigin,
221 WorldRayDirection,
222 ObjectRayOrigin,
223 ObjectRayDirection,
224 RayTmin,
225 RayTCurrentMax,
226 ObjectToWorld,
227 WorldToObject,
228 HitKind,
229 HitBarycentrics,
230}
231
232impl BuiltIn {
233 pub fn to_naga(&self) -> naga::BuiltIn {
234 match self {
235 &Self::Position { invariant } => naga::BuiltIn::Position { invariant },
236 Self::ViewIndex => naga::BuiltIn::ViewIndex,
237 Self::BaseInstance => naga::BuiltIn::BaseInstance,
238 Self::BaseVertex => naga::BuiltIn::BaseVertex,
239 Self::ClipDistances { .. } => naga::BuiltIn::ClipDistances,
240 Self::CullDistance => naga::BuiltIn::CullDistance,
241 Self::InstanceIndex => naga::BuiltIn::InstanceIndex,
242 Self::PointSize => naga::BuiltIn::PointSize,
243 Self::VertexIndex => naga::BuiltIn::VertexIndex,
244 Self::DrawIndex => naga::BuiltIn::DrawIndex,
245 Self::FragDepth => naga::BuiltIn::FragDepth,
246 Self::PointCoord => naga::BuiltIn::PointCoord,
247 Self::FrontFacing => naga::BuiltIn::FrontFacing,
248 Self::PrimitiveIndex => naga::BuiltIn::PrimitiveIndex,
249 Self::Barycentric { perspective } => naga::BuiltIn::Barycentric {
250 perspective: *perspective,
251 },
252 Self::SampleIndex => naga::BuiltIn::SampleIndex,
253 Self::SampleMask => naga::BuiltIn::SampleMask,
254 Self::GlobalInvocationId => naga::BuiltIn::GlobalInvocationId,
255 Self::LocalInvocationId => naga::BuiltIn::LocalInvocationId,
256 Self::LocalInvocationIndex => naga::BuiltIn::LocalInvocationIndex,
257 Self::WorkGroupId => naga::BuiltIn::WorkGroupId,
258 Self::WorkGroupSize => naga::BuiltIn::WorkGroupSize,
259 Self::NumWorkGroups => naga::BuiltIn::NumWorkGroups,
260 Self::NumSubgroups => naga::BuiltIn::NumSubgroups,
261 Self::SubgroupId => naga::BuiltIn::SubgroupId,
262 Self::SubgroupSize => naga::BuiltIn::SubgroupSize,
263 Self::SubgroupInvocationId => naga::BuiltIn::SubgroupInvocationId,
264 Self::MeshTaskSize => naga::BuiltIn::MeshTaskSize,
265 Self::CullPrimitive => naga::BuiltIn::CullPrimitive,
266 Self::PointIndex => naga::BuiltIn::PointIndex,
267 Self::LineIndices => naga::BuiltIn::LineIndices,
268 Self::TriangleIndices => naga::BuiltIn::TriangleIndices,
269 Self::VertexCount => naga::BuiltIn::VertexCount,
270 Self::Vertices => naga::BuiltIn::Vertices,
271 Self::PrimitiveCount => naga::BuiltIn::PrimitiveCount,
272 Self::Primitives => naga::BuiltIn::Primitives,
273 Self::RayInvocationId => naga::BuiltIn::RayInvocationId,
274 Self::NumRayInvocations => naga::BuiltIn::NumRayInvocations,
275 Self::InstanceCustomData => naga::BuiltIn::InstanceCustomData,
276 Self::GeometryIndex => naga::BuiltIn::GeometryIndex,
277 Self::WorldRayOrigin => naga::BuiltIn::WorldRayOrigin,
278 Self::WorldRayDirection => naga::BuiltIn::WorldRayDirection,
279 Self::ObjectRayOrigin => naga::BuiltIn::ObjectRayOrigin,
280 Self::ObjectRayDirection => naga::BuiltIn::ObjectRayDirection,
281 Self::RayTmin => naga::BuiltIn::RayTmin,
282 Self::RayTCurrentMax => naga::BuiltIn::RayTCurrentMax,
283 Self::ObjectToWorld => naga::BuiltIn::ObjectToWorld,
284 Self::WorldToObject => naga::BuiltIn::WorldToObject,
285 Self::HitKind => naga::BuiltIn::HitKind,
286 Self::HitBarycentrics => naga::BuiltIn::HitBarycentrics,
287 }
288 }
289}
290
291#[derive(Debug)]
292struct EntryPointMeshInfo {
293 max_vertices: u32,
294 max_primitives: u32,
295 primitive_topology: wgt::PrimitiveTopology,
296}
297
298#[derive(Debug, Default)]
302struct EntryPoint {
303 inputs: Vec<Varying>,
309
310 outputs: Vec<Varying>,
318
319 resources: Vec<naga::Handle<Resource>>,
329
330 sampling_pairs: FastHashSet<(naga::Handle<Resource>, naga::Handle<Resource>)>,
337
338 workgroup_size: [u32; 3],
345
346 workgroup_storage_size: u64,
352
353 dual_source_blending: bool,
355
356 task_payload_size: Option<u32>,
359
360 mesh_info: Option<EntryPointMeshInfo>,
362
363 immediate_usage: naga::valid::ImmediateUsage,
365
366 ray_tracing_payload: Option<RayTracingPayloadType>,
368}
369
370#[derive(Debug, Hash, PartialEq, Eq)]
371struct EntryPointKey(naga::ShaderStage, String);
372
373#[derive(Debug, Hash, PartialEq, Eq)]
374struct EntryPointKeyRef<'a>(naga::ShaderStage, &'a str);
375
376impl hashbrown::Equivalent<EntryPointKey> for EntryPointKeyRef<'_> {
377 fn equivalent(&self, key: &EntryPointKey) -> bool {
378 self.0 == key.0 && self.1 == key.1
379 }
380}
381
382#[derive(Debug, PartialEq, Eq, Clone)]
383pub enum RayTracingPayloadType {
387 Numeric(NumericType),
389 Struct {
391 members: Vec<RayTracingPayloadMember>,
393 span: u32,
395 },
396 Array {
398 inner: Box<RayTracingPayloadType>,
400 size: NonZeroU32,
402 stride: u32,
404 },
405}
406
407#[derive(Debug, PartialEq, Eq, Clone)]
408pub struct RayTracingPayloadMember {
409 offset: u32,
410 ty: Box<RayTracingPayloadType>,
411}
412
413impl RayTracingPayloadType {
414 pub fn from_naga(ty: &naga::TypeInner, module: &naga::Module) -> Option<Self> {
415 Some(match ty {
416 naga::TypeInner::Scalar(scalar) => Self::Numeric(NumericType {
417 dim: NumericDimension::Scalar,
418 scalar: *scalar,
419 }),
420 naga::TypeInner::Vector { size, scalar } => Self::Numeric(NumericType {
421 dim: NumericDimension::Vector(*size),
422 scalar: *scalar,
423 }),
424 naga::TypeInner::Matrix {
425 columns,
426 rows,
427 scalar,
428 } => Self::Numeric(NumericType {
429 dim: NumericDimension::Matrix(*columns, *rows),
430 scalar: *scalar,
431 }),
432 naga::TypeInner::Struct { members, span } => {
433 let mut struct_members = Vec::with_capacity(members.len());
434
435 for member in members {
436 let ty = &module.types[member.ty].inner;
437
438 struct_members.push(RayTracingPayloadMember {
439 offset: member.offset,
440 ty: Box::new(Self::from_naga(ty, module)?),
441 });
442 }
443
444 Self::Struct {
445 members: struct_members,
446 span: *span,
447 }
448 }
449 naga::TypeInner::Array {
450 base,
451 size: naga::ArraySize::Constant(size),
452 stride,
453 } => {
454 let ty = &module.types[*base].inner;
455
456 Self::Array {
457 inner: Box::new(Self::from_naga(ty, module)?),
458 size: *size,
459 stride: *stride,
460 }
461 }
462 _ => return None,
463 })
464 }
465}
466
467#[derive(Debug)]
471pub struct Interface {
472 limits: wgt::Limits,
478
479 resources: naga::Arena<Resource>,
490
491 entry_points: FastHashMap<EntryPointKey, EntryPoint>,
497}
498
499#[derive(Clone, Debug, Error)]
500#[non_exhaustive]
501pub enum BindingError {
502 #[error("Binding is missing from the pipeline layout")]
503 Missing,
504 #[error("Visibility flags don't include the shader stage")]
505 Invisible,
506 #[error(
507 "Type on the shader side ({shader:?}) does not match the pipeline binding ({binding:?})"
508 )]
509 WrongType {
510 binding: BindingTypeName,
511 shader: BindingTypeName,
512 },
513 #[error("Storage class {binding:?} doesn't match the shader {shader:?}")]
514 WrongAddressSpace {
515 binding: naga::AddressSpace,
516 shader: naga::AddressSpace,
517 },
518 #[error("Address space {space:?} is not a valid Buffer address space")]
519 WrongBufferAddressSpace { space: naga::AddressSpace },
520 #[error("Buffer structure size {buffer_size}, added to one element of an unbound array, if it's the last field, ended up greater than the given `min_binding_size`, which is {min_binding_size}")]
521 WrongBufferSize {
522 buffer_size: wgt::BufferSize,
523 min_binding_size: wgt::BufferSize,
524 },
525 #[error("View dimension {dim:?} (is array: {is_array}) doesn't match the binding {binding:?}")]
526 WrongTextureViewDimension {
527 dim: naga::ImageDimension,
528 is_array: bool,
529 binding: BindingType,
530 },
531 #[error("Texture class {binding:?} doesn't match the shader {shader:?}")]
532 WrongTextureClass {
533 binding: naga::ImageClass,
534 shader: naga::ImageClass,
535 },
536 #[error("Comparison flag doesn't match the shader")]
537 WrongSamplerComparison,
538 #[error("Derived bind group layout type is not consistent between stages")]
539 InconsistentlyDerivedType,
540 #[error("Texture format {0:?} is not supported for storage use")]
541 BadStorageFormat(wgt::TextureFormat),
542}
543
544impl WebGpuError for BindingError {
545 fn webgpu_error_type(&self) -> ErrorType {
546 ErrorType::Validation
547 }
548}
549
550#[derive(Clone, Debug, Error)]
551#[non_exhaustive]
552pub enum FilteringError {
553 #[error("Integer textures can't be sampled with a filtering sampler")]
554 Integer,
555 #[error("Non-filterable float textures can't be sampled with a filtering sampler")]
556 Float,
557}
558
559impl WebGpuError for FilteringError {
560 fn webgpu_error_type(&self) -> ErrorType {
561 ErrorType::Validation
562 }
563}
564
565#[derive(Clone, Debug, Error)]
566#[non_exhaustive]
567pub enum InputError {
568 #[error("Input is not provided by the earlier stage in the pipeline")]
569 Missing,
570 #[error("Input type is not compatible with the provided {0}")]
571 WrongType(NumericType),
572 #[error("Input interpolation doesn't match provided {0:?}")]
573 InterpolationMismatch(Option<naga::Interpolation>),
574 #[error("Input sampling doesn't match provided {0:?}")]
575 SamplingMismatch(Option<naga::Sampling>),
576 #[error("Pipeline input has per_primitive={pipeline_input}, but shader expects per_primitive={shader}")]
577 WrongPerPrimitive { pipeline_input: bool, shader: bool },
578}
579
580impl WebGpuError for InputError {
581 fn webgpu_error_type(&self) -> ErrorType {
582 ErrorType::Validation
583 }
584}
585
586#[derive(Clone, Debug, Error)]
588#[non_exhaustive]
589pub enum StageError {
590 #[error("Unable to find entry point {0:?}")]
591 NoEntryPointWithName(String),
592 #[error("Unable to find entry point `{name}` for stage `{stage:?}`")]
593 NoEntryPointWithNameForStage {
594 name: String,
595 stage: naga::ShaderStage,
596 },
597 #[error(
598 "Unable to select an entry point: no entry points found in the provided shader module"
599 )]
600 NoEntryPoints,
601 #[error("No entry point found for stage `{0:?}`")]
602 NoEntryPointForStage(naga::ShaderStage),
603 #[error(
604 "Unable to select an entry point: \
605 multiple entry points were found in the provided shader module, \
606 but no entry point was specified"
607 )]
608 AmbiguousEntryPoint,
609 #[error("More than one entry point present in module for stage `{0:?}`, entry point name must be provided")]
610 AmbiguousEntryPointForStage(naga::ShaderStage),
611 #[error(
612 "Workgroup storage size {used} must be less than or equal to \
613 `Limits::{limit_desc}` ({limit})"
614 )]
615 WorkgroupStorageSizeLimitExceeded {
616 used: u64,
617 limit: u32,
618 limit_desc: &'static str,
619 },
620 #[error(transparent)]
621 InvalidWorkgroupSize(#[from] InvalidWorkgroupSizeError),
622 #[error("Shader global {0:?} is not available in the pipeline layout")]
623 Binding(naga::ResourceBinding, #[source] BindingError),
624 #[error("Unable to filter the texture ({texture:?}) by the sampler ({sampler:?})")]
625 Filtering {
626 texture: naga::ResourceBinding,
627 sampler: naga::ResourceBinding,
628 #[source]
629 error: FilteringError,
630 },
631 #[error("Location[{location}] {var} is not provided by the previous stage outputs")]
632 Input {
633 location: wgt::ShaderLocation,
634 var: InterfaceVar,
635 #[source]
636 error: InputError,
637 },
638 #[error(transparent)]
639 InvalidResource(#[from] InvalidResourceError),
640 #[error(
641 "vertex shader output location Location[{location}] ({var}) exceeds the \
642 `max_inter_stage_shader_variables` limit ({}, 0-based){}",
643 limit - 1,
645 display_deductions_as_optional_list(deductions, |d| d.for_location())
646 )]
647 VertexOutputLocationTooLarge {
648 location: u32,
649 var: InterfaceVar,
650 limit: u32,
651 deductions: Vec<MaxVertexShaderOutputDeduction>,
652 },
653 #[error(
654 "found {num_found} user-defined vertex shader output variables, which exceeds the \
655 `max_inter_stage_shader_variables` limit ({limit}){}",
656 display_deductions_as_optional_list(deductions, |d| d.for_variables())
657 )]
658 TooManyUserDefinedVertexOutputs {
659 num_found: u32,
660 limit: u32,
661 deductions: Vec<MaxVertexShaderOutputDeduction>,
662 },
663 #[error(
664 "fragment shader input location Location[{location}] ({var}) exceeds the \
665 `max_inter_stage_shader_variables` limit ({}, 0-based){}",
666 limit - 1,
668 display_deductions_as_optional_list(deductions, |d| d.for_variables())
672 )]
673 FragmentInputLocationTooLarge {
674 location: u32,
675 var: InterfaceVar,
676 limit: u32,
677 deductions: Vec<MaxFragmentShaderInputDeduction>,
678 },
679 #[error(
680 "found {num_found} user-defined fragment shader input variables, which exceeds the \
681 `max_inter_stage_shader_variables` limit ({limit}){}",
682 display_deductions_as_optional_list(deductions, |d| d.for_variables())
683 )]
684 TooManyUserDefinedFragmentInputs {
685 num_found: u32,
686 limit: u32,
687 deductions: Vec<MaxFragmentShaderInputDeduction>,
688 },
689 #[error(
690 "Location[{location}] {var}'s index exceeds the `max_color_attachments` limit ({limit})"
691 )]
692 ColorAttachmentLocationTooLarge {
693 location: u32,
694 var: InterfaceVar,
695 limit: u32,
696 },
697 #[error("Mesh shaders are limited to {limit} output vertices by `Limits::max_mesh_output_vertices`, but the shader has a maximum number of {value}")]
698 TooManyMeshVertices { limit: u32, value: u32 },
699 #[error("Mesh shaders are limited to {limit} output primitives by `Limits::max_mesh_output_primitives`, but the shader has a maximum number of {value}")]
700 TooManyMeshPrimitives { limit: u32, value: u32 },
701 #[error("Mesh or task shaders are limited to {limit} bytes of task payload by `Limits::max_task_payload_size`, but the shader has a task payload of size {value}")]
702 TaskPayloadTooLarge { limit: u32, value: u32 },
703 #[error("Mesh shader's task payload has size ({shader:?}), which doesn't match the payload declared in the task stage ({input:?})")]
704 TaskPayloadMustMatch {
705 input: Option<u32>,
706 shader: Option<u32>,
707 },
708 #[error("Primitive index can only be used in a fragment shader if the preceding shader was a vertex shader or a mesh shader that writes to primitive index.")]
709 InvalidPrimitiveIndex,
710 #[error("If a mesh shader writes to primitive index, it must be read by the fragment shader.")]
711 MissingPrimitiveIndex,
712 #[error("DrawId cannot be used in a mesh shader in a pipeline with a task shader")]
713 DrawIdError,
714 #[error("Pipeline uses dual-source blending, but the shader does not support it")]
715 InvalidDualSourceBlending,
716 #[error("Fragment shader writes depth, but pipeline does not have a depth attachment")]
717 MissingFragDepthAttachment,
718 #[error("Per vertex fragment inputs can only be used in triangle primitive pipelines")]
719 PerVertexNotTriangles,
720 #[error("Mesh shader pipelines must have primitive topology of TriangleList, LineList or PointList, and this must match with what the mesh shader declares.")]
721 MeshTopologyMismatch,
722 #[error("Pipeline layout immediate size ({layout}) must be >= the required immediate size ({required}) of the shader entry point")]
723 LayoutImmediateSize { layout: u32, required: u32 },
724 #[error("Ray tracing payloads do not match.")]
725 RayTracingPayloadMismatch,
726}
727
728impl WebGpuError for StageError {
729 fn webgpu_error_type(&self) -> ErrorType {
730 match self {
731 Self::Binding(_, e) => e.webgpu_error_type(),
732 Self::InvalidResource(e) => e.webgpu_error_type(),
733 Self::Filtering {
734 texture: _,
735 sampler: _,
736 error,
737 } => error.webgpu_error_type(),
738 Self::Input {
739 location: _,
740 var: _,
741 error,
742 } => error.webgpu_error_type(),
743 Self::WorkgroupStorageSizeLimitExceeded { .. }
744 | Self::NoEntryPointWithName { .. }
745 | Self::NoEntryPointWithNameForStage { .. }
746 | Self::NoEntryPoints
747 | Self::NoEntryPointForStage(_)
748 | Self::AmbiguousEntryPoint
749 | Self::AmbiguousEntryPointForStage(_)
750 | Self::InvalidWorkgroupSize { .. }
751 | Self::VertexOutputLocationTooLarge { .. }
752 | Self::TooManyUserDefinedVertexOutputs { .. }
753 | Self::FragmentInputLocationTooLarge { .. }
754 | Self::TooManyUserDefinedFragmentInputs { .. }
755 | Self::ColorAttachmentLocationTooLarge { .. }
756 | Self::TooManyMeshVertices { .. }
757 | Self::TooManyMeshPrimitives { .. }
758 | Self::TaskPayloadTooLarge { .. }
759 | Self::TaskPayloadMustMatch { .. }
760 | Self::InvalidPrimitiveIndex
761 | Self::MissingPrimitiveIndex
762 | Self::DrawIdError
763 | Self::InvalidDualSourceBlending
764 | Self::MissingFragDepthAttachment
765 | Self::PerVertexNotTriangles
766 | Self::MeshTopologyMismatch
767 | Self::LayoutImmediateSize { .. }
768 | Self::RayTracingPayloadMismatch => ErrorType::Validation,
769 }
770 }
771}
772
773pub use wgpu_naga_bridge::map_storage_format_from_naga;
774pub use wgpu_naga_bridge::map_storage_format_to_naga;
775
776impl Resource {
777 fn check_binding_use(&self, entry: &BindGroupLayoutEntry) -> Result<(), BindingError> {
778 match self.ty {
779 ResourceType::Buffer {
780 minimum_binding_size,
781 } => {
782 let min_size = match entry.ty {
783 BindingType::Buffer {
784 ty,
785 has_dynamic_offset: _,
786 min_binding_size,
787 } => {
788 let class = match ty {
789 wgt::BufferBindingType::Uniform => naga::AddressSpace::Uniform,
790 wgt::BufferBindingType::Storage { read_only } => {
791 let mut naga_access = naga::StorageAccess::LOAD;
792 naga_access.set(naga::StorageAccess::STORE, !read_only);
793 naga::AddressSpace::Storage {
794 access: naga_access,
795 }
796 }
797 };
798 if self.class != class {
799 return Err(BindingError::WrongAddressSpace {
800 binding: class,
801 shader: self.class,
802 });
803 }
804 min_binding_size
805 }
806 _ => {
807 return Err(BindingError::WrongType {
808 binding: (&entry.ty).into(),
809 shader: (&self.ty).into(),
810 })
811 }
812 };
813 match min_size {
814 Some(non_zero) if non_zero < minimum_binding_size => {
815 return Err(BindingError::WrongBufferSize {
816 buffer_size: minimum_binding_size,
817 min_binding_size: non_zero,
818 })
819 }
820 _ => (),
821 }
822 }
823 ResourceType::Sampler { comparison } => match entry.ty {
824 BindingType::Sampler(ty) => {
825 if (ty == wgt::SamplerBindingType::Comparison) != comparison {
826 return Err(BindingError::WrongSamplerComparison);
827 }
828 }
829 _ => {
830 return Err(BindingError::WrongType {
831 binding: (&entry.ty).into(),
832 shader: (&self.ty).into(),
833 })
834 }
835 },
836 ResourceType::Texture {
837 dim,
838 arrayed,
839 class: shader_class,
840 } => {
841 let view_dimension = match entry.ty {
842 BindingType::Texture { view_dimension, .. }
843 | BindingType::StorageTexture { view_dimension, .. } => view_dimension,
844 BindingType::ExternalTexture => wgt::TextureViewDimension::D2,
845 _ => {
846 return Err(BindingError::WrongTextureViewDimension {
847 dim,
848 is_array: false,
849 binding: entry.ty,
850 })
851 }
852 };
853 if arrayed {
854 match (dim, view_dimension) {
855 (naga::ImageDimension::D2, wgt::TextureViewDimension::D2Array) => (),
856 (naga::ImageDimension::Cube, wgt::TextureViewDimension::CubeArray) => (),
857 _ => {
858 return Err(BindingError::WrongTextureViewDimension {
859 dim,
860 is_array: true,
861 binding: entry.ty,
862 })
863 }
864 }
865 } else {
866 match (dim, view_dimension) {
867 (naga::ImageDimension::D1, wgt::TextureViewDimension::D1) => (),
868 (naga::ImageDimension::D2, wgt::TextureViewDimension::D2) => (),
869 (naga::ImageDimension::D3, wgt::TextureViewDimension::D3) => (),
870 (naga::ImageDimension::Cube, wgt::TextureViewDimension::Cube) => (),
871 _ => {
872 return Err(BindingError::WrongTextureViewDimension {
873 dim,
874 is_array: false,
875 binding: entry.ty,
876 })
877 }
878 }
879 }
880 match entry.ty {
881 BindingType::Texture {
882 sample_type,
883 view_dimension: _,
884 multisampled: multi,
885 } => {
886 let binding_class = match sample_type {
887 wgt::TextureSampleType::Float { .. } => naga::ImageClass::Sampled {
888 kind: naga::ScalarKind::Float,
889 multi,
890 },
891 wgt::TextureSampleType::Sint => naga::ImageClass::Sampled {
892 kind: naga::ScalarKind::Sint,
893 multi,
894 },
895 wgt::TextureSampleType::Uint => naga::ImageClass::Sampled {
896 kind: naga::ScalarKind::Uint,
897 multi,
898 },
899 wgt::TextureSampleType::Depth => naga::ImageClass::Depth { multi },
900 };
901 if shader_class == binding_class {
902 Ok(())
903 } else {
904 Err(binding_class)
905 }
906 }
907 BindingType::StorageTexture {
908 access: wgt_binding_access,
909 format: wgt_binding_format,
910 view_dimension: _,
911 } => {
912 const LOAD_STORE: naga::StorageAccess =
913 naga::StorageAccess::LOAD.union(naga::StorageAccess::STORE);
914 let binding_format = map_storage_format_to_naga(wgt_binding_format)
915 .ok_or(BindingError::BadStorageFormat(wgt_binding_format))?;
916 let binding_access = match wgt_binding_access {
917 wgt::StorageTextureAccess::ReadOnly => naga::StorageAccess::LOAD,
918 wgt::StorageTextureAccess::WriteOnly => naga::StorageAccess::STORE,
919 wgt::StorageTextureAccess::ReadWrite => LOAD_STORE,
920 wgt::StorageTextureAccess::Atomic => {
921 naga::StorageAccess::ATOMIC | LOAD_STORE
922 }
923 };
924 match shader_class {
925 naga::ImageClass::Storage {
928 format: shader_format,
929 access: shader_access,
930 } if shader_format == binding_format
931 && (shader_access == binding_access
932 || shader_access == naga::StorageAccess::STORE
933 && binding_access == LOAD_STORE) =>
934 {
935 Ok(())
936 }
937 _ => Err(naga::ImageClass::Storage {
938 format: binding_format,
939 access: binding_access,
940 }),
941 }
942 }
943 BindingType::ExternalTexture => {
944 let binding_class = naga::ImageClass::External;
945 if shader_class == binding_class {
946 Ok(())
947 } else {
948 Err(binding_class)
949 }
950 }
951 _ => {
952 return Err(BindingError::WrongType {
953 binding: (&entry.ty).into(),
954 shader: (&self.ty).into(),
955 })
956 }
957 }
958 .map_err(|binding_class| BindingError::WrongTextureClass {
959 binding: binding_class,
960 shader: shader_class,
961 })?;
962 }
963 ResourceType::AccelerationStructure { vertex_return } => match entry.ty {
964 BindingType::AccelerationStructure {
965 vertex_return: entry_vertex_return,
966 } if vertex_return == entry_vertex_return => (),
967 _ => {
968 return Err(BindingError::WrongType {
969 binding: (&entry.ty).into(),
970 shader: (&self.ty).into(),
971 })
972 }
973 },
974 };
975
976 Ok(())
977 }
978
979 fn derive_binding_type(
980 &self,
981 is_reffed_by_sampler_in_entrypoint: bool,
982 ) -> Result<BindingType, BindingError> {
983 Ok(match self.ty {
984 ResourceType::Buffer {
985 minimum_binding_size,
986 } => BindingType::Buffer {
987 ty: match self.class {
988 naga::AddressSpace::Uniform => wgt::BufferBindingType::Uniform,
989 naga::AddressSpace::Storage { access } => wgt::BufferBindingType::Storage {
990 read_only: access == naga::StorageAccess::LOAD,
991 },
992 _ => return Err(BindingError::WrongBufferAddressSpace { space: self.class }),
993 },
994 has_dynamic_offset: false,
995 min_binding_size: Some(minimum_binding_size),
996 },
997 ResourceType::Sampler { comparison } => BindingType::Sampler(if comparison {
998 wgt::SamplerBindingType::Comparison
999 } else {
1000 wgt::SamplerBindingType::Filtering
1001 }),
1002 ResourceType::Texture {
1003 dim,
1004 arrayed,
1005 class,
1006 } => {
1007 let view_dimension = match dim {
1008 naga::ImageDimension::D1 => wgt::TextureViewDimension::D1,
1009 naga::ImageDimension::D2 if arrayed => wgt::TextureViewDimension::D2Array,
1010 naga::ImageDimension::D2 => wgt::TextureViewDimension::D2,
1011 naga::ImageDimension::D3 => wgt::TextureViewDimension::D3,
1012 naga::ImageDimension::Cube if arrayed => wgt::TextureViewDimension::CubeArray,
1013 naga::ImageDimension::Cube => wgt::TextureViewDimension::Cube,
1014 };
1015 match class {
1016 naga::ImageClass::Sampled { multi, kind } => BindingType::Texture {
1017 sample_type: match kind {
1018 naga::ScalarKind::Float => wgt::TextureSampleType::Float {
1019 filterable: is_reffed_by_sampler_in_entrypoint,
1020 },
1021 naga::ScalarKind::Sint => wgt::TextureSampleType::Sint,
1022 naga::ScalarKind::Uint => wgt::TextureSampleType::Uint,
1023 naga::ScalarKind::AbstractInt
1024 | naga::ScalarKind::AbstractFloat
1025 | naga::ScalarKind::Bool => unreachable!(),
1026 },
1027 view_dimension,
1028 multisampled: multi,
1029 },
1030 naga::ImageClass::Depth { multi } => BindingType::Texture {
1031 sample_type: wgt::TextureSampleType::Depth,
1032 view_dimension,
1033 multisampled: multi,
1034 },
1035 naga::ImageClass::Storage { format, access } => BindingType::StorageTexture {
1036 access: {
1037 const LOAD_STORE: naga::StorageAccess =
1038 naga::StorageAccess::LOAD.union(naga::StorageAccess::STORE);
1039 match access {
1040 naga::StorageAccess::LOAD => wgt::StorageTextureAccess::ReadOnly,
1041 naga::StorageAccess::STORE => wgt::StorageTextureAccess::WriteOnly,
1042 LOAD_STORE => wgt::StorageTextureAccess::ReadWrite,
1043 _ if access.contains(naga::StorageAccess::ATOMIC) => {
1044 wgt::StorageTextureAccess::Atomic
1045 }
1046 _ => unreachable!(),
1047 }
1048 },
1049 view_dimension,
1050 format: {
1051 let f = map_storage_format_from_naga(format);
1052 let original = map_storage_format_to_naga(f)
1053 .ok_or(BindingError::BadStorageFormat(f))?;
1054 debug_assert_eq!(format, original);
1055 f
1056 },
1057 },
1058 naga::ImageClass::External => BindingType::ExternalTexture,
1059 }
1060 }
1061 ResourceType::AccelerationStructure { vertex_return } => {
1062 BindingType::AccelerationStructure { vertex_return }
1063 }
1064 })
1065 }
1066}
1067
1068impl NumericType {
1069 fn from_vertex_format(format: wgt::VertexFormat) -> Self {
1070 use naga::{Scalar, VectorSize as Vs};
1071 use wgt::VertexFormat as Vf;
1072
1073 let (dim, scalar) = match format {
1074 Vf::Uint8 | Vf::Uint16 | Vf::Uint32 => (NumericDimension::Scalar, Scalar::U32),
1075 Vf::Uint8x2 | Vf::Uint16x2 | Vf::Uint32x2 => {
1076 (NumericDimension::Vector(Vs::Bi), Scalar::U32)
1077 }
1078 Vf::Uint32x3 => (NumericDimension::Vector(Vs::Tri), Scalar::U32),
1079 Vf::Uint8x4 | Vf::Uint16x4 | Vf::Uint32x4 => {
1080 (NumericDimension::Vector(Vs::Quad), Scalar::U32)
1081 }
1082 Vf::Sint8 | Vf::Sint16 | Vf::Sint32 => (NumericDimension::Scalar, Scalar::I32),
1083 Vf::Sint8x2 | Vf::Sint16x2 | Vf::Sint32x2 => {
1084 (NumericDimension::Vector(Vs::Bi), Scalar::I32)
1085 }
1086 Vf::Sint32x3 => (NumericDimension::Vector(Vs::Tri), Scalar::I32),
1087 Vf::Sint8x4 | Vf::Sint16x4 | Vf::Sint32x4 => {
1088 (NumericDimension::Vector(Vs::Quad), Scalar::I32)
1089 }
1090 Vf::Unorm8 | Vf::Unorm16 | Vf::Snorm8 | Vf::Snorm16 | Vf::Float16 | Vf::Float32 => {
1091 (NumericDimension::Scalar, Scalar::F32)
1092 }
1093 Vf::Unorm8x2
1094 | Vf::Snorm8x2
1095 | Vf::Unorm16x2
1096 | Vf::Snorm16x2
1097 | Vf::Float16x2
1098 | Vf::Float32x2 => (NumericDimension::Vector(Vs::Bi), Scalar::F32),
1099 Vf::Float32x3 => (NumericDimension::Vector(Vs::Tri), Scalar::F32),
1100 Vf::Unorm8x4
1101 | Vf::Snorm8x4
1102 | Vf::Unorm16x4
1103 | Vf::Snorm16x4
1104 | Vf::Float16x4
1105 | Vf::Float32x4
1106 | Vf::Unorm10_10_10_2
1107 | Vf::Unorm8x4Bgra
1108 | Vf::Snorm10_10_10_2 => (NumericDimension::Vector(Vs::Quad), Scalar::F32),
1109 Vf::Float64 => (NumericDimension::Scalar, Scalar::F64),
1110 Vf::Float64x2 => (NumericDimension::Vector(Vs::Bi), Scalar::F64),
1111 Vf::Float64x3 => (NumericDimension::Vector(Vs::Tri), Scalar::F64),
1112 Vf::Float64x4 => (NumericDimension::Vector(Vs::Quad), Scalar::F64),
1113 };
1114
1115 NumericType {
1116 dim,
1117 scalar,
1120 }
1121 }
1122
1123 fn from_texture_format(format: wgt::TextureFormat) -> Self {
1124 use naga::{Scalar, VectorSize as Vs};
1125 use wgt::TextureFormat as Tf;
1126
1127 let (dim, scalar) = match format {
1128 Tf::R8Unorm | Tf::R8Snorm | Tf::R16Float | Tf::R32Float => {
1129 (NumericDimension::Scalar, Scalar::F32)
1130 }
1131 Tf::R8Uint | Tf::R16Uint | Tf::R32Uint => (NumericDimension::Scalar, Scalar::U32),
1132 Tf::R8Sint | Tf::R16Sint | Tf::R32Sint => (NumericDimension::Scalar, Scalar::I32),
1133 Tf::Rg8Unorm | Tf::Rg8Snorm | Tf::Rg16Float | Tf::Rg32Float => {
1134 (NumericDimension::Vector(Vs::Bi), Scalar::F32)
1135 }
1136 Tf::R64Uint => (NumericDimension::Scalar, Scalar::U64),
1137 Tf::Rg8Uint | Tf::Rg16Uint | Tf::Rg32Uint => {
1138 (NumericDimension::Vector(Vs::Bi), Scalar::U32)
1139 }
1140 Tf::Rg8Sint | Tf::Rg16Sint | Tf::Rg32Sint => {
1141 (NumericDimension::Vector(Vs::Bi), Scalar::I32)
1142 }
1143 Tf::R16Snorm | Tf::R16Unorm => (NumericDimension::Scalar, Scalar::F32),
1144 Tf::Rg16Snorm | Tf::Rg16Unorm => (NumericDimension::Vector(Vs::Bi), Scalar::F32),
1145 Tf::Rgba16Snorm | Tf::Rgba16Unorm => (NumericDimension::Vector(Vs::Quad), Scalar::F32),
1146 Tf::Rgba8Unorm
1147 | Tf::Rgba8UnormSrgb
1148 | Tf::Rgba8Snorm
1149 | Tf::Bgra8Unorm
1150 | Tf::Bgra8UnormSrgb
1151 | Tf::Rgb10a2Unorm
1152 | Tf::Rgba16Float
1153 | Tf::Rgba32Float => (NumericDimension::Vector(Vs::Quad), Scalar::F32),
1154 Tf::Rgba8Uint | Tf::Rgba16Uint | Tf::Rgba32Uint | Tf::Rgb10a2Uint => {
1155 (NumericDimension::Vector(Vs::Quad), Scalar::U32)
1156 }
1157 Tf::Rgba8Sint | Tf::Rgba16Sint | Tf::Rgba32Sint => {
1158 (NumericDimension::Vector(Vs::Quad), Scalar::I32)
1159 }
1160 Tf::Rg11b10Ufloat => (NumericDimension::Vector(Vs::Tri), Scalar::F32),
1161 Tf::Stencil8
1162 | Tf::Depth16Unorm
1163 | Tf::Depth32Float
1164 | Tf::Depth32FloatStencil8
1165 | Tf::Depth24Plus
1166 | Tf::Depth24PlusStencil8 => {
1167 panic!("Unexpected depth format")
1168 }
1169 Tf::NV12 => panic!("Unexpected nv12 format"),
1170 Tf::P010 => panic!("Unexpected p010 format"),
1171 Tf::Rgb9e5Ufloat => (NumericDimension::Vector(Vs::Tri), Scalar::F32),
1172 Tf::Bc1RgbaUnorm
1173 | Tf::Bc1RgbaUnormSrgb
1174 | Tf::Bc2RgbaUnorm
1175 | Tf::Bc2RgbaUnormSrgb
1176 | Tf::Bc3RgbaUnorm
1177 | Tf::Bc3RgbaUnormSrgb
1178 | Tf::Bc7RgbaUnorm
1179 | Tf::Bc7RgbaUnormSrgb
1180 | Tf::Etc2Rgb8A1Unorm
1181 | Tf::Etc2Rgb8A1UnormSrgb
1182 | Tf::Etc2Rgba8Unorm
1183 | Tf::Etc2Rgba8UnormSrgb => (NumericDimension::Vector(Vs::Quad), Scalar::F32),
1184 Tf::Bc4RUnorm | Tf::Bc4RSnorm | Tf::EacR11Unorm | Tf::EacR11Snorm => {
1185 (NumericDimension::Scalar, Scalar::F32)
1186 }
1187 Tf::Bc5RgUnorm | Tf::Bc5RgSnorm | Tf::EacRg11Unorm | Tf::EacRg11Snorm => {
1188 (NumericDimension::Vector(Vs::Bi), Scalar::F32)
1189 }
1190 Tf::Bc6hRgbUfloat | Tf::Bc6hRgbFloat | Tf::Etc2Rgb8Unorm | Tf::Etc2Rgb8UnormSrgb => {
1191 (NumericDimension::Vector(Vs::Tri), Scalar::F32)
1192 }
1193 Tf::Astc {
1194 block: _,
1195 channel: _,
1196 } => (NumericDimension::Vector(Vs::Quad), Scalar::F32),
1197 };
1198
1199 NumericType {
1200 dim,
1201 scalar,
1204 }
1205 }
1206
1207 fn compatible_with_shader_output(self, shader: NumericType) -> bool {
1208 if self.scalar.kind != shader.scalar.kind {
1209 return false;
1210 }
1211 match (self.dim, shader.dim) {
1212 (NumericDimension::Scalar, NumericDimension::Scalar) => true,
1213 (NumericDimension::Scalar, NumericDimension::Vector(_)) => true,
1214 (NumericDimension::Vector(s0), NumericDimension::Vector(s1)) => s0 <= s1,
1215 (NumericDimension::Matrix(c0, r0), NumericDimension::Matrix(c1, r1)) => {
1216 c0 == c1 && r0 == r1
1217 }
1218 _ => false,
1219 }
1220 }
1221}
1222
1223pub fn check_color_attachment_compatibility(
1225 state: &wgt::ColorTargetState,
1226 output_ty: NumericType,
1227) -> Result<(), ColorStateError> {
1228 let pipeline_ty = NumericType::from_texture_format(state.format);
1229 if !pipeline_ty.compatible_with_shader_output(output_ty) {
1230 return Err(ColorStateError::IncompatibleFormat {
1231 pipeline: pipeline_ty,
1232 shader: output_ty,
1233 });
1234 }
1235 if let Some(blend) = state.blend {
1236 for (factor, name) in [
1237 (blend.color.src_factor, "source"),
1238 (blend.color.dst_factor, "destination"),
1239 ] {
1240 if factor.uses_source_alpha()
1241 && output_ty.dim != NumericDimension::Vector(naga::VectorSize::Quad)
1242 {
1243 return Err(ColorStateError::InvalidAlphaBlend {
1244 which: name,
1245 factor,
1246 });
1247 }
1248 }
1249 }
1250
1251 Ok(())
1252}
1253
1254pub enum BindingLayoutSource {
1255 Derived(Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>),
1259 Provided(Arc<crate::binding_model::PipelineLayout>),
1263}
1264
1265impl BindingLayoutSource {
1266 pub fn new_derived(limits: &wgt::Limits) -> Self {
1267 let mut array = ArrayVec::new();
1268 for _ in 0..limits.max_bind_groups {
1269 array.push(Default::default());
1270 }
1271 BindingLayoutSource::Derived(Box::new(array))
1272 }
1273}
1274
1275pub struct PipelineResources {
1277 pub layout: BindingLayoutSource,
1278 pub minimum_binding_sizes: FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
1279 pub immediates: naga::valid::ImmediateUsage,
1280}
1281
1282impl PipelineResources {
1283 pub fn new(layout: BindingLayoutSource) -> Self {
1284 Self {
1285 layout,
1286 minimum_binding_sizes: FastHashMap::default(),
1287 immediates: Default::default(),
1288 }
1289 }
1290}
1291
1292#[derive(Debug, Clone, Default)]
1297pub struct StageIo {
1298 pub varyings: FastHashMap<wgt::ShaderLocation, InterfaceVar>,
1300
1301 pub task_payload_size: Option<u32>,
1305
1306 pub primitive_index: Option<bool>,
1314 pub ray_tracing_payload: Option<RayTracingPayloadType>,
1315}
1316
1317impl Interface {
1318 fn populate(
1332 list: &mut Vec<Varying>,
1333 binding: Option<&naga::Binding>,
1334 ty: naga::Handle<naga::Type>,
1335 arena: &naga::UniqueArena<naga::Type>,
1336 ) {
1337 let numeric_ty = match arena[ty].inner {
1338 naga::TypeInner::Scalar(scalar) => NumericType {
1339 dim: NumericDimension::Scalar,
1340 scalar,
1341 },
1342 naga::TypeInner::Vector { size, scalar } => NumericType {
1343 dim: NumericDimension::Vector(size),
1344 scalar,
1345 },
1346 naga::TypeInner::Matrix {
1347 columns,
1348 rows,
1349 scalar,
1350 } => NumericType {
1351 dim: NumericDimension::Matrix(columns, rows),
1352 scalar,
1353 },
1354 naga::TypeInner::Struct { ref members, .. } => {
1355 for member in members {
1356 Self::populate(list, member.binding.as_ref(), member.ty, arena);
1357 }
1358 return;
1359 }
1360 naga::TypeInner::Array { base, size, stride }
1361 if matches!(
1362 binding,
1363 Some(naga::Binding::BuiltIn(naga::BuiltIn::ClipDistances)),
1364 ) =>
1365 {
1366 debug_assert_eq!(
1368 &arena[base].inner,
1369 &naga::TypeInner::Scalar(naga::Scalar::F32)
1370 );
1371 debug_assert_eq!(stride, 4);
1372
1373 let naga::ArraySize::Constant(array_size) = size else {
1374 unreachable!("non-constant array size for `clip_distances`")
1381 };
1382 let array_size = array_size.get();
1383
1384 list.push(Varying::BuiltIn(BuiltIn::ClipDistances { array_size }));
1385 return;
1386 }
1387 ref other => {
1388 log::error!("Unexpected varying type: {other:?}");
1389 return;
1390 }
1391 };
1392
1393 let varying = match binding {
1394 Some(&naga::Binding::Location {
1395 location,
1396 interpolation,
1397 sampling,
1398 per_primitive,
1399 blend_src: _,
1400 }) => Varying::UserDefined {
1401 location,
1402 iv: InterfaceVar {
1403 ty: numeric_ty,
1404 interpolation,
1405 sampling,
1406 per_primitive,
1407 },
1408 },
1409 Some(&naga::Binding::BuiltIn(built_in)) => Varying::BuiltIn(match built_in {
1410 naga::BuiltIn::Position { invariant } => BuiltIn::Position { invariant },
1411 naga::BuiltIn::ViewIndex => BuiltIn::ViewIndex,
1412 naga::BuiltIn::BaseInstance => BuiltIn::BaseInstance,
1413 naga::BuiltIn::BaseVertex => BuiltIn::BaseVertex,
1414 naga::BuiltIn::ClipDistances => unreachable!(),
1415 naga::BuiltIn::CullDistance => BuiltIn::CullDistance,
1416 naga::BuiltIn::InstanceIndex => BuiltIn::InstanceIndex,
1417 naga::BuiltIn::PointSize => BuiltIn::PointSize,
1418 naga::BuiltIn::VertexIndex => BuiltIn::VertexIndex,
1419 naga::BuiltIn::DrawIndex => BuiltIn::DrawIndex,
1420 naga::BuiltIn::FragDepth => BuiltIn::FragDepth,
1421 naga::BuiltIn::PointCoord => BuiltIn::PointCoord,
1422 naga::BuiltIn::FrontFacing => BuiltIn::FrontFacing,
1423 naga::BuiltIn::PrimitiveIndex => BuiltIn::PrimitiveIndex,
1424 naga::BuiltIn::Barycentric { perspective } => BuiltIn::Barycentric { perspective },
1425 naga::BuiltIn::SampleIndex => BuiltIn::SampleIndex,
1426 naga::BuiltIn::SampleMask => BuiltIn::SampleMask,
1427 naga::BuiltIn::GlobalInvocationId => BuiltIn::GlobalInvocationId,
1428 naga::BuiltIn::LocalInvocationId => BuiltIn::LocalInvocationId,
1429 naga::BuiltIn::LocalInvocationIndex => BuiltIn::LocalInvocationIndex,
1430 naga::BuiltIn::WorkGroupId => BuiltIn::WorkGroupId,
1431 naga::BuiltIn::WorkGroupSize => BuiltIn::WorkGroupSize,
1432 naga::BuiltIn::NumWorkGroups => BuiltIn::NumWorkGroups,
1433 naga::BuiltIn::NumSubgroups => BuiltIn::NumSubgroups,
1434 naga::BuiltIn::SubgroupId => BuiltIn::SubgroupId,
1435 naga::BuiltIn::SubgroupSize => BuiltIn::SubgroupSize,
1436 naga::BuiltIn::SubgroupInvocationId => BuiltIn::SubgroupInvocationId,
1437 naga::BuiltIn::MeshTaskSize => BuiltIn::MeshTaskSize,
1438 naga::BuiltIn::CullPrimitive => BuiltIn::CullPrimitive,
1439 naga::BuiltIn::PointIndex => BuiltIn::PointIndex,
1440 naga::BuiltIn::LineIndices => BuiltIn::LineIndices,
1441 naga::BuiltIn::TriangleIndices => BuiltIn::TriangleIndices,
1442 naga::BuiltIn::VertexCount => BuiltIn::VertexCount,
1443 naga::BuiltIn::Vertices => BuiltIn::Vertices,
1444 naga::BuiltIn::PrimitiveCount => BuiltIn::PrimitiveCount,
1445 naga::BuiltIn::Primitives => BuiltIn::Primitives,
1446 naga::BuiltIn::RayInvocationId => BuiltIn::RayInvocationId,
1447 naga::BuiltIn::NumRayInvocations => BuiltIn::NumRayInvocations,
1448 naga::BuiltIn::InstanceCustomData => BuiltIn::InstanceCustomData,
1449 naga::BuiltIn::GeometryIndex => BuiltIn::GeometryIndex,
1450 naga::BuiltIn::WorldRayOrigin => BuiltIn::WorldRayOrigin,
1451 naga::BuiltIn::WorldRayDirection => BuiltIn::WorldRayDirection,
1452 naga::BuiltIn::ObjectRayOrigin => BuiltIn::ObjectRayOrigin,
1453 naga::BuiltIn::ObjectRayDirection => BuiltIn::ObjectRayDirection,
1454 naga::BuiltIn::RayTmin => BuiltIn::RayTmin,
1455 naga::BuiltIn::RayTCurrentMax => BuiltIn::RayTCurrentMax,
1456 naga::BuiltIn::ObjectToWorld => BuiltIn::ObjectToWorld,
1457 naga::BuiltIn::WorldToObject => BuiltIn::WorldToObject,
1458 naga::BuiltIn::HitKind => BuiltIn::HitKind,
1459 naga::BuiltIn::HitBarycentrics => BuiltIn::HitBarycentrics,
1460 }),
1461 None => {
1462 log::error!("Missing binding for a varying");
1463 return;
1464 }
1465 };
1466 list.push(varying);
1467 }
1468
1469 pub fn new(module: &naga::Module, info: &naga::valid::ModuleInfo, limits: wgt::Limits) -> Self {
1475 let mut resources = naga::Arena::new();
1476 let mut resource_mapping = FastHashMap::default();
1477 for (var_handle, var) in module.global_variables.iter() {
1478 let Some(bind) = var.binding else { continue };
1479
1480 let naga_ty = &module.types[var.ty].inner;
1481
1482 let inner_ty = match *naga_ty {
1483 naga::TypeInner::BindingArray { base, .. } => &module.types[base].inner,
1484 ref ty => ty,
1485 };
1486
1487 let ty = match *inner_ty {
1488 naga::TypeInner::Image {
1489 dim,
1490 arrayed,
1491 class,
1492 } => ResourceType::Texture {
1493 dim,
1494 arrayed,
1495 class,
1496 },
1497 naga::TypeInner::Sampler { comparison } => ResourceType::Sampler { comparison },
1498 naga::TypeInner::AccelerationStructure { vertex_return } => {
1499 ResourceType::AccelerationStructure { vertex_return }
1500 }
1501 ref other => ResourceType::Buffer {
1502 minimum_binding_size: wgt::BufferSize::new(other.size(module.to_ctx()) as u64)
1503 .unwrap(),
1504 },
1505 };
1506 let handle = resources.append(
1507 Resource {
1508 name: var.name.clone(),
1509 bind,
1510 ty,
1511 class: var.space,
1512 },
1513 Default::default(),
1514 );
1515 resource_mapping.insert(var_handle, handle);
1516 }
1517
1518 let mut entry_points = FastHashMap::default();
1519 entry_points.reserve(module.entry_points.len());
1520 for (index, entry_point) in module.entry_points.iter().enumerate() {
1521 let func_info = info.get_entry_point(index);
1522 let mut ep = EntryPoint::default();
1523 for arg in entry_point.function.arguments.iter() {
1524 Self::populate(&mut ep.inputs, arg.binding.as_ref(), arg.ty, &module.types);
1525 }
1526 if let Some(ref result) = entry_point.function.result {
1527 Self::populate(
1528 &mut ep.outputs,
1529 result.binding.as_ref(),
1530 result.ty,
1531 &module.types,
1532 );
1533 }
1534
1535 let mut workgroup_storage_size = 0u64;
1536 for (var_handle, var) in module.global_variables.iter() {
1537 let usage = func_info[var_handle];
1538 if !usage.is_empty() {
1539 if var.binding.is_some() {
1540 ep.resources.push(resource_mapping[&var_handle]);
1541 }
1542 if var.space == naga::AddressSpace::WorkGroup {
1543 let size = module.types[var.ty].inner.size(module.to_ctx());
1544 workgroup_storage_size = workgroup_storage_size
1545 .saturating_add(u64::from(size).next_multiple_of(16));
1546 }
1547 }
1548 }
1549 ep.workgroup_storage_size = workgroup_storage_size;
1550
1551 for key in func_info.sampling_set.iter() {
1552 ep.sampling_pairs
1553 .insert((resource_mapping[&key.image], resource_mapping[&key.sampler]));
1554 }
1555 ep.dual_source_blending = func_info.dual_source_blending;
1556 ep.workgroup_size = entry_point.workgroup_size;
1557
1558 let mut used_immediates = module
1561 .global_variables
1562 .iter()
1563 .filter(|&(_, var)| var.space == naga::AddressSpace::Immediate)
1564 .map(|(handle, _)| handle)
1565 .filter(|&handle| !func_info[handle].is_empty());
1566 ep.immediate_usage = used_immediates
1567 .next()
1568 .map(|handle| {
1569 naga::valid::ImmediateUsage::from_type(
1570 &module.types[module.global_variables[handle].ty].inner,
1571 &module.types,
1572 module.to_ctx(),
1573 )
1574 })
1575 .unwrap_or_default();
1576 assert!(used_immediates.next().is_none());
1577
1578 if let Some(task_payload) = entry_point.task_payload {
1579 ep.task_payload_size = Some(
1580 module.types[module.global_variables[task_payload].ty]
1581 .inner
1582 .size(module.to_ctx()),
1583 );
1584 }
1585 if let Some(ref mesh_info) = entry_point.mesh_info {
1586 ep.mesh_info = Some(EntryPointMeshInfo {
1587 max_vertices: mesh_info.max_vertices,
1588 max_primitives: mesh_info.max_primitives,
1589 primitive_topology: match mesh_info.topology {
1590 naga::MeshOutputTopology::Triangles => wgt::PrimitiveTopology::TriangleList,
1591 naga::MeshOutputTopology::Lines => wgt::PrimitiveTopology::LineList,
1592 naga::MeshOutputTopology::Points => wgt::PrimitiveTopology::PointList,
1593 },
1594 });
1595 Self::populate(
1596 &mut ep.outputs,
1597 None,
1598 mesh_info.vertex_output_type,
1599 &module.types,
1600 );
1601 Self::populate(
1602 &mut ep.outputs,
1603 None,
1604 mesh_info.primitive_output_type,
1605 &module.types,
1606 );
1607 }
1608
1609 if matches!(
1611 entry_point.stage,
1612 naga::ShaderStage::ClosestHit | naga::ShaderStage::AnyHit | naga::ShaderStage::Miss
1613 ) {
1614 let ray_payload = entry_point
1615 .incoming_ray_payload
1616 .expect("these stages must have an incoming payload");
1617 let ty = module.global_variables[ray_payload].ty;
1618
1619 ep.ray_tracing_payload = Some(
1620 RayTracingPayloadType::from_naga(&module.types[ty].inner, module)
1621 .expect("naga should already validate invalid payloads out!"),
1622 );
1623 }
1624 else if matches!(entry_point.stage, naga::ShaderStage::RayGeneration) {
1627 for (handle, gv) in module.global_variables.iter() {
1628 if !func_info[handle].is_empty() && gv.space == naga::AddressSpace::RayPayload {
1629 ep.ray_tracing_payload = Some(
1630 RayTracingPayloadType::from_naga(&module.types[gv.ty].inner, module)
1631 .expect("naga should already validate invalid payloads out!"),
1632 );
1633 }
1634 }
1635 }
1636
1637 entry_points.insert(
1638 EntryPointKey(entry_point.stage, entry_point.name.clone()),
1639 ep,
1640 );
1641 }
1642
1643 Self {
1644 limits,
1645 resources,
1646 entry_points,
1647 }
1648 }
1649
1650 fn immediate_usage(
1651 &self,
1652 stage: naga::ShaderStage,
1653 entry_point_name: &str,
1654 ) -> naga::valid::ImmediateUsage {
1655 self.entry_points
1656 .get(&EntryPointKeyRef(stage, entry_point_name))
1657 .map(|ep| ep.immediate_usage)
1658 .unwrap_or_default()
1659 }
1660
1661 pub fn check_stage(
1683 &self,
1684 resources: &mut PipelineResources,
1685 entry_point_name: &str,
1686 shader_stage: ShaderStageForValidation,
1687 inputs: StageIo,
1688 primitive_topology: Option<wgt::PrimitiveTopology>,
1689 ) -> Result<StageIo, StageError> {
1690 let pair = EntryPointKeyRef(shader_stage.to_naga(), entry_point_name);
1693 let entry_point = match self.entry_points.get(&pair) {
1694 Some(some) => some,
1695 None => {
1696 return Err(StageError::NoEntryPointWithNameForStage {
1697 name: pair.1.to_string(),
1698 stage: shader_stage.to_naga(),
1699 })
1700 }
1701 };
1702 let EntryPointKeyRef(_, entry_point_name) = pair;
1703
1704 let stage_bit = shader_stage.to_wgt_bit();
1705 let PipelineResources {
1706 ref mut layout,
1707 ref mut minimum_binding_sizes,
1708 ref mut immediates,
1709 } = *resources;
1710
1711 for &handle in entry_point.resources.iter() {
1713 let res = &self.resources[handle];
1714 let result = 'err: {
1715 match layout {
1716 BindingLayoutSource::Provided(pipeline_layout) => {
1717 if let ResourceType::Buffer {
1719 minimum_binding_size,
1720 } = res.ty
1721 {
1722 match minimum_binding_sizes.entry(res.bind) {
1723 Entry::Occupied(e) => {
1724 *e.into_mut() = minimum_binding_size.max(*e.get());
1725 }
1726 Entry::Vacant(e) => {
1727 e.insert(minimum_binding_size);
1728 }
1729 }
1730 }
1731
1732 let Some(entry) =
1733 pipeline_layout.get_bgl_entry(res.bind.group, res.bind.binding)
1734 else {
1735 break 'err Err(BindingError::Missing);
1736 };
1737
1738 if !entry.visibility.contains(stage_bit) {
1739 break 'err Err(BindingError::Invisible);
1740 }
1741
1742 res.check_binding_use(entry)
1743 }
1744 BindingLayoutSource::Derived(layouts) => {
1745 let Some(map) = layouts.get_mut(res.bind.group as usize) else {
1746 break 'err Err(BindingError::Missing);
1747 };
1748
1749 let ty = match res.derive_binding_type(
1750 entry_point
1751 .sampling_pairs
1752 .iter()
1753 .any(|&(im, _samp)| im == handle),
1754 ) {
1755 Ok(ty) => ty,
1756 Err(error) => break 'err Err(error),
1757 };
1758
1759 match map.entry(res.bind.binding) {
1760 indexmap::map::Entry::Occupied(e) if e.get().ty != ty => {
1761 break 'err Err(BindingError::InconsistentlyDerivedType)
1762 }
1763 indexmap::map::Entry::Occupied(e) => {
1764 e.into_mut().visibility |= stage_bit;
1765 }
1766 indexmap::map::Entry::Vacant(e) => {
1767 e.insert(BindGroupLayoutEntry {
1768 binding: res.bind.binding,
1769 ty,
1770 visibility: stage_bit,
1771 count: None,
1772 });
1773 }
1774 }
1775 Ok(())
1776 }
1777 }
1778 };
1779 if let Err(error) = result {
1780 return Err(StageError::Binding(res.bind, error));
1781 }
1782 }
1783
1784 if let BindingLayoutSource::Provided(pipeline_layout) = layout {
1789 for &(texture_handle, sampler_handle) in entry_point.sampling_pairs.iter() {
1790 let texture_bind = &self.resources[texture_handle].bind;
1791 let sampler_bind = &self.resources[sampler_handle].bind;
1792 let texture_layout = pipeline_layout
1793 .get_bgl_entry(texture_bind.group, texture_bind.binding)
1794 .unwrap();
1795 let sampler_layout = pipeline_layout
1796 .get_bgl_entry(sampler_bind.group, sampler_bind.binding)
1797 .unwrap();
1798 assert!(texture_layout.visibility.contains(stage_bit));
1799 assert!(sampler_layout.visibility.contains(stage_bit));
1800
1801 let sampler_filtering = matches!(
1802 sampler_layout.ty,
1803 BindingType::Sampler(wgt::SamplerBindingType::Filtering)
1804 );
1805 let texture_sample_type = match texture_layout.ty {
1806 BindingType::Texture { sample_type, .. } => sample_type,
1807 BindingType::ExternalTexture => {
1808 wgt::TextureSampleType::Float { filterable: true }
1809 }
1810 _ => unreachable!(),
1811 };
1812
1813 let error = match (sampler_filtering, texture_sample_type) {
1814 (true, wgt::TextureSampleType::Float { filterable: false }) => {
1815 Some(FilteringError::Float)
1816 }
1817 (true, wgt::TextureSampleType::Sint) => Some(FilteringError::Integer),
1818 (true, wgt::TextureSampleType::Uint) => Some(FilteringError::Integer),
1819 _ => None,
1820 };
1821
1822 if let Some(error) = error {
1823 return Err(StageError::Filtering {
1824 texture: *texture_bind,
1825 sampler: *sampler_bind,
1826 error,
1827 });
1828 }
1829 }
1830 }
1831
1832 if shader_stage.to_naga().compute_like() {
1834 let workgroup_size_check = match shader_stage.to_naga() {
1835 naga::ShaderStage::Compute => WorkgroupSizeCheck {
1836 dimensions: &entry_point.workgroup_size,
1837 per_dimension_limits: &[
1838 self.limits.max_compute_workgroup_size_x,
1839 self.limits.max_compute_workgroup_size_y,
1840 self.limits.max_compute_workgroup_size_z,
1841 ],
1842 per_dimension_limits_desc: "max_compute_workgroup_size_*",
1843
1844 total_limit: self.limits.max_compute_invocations_per_workgroup,
1845 total_limit_desc: "max_compute_invocations_per_workgroup",
1846 },
1847 naga::ShaderStage::Task => WorkgroupSizeCheck {
1848 dimensions: &entry_point.workgroup_size,
1849 per_dimension_limits: &[self.limits.max_task_invocations_per_dimension; 3],
1850 per_dimension_limits_desc: "max_task_invocations_per_dimension",
1851
1852 total_limit: self.limits.max_task_invocations_per_workgroup,
1853 total_limit_desc: "max_task_invocations_per_workgroup",
1854 },
1855 naga::ShaderStage::Mesh => WorkgroupSizeCheck {
1856 dimensions: &entry_point.workgroup_size,
1857 per_dimension_limits: &[self.limits.max_mesh_invocations_per_dimension; 3],
1858 per_dimension_limits_desc: "max_mesh_invocations_per_dimension",
1859
1860 total_limit: self.limits.max_mesh_invocations_per_workgroup,
1861 total_limit_desc: "max_mesh_invocations_per_workgroup",
1862 },
1863 _ => unreachable!(),
1864 };
1865
1866 if entry_point.workgroup_storage_size
1867 > u64::from(self.limits.max_compute_workgroup_storage_size)
1868 {
1869 return Err(StageError::WorkgroupStorageSizeLimitExceeded {
1870 used: entry_point.workgroup_storage_size,
1871 limit: self.limits.max_compute_workgroup_storage_size,
1872 limit_desc: "max_compute_workgroup_storage_size",
1873 });
1874 }
1875
1876 let total = workgroup_size_check.check_and_compute_total_invocations()?;
1877 if total == 0 {
1878 return Err(StageError::InvalidWorkgroupSize(
1879 InvalidWorkgroupSizeError::Zero {
1880 dimensions: entry_point.workgroup_size,
1881 },
1882 ));
1883 }
1884 }
1885
1886 let mut this_stage_primitive_index = false;
1887 let mut has_draw_id = false;
1888 let mut has_per_vertex = false;
1889
1890 for input in entry_point.inputs.iter() {
1892 match *input {
1893 Varying::UserDefined { location, ref iv } => {
1894 let result = inputs
1895 .varyings
1896 .get(&location)
1897 .ok_or(InputError::Missing)
1898 .and_then(|provided| {
1899 let (compatible, per_primitive_correct) = match shader_stage.to_naga() {
1900 naga::ShaderStage::Vertex => {
1903 let is_compatible =
1904 iv.ty.scalar.kind == provided.ty.scalar.kind;
1905 (is_compatible, !iv.per_primitive)
1907 }
1908 naga::ShaderStage::Fragment => {
1909 if iv.interpolation != provided.interpolation {
1910 return Err(InputError::InterpolationMismatch(
1911 provided.interpolation,
1912 ));
1913 }
1914 if iv.sampling != provided.sampling {
1915 return Err(InputError::SamplingMismatch(
1916 provided.sampling,
1917 ));
1918 }
1919 (
1920 iv.ty == provided.ty,
1921 iv.per_primitive == provided.per_primitive,
1922 )
1923 }
1924 naga::ShaderStage::Compute
1926 | naga::ShaderStage::Task
1927 | naga::ShaderStage::Mesh => (false, false),
1928 naga::ShaderStage::RayGeneration
1929 | naga::ShaderStage::AnyHit
1930 | naga::ShaderStage::ClosestHit
1931 | naga::ShaderStage::Miss => {
1932 unreachable!()
1933 }
1934 };
1935 if !compatible {
1936 return Err(InputError::WrongType(provided.ty));
1937 } else if !per_primitive_correct {
1938 return Err(InputError::WrongPerPrimitive {
1939 pipeline_input: provided.per_primitive,
1940 shader: iv.per_primitive,
1941 });
1942 }
1943 Ok(())
1944 });
1945
1946 if let Err(error) = result {
1947 return Err(StageError::Input {
1948 location,
1949 var: iv.clone(),
1950 error,
1951 });
1952 }
1953 has_per_vertex |= iv.interpolation == Some(naga::Interpolation::PerVertex);
1954 }
1955 Varying::BuiltIn(BuiltIn::PrimitiveIndex) => {
1956 this_stage_primitive_index = true;
1957 }
1958 Varying::BuiltIn(BuiltIn::DrawIndex) => {
1959 has_draw_id = true;
1960 }
1961 Varying::BuiltIn(_) => {}
1962 }
1963 }
1964
1965 match shader_stage {
1966 ShaderStageForValidation::Vertex {
1967 topology,
1968 compare_function,
1969 } => {
1970 let mut max_vertex_shader_output_variables =
1971 self.limits.max_inter_stage_shader_variables;
1972 let mut max_vertex_shader_output_location = max_vertex_shader_output_variables - 1;
1973
1974 let point_list_deduction = if topology == wgt::PrimitiveTopology::PointList {
1975 Some(MaxVertexShaderOutputDeduction::PointListPrimitiveTopology)
1976 } else {
1977 None
1978 };
1979
1980 let clip_distance_deductions = entry_point.outputs.iter().filter_map(|output| {
1981 if let &Varying::BuiltIn(BuiltIn::ClipDistances { array_size }) = output {
1982 Some(MaxVertexShaderOutputDeduction::ClipDistances { array_size })
1983 } else {
1984 None
1985 }
1986 });
1987 debug_assert!(
1988 clip_distance_deductions.clone().count() <= 1,
1989 "multiple `clip_distances` outputs found"
1990 );
1991
1992 let deductions = point_list_deduction
1993 .into_iter()
1994 .chain(clip_distance_deductions);
1995
1996 for deduction in deductions.clone() {
1997 max_vertex_shader_output_variables = max_vertex_shader_output_variables
2000 .checked_sub(deduction.for_variables())
2001 .unwrap();
2002 max_vertex_shader_output_location = max_vertex_shader_output_location
2003 .checked_sub(deduction.for_location())
2004 .unwrap();
2005 }
2006
2007 let mut num_user_defined_outputs = 0;
2008
2009 for output in entry_point.outputs.iter() {
2010 match *output {
2011 Varying::UserDefined { ref iv, location } => {
2012 if location > max_vertex_shader_output_location {
2013 return Err(StageError::VertexOutputLocationTooLarge {
2014 location,
2015 var: iv.clone(),
2016 limit: self.limits.max_inter_stage_shader_variables,
2017 deductions: deductions.collect(),
2018 });
2019 }
2020 num_user_defined_outputs += 1;
2021 }
2022 Varying::BuiltIn(_) => {}
2023 };
2024
2025 if let Some(
2026 cmp @ wgt::CompareFunction::Equal | cmp @ wgt::CompareFunction::NotEqual,
2027 ) = compare_function
2028 {
2029 if let Varying::BuiltIn(BuiltIn::Position { invariant: false }) = *output {
2030 log::warn!(
2031 concat!(
2032 "Vertex shader with entry point {} outputs a ",
2033 "@builtin(position) without the @invariant attribute and ",
2034 "is used in a pipeline with {cmp:?}. On some machines, ",
2035 "this can cause bad artifacting as {cmp:?} assumes the ",
2036 "values output from the vertex shader exactly match the ",
2037 "value in the depth buffer. The @invariant attribute on the ",
2038 "@builtin(position) vertex output ensures that the exact ",
2039 "same pixel depths are used every render."
2040 ),
2041 entry_point_name,
2042 cmp = cmp
2043 );
2044 }
2045 }
2046 }
2047
2048 if num_user_defined_outputs > max_vertex_shader_output_variables {
2049 return Err(StageError::TooManyUserDefinedVertexOutputs {
2050 num_found: num_user_defined_outputs,
2051 limit: self.limits.max_inter_stage_shader_variables,
2052 deductions: deductions.collect(),
2053 });
2054 }
2055 }
2056 ShaderStageForValidation::Fragment {
2057 dual_source_blending,
2058 has_depth_attachment,
2059 } => {
2060 let mut max_fragment_shader_input_variables =
2061 self.limits.max_inter_stage_shader_variables;
2062
2063 let deductions = entry_point.inputs.iter().filter_map(|output| match output {
2064 Varying::UserDefined { .. } => None,
2065 Varying::BuiltIn(builtin) => {
2066 MaxFragmentShaderInputDeduction::from_inter_stage_builtin(builtin.to_naga())
2067 .or_else(|| {
2068 unreachable!(
2069 concat!(
2070 "unexpected built-in provided; ",
2071 "{:?} is not used for fragment stage input",
2072 ),
2073 builtin
2074 )
2075 })
2076 }
2077 });
2078
2079 for deduction in deductions.clone() {
2080 max_fragment_shader_input_variables = max_fragment_shader_input_variables
2083 .checked_sub(deduction.for_variables())
2084 .unwrap();
2085 }
2086
2087 let mut num_user_defined_inputs = 0;
2088
2089 for output in entry_point.inputs.iter() {
2090 match *output {
2091 Varying::UserDefined { ref iv, location } => {
2092 if location >= self.limits.max_inter_stage_shader_variables {
2093 return Err(StageError::FragmentInputLocationTooLarge {
2094 location,
2095 var: iv.clone(),
2096 limit: self.limits.max_inter_stage_shader_variables,
2097 deductions: deductions.collect(),
2098 });
2099 }
2100 num_user_defined_inputs += 1;
2101 }
2102 Varying::BuiltIn(_) => {}
2103 };
2104 }
2105
2106 if num_user_defined_inputs > max_fragment_shader_input_variables {
2107 return Err(StageError::TooManyUserDefinedFragmentInputs {
2108 num_found: num_user_defined_inputs,
2109 limit: self.limits.max_inter_stage_shader_variables,
2110 deductions: deductions.collect(),
2111 });
2112 }
2113
2114 for output in &entry_point.outputs {
2115 let &Varying::UserDefined { location, ref iv } = output else {
2116 continue;
2117 };
2118 if location >= self.limits.max_color_attachments {
2119 return Err(StageError::ColorAttachmentLocationTooLarge {
2120 location,
2121 var: iv.clone(),
2122 limit: self.limits.max_color_attachments,
2123 });
2124 }
2125 }
2126
2127 if dual_source_blending && !entry_point.dual_source_blending {
2132 return Err(StageError::InvalidDualSourceBlending);
2133 }
2134
2135 if entry_point
2136 .outputs
2137 .contains(&Varying::BuiltIn(BuiltIn::FragDepth))
2138 && !has_depth_attachment
2139 {
2140 return Err(StageError::MissingFragDepthAttachment);
2141 }
2142 }
2143 ShaderStageForValidation::Mesh => {
2144 for output in &entry_point.outputs {
2145 if matches!(output, Varying::BuiltIn(BuiltIn::PrimitiveIndex)) {
2146 this_stage_primitive_index = true;
2147 }
2148 }
2149 }
2150 _ => (),
2151 }
2152
2153 if let Some(ref mesh_info) = entry_point.mesh_info {
2154 if mesh_info.max_vertices > self.limits.max_mesh_output_vertices {
2155 return Err(StageError::TooManyMeshVertices {
2156 limit: self.limits.max_mesh_output_vertices,
2157 value: mesh_info.max_vertices,
2158 });
2159 }
2160 if mesh_info.max_primitives > self.limits.max_mesh_output_primitives {
2161 return Err(StageError::TooManyMeshPrimitives {
2162 limit: self.limits.max_mesh_output_primitives,
2163 value: mesh_info.max_primitives,
2164 });
2165 }
2166 if primitive_topology != Some(mesh_info.primitive_topology) {
2167 return Err(StageError::MeshTopologyMismatch);
2168 }
2169 }
2170 if let Some(task_payload_size) = entry_point.task_payload_size {
2171 if task_payload_size > self.limits.max_task_payload_size {
2172 return Err(StageError::TaskPayloadTooLarge {
2173 limit: self.limits.max_task_payload_size,
2174 value: task_payload_size,
2175 });
2176 }
2177 }
2178 if shader_stage.to_naga() == naga::ShaderStage::Mesh
2179 && entry_point.task_payload_size != inputs.task_payload_size
2180 {
2181 return Err(StageError::TaskPayloadMustMatch {
2182 input: inputs.task_payload_size,
2183 shader: entry_point.task_payload_size,
2184 });
2185 }
2186
2187 if shader_stage.to_naga() == naga::ShaderStage::Fragment
2189 && this_stage_primitive_index
2190 && inputs.primitive_index == Some(false)
2191 {
2192 return Err(StageError::InvalidPrimitiveIndex);
2193 } else if shader_stage.to_naga() == naga::ShaderStage::Fragment
2194 && !this_stage_primitive_index
2195 && inputs.primitive_index == Some(true)
2196 {
2197 return Err(StageError::MissingPrimitiveIndex);
2198 }
2199 if shader_stage.to_naga() == naga::ShaderStage::Mesh
2200 && inputs.task_payload_size.is_some()
2201 && has_draw_id
2202 {
2203 return Err(StageError::DrawIdError);
2204 }
2205
2206 if primitive_topology.is_none_or(|e| !e.is_triangles()) && has_per_vertex {
2207 return Err(StageError::PerVertexNotTriangles);
2208 }
2209
2210 let outputs = entry_point
2211 .outputs
2212 .iter()
2213 .filter_map(|output| match *output {
2214 Varying::UserDefined { location, ref iv } => Some((location, iv.clone())),
2215 Varying::BuiltIn(_) => None,
2216 })
2217 .collect();
2218
2219 let immediate_usage = self
2220 .immediate_usage(shader_stage.to_naga(), entry_point_name)
2221 .merge(immediates);
2222
2223 if let BindingLayoutSource::Provided(pipeline_layout) = layout {
2225 if pipeline_layout.immediate_size < immediate_usage.size() {
2226 return Err(StageError::LayoutImmediateSize {
2227 layout: pipeline_layout.immediate_size,
2228 required: immediate_usage.size(),
2229 });
2230 }
2231 }
2232
2233 *immediates = immediate_usage;
2234
2235 let mut ray_tracing_payload = inputs.ray_tracing_payload;
2236
2237 let current_ray_payload = entry_point.ray_tracing_payload.clone();
2238
2239 if let (Some(ray_tracing_payload), Some(current_ray_payload)) =
2240 (ray_tracing_payload.as_ref(), current_ray_payload.as_ref())
2241 {
2242 if ray_tracing_payload != current_ray_payload {
2243 return Err(StageError::RayTracingPayloadMismatch);
2244 }
2245 }
2246
2247 if let Some(current_ray_payload) = current_ray_payload {
2251 ray_tracing_payload = Some(current_ray_payload)
2252 }
2253
2254 Ok(StageIo {
2255 task_payload_size: entry_point.task_payload_size,
2256 varyings: outputs,
2257 primitive_index: if shader_stage.to_naga() == naga::ShaderStage::Mesh {
2258 Some(this_stage_primitive_index)
2259 } else {
2260 None
2261 },
2262 ray_tracing_payload,
2263 })
2264 }
2265}
2266
2267pub fn check_color_attachment_count(
2268 num_attachments: usize,
2269 limit: u32,
2270) -> Result<(), ColorAttachmentError> {
2271 let limit = usize::try_from(limit).unwrap();
2272 if num_attachments > limit {
2273 return Err(ColorAttachmentError::TooMany {
2274 given: num_attachments,
2275 limit,
2276 });
2277 }
2278
2279 Ok(())
2280}
2281
2282pub fn validate_color_attachment_bytes_per_sample(
2288 attachment_formats: impl IntoIterator<Item = wgt::TextureFormat>,
2289 limit: u32,
2290) -> Result<(), ColorAttachmentError> {
2291 let mut total_bytes_per_sample: u32 = 0;
2292 for format in attachment_formats {
2293 let byte_cost = format.target_pixel_byte_cost().unwrap();
2294 let alignment = format.target_component_alignment().unwrap();
2295
2296 total_bytes_per_sample = total_bytes_per_sample.next_multiple_of(alignment);
2297 total_bytes_per_sample += byte_cost;
2298 }
2299
2300 if total_bytes_per_sample > limit {
2301 return Err(ColorAttachmentError::TooManyBytesPerSample {
2302 total: total_bytes_per_sample,
2303 limit,
2304 });
2305 }
2306
2307 Ok(())
2308}
2309
2310#[derive(Clone, Debug, Error)]
2311pub enum InvalidWorkgroupSizeError {
2312 #[error(
2313 "Workgroup size {dimensions:?} ({total} total invocations) must be less or equal to \
2314 the per-dimension limit `Limits::{per_dimension_limits_desc}` of {per_dimension_limits:?} \
2315 and the total invocation limit `Limits::{total_limit_desc}` of {total_limit}"
2316 )]
2317 LimitExceeded {
2318 dimensions: [u32; 3],
2319 per_dimension_limits: [u32; 3],
2320 per_dimension_limits_desc: &'static str,
2321 total: u32,
2322 total_limit: u32,
2323 total_limit_desc: &'static str,
2324 },
2325 #[error("Workgroup sizes {dimensions:?} must be positive")]
2326 Zero { dimensions: [u32; 3] },
2327}
2328
2329#[derive(Clone, Debug)]
2332pub(crate) struct WorkgroupSizeCheck<'a> {
2333 pub dimensions: &'a [u32; 3],
2334 pub per_dimension_limits: &'a [u32; 3],
2335 pub per_dimension_limits_desc: &'static str,
2336 pub total_limit: u32,
2337 pub total_limit_desc: &'static str,
2338}
2339
2340impl WorkgroupSizeCheck<'_> {
2341 pub(crate) fn check_and_compute_total_invocations(
2347 self,
2348 ) -> Result<u32, InvalidWorkgroupSizeError> {
2349 let Self {
2350 dimensions,
2351 per_dimension_limits,
2352 per_dimension_limits_desc,
2353 total_limit,
2354 total_limit_desc,
2355 } = self;
2356
2357 let total = dimensions
2358 .iter()
2359 .fold(1u32, |total, &dim| total.saturating_mul(dim));
2360
2361 let invalid_total_invocations = total > total_limit;
2362
2363 let dimension_too_large = dimensions
2364 .iter()
2365 .zip(per_dimension_limits.iter())
2366 .any(|(dim, limit)| dim > limit);
2367
2368 if invalid_total_invocations || dimension_too_large {
2369 Err(InvalidWorkgroupSizeError::LimitExceeded {
2370 dimensions: *dimensions,
2371 per_dimension_limits: *per_dimension_limits,
2372 per_dimension_limits_desc,
2373 total,
2374 total_limit,
2375 total_limit_desc,
2376 })
2377 } else {
2378 Ok(total)
2379 }
2380 }
2381}
2382
2383pub enum ShaderStageForValidation {
2384 Vertex {
2385 topology: wgt::PrimitiveTopology,
2386 compare_function: Option<wgt::CompareFunction>,
2387 },
2388 Mesh,
2389 Fragment {
2390 dual_source_blending: bool,
2391 has_depth_attachment: bool,
2392 },
2393 Compute,
2394 Task,
2395 RayGeneration,
2396 Miss,
2397 ClosestHit {
2398 triangle: bool,
2399 },
2400 AnyHit {
2401 triangle: bool,
2402 },
2403}
2404
2405impl ShaderStageForValidation {
2406 pub fn to_naga(&self) -> naga::ShaderStage {
2407 match self {
2408 Self::Vertex { .. } => naga::ShaderStage::Vertex,
2409 Self::Mesh => naga::ShaderStage::Mesh,
2410 Self::Fragment { .. } => naga::ShaderStage::Fragment,
2411 Self::Compute => naga::ShaderStage::Compute,
2412 Self::Task => naga::ShaderStage::Task,
2413 Self::RayGeneration => naga::ShaderStage::RayGeneration,
2414 Self::Miss => naga::ShaderStage::Miss,
2415 Self::AnyHit { .. } => naga::ShaderStage::AnyHit,
2416 Self::ClosestHit { .. } => naga::ShaderStage::ClosestHit,
2417 }
2418 }
2419
2420 pub fn to_wgt_bit(&self) -> wgt::ShaderStages {
2421 match self {
2422 Self::Vertex { .. } => wgt::ShaderStages::VERTEX,
2423 Self::Mesh => wgt::ShaderStages::MESH,
2424 Self::Fragment { .. } => wgt::ShaderStages::FRAGMENT,
2425 Self::Compute => wgt::ShaderStages::COMPUTE,
2426 Self::Task => wgt::ShaderStages::TASK,
2427 Self::RayGeneration => wgt::ShaderStages::RAY_GENERATION,
2428 Self::Miss => wgt::ShaderStages::MISS,
2429 Self::AnyHit { .. } => wgt::ShaderStages::ANY_HIT,
2430 Self::ClosestHit { .. } => wgt::ShaderStages::CLOSEST_HIT,
2431 }
2432 }
2433}