wgpu_types/shader.rs
1use alloc::borrow::Cow;
2
3/// Describes how shader bound checks should be performed.
4#[derive(Copy, Clone, Debug)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6pub struct ShaderRuntimeChecks {
7 /// Enforce bounds checks in shaders, even if the underlying driver doesn't
8 /// support doing so natively.
9 ///
10 /// When this is `true`, `wgpu` promises that shaders can only read or
11 /// write the accessible region of a bindgroup's buffer bindings. If
12 /// the underlying graphics platform cannot implement these bounds checks
13 /// itself, `wgpu` will inject bounds checks before presenting the
14 /// shader to the platform.
15 ///
16 /// When this is `false`, `wgpu` only enforces such bounds checks if the
17 /// underlying platform provides a way to do so itself. `wgpu` does not
18 /// itself add any bounds checks to generated shader code.
19 ///
20 /// Note that `wgpu` users may try to initialize only those portions of
21 /// buffers that they anticipate might be read from. Passing `false` here
22 /// may allow shaders to see wider regions of the buffers than expected,
23 /// making such deferred initialization visible to the application.
24 pub bounds_checks: bool,
25 ///
26 /// If false, the caller MUST ensure that all passed shaders do not contain any infinite loops.
27 ///
28 /// If it does, backend compilers MAY treat such a loop as unreachable code and draw
29 /// conclusions about other safety-critical code paths. This option SHOULD NOT be disabled
30 /// when running untrusted code.
31 pub force_loop_bounding: bool,
32 /// If false, the caller **MUST** ensure that in all passed shaders every function operating
33 /// on a ray query must obey these rules (functions using wgsl naming)
34 /// - `rayQueryInitialize` must have called before `rayQueryProceed`
35 /// - `rayQueryProceed` must have been called, returned true and have hit an AABB before
36 /// `rayQueryGenerateIntersection` is called
37 /// - `rayQueryProceed` must have been called, returned true and have hit a triangle before
38 /// `rayQueryConfirmIntersection` is called
39 /// - `rayQueryProceed` must have been called and have returned true before `rayQueryTerminate`,
40 /// `getCandidateHitVertexPositions` or `rayQueryGetCandidateIntersection` is called
41 /// - `rayQueryProceed` must have been called and have returned false before `rayQueryGetCommittedIntersection`
42 /// or `getCommittedHitVertexPositions` are called
43 /// - when calling `rayQueryInitialize`, the ray desc argument must not contain NaNs in any floating point
44 /// values and must not contain Infs in any component of `dir`, `origin`, `tmin`
45 pub ray_query_initialization_tracking: bool,
46
47 /// If false, task shaders will not validate that the mesh shader grid they dispatch is within legal limits.
48 pub task_shader_dispatch_tracking: bool,
49
50 /// If false, mesh shaders won't clamp the output primitives' vertex indices, which can lead to
51 /// undefined behavior and arbitrary memory access.
52 pub mesh_shader_primitive_indices_clamp: bool,
53
54 /// If false, integer division and modulo operations will use raw instructions
55 /// without guards against division by zero or signed integer overflow
56 /// (`INT_MIN / -1`). The caller **MUST** ensure that all divisors are non-zero
57 /// and that no signed overflow occurs.
58 pub int_div_checks: bool,
59}
60
61impl ShaderRuntimeChecks {
62 /// Creates a new configuration where the shader is fully checked.
63 #[must_use]
64 pub const fn checked() -> Self {
65 Self::all(true)
66 }
67
68 /// Creates a new configuration where none of the checks are performed.
69 #[must_use]
70 pub const fn unchecked() -> Self {
71 Self::all(false)
72 }
73
74 /// Creates a new configuration where all checks are enabled or disabled. To safely
75 /// create a configuration with all checks enabled, use [`ShaderRuntimeChecks::checked`].
76 #[must_use]
77 pub const fn all(all_checks: bool) -> Self {
78 Self {
79 bounds_checks: all_checks,
80 force_loop_bounding: all_checks,
81 ray_query_initialization_tracking: all_checks,
82 task_shader_dispatch_tracking: all_checks,
83 mesh_shader_primitive_indices_clamp: all_checks,
84 int_div_checks: all_checks,
85 }
86 }
87}
88
89impl Default for ShaderRuntimeChecks {
90 fn default() -> Self {
91 Self::checked()
92 }
93}
94
95/// Describes a single entry point in a passthrough shader descriptor.
96#[derive(Debug, Clone)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
98pub struct PassthroughShaderEntryPoint<'a> {
99 /// The name of the entry point. Only used in validation and for GLSL or DXIL.
100 pub name: Cow<'a, str>,
101 /// Number of workgroups in each dimension x, y and z. Only used for metal with
102 /// compute-like shader stages.
103 pub workgroup_size: (u32, u32, u32),
104}
105
106/// Descriptor for a shader module given by any of several sources.
107/// These shaders are passed through directly to the underlying api.
108/// At least one shader type that may be used by the backend must be `Some` or a panic is raised.
109///
110/// Note that you shouldn't expect this to work with bindings except on SPIR-V, and even on SPIR-V
111/// there will be some caveats.
112#[derive(Debug, Clone)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
114pub struct CreateShaderModuleDescriptorPassthrough<'a, L> {
115 /// Debug label of the shader module. This will show up in graphics debuggers for easy identification.
116 pub label: L,
117 /// The list of entry points and their corresponding workgroup sizes.
118 pub entry_points: Cow<'a, [PassthroughShaderEntryPoint<'a>]>,
119
120 /// Binary SPIR-V data, in 4-byte words.
121 pub spirv: Option<Cow<'a, [u32]>>,
122 /// Shader DXIL source.
123 pub dxil: Option<Cow<'a, [u8]>>,
124 /// Shader HLSL source.
125 pub hlsl: Option<Cow<'a, str>>,
126 /// Shader MetalLib source.
127 pub metallib: Option<Cow<'a, [u8]>>,
128 /// Shader MSL source.
129 pub msl: Option<Cow<'a, str>>,
130 /// Shader GLSL source (currently unused).
131 pub glsl: Option<Cow<'a, str>>,
132 /// Shader WGSL source.
133 pub wgsl: Option<Cow<'a, str>>,
134}
135
136// This is so people don't have to fill in fields they don't use, like num_workgroups,
137// entry_point, or other shader languages they didn't compile for
138impl<'a, L: Default> Default for CreateShaderModuleDescriptorPassthrough<'a, L> {
139 fn default() -> Self {
140 Self {
141 label: Default::default(),
142 entry_points: Cow::Borrowed(&[]),
143 spirv: None,
144 dxil: None,
145 metallib: None,
146 msl: None,
147 hlsl: None,
148 glsl: None,
149 wgsl: None,
150 }
151 }
152}
153
154impl<'a, L> CreateShaderModuleDescriptorPassthrough<'a, L> {
155 /// Takes a closure and maps the label of the shader module descriptor into another.
156 pub fn map_label<K>(
157 &self,
158 fun: impl FnOnce(&L) -> K,
159 ) -> CreateShaderModuleDescriptorPassthrough<'a, K> {
160 CreateShaderModuleDescriptorPassthrough {
161 label: fun(&self.label),
162 entry_points: self.entry_points.clone(),
163 spirv: self.spirv.clone(),
164 metallib: self.metallib.clone(),
165 dxil: self.dxil.clone(),
166 msl: self.msl.clone(),
167 hlsl: self.hlsl.clone(),
168 glsl: self.glsl.clone(),
169 wgsl: self.wgsl.clone(),
170 }
171 }
172
173 #[cfg(feature = "trace")]
174 /// Returns the source data for tracing purpose.
175 pub fn trace_data(&self) -> &[u8] {
176 if let Some(spirv) = &self.spirv {
177 bytemuck::cast_slice(spirv)
178 } else if let Some(metallib) = &self.metallib {
179 metallib
180 } else if let Some(msl) = &self.msl {
181 msl.as_bytes()
182 } else if let Some(dxil) = &self.dxil {
183 dxil
184 } else if let Some(hlsl) = &self.hlsl {
185 hlsl.as_bytes()
186 } else if let Some(glsl) = &self.glsl {
187 glsl.as_bytes()
188 } else if let Some(wgsl) = &self.wgsl {
189 wgsl.as_bytes()
190 } else {
191 panic!("No binary data provided to `ShaderModuleDescriptorGeneric`")
192 }
193 }
194
195 #[cfg(feature = "trace")]
196 /// Returns the binary file extension for tracing purpose.
197 pub fn trace_binary_ext(&self) -> &'static str {
198 if self.spirv.is_some() {
199 "spv"
200 } else if self.metallib.is_some() {
201 "metallib"
202 } else if self.msl.is_some() {
203 "metal"
204 } else if self.dxil.is_some() {
205 "dxil"
206 } else if self.hlsl.is_some() {
207 "hlsl"
208 } else if self.glsl.is_some() {
209 "glsl"
210 } else if self.wgsl.is_some() {
211 "wgsl"
212 } else {
213 panic!("No binary data provided to `ShaderModuleDescriptorGeneric`")
214 }
215 }
216}