Skip to main content

wgpu_types/
limits.rs

1//! [`Limits`] and downlevel-related types.
2
3use core::cmp::Ordering;
4
5#[cfg(any(feature = "serde", test))]
6use serde::{Deserialize, Serialize};
7
8#[cfg(doc)]
9use crate::{Features, TextureFormat};
10
11use crate::link_to_wgpu_item;
12
13/// Invoke a macro for each of the limits.
14///
15/// The supplied macro should take two arguments. The first is a limit name, as
16/// an identifier, typically used to access a member of `struct Limits`. The
17/// second is `Ordering::Less` if valid values are less than the limit (the
18/// common case), or `Ordering::Greater` if valid values are more than the limit
19/// (for limits like alignments, which are minima instead of maxima).
20macro_rules! with_limits {
21    ($macro_name:ident) => {
22        $macro_name!(max_texture_dimension_1d, Ordering::Less);
23        $macro_name!(max_texture_dimension_2d, Ordering::Less);
24        $macro_name!(max_texture_dimension_3d, Ordering::Less);
25        $macro_name!(max_texture_array_layers, Ordering::Less);
26        $macro_name!(max_bind_groups, Ordering::Less);
27        $macro_name!(max_bind_groups_plus_vertex_buffers, Ordering::Less);
28        $macro_name!(max_bindings_per_bind_group, Ordering::Less);
29        $macro_name!(
30            max_dynamic_uniform_buffers_per_pipeline_layout,
31            Ordering::Less
32        );
33        $macro_name!(
34            max_dynamic_storage_buffers_per_pipeline_layout,
35            Ordering::Less
36        );
37        $macro_name!(max_sampled_textures_per_shader_stage, Ordering::Less);
38        $macro_name!(max_samplers_per_shader_stage, Ordering::Less);
39        $macro_name!(max_storage_buffers_per_shader_stage, Ordering::Less);
40        $macro_name!(max_storage_buffers_in_vertex_stage, Ordering::Less);
41        $macro_name!(max_storage_buffers_in_fragment_stage, Ordering::Less);
42        $macro_name!(max_storage_textures_per_shader_stage, Ordering::Less);
43        $macro_name!(max_storage_textures_in_vertex_stage, Ordering::Less);
44        $macro_name!(max_storage_textures_in_fragment_stage, Ordering::Less);
45        $macro_name!(max_uniform_buffers_per_shader_stage, Ordering::Less);
46        $macro_name!(max_binding_array_elements_per_shader_stage, Ordering::Less);
47        $macro_name!(
48            max_binding_array_acceleration_structure_elements_per_shader_stage,
49            Ordering::Less
50        );
51        $macro_name!(
52            max_binding_array_sampler_elements_per_shader_stage,
53            Ordering::Less
54        );
55
56        $macro_name!(max_uniform_buffer_binding_size, Ordering::Less);
57        $macro_name!(max_storage_buffer_binding_size, Ordering::Less);
58        $macro_name!(max_vertex_buffers, Ordering::Less);
59        $macro_name!(max_buffer_size, Ordering::Less);
60        $macro_name!(max_vertex_attributes, Ordering::Less);
61        $macro_name!(max_vertex_buffer_array_stride, Ordering::Less);
62        $macro_name!(max_inter_stage_shader_variables, Ordering::Less);
63        $macro_name!(min_uniform_buffer_offset_alignment, Ordering::Greater);
64        $macro_name!(min_storage_buffer_offset_alignment, Ordering::Greater);
65        $macro_name!(max_color_attachments, Ordering::Less);
66        $macro_name!(max_color_attachment_bytes_per_sample, Ordering::Less);
67        $macro_name!(max_compute_workgroup_storage_size, Ordering::Less);
68        $macro_name!(max_compute_invocations_per_workgroup, Ordering::Less);
69        $macro_name!(max_compute_workgroup_size_x, Ordering::Less);
70        $macro_name!(max_compute_workgroup_size_y, Ordering::Less);
71        $macro_name!(max_compute_workgroup_size_z, Ordering::Less);
72        $macro_name!(max_compute_workgroups_per_dimension, Ordering::Less);
73
74        $macro_name!(max_immediate_size, Ordering::Less);
75        $macro_name!(max_non_sampler_bindings, Ordering::Less);
76
77        $macro_name!(max_task_workgroup_total_count, Ordering::Less);
78        $macro_name!(max_task_workgroups_per_dimension, Ordering::Less);
79        $macro_name!(max_mesh_workgroup_total_count, Ordering::Less);
80        $macro_name!(max_mesh_workgroups_per_dimension, Ordering::Less);
81        $macro_name!(max_task_invocations_per_workgroup, Ordering::Less);
82        $macro_name!(max_task_invocations_per_dimension, Ordering::Less);
83        $macro_name!(max_mesh_invocations_per_workgroup, Ordering::Less);
84        $macro_name!(max_mesh_invocations_per_dimension, Ordering::Less);
85
86        $macro_name!(max_task_payload_size, Ordering::Less);
87        $macro_name!(max_mesh_output_vertices, Ordering::Less);
88        $macro_name!(max_mesh_output_primitives, Ordering::Less);
89        $macro_name!(max_mesh_output_layers, Ordering::Less);
90        $macro_name!(max_mesh_multiview_view_count, Ordering::Less);
91
92        $macro_name!(max_blas_primitive_count, Ordering::Less);
93        $macro_name!(max_blas_geometry_count, Ordering::Less);
94        $macro_name!(max_tlas_instance_count, Ordering::Less);
95        $macro_name!(max_acceleration_structures_per_shader_stage, Ordering::Less);
96        $macro_name!(
97            max_buffers_and_acceleration_structures_per_shader_stage,
98            Ordering::Less
99        );
100
101        $macro_name!(max_multiview_view_count, Ordering::Less);
102
103        $macro_name!(max_ray_dispatch_count, Ordering::Less);
104        $macro_name!(max_ray_recursion_depth, Ordering::Less);
105    };
106}
107
108/// Represents the sets of limits an adapter/device supports.
109///
110/// We provide three different defaults.
111/// - [`Limits::downlevel_defaults()`]. This is a set of limits that is guaranteed to work on almost
112///   all backends, including the "downlevel" OpenGL backend, but excluding WebGL2. For
113///   most applications we recommend using these limits, assuming they are high enough for your
114///   application, and you do not intend to support WebGL.
115/// - [`Limits::downlevel_webgl2_defaults()`] This is a set of limits that is lower even than the
116///   [`downlevel_defaults()`], configured to be low enough to support running in the browser using
117///   WebGL2.
118/// - [`Limits::default()`]. This is the set of limits that is guaranteed to work on all modern
119///   backends and is guaranteed to be supported by WebGPU. Applications needing more modern
120///   features can use this as a reasonable set of limits if they are targeting only desktop and
121///   modern mobile devices.
122///
123/// We recommend starting with the most restrictive limits you can and manually increasing the
124/// limits you need boosted. This will let you stay running on all hardware that supports the limits
125/// you need.
126///
127/// Limits "better" than the default must be supported by the adapter and requested when requesting
128/// a device. If limits "better" than the adapter supports are requested, requesting a device will
129/// panic. Once a device is requested, you may only use resources up to the limits requested _even_
130/// if the adapter supports "better" limits.
131///
132/// Requesting limits that are "better" than you need may cause performance to decrease because the
133/// implementation needs to support more than is needed. You should ideally only request exactly
134/// what you need.
135///
136/// Corresponds to [WebGPU `GPUSupportedLimits`](
137/// https://gpuweb.github.io/gpuweb/#gpusupportedlimits).
138///
139/// [`downlevel_defaults()`]: Limits::downlevel_defaults
140#[repr(C)]
141// Even though this type is simple, it is not copy because it is large.
142// https://rust-lang.github.io/rust-clippy/master/#large_types_passed_by_value
143#[derive(Clone, Debug, PartialEq, Eq, Hash)]
144#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
145#[cfg_attr(feature = "serde", serde(rename_all = "camelCase", default))]
146pub struct Limits {
147    /// Maximum allowed value for the `size.width` of a texture created with `TextureDimension::D1`.
148    /// Defaults to 8192. Higher is "better".
149    #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension1D"))]
150    pub max_texture_dimension_1d: u32,
151    /// Maximum allowed value for the `size.width` and `size.height` of a texture created with `TextureDimension::D2`.
152    /// Defaults to 8192. Higher is "better".
153    #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension2D"))]
154    pub max_texture_dimension_2d: u32,
155    /// Maximum allowed value for the `size.width`, `size.height`, and `size.depth_or_array_layers`
156    /// of a texture created with `TextureDimension::D3`.
157    /// Defaults to 2048. Higher is "better".
158    #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension3D"))]
159    pub max_texture_dimension_3d: u32,
160    /// Maximum allowed value for the `size.depth_or_array_layers` of a texture created with `TextureDimension::D2`.
161    /// Defaults to 256. Higher is "better".
162    pub max_texture_array_layers: u32,
163    /// Amount of bind groups that can be attached to a pipeline at the same time. Defaults to 4. Higher is "better".
164    pub max_bind_groups: u32,
165    /// The maximum number of bind group and vertex buffer slots used simultaneously, counting any empty slots below the highest index.
166    /// Defaults to 24. Higher is "better".
167    pub max_bind_groups_plus_vertex_buffers: u32,
168    /// Maximum binding index allowed in `create_bind_group_layout`. Defaults to 1000. Higher is "better".
169    pub max_bindings_per_bind_group: u32,
170    /// Amount of uniform buffer bindings that can be dynamic in a single pipeline. Defaults to 8. Higher is "better".
171    pub max_dynamic_uniform_buffers_per_pipeline_layout: u32,
172    /// Amount of storage buffer bindings that can be dynamic in a single pipeline. Defaults to 4. Higher is "better".
173    pub max_dynamic_storage_buffers_per_pipeline_layout: u32,
174    /// Amount of sampled textures visible in a single shader stage. Defaults to 16. Higher is "better".
175    pub max_sampled_textures_per_shader_stage: u32,
176    /// Amount of samplers visible in a single shader stage. Defaults to 16. Higher is "better".
177    pub max_samplers_per_shader_stage: u32,
178    /// Amount of storage buffers visible in a single shader stage. Defaults to 8. Higher is "better".
179    pub max_storage_buffers_per_shader_stage: u32,
180    /// Amount of storage buffers visible in a vertex shader stage. Defaults to 8. Higher is "better".
181    ///
182    /// Outside of compat mode (which is not implemented, see
183    /// <https://github.com/gfx-rs/wgpu/issues/8124>), this is set to the value of
184    /// `max_storage_buffers_per_shader_stage`.
185    pub max_storage_buffers_in_vertex_stage: u32,
186    /// Amount of storage buffers visible in a fragment shader stage. Defaults to 8. Higher is "better".
187    ///
188    /// Outside of compat mode (which is not implemented, see
189    /// <https://github.com/gfx-rs/wgpu/issues/8124>), this is set to the value of
190    /// `max_storage_buffers_per_shader_stage`.
191    pub max_storage_buffers_in_fragment_stage: u32,
192    /// Amount of storage textures visible in a single shader stage. Defaults to 4. Higher is "better".
193    pub max_storage_textures_per_shader_stage: u32,
194    /// Amount of storage textures visible in a vertex shader stage. Defaults to 4. Higher is "better".
195    ///
196    /// Outside of compat mode (which is not implemented, see
197    /// <https://github.com/gfx-rs/wgpu/issues/8124>), this is set to the value of
198    /// `max_storage_textures_per_shader_stage`.
199    pub max_storage_textures_in_vertex_stage: u32,
200    /// Amount of storage textures visible in a fragment shader stage. Defaults to 4. Higher is "better".
201    ///
202    /// Outside of compat mode (which is not implemented, see
203    /// <https://github.com/gfx-rs/wgpu/issues/8124>), this is set to the value of
204    /// `max_storage_textures_per_shader_stage`.
205    pub max_storage_textures_in_fragment_stage: u32,
206    /// Amount of uniform buffers visible in a single shader stage. Defaults to 12. Higher is "better".
207    pub max_uniform_buffers_per_shader_stage: u32,
208    /// Amount of individual resources within binding arrays that can be accessed in a single shader stage. Applies
209    /// to all types of bindings except samplers.
210    ///
211    /// This "defaults" to 0. However if binding arrays are supported, all devices can support 500,000. Higher is "better".
212    pub max_binding_array_elements_per_shader_stage: u32,
213    /// Amount of individual acceleration structures within binding arrays that can be accessed in a single shader stage.
214    ///
215    /// This "defaults" to 0. Higher is "better".
216    pub max_binding_array_acceleration_structure_elements_per_shader_stage: u32,
217    /// Amount of individual samplers within binding arrays that can be accessed in a single shader stage.
218    ///
219    /// This "defaults" to 0. However if binding arrays are supported, all devices can support 1,000. Higher is "better".
220    pub max_binding_array_sampler_elements_per_shader_stage: u32,
221    /// Maximum size in bytes of a binding to a uniform buffer. Defaults to 64 KiB. Higher is "better".
222    pub max_uniform_buffer_binding_size: u64,
223    /// Maximum size in bytes of a binding to a storage buffer. Defaults to 128 MiB. Higher is "better".
224    pub max_storage_buffer_binding_size: u64,
225    /// Maximum length of `VertexState::buffers` when creating a `RenderPipeline`.
226    /// Defaults to 8. Higher is "better".
227    pub max_vertex_buffers: u32,
228    /// A limit above which buffer allocations are guaranteed to fail.
229    /// Defaults to 256 MiB. Higher is "better".
230    ///
231    /// Buffer allocations below the maximum buffer size may not succeed depending on available memory,
232    /// fragmentation and other factors.
233    pub max_buffer_size: u64,
234    /// Maximum length of `VertexBufferLayout::attributes`, summed over all `VertexState::buffers`,
235    /// when creating a `RenderPipeline`.
236    /// Defaults to 16. Higher is "better".
237    pub max_vertex_attributes: u32,
238    /// Maximum value for `VertexBufferLayout::array_stride` when creating a `RenderPipeline`.
239    /// Defaults to 2048. Higher is "better".
240    pub max_vertex_buffer_array_stride: u32,
241    /// Maximum value for the number of input or output variables for inter-stage communication
242    /// (like vertex outputs or fragment inputs) `@location(…)`s (in WGSL parlance)
243    /// when creating a `RenderPipeline`.
244    /// Defaults to 16. Higher is "better".
245    pub max_inter_stage_shader_variables: u32,
246    /// Required `BufferBindingType::Uniform` alignment for `BufferBinding::offset`
247    /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
248    /// Defaults to 256. Lower is "better".
249    pub min_uniform_buffer_offset_alignment: u32,
250    /// Required `BufferBindingType::Storage` alignment for `BufferBinding::offset`
251    /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
252    /// Defaults to 256. Lower is "better".
253    pub min_storage_buffer_offset_alignment: u32,
254    /// The maximum allowed number of color attachments.
255    pub max_color_attachments: u32,
256    /// The maximum number of bytes necessary to hold one sample (pixel or subpixel) of render
257    /// pipeline output data, across all color attachments as described by [`TextureFormat::target_pixel_byte_cost`]
258    /// and [`TextureFormat::target_component_alignment`]. Defaults to 32. Higher is "better".
259    ///
260    /// ⚠️ `Rgba8Unorm`/`Rgba8Snorm`/`Bgra8Unorm`/`Bgra8Snorm` are deceptively 8 bytes per sample. ⚠️
261    pub max_color_attachment_bytes_per_sample: u32,
262    /// Maximum number of bytes used for workgroup memory in a compute entry point. Defaults to
263    /// 16384. Higher is "better".
264    pub max_compute_workgroup_storage_size: u32,
265    /// Maximum value of the product of the `workgroup_size` dimensions for a compute entry-point.
266    /// Defaults to 256. Higher is "better".
267    pub max_compute_invocations_per_workgroup: u32,
268    /// The maximum value of the `workgroup_size` X dimension for a compute stage `ShaderModule` entry-point.
269    /// Defaults to 256. Higher is "better".
270    pub max_compute_workgroup_size_x: u32,
271    /// The maximum value of the `workgroup_size` Y dimension for a compute stage `ShaderModule` entry-point.
272    /// Defaults to 256. Higher is "better".
273    pub max_compute_workgroup_size_y: u32,
274    /// The maximum value of the `workgroup_size` Z dimension for a compute stage `ShaderModule` entry-point.
275    /// Defaults to 64. Higher is "better".
276    pub max_compute_workgroup_size_z: u32,
277    /// The maximum value for each dimension of a `ComputePass::dispatch_workgroups(x, y, z)` operation.
278    /// Defaults to 65535. Higher is "better".
279    pub max_compute_workgroups_per_dimension: u32,
280
281    /// Amount of storage available for immediates in bytes. Defaults to 0. Higher is "better".
282    /// Requesting more than 0 during device creation requires [`Features::IMMEDIATES`] to be enabled.
283    ///
284    /// Expect the size to be:
285    /// - Vulkan: 128-256 bytes
286    /// - DX12: 128 bytes
287    /// - Metal: 4096 bytes
288    /// - OpenGL doesn't natively support immediates, and are emulated with uniforms,
289    ///   so this number is less useful but likely 256.
290    pub max_immediate_size: u32,
291    /// Maximum number of live non-sampler bindings.
292    ///
293    /// <div class="warning">
294    /// The default value is **1_000_000**, On systems with integrated GPUs (iGPUs)—particularly on Windows using the D3D12
295    /// backend—this can lead to significant system RAM consumption since iGPUs share system memory directly with the CPU.
296    /// </div>
297    ///
298    /// This limit only affects the d3d12 backend. Using a large number will allow the device
299    /// to create many bind groups at the cost of a large up-front allocation at device creation.
300    pub max_non_sampler_bindings: u32,
301
302    /// The maximum total value for a `RenderPass::draw_mesh_tasks(x, y, z)` call on a mesh pipeline with a task shader.
303    /// Higher is "better".
304    pub max_task_workgroup_total_count: u32,
305    /// The maximum value for each dimension of a `RenderPass::draw_mesh_tasks(x, y, z)` call on a mesh pipeline with a task shader.
306    /// Higher is "better".
307    pub max_task_workgroups_per_dimension: u32,
308    /// The maximum product of arguments of a `RenderPass::draw_mesh_tasks(x, y, z)` operation on a mesh shader pipeline
309    /// without task shaders.
310    /// Also for task shader outputs. Higher is "better".
311    pub max_mesh_workgroup_total_count: u32,
312    /// The maximum value for each dimension of a `RenderPass::draw_mesh_tasks(x, y, z)` operation on a mesh shader pipeline
313    /// without task shaders.
314    /// Also for task shader outputs. Higher is "better".
315    pub max_mesh_workgroups_per_dimension: u32,
316    // These are fundamentally different. It is very common for limits on mesh shaders to be much lower.
317    /// Maximum total number of invocations, or threads, per task shader workgroup. Higher is "better".
318    pub max_task_invocations_per_workgroup: u32,
319    /// The maximum value for each dimension of a task shader's workgroup size. Higher is "better".
320    pub max_task_invocations_per_dimension: u32,
321    /// Maximum total number of invocations, or threads, per mesh shader workgroup. Higher is "better".
322    pub max_mesh_invocations_per_workgroup: u32,
323    /// The maximum value for each dimension of a mesh shader's workgroup size. Higher is "better".
324    pub max_mesh_invocations_per_dimension: u32,
325
326    /// The maximum size of the payload passed from task to mesh shader. Higher is "better".
327    pub max_task_payload_size: u32,
328    /// The maximum number of vertices that a mesh shader may output. Higher is "better".
329    pub max_mesh_output_vertices: u32,
330    /// The maximum number of primitives that a mesh shader may output. Higher is "better".
331    pub max_mesh_output_primitives: u32,
332    /// The maximum number of layers that can be output from a mesh shader. Higher is "better".
333    /// See [#8509](https://github.com/gfx-rs/wgpu/issues/8509).
334    pub max_mesh_output_layers: u32,
335    /// The maximum number of views that can be used by a mesh shader in multiview rendering.
336    /// Higher is "better".
337    pub max_mesh_multiview_view_count: u32,
338
339    /// The maximum number of primitive (ex: triangles, aabbs) a BLAS is allowed to have. Requesting
340    /// more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`]
341    /// is enabled.
342    pub max_blas_primitive_count: u32,
343    /// The maximum number of geometry descriptors a BLAS is allowed to have. Requesting
344    /// more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`]
345    /// is enabled.
346    pub max_blas_geometry_count: u32,
347    /// The maximum number of instances a TLAS is allowed to have. Requesting more than 0 during
348    /// device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`]
349    /// is enabled.
350    pub max_tlas_instance_count: u32,
351    /// The maximum number of acceleration structures allowed to be used in a shader stage.
352    /// Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_QUERY`]
353    /// is enabled.
354    pub max_acceleration_structures_per_shader_stage: u32,
355    /// The combined number of buffers (storage and uniform), vertex buffers, and acceleration
356    /// structures that can be bound in a single shader stage.
357    pub max_buffers_and_acceleration_structures_per_shader_stage: u32,
358
359    /// The maximum number of views that can be used in multiview rendering
360    pub max_multiview_view_count: u32,
361
362    /// The maximum total number (`x*y*z`) of rays able to be dispatched by a trace rays call in a ray
363    /// tracing pass. Requesting more than 0 during device creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]
364    /// is enabled.
365    pub max_ray_dispatch_count: u32,
366    /// The maximum number that one can pass into a ray tracing pipeline creation to be the maximum ray
367    /// recursion depth. (the maximum of the max ray recursion depth) Requesting more than 0 during device
368    /// creation only makes sense if [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`] is enabled.
369    pub max_ray_recursion_depth: u32,
370}
371
372impl Default for Limits {
373    fn default() -> Self {
374        Self::defaults()
375    }
376}
377
378impl Limits {
379    /// These default limits are guaranteed to work on all modern
380    /// backends and guaranteed to be supported by WebGPU
381    ///
382    /// Those limits are as follows:
383    /// ```rust
384    /// # use wgpu_types::Limits;
385    /// assert_eq!(Limits::defaults(), Limits {
386    ///     max_texture_dimension_1d: 8192,
387    ///     max_texture_dimension_2d: 8192,
388    ///     max_texture_dimension_3d: 2048,
389    ///     max_texture_array_layers: 256,
390    ///     max_bind_groups: 4,
391    ///     max_bind_groups_plus_vertex_buffers: 24,
392    ///     max_bindings_per_bind_group: 1000,
393    ///     max_dynamic_uniform_buffers_per_pipeline_layout: 8,
394    ///     max_dynamic_storage_buffers_per_pipeline_layout: 4,
395    ///     max_sampled_textures_per_shader_stage: 16,
396    ///     max_samplers_per_shader_stage: 16,
397    ///     max_storage_buffers_per_shader_stage: 8,
398    ///     max_storage_buffers_in_vertex_stage: 8,
399    ///     max_storage_buffers_in_fragment_stage: 8,
400    ///     max_storage_textures_per_shader_stage: 4,
401    ///     max_storage_textures_in_vertex_stage: 4,
402    ///     max_storage_textures_in_fragment_stage: 4,
403    ///     max_uniform_buffers_per_shader_stage: 12,
404    ///     max_binding_array_elements_per_shader_stage: 0,
405    ///     max_binding_array_acceleration_structure_elements_per_shader_stage: 0,
406    ///     max_binding_array_sampler_elements_per_shader_stage: 0,
407    ///     max_uniform_buffer_binding_size: 64 << 10, // (64 KiB)
408    ///     max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
409    ///     max_vertex_buffers: 8,
410    ///     max_buffer_size: 256 << 20, // (256 MiB)
411    ///     max_vertex_attributes: 16,
412    ///     max_vertex_buffer_array_stride: 2048,
413    ///     max_inter_stage_shader_variables: 16,
414    ///     min_uniform_buffer_offset_alignment: 256,
415    ///     min_storage_buffer_offset_alignment: 256,
416    ///     max_color_attachments: 8,
417    ///     max_color_attachment_bytes_per_sample: 32,
418    ///     max_compute_workgroup_storage_size: 16384,
419    ///     max_compute_invocations_per_workgroup: 256,
420    ///     max_compute_workgroup_size_x: 256,
421    ///     max_compute_workgroup_size_y: 256,
422    ///     max_compute_workgroup_size_z: 64,
423    ///     max_compute_workgroups_per_dimension: 65535,
424    ///     max_immediate_size: 0,
425    ///     max_non_sampler_bindings: 1_000_000,
426    ///     max_task_workgroup_total_count: 0,
427    ///     max_task_workgroups_per_dimension: 0,
428    ///     max_mesh_workgroup_total_count: 0,
429    ///     max_mesh_workgroups_per_dimension: 0,
430    ///     max_task_invocations_per_workgroup: 0,
431    ///     max_task_invocations_per_dimension: 0,
432    ///     max_mesh_invocations_per_workgroup: 0,
433    ///     max_mesh_invocations_per_dimension: 0,
434    ///     max_task_payload_size: 0,
435    ///     max_mesh_output_vertices: 0,
436    ///     max_mesh_output_primitives: 0,
437    ///     max_mesh_output_layers: 0,
438    ///     max_mesh_multiview_view_count: 0,
439    ///     max_blas_primitive_count: 0,
440    ///     max_blas_geometry_count: 0,
441    ///     max_tlas_instance_count: 0,
442    ///     max_acceleration_structures_per_shader_stage: 0,
443    ///     max_buffers_and_acceleration_structures_per_shader_stage: 28, // sum of storage buffers, uniform buffers and vertex buffers limits
444    ///     max_multiview_view_count: 0,
445    ///     max_ray_dispatch_count: 0,
446    ///     max_ray_recursion_depth: 0,
447    /// });
448    /// ```
449    ///
450    /// Rust doesn't allow const in trait implementations, so we break this out
451    /// to allow reusing these defaults in const contexts
452    #[must_use]
453    pub const fn defaults() -> Self {
454        Self {
455            max_texture_dimension_1d: 8192,
456            max_texture_dimension_2d: 8192,
457            max_texture_dimension_3d: 2048,
458            max_texture_array_layers: 256,
459            max_bind_groups: 4,
460            max_bind_groups_plus_vertex_buffers: 24,
461            max_bindings_per_bind_group: 1000,
462            max_dynamic_uniform_buffers_per_pipeline_layout: 8,
463            max_dynamic_storage_buffers_per_pipeline_layout: 4,
464            max_sampled_textures_per_shader_stage: 16,
465            max_samplers_per_shader_stage: 16,
466            max_storage_buffers_per_shader_stage: 8,
467            max_storage_buffers_in_vertex_stage: 8,
468            max_storage_buffers_in_fragment_stage: 8,
469            max_storage_textures_per_shader_stage: 4,
470            max_storage_textures_in_vertex_stage: 4,
471            max_storage_textures_in_fragment_stage: 4,
472            max_uniform_buffers_per_shader_stage: 12,
473            max_binding_array_elements_per_shader_stage: 0,
474            max_binding_array_acceleration_structure_elements_per_shader_stage: 0,
475            max_binding_array_sampler_elements_per_shader_stage: 0,
476            max_uniform_buffer_binding_size: 64 << 10, // (64 KiB)
477            max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
478            max_vertex_buffers: 8,
479            max_buffer_size: 256 << 20, // (256 MiB)
480            max_vertex_attributes: 16,
481            max_vertex_buffer_array_stride: 2048,
482            max_inter_stage_shader_variables: 16,
483            min_uniform_buffer_offset_alignment: 256,
484            min_storage_buffer_offset_alignment: 256,
485            max_color_attachments: 8,
486            max_color_attachment_bytes_per_sample: 32,
487            max_compute_workgroup_storage_size: 16384,
488            max_compute_invocations_per_workgroup: 256,
489            max_compute_workgroup_size_x: 256,
490            max_compute_workgroup_size_y: 256,
491            max_compute_workgroup_size_z: 64,
492            max_compute_workgroups_per_dimension: 65535,
493            max_immediate_size: 0,
494            max_non_sampler_bindings: 1_000_000,
495
496            max_task_workgroup_total_count: 0,
497            max_task_workgroups_per_dimension: 0,
498            max_mesh_workgroup_total_count: 0,
499            max_mesh_workgroups_per_dimension: 0,
500            max_task_invocations_per_workgroup: 0,
501            max_task_invocations_per_dimension: 0,
502            max_mesh_invocations_per_workgroup: 0,
503            max_mesh_invocations_per_dimension: 0,
504            max_task_payload_size: 0,
505            max_mesh_output_vertices: 0,
506            max_mesh_output_primitives: 0,
507            max_mesh_output_layers: 0,
508            max_mesh_multiview_view_count: 0,
509
510            max_blas_primitive_count: 0,
511            max_blas_geometry_count: 0,
512            max_tlas_instance_count: 0,
513            max_acceleration_structures_per_shader_stage: 0,
514            max_buffers_and_acceleration_structures_per_shader_stage: 28,
515
516            max_multiview_view_count: 0,
517
518            max_ray_dispatch_count: 0,
519            max_ray_recursion_depth: 0,
520        }
521    }
522
523    /// These default limits are guaranteed to be compatible with GLES-3.1.
524    ///
525    /// Those limits are as follows (different from default are marked with *):
526    /// ```rust
527    /// # use wgpu_types::Limits;
528    /// assert_eq!(Limits::downlevel_defaults(), Limits {
529    ///     max_texture_dimension_1d: 2048, // *
530    ///     max_texture_dimension_2d: 2048, // *
531    ///     max_texture_dimension_3d: 256, // *
532    ///     max_texture_array_layers: 256,
533    ///     max_bind_groups: 4,
534    ///     max_bind_groups_plus_vertex_buffers: 24,
535    ///     max_bindings_per_bind_group: 1000,
536    ///     max_dynamic_uniform_buffers_per_pipeline_layout: 8,
537    ///     max_dynamic_storage_buffers_per_pipeline_layout: 4,
538    ///     max_sampled_textures_per_shader_stage: 16,
539    ///     max_samplers_per_shader_stage: 16,
540    ///     max_storage_buffers_per_shader_stage: 4, // *
541    ///     max_storage_buffers_in_vertex_stage: 4, // *
542    ///     max_storage_buffers_in_fragment_stage: 4, // *
543    ///     max_storage_textures_per_shader_stage: 4,
544    ///     max_storage_textures_in_vertex_stage: 4,
545    ///     max_storage_textures_in_fragment_stage: 4,
546    ///     max_uniform_buffers_per_shader_stage: 12,
547    ///     max_binding_array_elements_per_shader_stage: 0,
548    ///     max_binding_array_acceleration_structure_elements_per_shader_stage: 0,
549    ///     max_binding_array_sampler_elements_per_shader_stage: 0,
550    ///     max_uniform_buffer_binding_size: 16 << 10, // * (16 KiB)
551    ///     max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
552    ///     max_vertex_buffers: 8,
553    ///     max_vertex_attributes: 16,
554    ///     max_vertex_buffer_array_stride: 2048,
555    ///     max_immediate_size: 0,
556    ///     min_uniform_buffer_offset_alignment: 256,
557    ///     min_storage_buffer_offset_alignment: 256,
558    ///     max_inter_stage_shader_variables: 15,
559    ///     max_color_attachments: 4,
560    ///     max_color_attachment_bytes_per_sample: 32,
561    ///     max_compute_workgroup_storage_size: 16352, // *
562    ///     max_compute_invocations_per_workgroup: 256,
563    ///     max_compute_workgroup_size_x: 256,
564    ///     max_compute_workgroup_size_y: 256,
565    ///     max_compute_workgroup_size_z: 64,
566    ///     max_compute_workgroups_per_dimension: 65535,
567    ///     max_buffer_size: 256 << 20, // (256 MiB)
568    ///     max_non_sampler_bindings: 1_000_000,
569    ///
570    ///     max_task_workgroup_total_count: 0,
571    ///     max_task_workgroups_per_dimension: 0,
572    ///     max_mesh_workgroup_total_count: 0,
573    ///     max_mesh_workgroups_per_dimension: 0,
574    ///     max_task_invocations_per_workgroup: 0,
575    ///     max_task_invocations_per_dimension: 0,
576    ///     max_mesh_invocations_per_workgroup: 0,
577    ///     max_mesh_invocations_per_dimension: 0,
578    ///     max_task_payload_size: 0,
579    ///     max_mesh_output_vertices: 0,
580    ///     max_mesh_output_primitives: 0,
581    ///     max_mesh_output_layers: 0,
582    ///     max_mesh_multiview_view_count: 0,
583    ///
584    ///     max_blas_primitive_count: 0,
585    ///     max_blas_geometry_count: 0,
586    ///     max_tlas_instance_count: 0,
587    ///     max_acceleration_structures_per_shader_stage: 0,
588    ///     max_buffers_and_acceleration_structures_per_shader_stage: 24, // * sum of storage buffers, uniform buffers and vertex buffers limits
589    ///
590    ///     max_multiview_view_count: 0,
591    ///
592    ///     max_ray_dispatch_count: 0,
593    ///     max_ray_recursion_depth: 0,
594    /// });
595    /// ```
596    #[must_use]
597    pub const fn downlevel_defaults() -> Self {
598        Self {
599            max_texture_dimension_1d: 2048,
600            max_texture_dimension_2d: 2048,
601            max_texture_dimension_3d: 256,
602            max_storage_buffers_per_shader_stage: 4,
603            max_storage_buffers_in_vertex_stage: 4,
604            max_storage_buffers_in_fragment_stage: 4,
605            max_uniform_buffer_binding_size: 16 << 10, // (16 KiB)
606            max_inter_stage_shader_variables: 15,
607            max_color_attachments: 4,
608            // see: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7
609            max_compute_workgroup_storage_size: 16352,
610            max_buffers_and_acceleration_structures_per_shader_stage: 24,
611            ..Self::defaults()
612        }
613    }
614
615    /// These default limits are guaranteed to be compatible with GLES-3.0 and WebGL2
616    ///
617    /// Those limits are as follows (different from `downlevel_defaults` are marked with +,
618    /// *'s from `downlevel_defaults` shown as well.):
619    /// ```rust
620    /// # use wgpu_types::Limits;
621    /// assert_eq!(Limits::downlevel_webgl2_defaults(), Limits {
622    ///     max_texture_dimension_1d: 2048, // *
623    ///     max_texture_dimension_2d: 2048, // *
624    ///     max_texture_dimension_3d: 256, // *
625    ///     max_texture_array_layers: 256,
626    ///     max_bind_groups: 4,
627    ///     max_bind_groups_plus_vertex_buffers: 24,
628    ///     max_bindings_per_bind_group: 1000,
629    ///     max_dynamic_uniform_buffers_per_pipeline_layout: 8,
630    ///     max_dynamic_storage_buffers_per_pipeline_layout: 0, // +
631    ///     max_sampled_textures_per_shader_stage: 16,
632    ///     max_samplers_per_shader_stage: 16,
633    ///     max_storage_buffers_per_shader_stage: 0, // * +
634    ///     max_storage_buffers_in_vertex_stage: 0, // * +
635    ///     max_storage_buffers_in_fragment_stage: 0, // * +
636    ///     max_storage_textures_per_shader_stage: 0, // +
637    ///     max_storage_textures_in_vertex_stage: 0, // +
638    ///     max_storage_textures_in_fragment_stage: 0, // +
639    ///     max_uniform_buffers_per_shader_stage: 11, // +
640    ///     max_binding_array_elements_per_shader_stage: 0,
641    ///     max_binding_array_acceleration_structure_elements_per_shader_stage: 0,
642    ///     max_binding_array_sampler_elements_per_shader_stage: 0,
643    ///     max_uniform_buffer_binding_size: 16 << 10, // * (16 KiB)
644    ///     max_storage_buffer_binding_size: 0, // * +
645    ///     max_vertex_buffers: 8,
646    ///     max_vertex_attributes: 16,
647    ///     max_vertex_buffer_array_stride: 255, // +
648    ///     max_immediate_size: 0,
649    ///     min_uniform_buffer_offset_alignment: 256,
650    ///     min_storage_buffer_offset_alignment: 256,
651    ///     max_inter_stage_shader_variables: 15,
652    ///     max_color_attachments: 4,
653    ///     max_color_attachment_bytes_per_sample: 32,
654    ///     max_compute_workgroup_storage_size: 0, // +
655    ///     max_compute_invocations_per_workgroup: 0, // +
656    ///     max_compute_workgroup_size_x: 0, // +
657    ///     max_compute_workgroup_size_y: 0, // +
658    ///     max_compute_workgroup_size_z: 0, // +
659    ///     max_compute_workgroups_per_dimension: 0, // +
660    ///     max_buffer_size: 256 << 20, // (256 MiB),
661    ///     max_non_sampler_bindings: 1_000_000,
662    ///
663    ///     max_task_workgroup_total_count: 0,
664    ///     max_task_workgroups_per_dimension: 0,
665    ///     max_mesh_workgroup_total_count: 0,
666    ///     max_mesh_workgroups_per_dimension: 0,
667    ///     max_task_invocations_per_workgroup: 0,
668    ///     max_task_invocations_per_dimension: 0,
669    ///     max_mesh_invocations_per_workgroup: 0,
670    ///     max_mesh_invocations_per_dimension: 0,
671    ///     max_task_payload_size: 0,
672    ///     max_mesh_output_vertices: 0,
673    ///     max_mesh_output_primitives: 0,
674    ///     max_mesh_output_layers: 0,
675    ///     max_mesh_multiview_view_count: 0,
676    ///
677    ///     max_blas_primitive_count: 0,
678    ///     max_blas_geometry_count: 0,
679    ///     max_tlas_instance_count: 0,
680    ///     max_acceleration_structures_per_shader_stage: 0,
681    ///     max_buffers_and_acceleration_structures_per_shader_stage: 19, // * sum of storage buffers, uniform buffers and vertex buffers limits
682    ///
683    ///     max_multiview_view_count: 0,
684    ///
685    ///     max_ray_dispatch_count: 0,
686    ///     max_ray_recursion_depth: 0,
687    /// });
688    /// ```
689    #[must_use]
690    pub const fn downlevel_webgl2_defaults() -> Self {
691        Self {
692            max_uniform_buffers_per_shader_stage: 11,
693            max_storage_buffers_per_shader_stage: 0,
694            max_storage_buffers_in_vertex_stage: 0,
695            max_storage_buffers_in_fragment_stage: 0,
696            max_storage_textures_per_shader_stage: 0,
697            max_storage_textures_in_vertex_stage: 0,
698            max_storage_textures_in_fragment_stage: 0,
699            max_dynamic_storage_buffers_per_pipeline_layout: 0,
700            max_storage_buffer_binding_size: 0,
701            max_vertex_buffer_array_stride: 255,
702            max_compute_workgroup_storage_size: 0,
703            max_compute_invocations_per_workgroup: 0,
704            max_compute_workgroup_size_x: 0,
705            max_compute_workgroup_size_y: 0,
706            max_compute_workgroup_size_z: 0,
707            max_compute_workgroups_per_dimension: 0,
708
709            // Value supported by Intel Celeron B830 on Windows (OpenGL 3.1)
710            max_inter_stage_shader_variables: 15,
711
712            max_buffers_and_acceleration_structures_per_shader_stage: 19,
713
714            // Most of the values should be the same as the downlevel defaults
715            ..Self::downlevel_defaults()
716        }
717    }
718
719    /// Sets each limit to `i32::MAX` (or 1, in the case of lower-is-better limits).
720    ///
721    /// These values do not reflect the capabilities of any actual device. They are
722    /// used by the noop backend, and by the test that makes sure `with_limits!` is
723    /// exhaustive.
724    #[must_use]
725    pub const fn unlimited() -> Self {
726        /// Guaranteed to be no bigger than isize::MAX which is the maximum size of an allocation,
727        /// except on 16-bit platforms which we certainly don’t fit in.
728        const ALLOC_MAX_U32: u32 = i32::MAX as u32;
729        /// Guaranteed to be no bigger than isize::MAX which is the maximum size of an allocation,
730        /// except on 16-bit platforms which we certainly don’t fit in.
731        const ALLOC_MAX_U64: u64 = i32::MAX as u64;
732
733        Self {
734            max_texture_dimension_1d: ALLOC_MAX_U32,
735            max_texture_dimension_2d: ALLOC_MAX_U32,
736            max_texture_dimension_3d: ALLOC_MAX_U32,
737            max_texture_array_layers: ALLOC_MAX_U32,
738            max_bind_groups: ALLOC_MAX_U32,
739            max_bind_groups_plus_vertex_buffers: ALLOC_MAX_U32,
740            max_bindings_per_bind_group: ALLOC_MAX_U32,
741            max_dynamic_uniform_buffers_per_pipeline_layout: ALLOC_MAX_U32,
742            max_dynamic_storage_buffers_per_pipeline_layout: ALLOC_MAX_U32,
743            max_sampled_textures_per_shader_stage: ALLOC_MAX_U32,
744            max_samplers_per_shader_stage: ALLOC_MAX_U32,
745            max_storage_buffers_per_shader_stage: ALLOC_MAX_U32,
746            max_storage_buffers_in_vertex_stage: ALLOC_MAX_U32,
747            max_storage_buffers_in_fragment_stage: ALLOC_MAX_U32,
748            max_storage_textures_per_shader_stage: ALLOC_MAX_U32,
749            max_storage_textures_in_vertex_stage: ALLOC_MAX_U32,
750            max_storage_textures_in_fragment_stage: ALLOC_MAX_U32,
751            max_uniform_buffers_per_shader_stage: ALLOC_MAX_U32,
752            max_binding_array_elements_per_shader_stage: ALLOC_MAX_U32,
753            max_binding_array_sampler_elements_per_shader_stage: ALLOC_MAX_U32,
754            max_binding_array_acceleration_structure_elements_per_shader_stage: ALLOC_MAX_U32,
755            max_uniform_buffer_binding_size: ALLOC_MAX_U64,
756            max_storage_buffer_binding_size: ALLOC_MAX_U64,
757            max_vertex_buffers: ALLOC_MAX_U32,
758            max_buffer_size: ALLOC_MAX_U64,
759            max_vertex_attributes: ALLOC_MAX_U32,
760            max_vertex_buffer_array_stride: ALLOC_MAX_U32,
761            max_inter_stage_shader_variables: ALLOC_MAX_U32,
762            min_uniform_buffer_offset_alignment: 1,
763            min_storage_buffer_offset_alignment: 1,
764            max_color_attachments: ALLOC_MAX_U32,
765            max_color_attachment_bytes_per_sample: ALLOC_MAX_U32,
766            max_compute_workgroup_storage_size: ALLOC_MAX_U32,
767            max_compute_invocations_per_workgroup: ALLOC_MAX_U32,
768            max_compute_workgroup_size_x: ALLOC_MAX_U32,
769            max_compute_workgroup_size_y: ALLOC_MAX_U32,
770            max_compute_workgroup_size_z: ALLOC_MAX_U32,
771            max_compute_workgroups_per_dimension: ALLOC_MAX_U32,
772            max_immediate_size: ALLOC_MAX_U32,
773            max_non_sampler_bindings: ALLOC_MAX_U32,
774
775            max_task_workgroup_total_count: ALLOC_MAX_U32,
776            max_task_workgroups_per_dimension: ALLOC_MAX_U32,
777            max_mesh_workgroup_total_count: ALLOC_MAX_U32,
778            max_mesh_workgroups_per_dimension: ALLOC_MAX_U32,
779            max_task_invocations_per_workgroup: ALLOC_MAX_U32,
780            max_task_invocations_per_dimension: ALLOC_MAX_U32,
781            max_mesh_invocations_per_workgroup: ALLOC_MAX_U32,
782            max_mesh_invocations_per_dimension: ALLOC_MAX_U32,
783            max_task_payload_size: ALLOC_MAX_U32,
784            max_mesh_output_vertices: ALLOC_MAX_U32,
785            max_mesh_output_primitives: ALLOC_MAX_U32,
786            max_mesh_output_layers: ALLOC_MAX_U32,
787            max_mesh_multiview_view_count: ALLOC_MAX_U32,
788
789            max_blas_primitive_count: ALLOC_MAX_U32,
790            max_blas_geometry_count: ALLOC_MAX_U32,
791            max_tlas_instance_count: ALLOC_MAX_U32,
792            max_acceleration_structures_per_shader_stage: ALLOC_MAX_U32,
793            max_buffers_and_acceleration_structures_per_shader_stage: ALLOC_MAX_U32,
794
795            max_multiview_view_count: ALLOC_MAX_U32,
796            max_ray_dispatch_count: ALLOC_MAX_U32,
797            max_ray_recursion_depth: ALLOC_MAX_U32,
798        }
799    }
800
801    /// Modify the current limits to use the resolution limits of the other.
802    ///
803    /// This is useful because the swapchain might need to be larger than any other image in the application.
804    ///
805    /// If your application only needs 512x512, you might be running on a 4k display and need extremely high resolution limits.
806    #[must_use]
807    pub const fn using_resolution(self, other: Self) -> Self {
808        Self {
809            max_texture_dimension_1d: other.max_texture_dimension_1d,
810            max_texture_dimension_2d: other.max_texture_dimension_2d,
811            max_texture_dimension_3d: other.max_texture_dimension_3d,
812            ..self
813        }
814    }
815
816    /// Modify the current limits to use the buffer alignment limits of the adapter.
817    ///
818    /// This is useful for when you'd like to dynamically use the "best" supported buffer alignments.
819    #[must_use]
820    pub const fn using_alignment(self, other: Self) -> Self {
821        Self {
822            min_uniform_buffer_offset_alignment: other.min_uniform_buffer_offset_alignment,
823            min_storage_buffer_offset_alignment: other.min_storage_buffer_offset_alignment,
824            ..self
825        }
826    }
827
828    /// The minimum guaranteed limits for acceleration structures if you enable [`Features::EXPERIMENTAL_RAY_QUERY`]
829    #[must_use]
830    pub const fn using_minimum_supported_acceleration_structure_values(self) -> Self {
831        Self {
832            max_blas_geometry_count: (1 << 24) - 1, // 2^24 - 1: Vulkan's minimum
833            max_tlas_instance_count: (1 << 24) - 1, // 2^24 - 1: Vulkan's minimum
834            max_blas_primitive_count: 1 << 28,      // 2^28: Metal's minimum
835            // On metal acceleration structures are limited because they share buffer slots
836            max_acceleration_structures_per_shader_stage: 1,
837            max_buffers_and_acceleration_structures_per_shader_stage: 29,
838            ..self
839        }
840    }
841
842    /// Modify the current limits to use the acceleration structure limits of `other` (`other` could
843    /// be the limits of the adapter).
844    #[must_use]
845    pub const fn using_acceleration_structure_values(self, other: Self) -> Self {
846        Self {
847            max_blas_geometry_count: other.max_blas_geometry_count,
848            max_tlas_instance_count: other.max_tlas_instance_count,
849            max_blas_primitive_count: other.max_blas_primitive_count,
850            max_acceleration_structures_per_shader_stage: other
851                .max_acceleration_structures_per_shader_stage,
852            max_buffers_and_acceleration_structures_per_shader_stage: other
853                .max_buffers_and_acceleration_structures_per_shader_stage,
854            ..self
855        }
856    }
857
858    /// The minimum guaranteed limits for acceleration structures if you enable [`Features::EXPERIMENTAL_RAY_TRACING_PIPELINES`]
859    /// These may change in the future (including downwards).
860    #[must_use]
861    pub const fn using_minimum_supported_ray_tracing_pipeline_values(self) -> Self {
862        Self {
863            max_ray_dispatch_count: 1 << 30,
864            max_ray_recursion_depth: 1,
865            ..self
866        }
867    }
868
869    /// The recommended minimum limits for mesh shaders if you enable [`Features::EXPERIMENTAL_MESH_SHADER`]
870    ///
871    /// These are chosen somewhat arbitrarily. They are small enough that they should cover all physical devices,
872    /// but not necessarily all use cases.
873    #[must_use]
874    pub const fn using_recommended_minimum_mesh_shader_values(self) -> Self {
875        Self {
876            // These are DirectX limitations (both nvidia and AMD match these exactly on vulkan)
877            // Note that Mac2 (newest intel macs) support up to 1024, but this is low enough,
878            // to make use of mesh shaders nonviable in most cases.
879            // We therefore, don't expose mesh shading on these devices.
880            // In contrast, here is no limit for any A-series or M-series chip.
881            max_task_workgroup_total_count: 2u32.pow(22),
882            max_task_workgroups_per_dimension: 65535,
883            // These are metal limitations
884            // M3 ups both of these to 1M
885            max_mesh_workgroup_total_count: 1024,
886            max_mesh_workgroups_per_dimension: 1024,
887            // Nvidia limit on vulkan
888            max_task_invocations_per_workgroup: 128,
889            max_task_invocations_per_dimension: 64,
890
891            // DX12 limitation, revisit for vulkan
892            max_mesh_invocations_per_workgroup: 128,
893            max_mesh_invocations_per_dimension: 128,
894
895            // Metal specifies this as its max
896            max_task_payload_size: 16384 - 32,
897            // DX12 limitation, revisit for vulkan
898            max_mesh_output_vertices: 256,
899            max_mesh_output_primitives: 256,
900            // llvmpipe once again requires this to be 8. An RTX 3060 supports well over 1024.
901            // Also DX12 vaguely suggests going over this is illegal in some cases.
902            max_mesh_output_layers: 8,
903            // llvmpipe reports 0 multiview count, which just means no multiview is allowed
904            max_mesh_multiview_view_count: 0,
905            ..self
906        }
907    }
908
909    /// Compares every limits within self is within the limits given in `allowed`.
910    ///
911    /// If you need detailed information on failures, look at [`Limits::check_limits_with_fail_fn`].
912    #[must_use]
913    pub fn check_limits(&self, allowed: &Self) -> bool {
914        let mut within = true;
915        self.check_limits_with_fail_fn(allowed, true, |_, _, _| within = false);
916        within
917    }
918
919    /// Compares every limits within self is within the limits given in `allowed`.
920    /// For an easy to use binary choice, use [`Limits::check_limits`].
921    ///
922    /// If a value is not within the allowed limit, this function calls the `fail_fn`
923    /// with the:
924    ///  - limit name
925    ///  - self's limit
926    ///  - allowed's limit.
927    ///
928    /// If fatal is true, a single failure bails out the comparison after a single failure.
929    pub fn check_limits_with_fail_fn(
930        &self,
931        allowed: &Self,
932        fatal: bool,
933        mut fail_fn: impl FnMut(&'static str, u64, u64),
934    ) {
935        macro_rules! check_with_fail_fn {
936            ($name:ident, $ordering:expr) => {
937                let invalid_ord = $ordering.reverse();
938                if self.$name.cmp(&allowed.$name) == invalid_ord {
939                    fail_fn(stringify!($name), self.$name as u64, allowed.$name as u64);
940                    if fatal {
941                        return;
942                    }
943                }
944            };
945        }
946
947        with_limits!(check_with_fail_fn);
948    }
949
950    /// For each limit in `other` that is better than the value in `self`,
951    /// replace the value in `self` with the value from `other`.
952    ///
953    /// A request for a limit value less than the WebGPU-specified default must
954    /// be ignored. This function is used to clamp such requests to the default
955    /// value.
956    ///
957    /// This function is not for clamping requests for values beyond the
958    /// supported limits. For that purpose the desired function would be
959    /// `or_worse_values_from`.
960    #[must_use]
961    pub fn or_better_values_from(mut self, other: &Self) -> Self {
962        macro_rules! or_better_value_from {
963            ($name:ident, $ordering:expr) => {
964                match $ordering {
965                    // Limits that are maximum values (most of them)
966                    Ordering::Less => self.$name = self.$name.max(other.$name),
967                    // Limits that are minimum values
968                    Ordering::Greater => self.$name = self.$name.min(other.$name),
969                    Ordering::Equal => unreachable!(),
970                }
971            };
972        }
973
974        with_limits!(or_better_value_from);
975
976        self
977    }
978
979    /// For each limit in `other` that is worse than the value in `self`,
980    /// replace the value in `self` with the value from `other`.
981    ///
982    /// This function is for clamping requests for values beyond the
983    /// supported limits.
984    #[must_use]
985    pub fn or_worse_values_from(mut self, other: &Self) -> Self {
986        macro_rules! or_worse_value_from {
987            ($name:ident, $ordering:expr) => {
988                match $ordering {
989                    // Limits that are maximum values (most of them)
990                    Ordering::Less => self.$name = self.$name.min(other.$name),
991                    // Limits that are minimum values
992                    Ordering::Greater => self.$name = self.$name.max(other.$name),
993                    Ordering::Equal => unreachable!(),
994                }
995            };
996        }
997
998        with_limits!(or_worse_value_from);
999
1000        self
1001    }
1002
1003    /// Sets all native-only limits to zero, except for `max_non_sampler_bindings`.
1004    pub fn zero_native_only(&mut self) {
1005        let Self {
1006            max_texture_dimension_1d: _,
1007            max_texture_dimension_2d: _,
1008            max_texture_dimension_3d: _,
1009            max_texture_array_layers: _,
1010            max_bind_groups: _,
1011            max_bind_groups_plus_vertex_buffers: _,
1012            max_bindings_per_bind_group: _,
1013            max_dynamic_uniform_buffers_per_pipeline_layout: _,
1014            max_dynamic_storage_buffers_per_pipeline_layout: _,
1015            max_sampled_textures_per_shader_stage: _,
1016            max_samplers_per_shader_stage: _,
1017            max_storage_buffers_per_shader_stage: _,
1018            max_storage_buffers_in_vertex_stage: _,
1019            max_storage_buffers_in_fragment_stage: _,
1020            max_storage_textures_per_shader_stage: _,
1021            max_storage_textures_in_vertex_stage: _,
1022            max_storage_textures_in_fragment_stage: _,
1023            max_uniform_buffers_per_shader_stage: _,
1024            max_uniform_buffer_binding_size: _,
1025            max_storage_buffer_binding_size: _,
1026            max_vertex_buffers: _,
1027            max_buffer_size: _,
1028            max_vertex_attributes: _,
1029            max_vertex_buffer_array_stride: _,
1030            max_inter_stage_shader_variables: _,
1031            min_uniform_buffer_offset_alignment: _,
1032            min_storage_buffer_offset_alignment: _,
1033            max_color_attachments: _,
1034            max_color_attachment_bytes_per_sample: _,
1035            max_compute_workgroup_storage_size: _,
1036            max_compute_invocations_per_workgroup: _,
1037            max_compute_workgroup_size_x: _,
1038            max_compute_workgroup_size_y: _,
1039            max_compute_workgroup_size_z: _,
1040            max_compute_workgroups_per_dimension: _,
1041            max_immediate_size: _,
1042            max_non_sampler_bindings: _, // This is more of an internal setting rather than a limit and it can't be 0.
1043
1044            max_binding_array_elements_per_shader_stage,
1045            max_binding_array_acceleration_structure_elements_per_shader_stage,
1046            max_binding_array_sampler_elements_per_shader_stage,
1047            max_task_workgroup_total_count,
1048            max_task_workgroups_per_dimension,
1049            max_mesh_workgroup_total_count,
1050            max_mesh_workgroups_per_dimension,
1051            max_task_invocations_per_workgroup,
1052            max_task_invocations_per_dimension,
1053            max_mesh_invocations_per_workgroup,
1054            max_mesh_invocations_per_dimension,
1055            max_task_payload_size,
1056            max_mesh_output_vertices,
1057            max_mesh_output_primitives,
1058            max_mesh_output_layers,
1059            max_mesh_multiview_view_count,
1060            max_blas_primitive_count,
1061            max_blas_geometry_count,
1062            max_tlas_instance_count,
1063            max_acceleration_structures_per_shader_stage,
1064            max_buffers_and_acceleration_structures_per_shader_stage,
1065            max_multiview_view_count,
1066            max_ray_dispatch_count,
1067            max_ray_recursion_depth,
1068        } = self;
1069        *max_binding_array_elements_per_shader_stage = 0;
1070        *max_binding_array_acceleration_structure_elements_per_shader_stage = 0;
1071        *max_binding_array_sampler_elements_per_shader_stage = 0;
1072        *max_task_workgroup_total_count = 0;
1073        *max_task_workgroups_per_dimension = 0;
1074        *max_mesh_workgroup_total_count = 0;
1075        *max_mesh_workgroups_per_dimension = 0;
1076        *max_task_invocations_per_workgroup = 0;
1077        *max_task_invocations_per_dimension = 0;
1078        *max_mesh_invocations_per_workgroup = 0;
1079        *max_mesh_invocations_per_dimension = 0;
1080        *max_task_payload_size = 0;
1081        *max_mesh_output_vertices = 0;
1082        *max_mesh_output_primitives = 0;
1083        *max_mesh_output_layers = 0;
1084        *max_mesh_multiview_view_count = 0;
1085        *max_blas_primitive_count = 0;
1086        *max_blas_geometry_count = 0;
1087        *max_tlas_instance_count = 0;
1088        *max_acceleration_structures_per_shader_stage = 0;
1089        *max_buffers_and_acceleration_structures_per_shader_stage = 0;
1090        *max_multiview_view_count = 0;
1091        *max_ray_dispatch_count = 0;
1092        *max_ray_recursion_depth = 0;
1093    }
1094}
1095
1096/// Represents the sets of additional limits on an adapter,
1097/// which take place when running on downlevel backends.
1098#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1099#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1100pub struct DownlevelLimits {}
1101
1102/// Lists various ways the underlying platform does not conform to the WebGPU standard.
1103#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1105pub struct DownlevelCapabilities {
1106    /// Combined boolean flags.
1107    pub flags: DownlevelFlags,
1108    /// Additional limits
1109    pub limits: DownlevelLimits,
1110    /// Which collections of features shaders support. Defined in terms of D3D's shader models.
1111    pub shader_model: ShaderModel,
1112}
1113
1114impl Default for DownlevelCapabilities {
1115    fn default() -> Self {
1116        Self {
1117            flags: DownlevelFlags::all(),
1118            limits: DownlevelLimits::default(),
1119            shader_model: ShaderModel::Sm5,
1120        }
1121    }
1122}
1123
1124impl DownlevelCapabilities {
1125    /// Returns true if the underlying platform offers complete support of the baseline WebGPU standard.
1126    ///
1127    /// If this returns false, some parts of the API will result in validation errors where they would not normally.
1128    /// These parts can be determined by the values in this structure.
1129    #[must_use]
1130    pub fn is_webgpu_compliant(&self) -> bool {
1131        self.flags.contains(DownlevelFlags::compliant())
1132            && self.limits == DownlevelLimits::default()
1133            && self.shader_model >= ShaderModel::Sm5
1134    }
1135}
1136
1137bitflags::bitflags! {
1138    /// Binary flags listing features that may or may not be present on downlevel adapters.
1139    ///
1140    /// A downlevel adapter is a GPU adapter that wgpu supports, but with potentially limited
1141    /// features, due to the lack of hardware feature support.
1142    ///
1143    /// Flags that are **not** present for a downlevel adapter or device usually indicates
1144    /// non-compliance with the WebGPU specification, but not always.
1145    ///
1146    /// You can check whether a set of flags is compliant through the
1147    /// [`DownlevelCapabilities::is_webgpu_compliant()`] function.
1148    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1149    #[cfg_attr(feature = "serde", serde(transparent))]
1150    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1151    pub struct DownlevelFlags: u32 {
1152        /// The device supports compiling and using compute shaders.
1153        ///
1154        /// WebGL2, and GLES3.0 devices do not support compute.
1155        const COMPUTE_SHADERS = 1 << 0;
1156        /// Supports binding storage buffers and textures to fragment shaders.
1157        const FRAGMENT_WRITABLE_STORAGE = 1 << 1;
1158        /// Supports indirect drawing and dispatching.
1159        ///
1160        /// [`Self::COMPUTE_SHADERS`] must be present for this flag.
1161        ///
1162        /// WebGL2, GLES 3.0, and Metal on Apple1/Apple2 GPUs do not support indirect.
1163        const INDIRECT_EXECUTION = 1 << 2;
1164        /// Supports non-zero `base_vertex` parameter to direct indexed draw calls.
1165        ///
1166        /// Indirect calls, if supported, always support non-zero `base_vertex`.
1167        ///
1168        /// Supported by:
1169        /// - Vulkan
1170        /// - DX12
1171        /// - Metal on Apple3+ or Mac1+
1172        /// - OpenGL 3.2+
1173        /// - OpenGL ES 3.2
1174        const BASE_VERTEX = 1 << 3;
1175        /// Supports reading from a depth/stencil texture while using it as a read-only
1176        /// depth/stencil attachment.
1177        ///
1178        /// The WebGL2 and GLES backends do not support RODS.
1179        const READ_ONLY_DEPTH_STENCIL = 1 << 4;
1180        /// Supports textures with mipmaps which have a non power of two size.
1181        const NON_POWER_OF_TWO_MIPMAPPED_TEXTURES = 1 << 5;
1182        /// Supports textures that are cube arrays.
1183        const CUBE_ARRAY_TEXTURES = 1 << 6;
1184        /// Supports comparison samplers.
1185        const COMPARISON_SAMPLERS = 1 << 7;
1186        /// Supports different blend operations per color attachment.
1187        const INDEPENDENT_BLEND = 1 << 8;
1188        /// Supports storage buffers in vertex shaders.
1189        const VERTEX_STORAGE = 1 << 9;
1190
1191        /// Supports samplers with anisotropic filtering. Note this isn't actually required by
1192        /// WebGPU, the implementation is allowed to completely ignore aniso clamp. This flag is
1193        /// here for native backends so they can communicate to the user of aniso is enabled.
1194        ///
1195        /// All backends and all devices support anisotropic filtering.
1196        const ANISOTROPIC_FILTERING = 1 << 10;
1197
1198        /// Supports storage buffers in fragment shaders.
1199        const FRAGMENT_STORAGE = 1 << 11;
1200
1201        /// Supports sample-rate shading.
1202        const MULTISAMPLED_SHADING = 1 << 12;
1203
1204        /// Supports copies between depth textures and buffers.
1205        ///
1206        /// GLES/WebGL don't support this.
1207        const DEPTH_TEXTURE_AND_BUFFER_COPIES = 1 << 13;
1208
1209        /// Supports all the texture usages described in WebGPU. If this isn't supported, you
1210        /// should call `get_texture_format_features` to get how you can use textures of a given format
1211        const WEBGPU_TEXTURE_FORMAT_SUPPORT = 1 << 14;
1212
1213        /// Supports buffer bindings with sizes that aren't a multiple of 16.
1214        ///
1215        /// WebGL doesn't support this.
1216        const BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED = 1 << 15;
1217
1218        /// Supports buffers to combine [`BufferUsages::INDEX`] with usages other than [`BufferUsages::COPY_DST`] and [`BufferUsages::COPY_SRC`].
1219        /// Furthermore, in absence of this feature it is not allowed to copy index buffers from/to buffers with a set of usage flags containing
1220        /// [`BufferUsages::VERTEX`]/[`BufferUsages::UNIFORM`]/[`BufferUsages::STORAGE`] or [`BufferUsages::INDIRECT`].
1221        ///
1222        /// WebGL doesn't support this.
1223        const UNRESTRICTED_INDEX_BUFFER = 1 << 16;
1224
1225        /// Supports full 32-bit range indices (2^32-1 as opposed to 2^24-1 without this flag)
1226        ///
1227        /// Corresponds to Vulkan's `VkPhysicalDeviceFeatures.fullDrawIndexUint32`
1228        const FULL_DRAW_INDEX_UINT32 = 1 << 17;
1229
1230        /// Supports depth bias clamping
1231        ///
1232        /// Corresponds to Vulkan's `VkPhysicalDeviceFeatures.depthBiasClamp`
1233        const DEPTH_BIAS_CLAMP = 1 << 18;
1234
1235        /// Supports specifying which view format values are allowed when create_view() is called on a texture.
1236        ///
1237        /// The WebGL and GLES backends doesn't support this.
1238        const VIEW_FORMATS = 1 << 19;
1239
1240        /// With this feature not present, there are the following restrictions on `Queue::copy_external_image_to_texture`:
1241        /// - [`CopyExternalImageSourceInfo::origin`] must be zero.
1242        /// - [`CopyExternalImageDestInfo::color_space`] must be srgb.
1243        /// - If the source is an [`web_sys::ImageBitmap`]:
1244        ///   - [`CopyExternalImageSourceInfo::flip_y`] must be false.
1245        ///   - [`CopyExternalImageDestInfo::premultiplied_alpha`] must be false.
1246        ///
1247        /// WebGL doesn't support this. WebGPU does.
1248        const UNRESTRICTED_EXTERNAL_TEXTURE_COPIES = 1 << 20;
1249
1250        /// Supports specifying which view formats are allowed when calling create_view on the texture returned by
1251        /// `Surface::get_current_texture`.
1252        ///
1253        /// The GLES/WebGL and Vulkan on Android doesn't support this.
1254        const SURFACE_VIEW_FORMATS = 1 << 21;
1255
1256        /// If this is true, calls to `CommandEncoder::resolve_query_set` will be performed on the queue timeline.
1257        ///
1258        /// If this is false, calls to `CommandEncoder::resolve_query_set` will be performed on the device (i.e. cpu) timeline
1259        /// and will block that timeline until the query has data. You may work around this limitation by waiting until the submit
1260        /// whose queries you are resolving is fully finished (through use of `queue.on_submitted_work_done`) and only
1261        /// then submitting the resolve_query_set command. The queries will be guaranteed finished, so will not block.
1262        ///
1263        /// Supported by:
1264        /// - Vulkan,
1265        /// - DX12
1266        /// - Metal
1267        /// - OpenGL 4.4+
1268        ///
1269        /// Not Supported by:
1270        /// - GL ES / WebGL
1271        const NONBLOCKING_QUERY_RESOLVE = 1 << 22;
1272
1273        /// Supports features introduced in MSL 2.1.
1274        const MSL2_1 = 1 << 24;
1275
1276        /// The adapter supports the WebGPU texture compression requirement:
1277        /// BC || (ETC2 && ASTC).
1278        ///
1279        /// See <https://www.w3.org/TR/webgpu/#adapter-capability-guarantees>.
1280        const TEXTURE_COMPRESSION = 1 << 25;
1281
1282        /// Supports `@interpolate(linear)` (a.k.a. `noperspective`) on shader inter-stage
1283        /// variables.
1284        ///
1285        /// GLSL ES has no `noperspective` qualifier, so the GLES backend only supports this
1286        /// on desktop OpenGL, not on GLES/WebGL2.
1287        const LINEAR_INTERPOLATION = 1 << 26;
1288
1289        /// Texture views used for bindings can have any `dimension` compatible with the texture.
1290        ///
1291        /// When this is not present:
1292        /// - Texture views used for bindings must specify the same `dimension` as the
1293        ///   `texture_binding_view_dimension` inferred/specified when creating the texture.
1294        /// - If `texture_binding_view_dimension` is not specified, it will be inferred from the
1295        ///   texture dimension and array layer count.
1296        /// - `texture_binding_view_dimension` can only be `cube-array` if
1297        ///   [`CUBE_ARRAY_TEXTURES`](Self::CUBE_ARRAY_TEXTURES) is supported, and the array
1298        ///   layer count must then be a multiple of 6.
1299        ///
1300        /// See <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createtexture>
1301        const ARBITRARY_BINDING_VIEW_DIMENSIONS = 1 << 27;
1302        // Free flag slot at 1 << 23
1303    }
1304}
1305
1306impl DownlevelFlags {
1307    /// Returns the set of flags required for an adapter to be considered WebGPU compliant.
1308    ///
1309    /// The only downlevel flags that are not required on a compliant adapter are:
1310    /// - [`Self::ANISOTROPIC_FILTERING`], because the filtering behavior is
1311    ///   implementation-defined, so performing no filtering at all is allowed.
1312    /// - [`Self::SURFACE_VIEW_FORMATS`], because [`Surface`] does not exactly
1313    ///   correspond to a WebGPU canvas, and most users of `wgpu` desiring
1314    ///   strict WebGPU compliance implement canvas view formats by means
1315    ///   other than [`Surface`].
1316    ///
1317    #[doc = link_to_wgpu_item!(struct Surface)]
1318    #[must_use]
1319    pub const fn compliant() -> Self {
1320        // We use manual bit twiddling to make this a const fn as `Sub` and `.remove` aren't const
1321
1322        // WebGPU doesn't actually require aniso
1323        // or surface view formats, which only apply to `wgpu::Surface`
1324        Self::from_bits_truncate(
1325            Self::all().bits()
1326                & !(Self::ANISOTROPIC_FILTERING.bits() | Self::SURFACE_VIEW_FORMATS.bits()),
1327        )
1328    }
1329}
1330
1331/// Collections of shader features a device supports if they support less than WebGPU normally allows.
1332// TODO: Fill out the differences between shader models more completely
1333#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1334#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1335pub enum ShaderModel {
1336    /// Extremely limited shaders, including a total instruction limit.
1337    Sm2,
1338    /// Missing minor features and storage images.
1339    Sm4,
1340    /// WebGPU supports shader module 5.
1341    Sm5,
1342}
1343
1344#[cfg(test)]
1345mod tests {
1346    use super::*;
1347    use alloc::{format, string::String, vec::Vec};
1348
1349    fn side_by_side(left: &str, right: &str) -> String {
1350        let left_lines: Vec<&str> = left.lines().map(str::trim).collect();
1351        let right_lines: Vec<&str> = right.lines().map(str::trim).collect();
1352        let max_lines = left_lines.len().max(right_lines.len());
1353        let diffs: Vec<(&str, &str)> = (0..max_lines)
1354            .map(|i| {
1355                let l = *left_lines.get(i).unwrap_or(&"");
1356                let r = *right_lines.get(i).unwrap_or(&"");
1357                (l, r)
1358            })
1359            .filter(|(l, r)| l != r)
1360            .collect();
1361        let left_width = diffs.iter().map(|(l, _)| l.len()).max().unwrap_or(0);
1362        let mut out = String::new();
1363        for (l, r) in &diffs {
1364            out += &format!("{:<width$}  |  {}\n", l, r, width = left_width);
1365        }
1366        out
1367    }
1368
1369    #[test]
1370    fn with_limits_exhaustive() {
1371        // Check that all limits are included in `with_limits!`, by using it to
1372        // replicate `Limits::unlimited()`.
1373        let mut limits = Limits::default();
1374
1375        macro_rules! set_to_max {
1376            ($name:ident, $ordering:expr) => {
1377                if $ordering == Ordering::Less {
1378                    limits.$name = i32::MAX as _;
1379                } else {
1380                    limits.$name = 1;
1381                }
1382            };
1383        }
1384
1385        with_limits!(set_to_max);
1386
1387        assert_eq!(
1388            limits,
1389            Limits::unlimited(),
1390            "with_limits! did not replicate Limits::unlimited():\n{}",
1391            side_by_side(
1392                &format!("with_limits!\n------------\n{:#?}", limits),
1393                &format!(
1394                    "Limits::unlimited()\n-------------------\n{:#?}",
1395                    Limits::unlimited()
1396                ),
1397            )
1398        );
1399    }
1400}