Skip to main content

wgpu_core/device/
resource.rs

1use alloc::{
2    borrow::Cow,
3    boxed::Box,
4    string::{String, ToString as _},
5    sync::{Arc, Weak},
6    vec::Vec,
7};
8use core::{
9    fmt,
10    mem::{self, ManuallyDrop},
11    num::{NonZeroU32, NonZeroU64},
12};
13
14use arrayvec::ArrayVec;
15use bitflags::Flags;
16use scopeguard::{guard, ScopeGuard};
17use smallvec::SmallVec;
18use wgpu_sync::atomic::{AtomicBool, Ordering};
19use wgpu_sync::OnceCell;
20use wgt::{
21    error::WebGpuError, math::align_to, ColorWrites, DeviceLostReason, TextureFormat,
22    TextureSampleType, TextureViewDimension,
23};
24
25#[cfg(feature = "trace")]
26use crate::device::trace::{self, IntoTrace as _};
27use crate::{
28    api_log,
29    binding_model::{
30        self, BindGroup, BindGroupLayout, BindGroupLayoutEntryError, BindGroupLayoutState,
31        BindGroupState, CreateBindGroupError, CreateBindGroupLayoutError,
32    },
33    command, conv,
34    device::{
35        bgl, create_validator, life::WaitIdleError, map_buffer, stage_compiler::StageCompiler,
36        AttachmentData, BufferMapPendingClosure, DeviceLostInvocation, MapMode,
37        MissingDownlevelFlags, MissingFeatures, RenderPassContext,
38    },
39    error::ErrorSink,
40    hal_label,
41    init_tracker::{
42        BufferInitTracker, BufferInitTrackerAction, MemoryInitKind, TextureInitRange,
43        TextureInitTrackerAction,
44    },
45    instance::{Adapter, RequestDeviceError},
46    lock::{rank, Mutex, RwLock},
47    pipeline::{
48        self, shader_module_error_into_compilation_info, ColorStateError, PassthroughInterface,
49    },
50    pool::ResourcePool,
51    resource::{
52        self, Buffer, BufferState, ExternalTexture, ExternalTextureState, Labeled, ParentDevice,
53        QuerySet, QuerySetState, RawResourceAccess, ResourceState, Sampler, StagingBuffer, Texture,
54        TextureView, Tlas, TrackingData,
55    },
56    resource_log,
57    snatch::{SnatchGuard, SnatchLock, Snatchable},
58    timestamp_normalization::TIMESTAMP_NORMALIZATION_BUFFER_USES,
59    track::{BindGroupStates, DeviceTracker, TrackerIndexAllocators, UsageScope, UsageScopePool},
60    validation::{self, check_color_attachment_count},
61    weak_vec::WeakVec,
62    FastHashMap, LabelHelpers,
63};
64
65use super::{
66    queue::Queue, DeviceDescriptor, DeviceError, DeviceLostClosure, UserClosures, ZERO_BUFFER_SIZE,
67};
68
69use wgpu_sync::atomic::AtomicU64;
70
71pub(crate) struct CommandIndices {
72    /// The index of the last command submission that was attempted.
73    ///
74    /// Note that `fence` may never be signalled with this value, if the command
75    /// submission failed. If you need to wait for everything running on a
76    /// `Queue` to complete, wait for [`last_successful_submission_index`].
77    ///
78    /// [`last_successful_submission_index`]: Device::last_successful_submission_index
79    pub(crate) active_submission_index: hal::FenceValue,
80    pub(crate) next_acceleration_structure_build_command_index: u64,
81}
82
83/// Parameters provided to shaders via a uniform buffer of the type
84/// [`NagaExternalTextureParams`], describing an [`ExternalTexture`] resource
85/// binding.
86///
87/// [`NagaExternalTextureParams`]: naga::SpecialTypes::external_texture_params
88/// [`ExternalTexture`]: binding_model::BindingResource::ExternalTexture
89//
90// This definition must match Naga's special type definition generated by
91// [`naga::Module::generate_external_texture_types`] and naga's
92// [`naga::common::ExternalTextureParameter`] enum.
93#[repr(C)]
94#[derive(Copy, Clone, bytemuck::Zeroable, bytemuck::Pod)]
95pub struct ExternalTextureParams {
96    /// 4x4 column-major matrix with which to convert sampled YCbCr values
97    /// to RGBA.
98    ///
99    /// This is ignored when `num_planes` is 1.
100    pub yuv_conversion_matrix: [f32; 16],
101
102    /// 3x3 column-major matrix to transform linear RGB values in the source
103    /// color space to linear RGB values in the destination color space. In
104    /// combination with [`Self::src_transfer_function`] and
105    /// [`Self::dst_transfer_function`] this can be used to ensure that
106    /// [`ImageSample`] and [`ImageLoad`] operations return values in the
107    /// desired destination color space rather than the source color space of
108    /// the underlying planes.
109    ///
110    /// Includes a padding element after each column.
111    ///
112    /// [`ImageSample`]: naga::ir::Expression::ImageSample
113    /// [`ImageLoad`]: naga::ir::Expression::ImageLoad
114    pub gamut_conversion_matrix: [f32; 12],
115
116    /// Transfer function for the source color space. The *inverse* of this
117    /// will be applied to decode non-linear RGB to linear RGB in the source
118    /// color space.
119    pub src_transfer_function: wgt::ExternalTextureTransferFunction,
120
121    /// Transfer function for the destination color space. This will be applied
122    /// to encode linear RGB to non-linear RGB in the destination color space.
123    pub dst_transfer_function: wgt::ExternalTextureTransferFunction,
124
125    /// Transform to apply to [`ImageSample`] coordinates.
126    ///
127    /// This is a 3x2 column-major matrix representing an affine transform from
128    /// normalized texture coordinates to the normalized coordinates that should
129    /// be sampled from the external texture's underlying plane(s).
130    ///
131    /// This transform may scale, translate, flip, and rotate in 90-degree
132    /// increments, but the result of transforming the rectangle (0,0)..(1,1)
133    /// must be an axis-aligned rectangle that falls within the bounds of
134    /// (0,0)..(1,1).
135    ///
136    /// [`ImageSample`]: naga::ir::Expression::ImageSample
137    pub sample_transform: [f32; 6],
138
139    /// Transform to apply to [`ImageLoad`] coordinates.
140    ///
141    /// This is a 3x2 column-major matrix representing an affine transform from
142    /// non-normalized texel coordinates to the non-normalized coordinates of
143    /// the texel that should be loaded from the external texture's underlying
144    /// plane 0. For planes 1 and 2, if present, plane 0's coordinates are
145    /// scaled according to the textures' relative sizes.
146    ///
147    /// This transform may scale, translate, flip, and rotate in 90-degree
148    /// increments, but the result of transforming the rectangle (0,0)..[`size`]
149    /// must be an axis-aligned rectangle that falls within the bounds of
150    /// (0,0)..[`size`].
151    ///
152    /// [`ImageLoad`]: naga::ir::Expression::ImageLoad
153    /// [`size`]: Self::size
154    pub load_transform: [f32; 6],
155
156    /// Size of the external texture.
157    ///
158    /// This is the value that should be returned by size queries in shader
159    /// code; it does not necessarily match the dimensions of the underlying
160    /// texture(s). As a special case, if this is `[0, 0]`, the actual size of
161    /// plane 0 should be used instead.
162    ///
163    /// This must be consistent with [`sample_transform`]: it should be the size
164    /// in texels of the rectangle covered by the square (0,0)..(1,1) after
165    /// [`sample_transform`] has been applied to it.
166    ///
167    /// [`sample_transform`]: Self::sample_transform
168    pub size: [u32; 2],
169
170    /// Number of planes. 1 indicates a single RGBA plane. 2 indicates a Y
171    /// plane and an interleaved CbCr plane. 3 indicates separate Y, Cb, and Cr
172    /// planes.
173    pub num_planes: u32,
174    // Ensure the size of this struct matches the type generated by Naga.
175    pub _padding: [u8; 4],
176}
177
178const _: () =
179    assert!(size_of::<ExternalTextureParams>() == wgpu_hal::EXTERNAL_TEXTURE_PARAMS_SIZE as usize);
180const EXTERNAL_TEXTURE_PARAMS_BUFFER_SIZE: usize = {
181    size_of::<ExternalTextureParams>()
182        .next_multiple_of(wgpu_hal::UNIVERSAL_BUFFER_SIZE_ALIGNMENT as usize)
183};
184
185impl ExternalTextureParams {
186    pub fn from_desc<L>(desc: &wgt::ExternalTextureDescriptor<L>) -> Self {
187        let gamut_conversion_matrix = [
188            desc.gamut_conversion_matrix[0],
189            desc.gamut_conversion_matrix[1],
190            desc.gamut_conversion_matrix[2],
191            0.0, // padding
192            desc.gamut_conversion_matrix[3],
193            desc.gamut_conversion_matrix[4],
194            desc.gamut_conversion_matrix[5],
195            0.0, // padding
196            desc.gamut_conversion_matrix[6],
197            desc.gamut_conversion_matrix[7],
198            desc.gamut_conversion_matrix[8],
199            0.0, // padding
200        ];
201
202        Self {
203            yuv_conversion_matrix: desc.yuv_conversion_matrix,
204            gamut_conversion_matrix,
205            src_transfer_function: desc.src_transfer_function,
206            dst_transfer_function: desc.dst_transfer_function,
207            size: [desc.width, desc.height],
208            sample_transform: desc.sample_transform,
209            load_transform: desc.load_transform,
210            num_planes: desc.num_planes() as u32,
211            _padding: Default::default(),
212        }
213    }
214}
215
216/// Because all operations are push/swap (no longlived lock),
217/// we can have mutex without lock rank
218pub(crate) struct DeferredBufferMapPendingClosures(wgpu_sync::Mutex<Vec<BufferMapPendingClosure>>);
219
220impl DeferredBufferMapPendingClosures {
221    pub(crate) fn new() -> Self {
222        Self(wgpu_sync::Mutex::new(Vec::new()))
223    }
224
225    pub(crate) fn push(&self, closure: BufferMapPendingClosure) {
226        self.0.lock().push(closure);
227    }
228
229    pub(crate) fn swap(&self, other: &mut Vec<BufferMapPendingClosure>) {
230        mem::swap(&mut *self.0.lock(), other)
231    }
232}
233
234/// Structure describing a logical device. Some members are internally mutable,
235/// stored behind mutexes.
236pub struct Device {
237    pub(crate) queue: OnceCell<Weak<Queue>>,
238    pub(crate) zero_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
239    pub(crate) empty_bgl: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
240    /// The `label` from the descriptor used to create the resource.
241    label: String,
242
243    pub(crate) command_allocator: command::CommandAllocator,
244
245    /// Holding this lock for writing also serializes the operations on the
246    /// device's [`hal::Queue`] that must be externally synchronized:
247    /// submission, presentation, waiting for idle, and surface configuration.
248    pub(crate) command_indices: RwLock<CommandIndices>,
249
250    /// The index of the last successful submission to this device's
251    /// [`hal::Queue`].
252    ///
253    /// Unlike [`active_submission_index`], which is incremented each time
254    /// submission is attempted, this is updated only when submission succeeds,
255    /// so waiting for this value won't hang waiting for work that was never
256    /// submitted.
257    ///
258    /// [`active_submission_index`]: CommandIndices::active_submission_index
259    pub(crate) last_successful_submission_index: hal::AtomicFenceValue,
260
261    pub(crate) fence: ManuallyDrop<Box<dyn hal::DynFence>>,
262    pub(crate) snatchable_lock: SnatchLock,
263
264    /// Is this device valid? Valid is closely associated with "lose the device",
265    /// which can be triggered by various methods, including at the end of device
266    /// destroy, and by any GPU errors that cause us to no longer trust the state
267    /// of the device. Ideally we would like to fold valid into the storage of
268    /// the device itself (for example as an Error enum), but unfortunately we
269    /// need to continue to be able to retrieve the device in poll_devices to
270    /// determine if it can be dropped. If our internal accesses of devices were
271    /// done through ref-counted references and external accesses checked for
272    /// Error enums, we wouldn't need this. For now, we need it. All the call
273    /// sites where we check it are areas that should be revisited if we start
274    /// using ref-counted references for internal access.
275    pub(crate) valid: AtomicBool,
276
277    /// Closure to be called on "lose the device". This is invoked directly by
278    /// device.lose or by the UserCallbacks returned from maintain when the device
279    /// has been destroyed and its queues are empty.
280    pub(crate) device_lost_closure: Mutex<Option<DeviceLostClosure>>,
281
282    pub(crate) error_sink: ErrorSink,
283
284    /// Stores the state of buffers and textures.
285    pub(crate) trackers: Mutex<DeviceTracker>,
286    pub(crate) tracker_indices: TrackerIndexAllocators,
287    /// Pool of bind group layouts, allowing deduplication.
288    pub(crate) bgl_pool: ResourcePool<bgl::EntryMap, BindGroupLayout>,
289    pub(crate) alignments: hal::Alignments,
290    pub(crate) limits: wgt::Limits,
291    pub(crate) features: wgt::Features,
292    pub(crate) downlevel: wgt::DownlevelCapabilities,
293    /// Buffer uses listed here, are expected to be ordered by the underlying hardware.
294    /// If a usage is ordered, then if the buffer state doesn't change between draw calls,
295    /// there are no barriers needed for synchronization.
296    /// See the implementations of [`hal::Adapter::get_ordered_buffer_usages`] for hardware specific info
297    pub(crate) ordered_buffer_usages: wgt::BufferUses,
298    /// Texture uses listed here, are expected to be ordered by the underlying hardware.
299    /// If a usage is ordered, then if the buffer state doesn't change between draw calls,
300    /// there are no barriers needed for synchronization.
301    /// See the implementations of [`hal::Adapter::get_ordered_texture_usages`] for hardware specific info
302    pub(crate) ordered_texture_usages: wgt::TextureUses,
303    pub(crate) instance_flags: wgt::InstanceFlags,
304    pub(crate) deferred_destroy: Mutex<Vec<DeferredDestroy>>,
305    /// This closures were created in [`Buffer::drop`] where we do not run them to prevent locking problems.
306    pub(crate) deferred_buffer_map_pending_closures: DeferredBufferMapPendingClosures,
307    pub(crate) usage_scopes: UsageScopePool,
308    pub(crate) indirect_validation: Option<crate::indirect_validation::IndirectValidation>,
309    // Optional so that we can late-initialize this after the queue is created.
310    pub(crate) timestamp_normalizer: OnceCell<crate::timestamp_normalization::TimestampNormalizer>,
311    /// Uniform buffer containing [`ExternalTextureParams`] with values such
312    /// that a [`TextureView`] bound to a [`wgt::BindingType::ExternalTexture`]
313    /// binding point will be rendered correctly. Intended to be used as the
314    /// [`hal::ExternalTextureBinding::params`] field.
315    pub(crate) default_external_texture_params_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
316
317    // Drop order matters!
318    //
319    //  - Any member whose drop might destroy hal resources needs to be dropped
320    //    before the device. Most hal resources are handled manually in
321    //    `Device::drop`, but this applies to `command_allocator`.
322    //  - The device must be dropped before the adapter.
323    //  - Any member whose drop might write into the trace must be dropped
324    //    before the trace.
325    raw: Box<dyn hal::DynDevice>,
326    pub(crate) adapter: Arc<Adapter>,
327    #[cfg(feature = "trace")]
328    pub(crate) trace: Mutex<Option<Box<dyn trace::Trace + Send + Sync + 'static>>>,
329}
330
331#[cfg(send_sync)]
332const _: () = {
333    // SAFETY: Bounds checked below
334    unsafe impl Send for Device {}
335    // SAFETY: Bounds checked below
336    unsafe impl Sync for Device {}
337
338    fn _device_fields_are_send_sync(obj: &Device) {
339        fn _check_bound<T: Send + Sync>(_: &T) {}
340        let Device {
341            queue,
342            zero_buffer,
343            empty_bgl,
344            label,
345            command_allocator,
346            command_indices,
347            last_successful_submission_index,
348            fence,
349            snatchable_lock,
350            valid,
351            device_lost_closure,
352            error_sink,
353            trackers,
354            tracker_indices,
355            bgl_pool,
356            alignments,
357            limits,
358            features,
359            downlevel,
360            ordered_buffer_usages,
361            ordered_texture_usages,
362            instance_flags,
363            deferred_destroy,
364            deferred_buffer_map_pending_closures,
365            usage_scopes,
366            indirect_validation,
367            timestamp_normalizer,
368            default_external_texture_params_buffer,
369            raw,
370            adapter,
371            #[cfg(feature = "trace")]
372            trace,
373        } = obj;
374        _check_bound(queue);
375        _check_bound(zero_buffer);
376        _check_bound(empty_bgl);
377        _check_bound(label);
378        _check_bound(command_allocator);
379        _check_bound(command_indices);
380        _check_bound(last_successful_submission_index);
381        _check_bound(fence);
382        _check_bound(snatchable_lock);
383        _check_bound(valid);
384        _check_bound(device_lost_closure);
385        _check_bound(error_sink);
386        _check_bound(trackers);
387        _check_bound(tracker_indices);
388        _check_bound(bgl_pool);
389        _check_bound(alignments);
390        _check_bound(limits);
391        _check_bound(features);
392        _check_bound(downlevel);
393        _check_bound(ordered_buffer_usages);
394        _check_bound(ordered_texture_usages);
395        _check_bound(instance_flags);
396        _check_bound(deferred_destroy);
397        _check_bound(deferred_buffer_map_pending_closures);
398        _check_bound(usage_scopes);
399        _check_bound(indirect_validation);
400        _check_bound(timestamp_normalizer);
401        _check_bound(default_external_texture_params_buffer);
402        _check_bound(raw);
403        _check_bound(adapter);
404        #[cfg(feature = "trace")]
405        _check_bound(trace);
406    }
407};
408
409pub(crate) enum DeferredDestroy {
410    TextureViews(WeakVec<TextureView>),
411    BindGroups(WeakVec<BindGroup>),
412}
413
414impl fmt::Debug for Device {
415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416        f.debug_struct("Device")
417            .field("label", &self.label())
418            .field("limits", &self.limits)
419            .field("features", &self.features)
420            .field("downlevel", &self.downlevel)
421            .finish()
422    }
423}
424
425impl Drop for Device {
426    #[allow(trivial_casts)]
427    fn drop(&mut self) {
428        profiling::scope!("Device::drop");
429        api_log!("Device::drop {:?}", self as *const _);
430        resource_log!("Drop {}", self.error_ident());
431
432        // SAFETY: We are in the Drop impl and we don't use self.zero_buffer anymore after this
433        // point.
434        let zero_buffer = unsafe { ManuallyDrop::take(&mut self.zero_buffer) };
435        // SAFETY: We are in the Drop impl and we don't use self.empty_bgl anymore after this point.
436        let empty_bgl = unsafe { ManuallyDrop::take(&mut self.empty_bgl) };
437        // SAFETY: We are in the Drop impl and we don't use
438        // self.default_external_texture_params_buffer anymore after this point.
439        let default_external_texture_params_buffer =
440            unsafe { ManuallyDrop::take(&mut self.default_external_texture_params_buffer) };
441        // SAFETY: We are in the Drop impl and we don't use self.fence anymore after this point.
442        let fence = unsafe { ManuallyDrop::take(&mut self.fence) };
443        if let Some(indirect_validation) = self.indirect_validation.take() {
444            indirect_validation.dispose(self.raw.as_ref());
445        }
446        if let Some(timestamp_normalizer) = self.timestamp_normalizer.take() {
447            timestamp_normalizer.dispose(self.raw.as_ref());
448        }
449        unsafe {
450            self.raw.destroy_buffer(zero_buffer);
451            self.raw.destroy_bind_group_layout(empty_bgl);
452            self.raw
453                .destroy_buffer(default_external_texture_params_buffer);
454            self.raw.destroy_fence(fence);
455        }
456    }
457}
458
459impl Device {
460    pub fn features(&self) -> &wgt::Features {
461        &self.features
462    }
463
464    pub fn limits(&self) -> &wgt::Limits {
465        &self.limits
466    }
467
468    pub fn downlevel(&self) -> &wgt::DownlevelCapabilities {
469        &self.downlevel
470    }
471
472    pub fn adapter_info(&self) -> wgt::AdapterInfo {
473        self.adapter.get_info()
474    }
475}
476
477impl Device {
478    pub(crate) fn raw(&self) -> &dyn hal::DynDevice {
479        self.raw.as_ref()
480    }
481
482    pub fn require_features(&self, feature: wgt::Features) -> Result<(), MissingFeatures> {
483        if self.features.contains(feature) {
484            Ok(())
485        } else {
486            Err(MissingFeatures(feature))
487        }
488    }
489
490    pub(crate) fn require_downlevel_flags(
491        &self,
492        flags: wgt::DownlevelFlags,
493    ) -> Result<(), MissingDownlevelFlags> {
494        if self.downlevel.flags.contains(flags) {
495            Ok(())
496        } else {
497            Err(MissingDownlevelFlags(flags))
498        }
499    }
500
501    /// # Safety
502    ///
503    /// - See [wgpu::Device::start_graphics_debugger_capture][api] for details the safety.
504    ///
505    /// [api]: ../../wgpu/struct.Device.html#method.start_graphics_debugger_capture
506    pub unsafe fn start_graphics_debugger_capture(&self) {
507        api_log!("Device::start_graphics_debugger_capture");
508
509        if !self.is_valid() {
510            return;
511        }
512        unsafe { self.raw().start_graphics_debugger_capture() };
513    }
514
515    /// # Safety
516    ///
517    /// - See [wgpu::Device::stop_graphics_debugger_capture][api] for details the safety.
518    ///
519    /// [api]: ../../wgpu/struct.Device.html#method.stop_graphics_debugger_capture
520    pub unsafe fn stop_graphics_debugger_capture(&self) {
521        api_log!("Device::stop_graphics_debugger_capture");
522
523        if !self.is_valid() {
524            return;
525        }
526        unsafe { self.raw().stop_graphics_debugger_capture() };
527    }
528}
529
530impl Device {
531    pub(crate) fn new(
532        raw_device: Box<dyn hal::DynDevice>,
533        adapter: &Arc<Adapter>,
534        desc: &DeviceDescriptor,
535        instance_flags: wgt::InstanceFlags,
536    ) -> Result<Self, DeviceError> {
537        #[cfg(not(feature = "trace"))]
538        match &desc.trace {
539            wgt::Trace::Off => {}
540            _ => {
541                log::error!("wgpu-core feature 'trace' is not enabled");
542            }
543        };
544        #[cfg(feature = "trace")]
545        let trace: Option<Box<dyn trace::Trace + Send + Sync + 'static>> = match &desc.trace {
546            wgt::Trace::Off => None,
547            wgt::Trace::Directory(dir) => match trace::DiskTrace::new(dir.clone()) {
548                Ok(mut trace) => {
549                    trace::Trace::add(
550                        &mut trace,
551                        trace::Action::Init {
552                            desc: wgt::DeviceDescriptor {
553                                trace: wgt::Trace::Off,
554                                ..desc.clone()
555                            },
556                            backend: adapter.backend(),
557                        },
558                    );
559                    Some(Box::new(trace))
560                }
561                Err(e) => {
562                    log::error!("Unable to start a trace in '{dir:?}': {e}");
563                    None
564                }
565            },
566            wgt::Trace::Memory => {
567                let mut trace = trace::MemoryTrace::new();
568                trace::Trace::add(
569                    &mut trace,
570                    trace::Action::Init {
571                        desc: wgt::DeviceDescriptor {
572                            trace: wgt::Trace::Off,
573                            ..desc.clone()
574                        },
575                        backend: adapter.backend(),
576                    },
577                );
578                Some(Box::new(trace))
579            }
580            // The enum is non_exhaustive, so we must have a fallback arm (that should be
581            // unreachable in practice).
582            t => {
583                log::error!("unimplemented wgpu_types::Trace variant {t:?}");
584                None
585            }
586        };
587
588        let ordered_buffer_usages = adapter.raw.adapter.get_ordered_buffer_usages();
589        let ordered_texture_usages = adapter.raw.adapter.get_ordered_texture_usages();
590
591        // Resources requiring explicit destruction ahead of the device are wrapped in
592        // `ScopeGuard`s, which are defused just before the `Device` takes ownership of the
593        // resources.
594        let raw = raw_device.as_ref();
595
596        let fence = unsafe { raw_device.create_fence() }.map_err(DeviceError::from_hal)?;
597        let fence = guard(fence, |fence| unsafe { raw.destroy_fence(fence) });
598
599        let command_allocator = command::CommandAllocator::new();
600
601        let rt_uses = if desc
602            .required_features
603            .intersects(wgt::Features::EXPERIMENTAL_RAY_QUERY)
604        {
605            wgt::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT
606        } else {
607            wgt::BufferUses::empty()
608        };
609
610        // Create zeroed buffer used for texture clears (and raytracing if required).
611        let zero_buffer = unsafe {
612            raw_device.create_buffer(&hal::BufferDescriptor {
613                label: hal_label(Some("(wgpu internal) zero init buffer"), instance_flags),
614                size: ZERO_BUFFER_SIZE,
615                usage: wgt::BufferUses::COPY_SRC | wgt::BufferUses::COPY_DST | rt_uses,
616                memory_flags: hal::MemoryFlags::empty(),
617            })
618        }
619        .map_err(DeviceError::from_hal)?
620        .0;
621        let zero_buffer = guard(zero_buffer, |buffer| unsafe { raw.destroy_buffer(buffer) });
622
623        let empty_bgl = unsafe {
624            raw_device.create_bind_group_layout(&hal::BindGroupLayoutDescriptor {
625                label: None,
626                flags: hal::BindGroupLayoutFlags::empty(),
627                entries: &[],
628            })
629        }
630        .map_err(DeviceError::from_hal)?;
631        let empty_bgl = guard(empty_bgl, |bgl| unsafe {
632            raw.destroy_bind_group_layout(bgl)
633        });
634
635        let default_external_texture_params_buffer = unsafe {
636            raw_device.create_buffer(&hal::BufferDescriptor {
637                label: hal_label(
638                    Some("(wgpu internal) default external texture params buffer"),
639                    instance_flags,
640                ),
641                size: EXTERNAL_TEXTURE_PARAMS_BUFFER_SIZE as _,
642                usage: wgt::BufferUses::COPY_DST | wgt::BufferUses::UNIFORM,
643                memory_flags: hal::MemoryFlags::empty(),
644            })
645        }
646        .map_err(DeviceError::from_hal)?
647        .0;
648        let default_external_texture_params_buffer =
649            guard(default_external_texture_params_buffer, |buffer| unsafe {
650                raw.destroy_buffer(buffer)
651            });
652
653        // Cloned as we need them below anyway.
654        let alignments = adapter.raw.capabilities.alignments.clone();
655        let downlevel = adapter.raw.capabilities.downlevel.clone();
656        let limits = &adapter.raw.capabilities.limits;
657
658        let enable_indirect_validation = instance_flags
659            .contains(wgt::InstanceFlags::VALIDATION_INDIRECT_CALL)
660            && downlevel.flags.contains(
661                wgt::DownlevelFlags::INDIRECT_EXECUTION | wgt::DownlevelFlags::COMPUTE_SHADERS,
662            )
663            && limits.max_storage_buffers_per_shader_stage >= 2;
664
665        let indirect_validation = if enable_indirect_validation {
666            let indirect_validation = crate::indirect_validation::IndirectValidation::new(
667                raw,
668                &desc.required_limits,
669                &desc.required_features,
670                instance_flags,
671                adapter.backend(),
672            )?;
673            Some(guard(indirect_validation, |indirect_validation| {
674                indirect_validation.dispose(raw)
675            }))
676        } else {
677            None
678        };
679
680        // Error returns after we start consuming guards could bypass resource cleanup.
681        #[deny(clippy::question_mark_used)]
682        {
683            let zero_buffer = ScopeGuard::into_inner(zero_buffer);
684            let empty_bgl = ScopeGuard::into_inner(empty_bgl);
685            let default_external_texture_params_buffer =
686                ScopeGuard::into_inner(default_external_texture_params_buffer);
687            let fence = ScopeGuard::into_inner(fence);
688            let indirect_validation = indirect_validation.map(ScopeGuard::into_inner);
689
690            Ok(Self {
691                raw: raw_device,
692                adapter: adapter.clone(),
693                queue: OnceCell::new(),
694                zero_buffer: ManuallyDrop::new(zero_buffer),
695                empty_bgl: ManuallyDrop::new(empty_bgl),
696                default_external_texture_params_buffer: ManuallyDrop::new(
697                    default_external_texture_params_buffer,
698                ),
699                label: desc.label.to_string(),
700                command_allocator,
701                command_indices: RwLock::new(
702                    rank::DEVICE_COMMAND_INDICES,
703                    CommandIndices {
704                        active_submission_index: 0,
705                        // By starting at one, we can put the result in a NonZeroU64.
706                        next_acceleration_structure_build_command_index: 1,
707                    },
708                ),
709                last_successful_submission_index: AtomicU64::new(0),
710                fence: ManuallyDrop::new(fence),
711                snatchable_lock: unsafe { SnatchLock::new(rank::DEVICE_SNATCHABLE_LOCK) },
712                valid: AtomicBool::new(true),
713                device_lost_closure: Mutex::new(rank::DEVICE_LOST_CLOSURE, None),
714                error_sink: ErrorSink::new(),
715                trackers: Mutex::new(
716                    rank::DEVICE_TRACKERS,
717                    DeviceTracker::new(ordered_buffer_usages, ordered_texture_usages),
718                ),
719                tracker_indices: TrackerIndexAllocators::new(),
720                bgl_pool: ResourcePool::new(),
721                #[cfg(feature = "trace")]
722                trace: Mutex::new(rank::DEVICE_TRACE, trace),
723                alignments,
724                limits: desc.required_limits.clone(),
725                features: desc.required_features,
726                downlevel,
727                ordered_buffer_usages,
728                ordered_texture_usages,
729                instance_flags,
730                deferred_destroy: Mutex::new(rank::DEVICE_DEFERRED_DESTROY, Vec::new()),
731                usage_scopes: Mutex::new(rank::DEVICE_USAGE_SCOPES, Default::default()),
732                timestamp_normalizer: OnceCell::new(),
733                indirect_validation,
734                deferred_buffer_map_pending_closures: DeferredBufferMapPendingClosures::new(),
735            })
736        }
737    }
738
739    /// Initializes [`Device::default_external_texture_params_buffer`] with
740    /// required values such that a [`TextureView`] bound to a
741    /// [`wgt::BindingType::ExternalTexture`] binding point will be rendered
742    /// correctly.
743    fn init_default_external_texture_params_buffer(self: &Arc<Self>) -> Result<(), DeviceError> {
744        let data = ExternalTextureParams {
745            #[rustfmt::skip]
746            yuv_conversion_matrix: [
747                1.0, 0.0, 0.0, 0.0,
748                0.0, 1.0, 0.0, 0.0,
749                0.0, 0.0, 1.0, 0.0,
750                0.0, 0.0, 0.0, 1.0,
751            ],
752            #[rustfmt::skip]
753            gamut_conversion_matrix: [
754                1.0, 0.0, 0.0, /* padding */ 0.0,
755                0.0, 1.0, 0.0, /* padding */ 0.0,
756                0.0, 0.0, 1.0, /* padding */ 0.0,
757            ],
758            src_transfer_function: Default::default(),
759            dst_transfer_function: Default::default(),
760            size: [0, 0],
761            #[rustfmt::skip]
762            sample_transform: [
763                1.0, 0.0,
764                0.0, 1.0,
765                0.0, 0.0
766            ],
767            #[rustfmt::skip]
768            load_transform: [
769                1.0, 0.0,
770                0.0, 1.0,
771                0.0, 0.0
772            ],
773            num_planes: 1,
774            _padding: Default::default(),
775        };
776        let mut staging_buffer = StagingBuffer::new(
777            self,
778            wgt::BufferSize::new(EXTERNAL_TEXTURE_PARAMS_BUFFER_SIZE as _).unwrap(),
779        )?;
780        staging_buffer.write_with_zero_padding(bytemuck::bytes_of(&data));
781        let staging_buffer = staging_buffer.flush();
782
783        let params_buffer = self.default_external_texture_params_buffer.as_ref();
784        let queue = self.get_queue().unwrap();
785        let mut pending_writes = queue.pending_writes.lock();
786
787        unsafe {
788            pending_writes
789                .command_encoder
790                .transition_buffers(&[hal::BufferBarrier {
791                    buffer: params_buffer,
792                    usage: hal::StateTransition {
793                        from: wgt::BufferUses::MAP_WRITE,
794                        to: wgt::BufferUses::COPY_DST,
795                    },
796                }]);
797            pending_writes.command_encoder.copy_buffer_to_buffer(
798                staging_buffer.raw(),
799                params_buffer,
800                &[hal::BufferCopy {
801                    src_offset: 0,
802                    dst_offset: 0,
803                    size: staging_buffer.size,
804                }],
805            );
806            pending_writes.consume(staging_buffer);
807            pending_writes
808                .command_encoder
809                .transition_buffers(&[hal::BufferBarrier {
810                    buffer: params_buffer,
811                    usage: hal::StateTransition {
812                        from: wgt::BufferUses::COPY_DST,
813                        to: wgt::BufferUses::UNIFORM,
814                    },
815                }]);
816        }
817
818        Ok(())
819    }
820
821    pub fn late_init_resources_with_queue(self: &Arc<Self>) -> Result<(), RequestDeviceError> {
822        let queue = self.get_queue().unwrap();
823
824        let timestamp_normalizer = crate::timestamp_normalization::TimestampNormalizer::new(
825            self,
826            queue.get_raw_timestamp_period(),
827        )?;
828
829        self.timestamp_normalizer
830            .set(timestamp_normalizer)
831            .unwrap_or_else(|_| panic!("Called late_init_resources_with_queue twice"));
832
833        self.init_default_external_texture_params_buffer()?;
834
835        Ok(())
836    }
837
838    /// Returns the backend this device is using.
839    pub fn backend(&self) -> wgt::Backend {
840        self.adapter.backend()
841    }
842
843    /// Returns a reference to the adapter this device was created from.
844    pub fn adapter(&self) -> &Arc<Adapter> {
845        &self.adapter
846    }
847
848    /// Return true if `self` is still valid.
849    ///
850    /// Note that a `false` result here does *not* guarantee that no further activity will
851    /// occur on the `Device`. A [`Device`] can be marked invalid at any time, even while
852    /// locks are held, meaning that operations begun before the `Device` was marked
853    /// invalid will still generally run to completion. This is a consequence of
854    /// making [`Device::valid`] an `AtomicBool`. It could be avoided by making
855    /// [`Device::valid`] an ordinary `bool` field protected by the same locks that
856    /// all other operations acquire, but we use an `AtomicBool` because there
857    /// are many device validity checks and we want those to be cheap.
858    pub fn is_valid(&self) -> bool {
859        self.valid.load(Ordering::Acquire)
860    }
861
862    /// Return `Err(DeviceError)` if `self` is not valid. Otherwise, return `Ok(())`.
863    ///
864    /// Note that an `Err` result here does *not* guarantee that no further activity will
865    /// occur on the `Device`. See the documentation for [`is_valid`][Self::is_valid] for
866    /// details.
867    pub fn check_is_valid(&self) -> Result<(), DeviceError> {
868        if self.is_valid() {
869            Ok(())
870        } else {
871            Err(DeviceError::Lost)
872        }
873    }
874
875    /// Stop tracing and return the trace object.
876    ///
877    /// This is mostly useful for in-memory traces.
878    #[cfg(feature = "trace")]
879    pub fn take_trace(&self) -> Option<Box<dyn trace::Trace + Send + Sync + 'static>> {
880        self.trace.lock().take()
881    }
882
883    /// Checks that we are operating within the memory budget reported by the native APIs.
884    ///
885    /// If we are not, the device gets invalidated.
886    ///
887    /// The budget might fluctuate over the lifetime of the application, so it should be checked
888    /// somewhat frequently.
889    pub fn lose_if_oom(&self) {
890        let _ = self
891            .raw()
892            .check_if_oom()
893            .map_err(|e| self.handle_hal_error(e));
894    }
895
896    #[track_caller]
897    pub fn handle_hal_error(&self, error: hal::DeviceError) -> DeviceError {
898        match error {
899            hal::DeviceError::OutOfMemory
900            | hal::DeviceError::Lost
901            | hal::DeviceError::Unexpected => {
902                self.lose(&error.to_string());
903            }
904        }
905        DeviceError::from_hal(error)
906    }
907
908    #[track_caller]
909    pub fn handle_hal_error_with_nonfatal_oom(&self, error: hal::DeviceError) -> DeviceError {
910        match error {
911            hal::DeviceError::OutOfMemory => DeviceError::from_hal(error),
912            error => self.handle_hal_error(error),
913        }
914    }
915
916    /// Run some destroy operations that were deferred.
917    ///
918    /// Destroying the resources requires taking a write lock on the device's snatch lock,
919    /// so a good reason for deferring resource destruction is when we don't know for sure
920    /// how risky it is to take the lock (typically, it shouldn't be taken from the drop
921    /// implementation of a reference-counted structure).
922    /// The snatch lock must not be held while this function is called.
923    pub(crate) fn deferred_resource_destruction(&self) {
924        // Note that the deferred_destroy list may contain duplicate entries.
925        let deferred_destroy = mem::take(&mut *self.deferred_destroy.lock());
926        for item in deferred_destroy {
927            match item {
928                DeferredDestroy::TextureViews(views) => {
929                    for view in views {
930                        let Some(view) = view.upgrade() else {
931                            continue;
932                        };
933                        let Ok(view_state) = view.state() else {
934                            continue;
935                        };
936                        let Some(raw_view) =
937                            view_state.raw.snatch(&mut self.snatchable_lock.write())
938                        else {
939                            continue;
940                        };
941
942                        resource_log!("Destroy raw {}", view.error_ident());
943
944                        unsafe {
945                            self.raw().destroy_texture_view(raw_view);
946                        }
947                    }
948                }
949                DeferredDestroy::BindGroups(bind_groups) => {
950                    for bind_group in bind_groups {
951                        let Some(bind_group) = bind_group.upgrade() else {
952                            continue;
953                        };
954                        let Ok(bind_group_state) = bind_group.state() else {
955                            continue;
956                        };
957                        let Some(raw_bind_group) = bind_group_state
958                            .raw
959                            .snatch(&mut self.snatchable_lock.write())
960                        else {
961                            continue;
962                        };
963
964                        resource_log!("Destroy raw {}", bind_group.error_ident());
965
966                        unsafe {
967                            self.raw().destroy_bind_group(raw_bind_group);
968                        }
969                    }
970                }
971            }
972        }
973    }
974
975    pub fn get_queue(&self) -> Option<Arc<Queue>> {
976        self.queue.get().as_ref()?.upgrade()
977    }
978
979    pub fn set_queue(&self, queue: &Arc<Queue>) {
980        assert!(self.queue.set(Arc::downgrade(queue)).is_ok());
981    }
982
983    /// Check device for freeable resources and completed buffer mappings.
984    pub fn poll(
985        &self,
986        poll_type: wgt::PollType<crate::SubmissionIndex>,
987    ) -> Result<wgt::PollStatus, WaitIdleError> {
988        api_log!("Device::poll {poll_type:?}");
989        let (user_closures, result) = self.poll_and_return_closures(poll_type);
990        user_closures.fire();
991        result
992    }
993
994    /// Poll the device, returning any `UserClosures` that need to be executed.
995    ///
996    /// The caller must invoke the `UserClosures` even if this function returns
997    /// an error. This is an internal helper, used by [`Device::poll`] and
998    /// [`Instance::poll_all_devices`], so that `poll_all_devices` can invoke
999    /// closures once after all devices have been polled.
1000    ///
1001    /// [`Instance::poll_all_devices`]: crate::instance::Instance::poll_all_devices
1002    pub(crate) fn poll_and_return_closures(
1003        &self,
1004        poll_type: wgt::PollType<crate::SubmissionIndex>,
1005    ) -> (UserClosures, Result<wgt::PollStatus, WaitIdleError>) {
1006        let snatch_guard = self.snatchable_lock.read();
1007        let maintain_result = self.maintain(poll_type, snatch_guard);
1008
1009        self.lose_if_oom();
1010
1011        // Some deferred destroys are scheduled in maintain so run this right after
1012        // to avoid holding on to them until the next device poll.
1013        self.deferred_resource_destruction();
1014
1015        maintain_result
1016    }
1017
1018    /// Check the current status of the GPU and process any submissions that have
1019    /// finished.
1020    ///
1021    /// The `poll_type` argument tells if this function should wait for a particular
1022    /// submission index to complete, or if it should just poll the current status.
1023    ///
1024    /// This will process _all_ completed submissions, even if the caller only asked
1025    /// us to poll to a given submission index.
1026    ///
1027    /// The returned [`UserClosures`] contains callbacks that need to be invoked informing
1028    /// the user about various things occurring. These happen and should be handled even
1029    /// if this function returns an error, hence they are outside of the result.
1030    pub(crate) fn maintain<'this>(
1031        &'this self,
1032        poll_type: wgt::PollType<crate::SubmissionIndex>,
1033        snatch_guard: SnatchGuard,
1034    ) -> (UserClosures, Result<wgt::PollStatus, WaitIdleError>) {
1035        profiling::scope!("Device::maintain");
1036
1037        let mut user_closures = UserClosures::default();
1038
1039        self.deferred_buffer_map_pending_closures
1040            .swap(&mut user_closures.mappings);
1041
1042        // If a wait was requested, determine which submission index to wait for.
1043        let wait_submission_index = match poll_type {
1044            wgt::PollType::Wait {
1045                submission_index: Some(submission_index),
1046                ..
1047            } => {
1048                let last_successful_submission_index = self
1049                    .last_successful_submission_index
1050                    .load(Ordering::Acquire);
1051
1052                if submission_index > last_successful_submission_index {
1053                    let result = Err(WaitIdleError::WrongSubmissionIndex(
1054                        submission_index,
1055                        last_successful_submission_index,
1056                    ));
1057
1058                    return (user_closures, result);
1059                }
1060
1061                Some(submission_index)
1062            }
1063            wgt::PollType::Wait {
1064                submission_index: None,
1065                ..
1066            } => Some(
1067                self.last_successful_submission_index
1068                    .load(Ordering::Acquire),
1069            ),
1070            wgt::PollType::Poll => None,
1071        };
1072
1073        // If a target submission index was specified, wait for it, and set
1074        // `wait_succeeded` to `Some(bool)` indicating success or timeout. If
1075        // no target was specified, set `wait_succeeded` to `None`.
1076        let wait_succeeded = if let Some(target_submission_index) = wait_submission_index {
1077            log::trace!("Device::maintain: waiting for submission index {target_submission_index}");
1078
1079            let wait_timeout = match poll_type {
1080                wgt::PollType::Wait { timeout, .. } => timeout,
1081                wgt::PollType::Poll => unreachable!(
1082                    "`wait_submission_index` index for poll type `Poll` should be None"
1083                ),
1084            };
1085
1086            let wait_result = unsafe {
1087                self.raw()
1088                    .wait(self.fence.as_ref(), target_submission_index, wait_timeout)
1089            };
1090
1091            match wait_result {
1092                Ok(succeeded) => Some(succeeded),
1093                Err(e) => {
1094                    let hal_error: WaitIdleError = self.handle_hal_error(e).into();
1095                    return (user_closures, Err(hal_error));
1096                }
1097            }
1098        } else {
1099            None
1100        };
1101
1102        // Get the currently finished submission index. This may be higher than the requested
1103        // wait, or it may be less than the requested wait if the wait failed.
1104        let fence_value_result = unsafe { self.raw().get_fence_value(self.fence.as_ref()) };
1105        let current_finished_submission = match fence_value_result {
1106            Ok(fence_value) => fence_value,
1107            Err(e) => {
1108                let hal_error: WaitIdleError = self.handle_hal_error(e).into();
1109                return (user_closures, Err(hal_error));
1110            }
1111        };
1112
1113        // When a device is marked invalid, we must destroy all its hal resources once its
1114        // queue is empty, by calling `release_gpu_resources`.
1115        //
1116        // However, checking device validity for this purpose is tricky. A device can be
1117        // marked invalid at any time, regardless of what locks are held. This means that,
1118        // even though queue submission does check device validity at the start (in
1119        // `Queue::allocate_submission`), the submission will proceed even if the
1120        // device gets marked invalid after that check. Thus, other threads can observe
1121        // the queue becoming non-empty even after they have observed the device to be
1122        // invalid.
1123        //
1124        // In this function, for `release_gpu_resources` to work as intended, we must be
1125        // sure that no further work can be submitted. Specifically, we must be sure that
1126        // if we see the device marked invalid, then so will any subsequent attempts to
1127        // submit work to the queue, causing them to fail. To accomplish this, it suffices
1128        // to hold the same lock while we call `is_valid` that `Queue::allocate_submission`
1129        // holds while it does the submission.
1130        let device_valid = {
1131            let _command_indices_guard = self.command_indices.read();
1132            self.is_valid()
1133        };
1134
1135        // Maintain all finished submissions on the queue, updating the relevant user closures and
1136        // collecting if the queue is empty.
1137        //
1138        // We don't use the result of the wait here, as we want to progress forward as far as
1139        // possible and the wait could have been for submissions that finished long ago.
1140        let mut queue_empty = false;
1141        if let Some(queue) = self.get_queue() {
1142            let queue_result = queue.maintain(current_finished_submission, &snatch_guard);
1143            (
1144                user_closures.submissions,
1145                user_closures.mappings,
1146                user_closures.blas_compact_ready,
1147                queue_empty,
1148            ) = queue_result;
1149            // DEADLOCK PREVENTION: We must drop `snatch_guard` before `queue` goes out of scope.
1150            //
1151            // `Queue::drop` acquires the snatch guard. If we still hold it when `queue` is dropped
1152            // at the end of this block, we would deadlock. This can happen in the following
1153            // scenario:
1154            //
1155            // - Thread A calls `Device::maintain` while Thread B holds the last strong ref to the
1156            //   queue.
1157            // - Thread A calls `self.get_queue()`, obtaining a new strong ref, and enters this
1158            //   branch.
1159            // - Thread B drops its strong ref, making Thread A's ref the last one.
1160            // - When `queue` goes out of scope here, `Queue::drop` runs and tries to acquire the
1161            //   snatch guard — but Thread A (this thread) still holds it, causing a deadlock.
1162            drop(snatch_guard);
1163        } else {
1164            drop(snatch_guard);
1165        };
1166
1167        // Based on the queue empty status, and the current finished submission index, determine
1168        // the result of the poll.
1169        //
1170        // After a successful wait, `current_finished_submission` should match or exceed
1171        // the target. But after a timeout, more work may have finished before
1172        // `current_finished_submission` is read, so it could be on either side of the
1173        // target, and the queue can also become empty before `Queue::maintain`
1174        // computes `queue_empty`.
1175        //
1176        // We report as accurately as we can with the information available. In
1177        // particular, when our wait timed out but `queue_empty` comes back `true`, we
1178        // report `WaitSucceeded` if `current_finished_submission` reached the target,
1179        // and `Timeout` if it didn't. We don't want to risk reporting `QueueEmpty`
1180        // without actually having seen that the target submission is retired.
1181        let result = if queue_empty && wait_succeeded != Some(false) {
1182            if let Some(wait_submission_index) = wait_submission_index {
1183                // Sanity-check that we don't report `QueueEmpty` without
1184                // reaching the target submission index.
1185                assert!(
1186                    current_finished_submission >= wait_submission_index,
1187                    concat!(
1188                        "If the queue is empty, the current submission index ",
1189                        "({}) should be at least the wait submission index ({})",
1190                    ),
1191                    current_finished_submission,
1192                    wait_submission_index,
1193                );
1194            } else {
1195                // We didn't wait (passive poll), safe to report `QueueEmpty`.
1196            }
1197
1198            Ok(wgt::PollStatus::QueueEmpty)
1199        } else if let Some(wait_submission_index) = wait_submission_index {
1200            // This is theoretically possible to succeed more than checking on the poll result
1201            // as submissions could have finished in the time between the timeout resolving,
1202            // the thread getting scheduled again, and us checking the fence value.
1203            if current_finished_submission >= wait_submission_index {
1204                Ok(wgt::PollStatus::WaitSucceeded)
1205            } else {
1206                Err(WaitIdleError::Timeout)
1207            }
1208        } else {
1209            Ok(wgt::PollStatus::Poll)
1210        };
1211
1212        // Detect if we have been destroyed and now need to lose the device.
1213        //
1214        // If we are invalid (set at start of destroy) and our queue is empty,
1215        // and we have a DeviceLostClosure, return the closure to be called by
1216        // our caller. This will complete the steps for both destroy and for
1217        // "lose the device".
1218        let mut should_release_gpu_resource = false;
1219        if !device_valid && queue_empty {
1220            // We can release gpu resources associated with this device (but not
1221            // while holding the life_tracker lock).
1222            should_release_gpu_resource = true;
1223
1224            // If we have a DeviceLostClosure, build an invocation with the
1225            // reason DeviceLostReason::Destroyed and no message.
1226            if let Some(device_lost_closure) = self.device_lost_closure.lock().take() {
1227                user_closures
1228                    .device_lost_invocations
1229                    .push(DeviceLostInvocation {
1230                        closure: device_lost_closure,
1231                        reason: DeviceLostReason::Destroyed,
1232                        message: String::new(),
1233                    });
1234            }
1235        }
1236
1237        if should_release_gpu_resource {
1238            self.release_gpu_resources();
1239        }
1240
1241        (user_closures, result)
1242    }
1243
1244    pub fn create_buffer_inner(
1245        self: &Arc<Self>,
1246        desc: &resource::BufferDescriptor,
1247    ) -> Result<Arc<Buffer>, resource::CreateBufferError> {
1248        self.check_is_valid()?;
1249
1250        if desc.size > self.limits.max_buffer_size {
1251            return Err(resource::CreateBufferError::MaxBufferSize {
1252                requested: desc.size,
1253                maximum: self.limits.max_buffer_size,
1254            });
1255        }
1256
1257        if desc
1258            .usage
1259            .intersects(wgt::BufferUsages::BLAS_INPUT | wgt::BufferUsages::TLAS_INPUT)
1260        {
1261            self.require_acceleration_structures()?;
1262        }
1263
1264        if desc.usage.contains(wgt::BufferUsages::INDEX)
1265            && desc.usage.contains(
1266                wgt::BufferUsages::VERTEX
1267                    | wgt::BufferUsages::UNIFORM
1268                    | wgt::BufferUsages::INDIRECT
1269                    | wgt::BufferUsages::STORAGE,
1270            )
1271        {
1272            self.require_downlevel_flags(wgt::DownlevelFlags::UNRESTRICTED_INDEX_BUFFER)?;
1273        }
1274
1275        if desc.usage.is_empty() || desc.usage.contains_unknown_bits() {
1276            return Err(resource::CreateBufferError::InvalidUsage(desc.usage));
1277        }
1278
1279        if !self
1280            .features
1281            .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS)
1282        {
1283            use wgt::BufferUsages as Bu;
1284            let write_mismatch = desc.usage.contains(Bu::MAP_WRITE)
1285                && !(Bu::MAP_WRITE | Bu::COPY_SRC).contains(desc.usage);
1286            let read_mismatch = desc.usage.contains(Bu::MAP_READ)
1287                && !(Bu::MAP_READ | Bu::COPY_DST).contains(desc.usage);
1288            if write_mismatch || read_mismatch {
1289                return Err(resource::CreateBufferError::UsageMismatch(desc.usage));
1290            }
1291        }
1292
1293        let mut usage = conv::map_buffer_usage(desc.usage);
1294
1295        if desc.usage.contains(wgt::BufferUsages::INDIRECT) {
1296            self.require_downlevel_flags(wgt::DownlevelFlags::INDIRECT_EXECUTION)?;
1297            // We are going to be reading from it, internally;
1298            // when validating the content of the buffer
1299            usage |= wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::STORAGE_READ_WRITE;
1300        }
1301
1302        if desc.usage.contains(wgt::BufferUsages::QUERY_RESOLVE) {
1303            usage |= TIMESTAMP_NORMALIZATION_BUFFER_USES;
1304        }
1305
1306        if desc.mapped_at_creation {
1307            if !desc.size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1308                return Err(resource::CreateBufferError::UnalignedSize);
1309            }
1310            if !desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
1311                // we are going to be copying into it, internally
1312                usage |= wgt::BufferUses::COPY_DST;
1313            }
1314        } else {
1315            // We are required to zero out (initialize) all memory. This is done
1316            // on demand using clear_buffer which requires write transfer usage!
1317            usage |= wgt::BufferUses::COPY_DST;
1318        }
1319
1320        // The great thing about buffer sizes is there are so many to choose from!
1321        //  - The application may request an arbitrary byte-aligned size.
1322        //  - If the buffer supports usage as a vertex or index buffer, we must ensure there
1323        //    is a naturally aligned block of 4B at the end of the buffer. Zero-size bindings
1324        //    are not supported by hal and are redirected to this block by
1325        //    `resolve_vertex_or_index_binding_range`.
1326        //  - The overall buffer size must be a non-zero multiple of COPY_BUFFER_ALIGNMENT (4).
1327        //    In some cases additional platform-dependent requirements may apply. The actual
1328        //    allocated size of the buffer is returned by hal along with the buffer object from
1329        //    `create_buffer`. `wgpu-core` is responsible for ensuring that any region of the
1330        //    buffer, including hal-added padding, is initialized before it may be accessed.
1331        //
1332        // Because buffer writes for initialization operate at multiples of COPY_BUFFER_ALIGNMENT,
1333        // and because initialization tracking will never determine that it is necessary to
1334        // initialize a region outside the application-visible range, round the tracked
1335        // initialization range down to a multiple of COPY_BUFFER_ALIGNMENT (tail_start), and
1336        // eagerly zero-initialize from there to the buffer's true end.
1337
1338        let padded_size = if desc.size == 0 {
1339            wgt::COPY_BUFFER_ALIGNMENT
1340        } else if desc
1341            .usage
1342            .intersects(wgt::BufferUsages::VERTEX | wgt::BufferUsages::INDEX)
1343        {
1344            // We require 4B of padding with 4B alignment. See above.
1345            align_to(desc.size, wgt::COPY_BUFFER_ALIGNMENT) + wgt::COPY_BUFFER_ALIGNMENT
1346        } else {
1347            align_to(desc.size, wgt::COPY_BUFFER_ALIGNMENT)
1348        };
1349        let tail_start = desc.size & !(wgt::COPY_BUFFER_ALIGNMENT - 1);
1350
1351        let hal_desc = hal::BufferDescriptor {
1352            label: desc.label.to_hal(self.instance_flags),
1353            size: padded_size,
1354            usage,
1355            memory_flags: hal::MemoryFlags::empty(),
1356        };
1357        let (buffer, final_size) = unsafe { self.raw().create_buffer(&hal_desc) }
1358            .map_err(|e| self.handle_hal_error_with_nonfatal_oom(e))?;
1359
1360        debug_assert!(final_size >= padded_size);
1361
1362        let timestamp_normalization_bind_group = Snatchable::new(unsafe {
1363            // SAFETY: The size passed here must be 4B aligned, >= the application size, and
1364            // <= the buffer size.
1365            self.timestamp_normalizer
1366                .get()
1367                .unwrap()
1368                .create_normalization_bind_group(
1369                    self,
1370                    &*buffer,
1371                    desc.label.as_deref(),
1372                    wgt::BufferSize::new(hal_desc.size).unwrap(),
1373                    desc.usage,
1374                )
1375        }?);
1376
1377        let indirect_validation_bind_groups =
1378            self.create_indirect_validation_bind_groups(buffer.as_ref(), desc.size, desc.usage)?;
1379
1380        let buffer = Buffer {
1381            state: ResourceState::Valid(BufferState {
1382                raw: Snatchable::new(buffer),
1383            }),
1384            device: self.clone(),
1385            usage: desc.usage,
1386            size: desc.size,
1387            initialization_status: RwLock::new(
1388                rank::BUFFER_INITIALIZATION_STATUS,
1389                BufferInitTracker::new(tail_start),
1390            ),
1391            map_state: Arc::new(RwLock::new(
1392                rank::BUFFER_MAP_STATE,
1393                resource::BufferMapState::Idle,
1394            )),
1395            label: desc.label.to_string(),
1396            tracking_data: TrackingData::new(self.tracker_indices.buffers.clone()),
1397            bind_groups: Mutex::new(rank::BUFFER_BIND_GROUPS, WeakVec::new()),
1398            timestamp_normalization_bind_group,
1399            indirect_validation_bind_groups,
1400        };
1401
1402        let buffer = Arc::new(buffer);
1403
1404        let init_buffer_tail = |buffer, snatch_guard| {
1405            let mapping = map_buffer(
1406                buffer,
1407                tail_start,
1408                final_size - tail_start,
1409                MapMode::Write,
1410                snatch_guard,
1411            )?;
1412            let raw = buffer
1413                .raw(snatch_guard)
1414                .expect("newly-created buffer cannot be destroyed");
1415            unsafe {
1416                // SAFETY: The buffer tail is valid and aligned.
1417                mapping
1418                    .ptr
1419                    .write_bytes(0, (final_size - tail_start) as usize);
1420                if !mapping.is_coherent {
1421                    #[allow(clippy::single_range_in_vec_init)]
1422                    self.raw()
1423                        .flush_mapped_ranges(raw, &[tail_start..final_size]);
1424                }
1425                self.raw().unmap_buffer(raw);
1426            }
1427            Ok::<_, resource::CreateBufferError>(())
1428        };
1429
1430        let buffer_use = if !desc.mapped_at_creation {
1431            if tail_start == final_size {
1432                // No tail init necessary
1433            } else if desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
1434                // Tail init by mapping
1435                let snatch_guard = self.snatchable_lock.read();
1436                init_buffer_tail(&buffer, &snatch_guard)?;
1437            } else if let Some(queue) = self.get_queue() {
1438                // Schedule tail init in pending writes
1439                let snatch_guard = self.snatchable_lock.read();
1440                let mut pending_writes = queue.pending_writes.lock();
1441                self.trackers
1442                    .lock()
1443                    .buffers
1444                    .insert_single(&buffer, wgt::BufferUses::COPY_DST);
1445                pending_writes.clear_buffer(
1446                    self,
1447                    &buffer,
1448                    tail_start..final_size,
1449                    &snatch_guard,
1450                )?;
1451                return Ok(buffer);
1452            } else {
1453                // Queue is gone, buffer will not be used.
1454            }
1455            wgt::BufferUses::empty()
1456        } else if desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
1457            // Mapped-at-creation with MAP_WRITE. Tail init by mapping, then map the
1458            // application-visible portion of the buffer. Don't do both in the same
1459            // mapping, because the application shouldn't see the tail.
1460            let snatch_guard = self.snatchable_lock.read();
1461            if tail_start != final_size {
1462                init_buffer_tail(&buffer, &snatch_guard)?;
1463            }
1464            let map_size = buffer.size;
1465            let mapping = if map_size == 0 {
1466                hal::BufferMapping {
1467                    ptr: core::ptr::NonNull::dangling(),
1468                    is_coherent: true,
1469                }
1470            } else {
1471                map_buffer(&buffer, 0, map_size, MapMode::Write, &snatch_guard)?
1472            };
1473            drop(snatch_guard);
1474            *buffer.map_state.write() = resource::BufferMapState::Active {
1475                mapping,
1476                range: 0..map_size,
1477                host: MapMode::Write,
1478            };
1479            wgt::BufferUses::MAP_WRITE
1480        } else {
1481            // Mapped-at-creation without MAP_WRITE. Create and zero-initialize a staging
1482            // buffer for the entire buffer (including tail). It is okay to use a single
1483            // mapping, `get_mapped_range` will still only expose the application-visible
1484            // range. The application could corrupt the tail with an out-of-bounds write,
1485            // which may cause problems for its shaders if they read out-of-bounds, but
1486            // won't cause problems in wgpu.
1487            let mut staging_buffer =
1488                StagingBuffer::new(self, wgt::BufferSize::new(final_size).unwrap())?;
1489
1490            // Zero initialize memory and then mark the buffer as initialized
1491            // (it's guaranteed that this is the case by the time the buffer is usable)
1492            staging_buffer.write_zeros();
1493            buffer.initialization_status.write().drain(0..final_size);
1494
1495            *buffer.map_state.write() = resource::BufferMapState::Init { staging_buffer };
1496            wgt::BufferUses::COPY_DST
1497        };
1498
1499        // If we didn't add the buffer to the tracker already for initialization via
1500        // PendingWrites, do so now.
1501
1502        self.trackers
1503            .lock()
1504            .buffers
1505            .insert_single(&buffer, buffer_use);
1506
1507        Ok(buffer)
1508    }
1509
1510    pub fn create_buffer(self: &Arc<Self>, desc: &resource::BufferDescriptor) -> Arc<Buffer> {
1511        profiling::scope!("Device::create_buffer");
1512
1513        let buffer = self.create_buffer_inner(desc).unwrap_or_else(|err| {
1514            self.handle_error(err, desc.label.as_deref(), "Device::create_buffer");
1515            Buffer::invalid(Arc::clone(self), desc)
1516        });
1517        #[cfg(feature = "trace")]
1518        if let Some(ref mut trace) = *self.trace.lock() {
1519            use trace::IntoTrace;
1520            let mut desc = desc.clone();
1521            let mapped_at_creation = mem::replace(&mut desc.mapped_at_creation, false);
1522            if mapped_at_creation && !desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
1523                desc.usage |= wgt::BufferUsages::COPY_DST;
1524            }
1525            trace.add(trace::Action::CreateBuffer(buffer.to_trace(), desc));
1526        }
1527        api_log!(
1528            "Device::create_buffer({:?}{}) -> {:?}",
1529            desc.label.as_deref().unwrap_or(""),
1530            if desc.mapped_at_creation {
1531                ", mapped_at_creation"
1532            } else {
1533                ""
1534            },
1535            Arc::as_ptr(&buffer)
1536        );
1537        buffer
1538    }
1539
1540    #[cfg(feature = "replay")]
1541    pub fn set_buffer_data(
1542        self: &Arc<Self>,
1543        buffer: &Arc<Buffer>,
1544        offset: wgt::BufferAddress,
1545        data: &[u8],
1546        mode: MapMode,
1547    ) -> resource::BufferAccessResult {
1548        use crate::resource::RawResourceAccess;
1549
1550        let device = &buffer.device;
1551
1552        device.check_is_valid()?;
1553        buffer.check_usage(wgt::BufferUsages::MAP_WRITE)?;
1554
1555        let last_submission = device
1556            .get_queue()
1557            .and_then(|queue| queue.lock_life().get_buffer_latest_submission_index(buffer));
1558
1559        if let Some(last_submission) = last_submission {
1560            device.wait_for_submit(last_submission)?;
1561        }
1562
1563        let snatch_guard = device.snatchable_lock.read();
1564        let raw_buf = buffer.try_raw(&snatch_guard)?;
1565
1566        if offset > buffer.size {
1567            return Err(resource::BufferAccessError::OutOfBoundsStartOffsetOverrun {
1568                index: offset,
1569                max: buffer.size,
1570            });
1571        } else if buffer.size - offset < u64::try_from(data.len()).unwrap() {
1572            return Err(resource::BufferAccessError::OutOfBoundsEndOffsetOverrun {
1573                index: offset,
1574                size: u64::try_from(data.len()).unwrap(),
1575                max: buffer.size,
1576            });
1577        }
1578
1579        let mapping = unsafe {
1580            device
1581                .raw()
1582                .map_buffer(raw_buf, offset..offset + u64::try_from(data.len()).unwrap())
1583        }
1584        .map_err(|e| device.handle_hal_error(e))?;
1585
1586        unsafe { core::ptr::copy_nonoverlapping(data.as_ptr(), mapping.ptr.as_ptr(), data.len()) };
1587
1588        if !mapping.is_coherent {
1589            #[allow(clippy::single_range_in_vec_init)]
1590            unsafe {
1591                device
1592                    .raw()
1593                    .flush_mapped_ranges(raw_buf, &[offset..offset + data.len() as u64])
1594            };
1595        }
1596
1597        unsafe { device.raw().unmap_buffer(raw_buf) };
1598
1599        Ok(mode)
1600    }
1601
1602    /// # Safety
1603    ///
1604    /// - `hal_texture` must be created from `device_id` corresponding raw handle.
1605    /// - `hal_texture` must be created respecting `desc`
1606    /// - `hal_texture` must be initialized
1607    /// - The `initial_state` must match the actual driver-side state of
1608    ///   the wrapped resource at the moment of wrap.
1609    pub unsafe fn create_texture_from_hal(
1610        self: &Arc<Self>,
1611        hal_texture: Box<dyn hal::DynTexture>,
1612        desc: &resource::TextureDescriptor,
1613        initial_state: wgt::TextureUses,
1614        cleared: bool,
1615    ) -> (Arc<Texture>, Option<resource::CreateTextureError>) {
1616        profiling::scope!("Device::create_texture_from_hal");
1617
1618        let (texture, error) =
1619            match self.create_texture_from_hal_inner(hal_texture, desc, initial_state, cleared) {
1620                Ok(texture) => (texture, None),
1621                Err(e) => (Texture::invalid(self, desc), Some(e)),
1622            };
1623
1624        // NB: Any change done through the raw texture handle will not be
1625        // recorded in the replay
1626        #[cfg(feature = "trace")]
1627        if let Some(ref mut trace) = *self.trace.lock() {
1628            trace.add(trace::Action::CreateTexture(
1629                texture.to_trace(),
1630                desc.clone(),
1631            ));
1632        }
1633
1634        api_log!(
1635            "Device::create_texture({desc:?}) -> {:?}",
1636            Arc::as_ptr(&texture)
1637        );
1638
1639        (texture, error)
1640    }
1641
1642    pub(crate) fn create_texture_from_hal_inner(
1643        self: &Arc<Self>,
1644        hal_texture: Box<dyn hal::DynTexture>,
1645        desc: &resource::TextureDescriptor,
1646        initial_state: wgt::TextureUses,
1647        cleared: bool,
1648    ) -> Result<Arc<Texture>, resource::CreateTextureError> {
1649        // Count the raw texture before validation so the error paths below can
1650        // hand it back through `destroy_texture`. Merely dropping a hal texture
1651        // does not release what it wraps — e.g. an imported WebGL handle would
1652        // stay registered in glow's resource tracker forever.
1653        unsafe { self.raw().add_raw_texture(&*hal_texture) };
1654
1655        if let Err(error) = self.check_is_valid() {
1656            unsafe { self.raw().destroy_texture(hal_texture) };
1657            return Err(error.into());
1658        }
1659
1660        let format_features = match self.describe_format_features(desc.format) {
1661            Ok(format_features) => format_features,
1662            Err(error) => {
1663                unsafe { self.raw().destroy_texture(hal_texture) };
1664                return Err(resource::CreateTextureError::MissingFeatures(
1665                    desc.format,
1666                    error,
1667                ));
1668            }
1669        };
1670
1671        let texture = Texture::new(
1672            self,
1673            resource::TextureInner::Native { raw: hal_texture },
1674            conv::map_texture_usage(desc.usage, desc.format.into(), format_features.flags),
1675            desc,
1676            format_features,
1677            resource::TextureClearMode::None,
1678            !cleared, // inverted so it marks the tracker properly
1679            self.resolve_texture_binding_view_dimension(desc),
1680        );
1681
1682        let texture = Arc::new(texture);
1683
1684        self.trackers
1685            .lock()
1686            .textures
1687            .insert_single(&texture, initial_state);
1688
1689        Ok(texture)
1690    }
1691
1692    /// # Safety
1693    ///
1694    /// - `hal_buffer` must have been created on this device.
1695    /// - `hal_buffer` must have been created respecting `desc` (in particular, the size,
1696    ///   which must always be a multiple of 4, and may be subject to other requirements).
1697    /// - `hal_buffer` must be initialized.
1698    /// - `hal_buffer` must not have zero size.
1699    pub unsafe fn create_buffer_from_hal(
1700        self: &Arc<Self>,
1701        hal_buffer: Box<dyn hal::DynBuffer>,
1702        desc: &resource::BufferDescriptor,
1703    ) -> (Arc<Buffer>, Option<resource::CreateBufferError>) {
1704        profiling::scope!("Device::create_buffer");
1705        let (buffer, error) = match unsafe { self.create_buffer_from_hal_inner(hal_buffer, desc) } {
1706            Ok(buffer) => (buffer, None),
1707            Err(e) => (Buffer::invalid(Arc::clone(self), desc), Some(e)),
1708        };
1709
1710        // NB: Any change done through the raw buffer handle will not be
1711        // recorded in the replay
1712        #[cfg(feature = "trace")]
1713        if let Some(trace) = self.trace.lock().as_mut() {
1714            use trace::IntoTrace;
1715            trace.add(trace::Action::CreateBuffer(buffer.to_trace(), desc.clone()));
1716        }
1717        api_log!("Device::create_buffer -> {:?}", Arc::as_ptr(&buffer));
1718        (buffer, error)
1719    }
1720
1721    /// # Safety
1722    ///
1723    /// Same safety requirements as `create_buffer_from_hal`.
1724    pub(crate) unsafe fn create_buffer_from_hal_inner(
1725        self: &Arc<Self>,
1726        hal_buffer: Box<dyn hal::DynBuffer>,
1727        desc: &resource::BufferDescriptor,
1728    ) -> Result<Arc<Buffer>, resource::CreateBufferError> {
1729        let timestamp_normalization_bind_group = Snatchable::new(unsafe {
1730            // SAFETY: The size passed here must be 4B aligned, >= the application size, and
1731            // <= the buffer size.
1732            self.timestamp_normalizer
1733                .get()
1734                .unwrap()
1735                .create_normalization_bind_group(
1736                    self,
1737                    &*hal_buffer,
1738                    desc.label.as_deref(),
1739                    wgt::BufferSize::new(desc.size).unwrap(),
1740                    desc.usage,
1741                )?
1742        });
1743
1744        let indirect_validation_bind_groups = self.create_indirect_validation_bind_groups(
1745            hal_buffer.as_ref(),
1746            desc.size,
1747            desc.usage,
1748        )?;
1749
1750        unsafe { self.raw().add_raw_buffer(&*hal_buffer) };
1751
1752        let buffer = Buffer {
1753            state: ResourceState::Valid(BufferState {
1754                raw: Snatchable::new(hal_buffer),
1755            }),
1756            device: self.clone(),
1757            usage: desc.usage,
1758            size: desc.size,
1759            initialization_status: RwLock::new(
1760                rank::BUFFER_INITIALIZATION_STATUS,
1761                BufferInitTracker::new(0),
1762            ),
1763            map_state: Arc::new(RwLock::new(
1764                rank::BUFFER_MAP_STATE,
1765                resource::BufferMapState::Idle,
1766            )),
1767            label: desc.label.to_string(),
1768            tracking_data: TrackingData::new(self.tracker_indices.buffers.clone()),
1769            bind_groups: Mutex::new(rank::BUFFER_BIND_GROUPS, WeakVec::new()),
1770            timestamp_normalization_bind_group,
1771            indirect_validation_bind_groups,
1772        };
1773
1774        let buffer = Arc::new(buffer);
1775
1776        self.trackers
1777            .lock()
1778            .buffers
1779            .insert_single(&buffer, wgt::BufferUses::empty());
1780
1781        Ok(buffer)
1782    }
1783
1784    /// If needed, creates the bind groups for indirect validation shaders to read
1785    /// from `raw_buffer`.
1786    ///
1787    /// `buffer_size` is the user-requested size of the buffer.
1788    fn create_indirect_validation_bind_groups(
1789        &self,
1790        raw_buffer: &dyn hal::DynBuffer,
1791        buffer_size: u64,
1792        usage: wgt::BufferUsages,
1793    ) -> Result<Snatchable<crate::indirect_validation::BindGroups>, resource::CreateBufferError>
1794    {
1795        if !usage.contains(wgt::BufferUsages::INDIRECT) {
1796            return Ok(Snatchable::empty());
1797        }
1798
1799        let Some(ref indirect_validation) = self.indirect_validation else {
1800            return Ok(Snatchable::empty());
1801        };
1802
1803        let bind_groups = crate::indirect_validation::BindGroups::new(
1804            indirect_validation,
1805            self,
1806            buffer_size,
1807            raw_buffer,
1808        )
1809        .map_err(resource::CreateBufferError::IndirectValidationBindGroup)?;
1810
1811        if let Some(bind_groups) = bind_groups {
1812            Ok(Snatchable::new(bind_groups))
1813        } else {
1814            Ok(Snatchable::empty())
1815        }
1816    }
1817
1818    /// Validate a texture descriptor.
1819    ///
1820    /// This applies the same validation as [`Self::create_texture`], without
1821    /// actually creating a texture.
1822    pub fn validate_texture_descriptor(
1823        self: &Arc<Self>,
1824        desc: &resource::TextureDescriptor,
1825    ) -> Result<(), resource::CreateTextureError> {
1826        self.validate_texture_descriptor_inner(desc)?;
1827        Ok(())
1828    }
1829
1830    /// Validate a texture descriptor.
1831    ///
1832    /// Implements the [validating GPUTextureDescriptor] algorithm, with some
1833    /// `wgpu` extensions.
1834    ///
1835    /// [validating GPUTextureDescriptor]: https://www.w3.org/TR/webgpu/#abstract-opdef-validating-gputexturedescriptor
1836    fn validate_texture_descriptor_inner(
1837        self: &Arc<Self>,
1838        desc: &resource::TextureDescriptor,
1839    ) -> Result<(wgt::TextureFormatFeatures, Vec<TextureFormat>), resource::CreateTextureError>
1840    {
1841        use resource::{
1842            CreateTextureError, TextureBindingViewDimensionError, TextureDimensionError,
1843        };
1844
1845        self.check_is_valid()?;
1846
1847        if desc.usage.is_empty() || desc.usage.contains_unknown_bits() {
1848            return Err(CreateTextureError::InvalidUsage(desc.usage));
1849        }
1850
1851        conv::check_texture_dimension_size(
1852            desc.dimension,
1853            desc.size,
1854            desc.sample_count,
1855            &self.limits,
1856        )?;
1857
1858        if desc.dimension != wgt::TextureDimension::D2 {
1859            // Depth textures can only be 2D
1860            if desc.format.is_depth_stencil_format() {
1861                return Err(CreateTextureError::InvalidDepthDimension(
1862                    desc.dimension,
1863                    desc.format,
1864                ));
1865            }
1866            // Transient textures can only be 2D
1867            if desc
1868                .usage
1869                .contains(wgt::TextureUsages::TRANSIENT_ATTACHMENT)
1870            {
1871                return Err(CreateTextureError::InvalidDimensionUsages(
1872                    wgt::TextureUsages::TRANSIENT_ATTACHMENT,
1873                    desc.dimension,
1874                ));
1875            }
1876        }
1877
1878        if desc.dimension != wgt::TextureDimension::D2
1879            && desc.dimension != wgt::TextureDimension::D3
1880        {
1881            // Compressed textures can only be 2D or 3D
1882            if desc.format.is_compressed() {
1883                return Err(CreateTextureError::InvalidCompressedDimension(
1884                    desc.dimension,
1885                    desc.format,
1886                ));
1887            }
1888
1889            // Renderable textures can only be 2D or 3D
1890            if desc.usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT) {
1891                return Err(CreateTextureError::InvalidDimensionUsages(
1892                    wgt::TextureUsages::RENDER_ATTACHMENT,
1893                    desc.dimension,
1894                ));
1895            }
1896        }
1897
1898        if desc.format.is_compressed() {
1899            let (block_width, block_height) = desc.format.block_dimensions();
1900
1901            if !desc.size.width.is_multiple_of(block_width) {
1902                return Err(CreateTextureError::InvalidDimension(
1903                    TextureDimensionError::NotMultipleOfBlockWidth {
1904                        width: desc.size.width,
1905                        block_width,
1906                        format: desc.format,
1907                    },
1908                ));
1909            }
1910
1911            if !desc.size.height.is_multiple_of(block_height) {
1912                return Err(CreateTextureError::InvalidDimension(
1913                    TextureDimensionError::NotMultipleOfBlockHeight {
1914                        height: desc.size.height,
1915                        block_height,
1916                        format: desc.format,
1917                    },
1918                ));
1919            }
1920
1921            if desc.dimension == wgt::TextureDimension::D3 {
1922                // Only BCn formats with Sliced 3D feature can be used for 3D textures
1923                if desc.format.is_bcn() {
1924                    self.require_features(wgt::Features::TEXTURE_COMPRESSION_BC_SLICED_3D)
1925                        .map_err(|error| CreateTextureError::MissingFeatures(desc.format, error))?;
1926                } else if desc.format.is_astc() {
1927                    self.require_features(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D)
1928                        .map_err(|error| CreateTextureError::MissingFeatures(desc.format, error))?;
1929                } else {
1930                    return Err(CreateTextureError::InvalidCompressedDimension(
1931                        desc.dimension,
1932                        desc.format,
1933                    ));
1934                }
1935            }
1936        }
1937
1938        let mips = desc.mip_level_count;
1939        let max_levels_allowed = desc.size.max_mips(desc.dimension).min(hal::MAX_MIP_LEVELS);
1940        if mips == 0 || mips > max_levels_allowed {
1941            return Err(CreateTextureError::InvalidMipLevelCount {
1942                requested: mips,
1943                maximum: max_levels_allowed,
1944            });
1945        }
1946
1947        {
1948            let (mut width_multiple, mut height_multiple) = desc.format.size_multiple_requirement();
1949
1950            if desc.format.is_multi_planar_format() {
1951                // TODO(https://github.com/gfx-rs/wgpu/issues/8491): fix
1952                // `mip_level_size` calculation for these formats and relax this
1953                // restriction.
1954                width_multiple <<= desc.mip_level_count.saturating_sub(1);
1955                height_multiple <<= desc.mip_level_count.saturating_sub(1);
1956            }
1957
1958            if !desc.size.width.is_multiple_of(width_multiple) {
1959                return Err(CreateTextureError::InvalidDimension(
1960                    TextureDimensionError::WidthNotMultipleOf {
1961                        width: desc.size.width,
1962                        multiple: width_multiple,
1963                        format: desc.format,
1964                    },
1965                ));
1966            }
1967
1968            if !desc.size.height.is_multiple_of(height_multiple) {
1969                return Err(CreateTextureError::InvalidDimension(
1970                    TextureDimensionError::HeightNotMultipleOf {
1971                        height: desc.size.height,
1972                        multiple: height_multiple,
1973                        format: desc.format,
1974                    },
1975                ));
1976            }
1977        }
1978
1979        if desc
1980            .usage
1981            .contains(wgt::TextureUsages::TRANSIENT_ATTACHMENT)
1982        {
1983            if desc.usage
1984                != (wgt::TextureUsages::TRANSIENT_ATTACHMENT
1985                    | wgt::TextureUsages::RENDER_ATTACHMENT)
1986            {
1987                return Err(CreateTextureError::InvalidTransientTextureUsage(desc.usage));
1988            }
1989
1990            if desc.mip_level_count != 1 {
1991                return Err(CreateTextureError::InvalidTransientTextureMipLevelCount(
1992                    desc.mip_level_count,
1993                ));
1994            }
1995
1996            if desc.size.depth_or_array_layers != 1 {
1997                return Err(CreateTextureError::InvalidTransientTextureLayerCount(
1998                    desc.size.depth_or_array_layers,
1999                ));
2000            }
2001
2002            if !desc.view_formats.is_empty() {
2003                return Err(CreateTextureError::InvalidTransientTextureViewFormats);
2004            }
2005        }
2006
2007        let format_features = self
2008            .describe_format_features(desc.format)
2009            .map_err(|error| CreateTextureError::MissingFeatures(desc.format, error))?;
2010
2011        if let Some(planes) = desc.format.planes() {
2012            for plane in 0..planes {
2013                let aspect = wgt::TextureAspect::from_plane(plane).unwrap();
2014                let format = desc.format.aspect_specific_format(aspect).unwrap();
2015                self.require_features(format.required_features())
2016                    .map_err(|error| CreateTextureError::MissingFeatures(desc.format, error))?;
2017            }
2018        }
2019
2020        if desc.sample_count > 1 {
2021            // <https://www.w3.org/TR/2025/CRD-webgpu-20251120/#:~:text=If%20descriptor%2EsampleCount%20%3E%201>
2022            //
2023            // Note that there are also some checks related to the sample count
2024            // in [`conv::check_texture_dimension_size`].
2025
2026            if desc.mip_level_count != 1 {
2027                return Err(CreateTextureError::InvalidMipLevelCount {
2028                    requested: desc.mip_level_count,
2029                    maximum: 1,
2030                });
2031            }
2032
2033            if desc.size.depth_or_array_layers != 1
2034                && !self.features.contains(wgt::Features::MULTISAMPLE_ARRAY)
2035            {
2036                return Err(CreateTextureError::InvalidDimension(
2037                    TextureDimensionError::MultisampledDepthOrArrayLayer(
2038                        desc.size.depth_or_array_layers,
2039                    ),
2040                ));
2041            }
2042
2043            if desc.usage.contains(wgt::TextureUsages::STORAGE_BINDING) {
2044                return Err(CreateTextureError::InvalidMultisampledStorageBinding);
2045            }
2046
2047            if !desc.usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT) {
2048                return Err(CreateTextureError::MultisampledNotRenderAttachment);
2049            }
2050
2051            if !format_features.flags.intersects(
2052                wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4
2053                    | wgt::TextureFormatFeatureFlags::MULTISAMPLE_X2
2054                    | wgt::TextureFormatFeatureFlags::MULTISAMPLE_X8
2055                    | wgt::TextureFormatFeatureFlags::MULTISAMPLE_X16,
2056            ) {
2057                return Err(CreateTextureError::InvalidMultisampledFormat(desc.format));
2058            }
2059
2060            if !format_features
2061                .flags
2062                .sample_count_supported(desc.sample_count)
2063            {
2064                return Err(CreateTextureError::InvalidSampleCount(
2065                    desc.sample_count,
2066                    desc.format,
2067                    desc.format
2068                        .guaranteed_format_features(self.features)
2069                        .flags
2070                        .supported_sample_counts(),
2071                    self.adapter
2072                        .get_texture_format_features(desc.format)
2073                        .flags
2074                        .supported_sample_counts(),
2075                ));
2076            };
2077        }
2078
2079        let missing_allowed_usages = desc.usage - format_features.allowed_usages;
2080        if !missing_allowed_usages.is_empty() {
2081            // detect downlevel incompatibilities
2082            let wgpu_allowed_usages = desc
2083                .format
2084                .guaranteed_format_features(self.features)
2085                .allowed_usages;
2086            let wgpu_missing_usages = desc.usage - wgpu_allowed_usages;
2087            return Err(CreateTextureError::InvalidFormatUsages(
2088                missing_allowed_usages,
2089                desc.format,
2090                wgpu_missing_usages.is_empty(),
2091            ));
2092        }
2093
2094        let mut hal_view_formats = Vec::new();
2095        for format in desc.view_formats.iter() {
2096            self.require_features(format.required_features())
2097                .map_err(|error| CreateTextureError::MissingFeatures(*format, error))?;
2098            if desc.format == *format {
2099                continue;
2100            }
2101            if desc.format.remove_srgb_suffix() != format.remove_srgb_suffix() {
2102                return Err(CreateTextureError::InvalidViewFormat(*format, desc.format));
2103            }
2104            hal_view_formats.push(*format);
2105        }
2106        if !hal_view_formats.is_empty() {
2107            self.require_downlevel_flags(wgt::DownlevelFlags::VIEW_FORMATS)?;
2108        }
2109
2110        if !self
2111            .downlevel
2112            .flags
2113            .contains(wgt::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS)
2114        {
2115            if let Some(texture_binding_view_dimension) = desc.texture_binding_view_dimension {
2116                match texture_binding_view_dimension {
2117                    TextureViewDimension::D2 => {
2118                        if desc.size.depth_or_array_layers != 1 {
2119                            return Err(CreateTextureError::InvalidTextureBindingViewDimension(
2120                                TextureBindingViewDimensionError::InvalidLayerCount {
2121                                    dimension: texture_binding_view_dimension,
2122                                    required: 1,
2123                                    actual: desc.size.depth_or_array_layers,
2124                                },
2125                            ));
2126                        }
2127                    }
2128                    TextureViewDimension::Cube => {
2129                        if desc.size.depth_or_array_layers != 6 {
2130                            return Err(CreateTextureError::InvalidTextureBindingViewDimension(
2131                                TextureBindingViewDimensionError::InvalidLayerCount {
2132                                    dimension: texture_binding_view_dimension,
2133                                    required: 6,
2134                                    actual: desc.size.depth_or_array_layers,
2135                                },
2136                            ));
2137                        }
2138                    }
2139                    TextureViewDimension::CubeArray => {
2140                        self.require_downlevel_flags(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES)?;
2141                        if !desc.size.depth_or_array_layers.is_multiple_of(6) {
2142                            return Err(CreateTextureError::InvalidTextureBindingViewDimension(
2143                                TextureBindingViewDimensionError::InvalidCubeArrayLayerCount(
2144                                    desc.size.depth_or_array_layers,
2145                                ),
2146                            ));
2147                        }
2148                    }
2149                    _ => {}
2150                }
2151            }
2152        }
2153
2154        Ok((format_features, hal_view_formats))
2155    }
2156
2157    fn resolve_texture_binding_view_dimension(
2158        &self,
2159        desc: &resource::TextureDescriptor,
2160    ) -> Option<TextureViewDimension> {
2161        if self
2162            .downlevel
2163            .flags
2164            .contains(wgt::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS)
2165        {
2166            None
2167        } else {
2168            Some(
2169                desc.texture_binding_view_dimension
2170                    .unwrap_or_else(|| desc.default_view_dimension()),
2171            )
2172        }
2173    }
2174
2175    fn create_texture_inner(
2176        self: &Arc<Self>,
2177        desc: &resource::TextureDescriptor,
2178    ) -> Result<Arc<Texture>, resource::CreateTextureError> {
2179        let (format_features, hal_view_formats) = self.validate_texture_descriptor_inner(desc)?;
2180
2181        let hal_usage = conv::map_texture_usage_for_texture(desc, &format_features);
2182
2183        let texture_binding_view_dimension = self.resolve_texture_binding_view_dimension(desc);
2184
2185        let hal_desc = hal::TextureDescriptor {
2186            label: desc.label.to_hal(self.instance_flags),
2187            size: desc.size,
2188            mip_level_count: desc.mip_level_count,
2189            sample_count: desc.sample_count,
2190            dimension: desc.dimension,
2191            format: desc.format,
2192            usage: hal_usage,
2193            memory_flags: hal::MemoryFlags::empty(),
2194            view_formats: hal_view_formats,
2195            texture_binding_view_dimension,
2196        };
2197
2198        let raw_texture = unsafe { self.raw().create_texture(&hal_desc) }
2199            .map_err(|e| self.handle_hal_error_with_nonfatal_oom(e))?;
2200
2201        let clear_mode = if hal_usage
2202            .contains(wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE)
2203            || hal_usage.contains(wgt::TextureUses::COLOR_TARGET)
2204                && desc.dimension == wgt::TextureDimension::D2
2205        {
2206            let (is_color, usage) = if desc.format.is_depth_stencil_format() {
2207                (
2208                    false,
2209                    wgt::TextureUses::DEPTH_WRITE | wgt::TextureUses::STENCIL_WRITE,
2210                )
2211            } else {
2212                (true, wgt::TextureUses::COLOR_TARGET)
2213            };
2214
2215            let clear_label = hal_label(
2216                Some("(wgpu internal) clear texture view"),
2217                self.instance_flags,
2218            );
2219
2220            let clear_views = resource::ClearViews::new(
2221                clear_label,
2222                usage,
2223                desc.format,
2224                desc.mip_level_count,
2225                desc.size.depth_or_array_layers,
2226                |desc| {
2227                    unsafe { self.raw().create_texture_view(raw_texture.as_ref(), desc) }
2228                        .map_err(|e| self.handle_hal_error(e))
2229                },
2230            )?;
2231            resource::TextureClearMode::RenderPass {
2232                clear_views,
2233                is_color,
2234            }
2235        } else {
2236            resource::TextureClearMode::BufferCopy
2237        };
2238
2239        let texture = Texture::new(
2240            self,
2241            resource::TextureInner::Native { raw: raw_texture },
2242            hal_usage,
2243            desc,
2244            format_features,
2245            clear_mode,
2246            true,
2247            texture_binding_view_dimension,
2248        );
2249
2250        let texture = Arc::new(texture);
2251
2252        self.trackers
2253            .lock()
2254            .textures
2255            .insert_single(&texture, wgt::TextureUses::UNINITIALIZED);
2256
2257        Ok(texture)
2258    }
2259
2260    /// <https://www.w3.org/TR/webgpu/#dom-gpudevice-createtexture>
2261    pub fn create_texture(self: &Arc<Self>, desc: &resource::TextureDescriptor) -> Arc<Texture> {
2262        profiling::scope!("Device::create_texture");
2263
2264        let texture = self.create_texture_inner(desc).unwrap_or_else(|err| {
2265            self.handle_error(err, desc.label.as_deref(), "Device::create_texture");
2266            Texture::invalid(self, desc)
2267        });
2268        api_log!(
2269            "Device::create_texture({desc:?}) -> {:?}",
2270            Arc::as_ptr(&texture)
2271        );
2272
2273        #[cfg(feature = "trace")]
2274        if let Some(ref mut trace) = *self.trace.lock() {
2275            use crate::device::trace::IntoTrace as _;
2276
2277            trace.add(trace::Action::CreateTexture(
2278                texture.to_trace(),
2279                desc.clone(),
2280            ));
2281        }
2282        texture
2283    }
2284
2285    /// Creates a texture that is guaranteed to be invalid
2286    pub fn create_texture_error(
2287        self: &Arc<Self>,
2288        desc: &resource::TextureDescriptor,
2289    ) -> Arc<Texture> {
2290        let texture = Texture::invalid(self, desc);
2291        #[cfg(feature = "trace")]
2292        if let Some(ref mut trace) = *self.trace.lock() {
2293            use crate::device::trace::IntoTrace as _;
2294
2295            trace.add(trace::Action::CreateTextureError(
2296                texture.to_trace(),
2297                desc.clone(),
2298            ));
2299        }
2300        texture
2301    }
2302
2303    pub fn create_external_texture(
2304        self: &Arc<Self>,
2305        desc: &resource::ExternalTextureDescriptor,
2306        planes: &[Arc<TextureView>],
2307    ) -> Arc<ExternalTexture> {
2308        profiling::scope!("Device::create_external_texture");
2309
2310        let external_texture = self
2311            .create_external_texture_inner(desc, planes)
2312            .unwrap_or_else(|err| {
2313                self.handle_error(
2314                    err,
2315                    desc.label.as_deref(),
2316                    "Device::create_external_texture",
2317                );
2318                ExternalTexture::invalid(Arc::clone(self), desc)
2319            });
2320
2321        #[cfg(feature = "trace")]
2322        if let Some(ref mut trace) = *self.trace.lock() {
2323            use crate::device::trace;
2324            use trace::IntoTrace as _;
2325
2326            let planes = Box::from(
2327                planes
2328                    .iter()
2329                    .map(|plane| plane.to_trace())
2330                    .collect::<Vec<_>>(),
2331            );
2332            trace.add(trace::Action::CreateExternalTexture {
2333                id: external_texture.to_trace(),
2334                desc: desc.clone(),
2335                planes,
2336            });
2337        }
2338
2339        api_log!(
2340            "Device::create_external_texture({desc:?}) -> {:?}",
2341            Arc::as_ptr(&external_texture)
2342        );
2343
2344        external_texture
2345    }
2346
2347    pub(crate) fn create_external_texture_inner(
2348        self: &Arc<Self>,
2349        desc: &resource::ExternalTextureDescriptor,
2350        planes: &[Arc<TextureView>],
2351    ) -> Result<Arc<ExternalTexture>, resource::CreateExternalTextureError> {
2352        use resource::CreateExternalTextureError;
2353        self.require_features(wgt::Features::EXTERNAL_TEXTURE)?;
2354        self.check_is_valid()?;
2355
2356        if desc.num_planes() != planes.len() {
2357            return Err(CreateExternalTextureError::IncorrectPlaneCount {
2358                format: desc.format,
2359                expected: desc.num_planes(),
2360                provided: planes.len(),
2361            });
2362        }
2363
2364        let planes = planes
2365            .iter()
2366            .enumerate()
2367            .map(|(i, plane)| {
2368                plane.same_device(self)?;
2369
2370                if plane.samples != 1 {
2371                    return Err(CreateExternalTextureError::InvalidPlaneMultisample(
2372                        plane.samples,
2373                    ));
2374                }
2375
2376                let sample_type = plane
2377                    .desc
2378                    .format
2379                    .sample_type(Some(plane.desc.range.aspect), Some(self.features))
2380                    .unwrap();
2381                if !matches!(sample_type, TextureSampleType::Float { filterable: true }) {
2382                    return Err(CreateExternalTextureError::InvalidPlaneSampleType {
2383                        format: plane.desc.format,
2384                        sample_type,
2385                    });
2386                }
2387
2388                if plane.desc.dimension != TextureViewDimension::D2 {
2389                    return Err(CreateExternalTextureError::InvalidPlaneDimension(
2390                        plane.desc.dimension,
2391                    ));
2392                }
2393
2394                let expected_components = match desc.format {
2395                    wgt::ExternalTextureFormat::Rgba => 4,
2396                    wgt::ExternalTextureFormat::Nv12 => match i {
2397                        0 => 1,
2398                        1 => 2,
2399                        _ => unreachable!(),
2400                    },
2401                    wgt::ExternalTextureFormat::Yu12 => 1,
2402                };
2403                if plane.desc.format.components() != expected_components {
2404                    return Err(CreateExternalTextureError::InvalidPlaneFormat {
2405                        format: desc.format,
2406                        plane: i,
2407                        expected: expected_components,
2408                        provided: plane.desc.format,
2409                    });
2410                }
2411
2412                plane.check_usage(wgt::TextureUsages::TEXTURE_BINDING)?;
2413                Ok(plane.clone())
2414            })
2415            .collect::<Result<_, _>>()?;
2416
2417        let params_data = ExternalTextureParams::from_desc(desc);
2418        let label = desc.label.as_ref().map(|l| alloc::format!("{l} params"));
2419        let params_desc = resource::BufferDescriptor {
2420            label: label.map(Cow::Owned),
2421            size: size_of_val(&params_data) as wgt::BufferAddress,
2422            usage: wgt::BufferUsages::UNIFORM | wgt::BufferUsages::COPY_DST,
2423            mapped_at_creation: false,
2424        };
2425        let params = self.create_buffer_inner(&params_desc)?;
2426        self.get_queue().unwrap().write_buffer_inner(
2427            params.clone(),
2428            0,
2429            bytemuck::bytes_of(&params_data),
2430        )?;
2431
2432        let external_texture = ExternalTexture {
2433            state: ResourceState::Valid(ExternalTextureState { params }),
2434            device: self.clone(),
2435            planes,
2436            label: desc.label.to_string(),
2437            tracking_data: TrackingData::new(self.tracker_indices.external_textures.clone()),
2438        };
2439        let external_texture = Arc::new(external_texture);
2440
2441        Ok(external_texture)
2442    }
2443
2444    pub fn create_sampler(self: &Arc<Self>, desc: &resource::SamplerDescriptor) -> Arc<Sampler> {
2445        profiling::scope!("Device::create_sampler");
2446
2447        let sampler = self.create_sampler_inner(desc).unwrap_or_else(|err| {
2448            self.handle_error(err, desc.label.as_deref(), "Device::create_sampler");
2449            Sampler::invalid(Arc::clone(self), desc)
2450        });
2451
2452        #[cfg(feature = "trace")]
2453        if let Some(ref mut trace) = *self.trace.lock() {
2454            use crate::device::trace::{Action, IntoTrace as _};
2455            trace.add(Action::CreateSampler(sampler.to_trace(), desc.clone()));
2456        }
2457
2458        api_log!("Device::create_sampler -> {:?}", Arc::as_ptr(&sampler));
2459
2460        sampler
2461    }
2462
2463    pub(crate) fn create_sampler_inner(
2464        self: &Arc<Self>,
2465        desc: &resource::SamplerDescriptor,
2466    ) -> Result<Arc<Sampler>, resource::CreateSamplerError> {
2467        self.check_is_valid()?;
2468
2469        if desc
2470            .address_modes
2471            .iter()
2472            .any(|am| am == &wgt::AddressMode::ClampToBorder)
2473        {
2474            self.require_features(wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER)?;
2475        }
2476
2477        if desc.border_color == Some(wgt::SamplerBorderColor::Zero) {
2478            self.require_features(wgt::Features::ADDRESS_MODE_CLAMP_TO_ZERO)?;
2479        }
2480
2481        if desc.lod_min_clamp < 0.0 {
2482            return Err(resource::CreateSamplerError::InvalidLodMinClamp(
2483                desc.lod_min_clamp,
2484            ));
2485        }
2486        if desc.lod_max_clamp < desc.lod_min_clamp {
2487            return Err(resource::CreateSamplerError::InvalidLodMaxClamp {
2488                lod_min_clamp: desc.lod_min_clamp,
2489                lod_max_clamp: desc.lod_max_clamp,
2490            });
2491        }
2492
2493        if desc.anisotropy_clamp < 1 {
2494            return Err(resource::CreateSamplerError::InvalidAnisotropy(
2495                desc.anisotropy_clamp,
2496            ));
2497        }
2498
2499        if desc.anisotropy_clamp != 1 {
2500            if !matches!(desc.min_filter, wgt::FilterMode::Linear) {
2501                return Err(
2502                    resource::CreateSamplerError::InvalidFilterModeWithAnisotropy {
2503                        filter_type: resource::SamplerFilterErrorType::MinFilter,
2504                        filter_mode: desc.min_filter,
2505                        anisotropic_clamp: desc.anisotropy_clamp,
2506                    },
2507                );
2508            }
2509            if !matches!(desc.mag_filter, wgt::FilterMode::Linear) {
2510                return Err(
2511                    resource::CreateSamplerError::InvalidFilterModeWithAnisotropy {
2512                        filter_type: resource::SamplerFilterErrorType::MagFilter,
2513                        filter_mode: desc.mag_filter,
2514                        anisotropic_clamp: desc.anisotropy_clamp,
2515                    },
2516                );
2517            }
2518            if !matches!(desc.mipmap_filter, wgt::MipmapFilterMode::Linear) {
2519                return Err(
2520                    resource::CreateSamplerError::InvalidMipmapFilterModeWithAnisotropy {
2521                        filter_type: resource::SamplerFilterErrorType::MipmapFilter,
2522                        filter_mode: desc.mipmap_filter,
2523                        anisotropic_clamp: desc.anisotropy_clamp,
2524                    },
2525                );
2526            }
2527        }
2528
2529        let anisotropy_clamp = if self
2530            .downlevel
2531            .flags
2532            .contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING)
2533        {
2534            // Clamp anisotropy clamp to [1, 16] per the wgpu-hal interface
2535            desc.anisotropy_clamp.min(16)
2536        } else {
2537            // If it isn't supported, set this unconditionally to 1
2538            1
2539        };
2540
2541        //TODO: check for wgt::DownlevelFlags::COMPARISON_SAMPLERS
2542
2543        let hal_desc = hal::SamplerDescriptor {
2544            label: desc.label.to_hal(self.instance_flags),
2545            address_modes: desc.address_modes,
2546            mag_filter: desc.mag_filter,
2547            min_filter: desc.min_filter,
2548            mipmap_filter: desc.mipmap_filter,
2549            lod_clamp: desc.lod_min_clamp..desc.lod_max_clamp,
2550            compare: desc.compare,
2551            anisotropy_clamp,
2552            border_color: desc.border_color,
2553        };
2554
2555        let raw = unsafe { self.raw().create_sampler(&hal_desc) }
2556            .map_err(|e| self.handle_hal_error_with_nonfatal_oom(e))?;
2557
2558        let sampler = Sampler {
2559            raw: ResourceState::Valid(raw),
2560            device: self.clone(),
2561            label: desc.label.to_string(),
2562            tracking_data: TrackingData::new(self.tracker_indices.samplers.clone()),
2563            comparison: desc.compare.is_some(),
2564            filtering: desc.min_filter == wgt::FilterMode::Linear
2565                || desc.mag_filter == wgt::FilterMode::Linear
2566                || desc.mipmap_filter == wgt::MipmapFilterMode::Linear,
2567        };
2568
2569        let sampler = Arc::new(sampler);
2570
2571        Ok(sampler)
2572    }
2573
2574    pub fn create_shader_module<'a>(
2575        self: &Arc<Self>,
2576        desc: &pipeline::ShaderModuleDescriptor<'a>,
2577        source: pipeline::ShaderModuleSource<'a>,
2578    ) -> Arc<pipeline::ShaderModule> {
2579        profiling::scope!("Device::create_shader_module");
2580        #[cfg(feature = "trace")]
2581        let data = self.trace.lock().as_mut().map(|trace| {
2582            use crate::device::trace::DataKind;
2583
2584            match source {
2585                #[cfg(feature = "wgsl")]
2586                pipeline::ShaderModuleSource::Wgsl(ref code) => {
2587                    trace.make_binary(DataKind::Wgsl, code.as_bytes())
2588                }
2589                #[cfg(feature = "glsl")]
2590                pipeline::ShaderModuleSource::Glsl(ref code, _) => {
2591                    trace.make_binary(DataKind::Glsl, code.as_bytes())
2592                }
2593                #[cfg(feature = "spirv")]
2594                pipeline::ShaderModuleSource::SpirV(ref code, _) => {
2595                    trace.make_binary(DataKind::Spv, bytemuck::cast_slice::<u32, u8>(code))
2596                }
2597                pipeline::ShaderModuleSource::Naga(ref module) => {
2598                    let string =
2599                        ron::ser::to_string_pretty(module, ron::ser::PrettyConfig::default())
2600                            .unwrap();
2601                    trace.make_binary(DataKind::Ron, string.as_bytes())
2602                }
2603                pipeline::ShaderModuleSource::Dummy(_) => {
2604                    panic!("found `ShaderModuleSource::Dummy`")
2605                }
2606            }
2607        });
2608        let shader = self
2609            .create_shader_module_inner(desc, source)
2610            .unwrap_or_else(|e| {
2611                let shader = pipeline::ShaderModule::invalid(
2612                    Arc::clone(self),
2613                    desc.label.to_string(),
2614                    shader_module_error_into_compilation_info(&e),
2615                );
2616                self.handle_error(e, desc.label.as_deref(), "Device::create_shader_module");
2617                shader
2618            });
2619        api_log!("Device::create_shader_module -> {:?}", Arc::as_ptr(&shader));
2620
2621        #[cfg(feature = "trace")]
2622        if let Some(data) = data {
2623            // We don't need these two operations with the trace to be atomic.
2624
2625            use crate::device::trace::IntoTrace as _;
2626            self.trace
2627                .lock()
2628                .as_mut()
2629                .expect("trace went away during create_shader_module?")
2630                .add(trace::Action::CreateShaderModule {
2631                    id: shader.to_trace(),
2632                    desc: desc.clone(),
2633                    data,
2634                });
2635        };
2636        shader
2637    }
2638
2639    pub(crate) fn create_shader_module_inner<'a>(
2640        self: &Arc<Self>,
2641        desc: &pipeline::ShaderModuleDescriptor<'a>,
2642        source: pipeline::ShaderModuleSource<'a>,
2643    ) -> Result<Arc<pipeline::ShaderModule>, pipeline::CreateShaderModuleError> {
2644        self.check_is_valid()?;
2645
2646        let (module, source) = match source {
2647            #[cfg(feature = "wgsl")]
2648            pipeline::ShaderModuleSource::Wgsl(code) => {
2649                profiling::scope!("naga::front::wgsl::parse");
2650                let capabilities = crate::device::features_to_naga_capabilities(
2651                    self.features,
2652                    self.downlevel.flags,
2653                );
2654                let mut options = naga::front::wgsl::Options::new();
2655                options.capabilities = capabilities;
2656                let mut frontend = naga::front::wgsl::Frontend::new_with_options(options);
2657                let module = frontend.parse(&code).map_err(|inner| {
2658                    pipeline::CreateShaderModuleError::Parsing(naga::error::ShaderError {
2659                        source: code.to_string(),
2660                        label: desc.label.as_ref().map(|l| l.to_string()),
2661                        inner: Box::new(inner),
2662                    })
2663                })?;
2664                (Cow::Owned(module), code.into_owned())
2665            }
2666            #[cfg(feature = "spirv")]
2667            pipeline::ShaderModuleSource::SpirV(spv, options) => {
2668                let parser = naga::front::spv::Frontend::new(spv.iter().cloned(), &options);
2669                profiling::scope!("naga::front::spv::Frontend");
2670                let module = parser.parse().map_err(|inner| {
2671                    pipeline::CreateShaderModuleError::ParsingSpirV(naga::error::ShaderError {
2672                        source: String::new(),
2673                        label: desc.label.as_ref().map(|l| l.to_string()),
2674                        inner: Box::new(inner),
2675                    })
2676                })?;
2677                (Cow::Owned(module), String::new())
2678            }
2679            #[cfg(feature = "glsl")]
2680            pipeline::ShaderModuleSource::Glsl(code, options) => {
2681                let mut parser = naga::front::glsl::Frontend::default();
2682                profiling::scope!("naga::front::glsl::Frontend.parse");
2683                let module = parser.parse(&options, &code).map_err(|inner| {
2684                    pipeline::CreateShaderModuleError::ParsingGlsl(naga::error::ShaderError {
2685                        source: code.to_string(),
2686                        label: desc.label.as_ref().map(|l| l.to_string()),
2687                        inner: Box::new(inner),
2688                    })
2689                })?;
2690                (Cow::Owned(module), code.into_owned())
2691            }
2692            pipeline::ShaderModuleSource::Naga(module) => (module, String::new()),
2693            pipeline::ShaderModuleSource::Dummy(_) => panic!("found `ShaderModuleSource::Dummy`"),
2694        };
2695        for (_, var) in module.global_variables.iter() {
2696            match var.binding {
2697                Some(br) if br.group >= self.limits.max_bind_groups => {
2698                    return Err(pipeline::CreateShaderModuleError::InvalidGroupIndex {
2699                        bind: br,
2700                        group: br.group,
2701                        limit: self.limits.max_bind_groups,
2702                    });
2703                }
2704                _ => continue,
2705            };
2706        }
2707
2708        profiling::scope!("naga::validate");
2709        let debug_source =
2710            if self.instance_flags.contains(wgt::InstanceFlags::DEBUG) && !source.is_empty() {
2711                Some(hal::DebugSource {
2712                    file_name: Cow::Owned(
2713                        desc.label
2714                            .as_ref()
2715                            .map_or("shader".to_string(), |l| l.to_string()),
2716                    ),
2717                    source_code: Cow::Owned(source.clone()),
2718                })
2719            } else {
2720                None
2721            };
2722
2723        let info = create_validator(
2724            self.features,
2725            self.downlevel.flags,
2726            naga::valid::ValidationFlags::all(),
2727        )
2728        .validate(&module)
2729        .map_err(|inner| {
2730            pipeline::CreateShaderModuleError::Validation(naga::error::ShaderError {
2731                source,
2732                label: desc.label.as_ref().map(|l| l.to_string()),
2733                inner,
2734            })
2735        })?;
2736
2737        // Defer creating the `wgpu_hal` shader module until pipeline creation,
2738        // when we can apply the pipeline's override values and validate the
2739        // result.
2740        let module = pipeline::ShaderModule {
2741            state: ResourceState::Valid(pipeline::ShaderModuleState::NagaModule {
2742                shader: hal::NagaShader {
2743                    module,
2744                    info,
2745                    debug_source,
2746                },
2747                runtime_checks: desc.runtime_checks,
2748            }),
2749            device: self.clone(),
2750            label: desc.label.to_string(),
2751            compilation_info: wgt::CompilationInfo::default(),
2752        };
2753
2754        let module = Arc::new(module);
2755
2756        Ok(module)
2757    }
2758
2759    /// # Safety
2760    ///
2761    /// This function passes source code or binary to the backend as-is and can potentially result in a
2762    /// driver crash.
2763    pub unsafe fn create_shader_module_passthrough<'a>(
2764        self: &Arc<Self>,
2765        desc: &pipeline::ShaderModuleDescriptorPassthrough<'a>,
2766    ) -> Arc<pipeline::ShaderModule> {
2767        profiling::scope!("Device::create_shader_module_passthrough");
2768
2769        let shader =
2770            unsafe { self.create_shader_module_passthrough_inner(desc) }.unwrap_or_else(|e| {
2771                let shader = pipeline::ShaderModule::invalid(
2772                    Arc::clone(self),
2773                    desc.label.to_string(),
2774                    shader_module_error_into_compilation_info(&e),
2775                );
2776                self.handle_error(
2777                    e,
2778                    desc.label.as_deref(),
2779                    "Device::create_shader_module_passthrough",
2780                );
2781                shader
2782            });
2783
2784        #[cfg(feature = "trace")]
2785        if let Some(ref mut trace) = *self.trace.lock() {
2786            use crate::device::trace::{DataKind, IntoTrace as _};
2787
2788            let mut file_names = Vec::new();
2789            for (data, kind) in [
2790                (
2791                    desc.spirv.as_ref().map(|a| bytemuck::cast_slice(a)),
2792                    DataKind::Spv,
2793                ),
2794                (desc.dxil.as_deref(), DataKind::Dxil),
2795                (desc.hlsl.as_ref().map(|a| a.as_bytes()), DataKind::Hlsl),
2796                (desc.metallib.as_deref(), DataKind::MetalLib),
2797                (desc.msl.as_ref().map(|a| a.as_bytes()), DataKind::Msl),
2798                (desc.glsl.as_ref().map(|a| a.as_bytes()), DataKind::Glsl),
2799                (desc.wgsl.as_ref().map(|a| a.as_bytes()), DataKind::Wgsl),
2800            ] {
2801                if let Some(data) = data {
2802                    file_names.push(trace.make_binary(kind, data));
2803                }
2804            }
2805            trace.add(trace::Action::CreateShaderModulePassthrough {
2806                id: shader.to_trace(),
2807                data: file_names,
2808                label: desc.label.clone(),
2809                entry_points: desc.entry_points.clone(),
2810            });
2811        };
2812        api_log!(
2813            "Device::create_shader_module_spirv -> {:?}",
2814            Arc::as_ptr(&shader)
2815        );
2816        shader
2817    }
2818
2819    pub(crate) unsafe fn create_shader_module_passthrough_inner<'a>(
2820        self: &Arc<Self>,
2821        descriptor: &pipeline::ShaderModuleDescriptorPassthrough<'a>,
2822    ) -> Result<Arc<pipeline::ShaderModule>, pipeline::CreateShaderModuleError> {
2823        self.check_is_valid()?;
2824        self.require_features(wgt::Features::PASSTHROUGH_SHADERS)?;
2825
2826        // Mainly important for GLSL or SPIR-V or DXIL, which each take exactly 1 entry point.
2827        if (descriptor.dxil.is_some() || descriptor.glsl.is_some())
2828            && descriptor.entry_points.len() != 1
2829        {
2830            return Err(pipeline::CreateShaderModuleError::IncorrectPassthroughEntryPointCount);
2831        }
2832
2833        let entry_point_hashmap = || {
2834            descriptor
2835                .entry_points
2836                .iter()
2837                .map(|e| (e.name.to_string(), e.workgroup_size))
2838                .collect()
2839        };
2840
2841        let hal_shader = match self.backend() {
2842            wgt::Backend::Vulkan => hal::ShaderInput::SpirV(
2843                descriptor
2844                    .spirv
2845                    .as_ref()
2846                    .ok_or(pipeline::CreateShaderModuleError::NotCompiledForBackend)?,
2847            ),
2848            wgt::Backend::Dx12 => {
2849                if let Some(dxil) = &descriptor.dxil {
2850                    hal::ShaderInput::Dxil { shader: dxil }
2851                } else if let Some(hlsl) = &descriptor.hlsl {
2852                    hal::ShaderInput::Hlsl { shader: hlsl }
2853                } else {
2854                    return Err(pipeline::CreateShaderModuleError::NotCompiledForBackend);
2855                }
2856            }
2857            wgt::Backend::Metal => {
2858                if let Some(metallib) = &descriptor.metallib {
2859                    hal::ShaderInput::MetalLib {
2860                        file: metallib,
2861                        num_workgroups: entry_point_hashmap(),
2862                    }
2863                } else if let Some(msl) = &descriptor.msl {
2864                    hal::ShaderInput::Msl {
2865                        shader: msl,
2866                        num_workgroups: entry_point_hashmap(),
2867                    }
2868                } else {
2869                    return Err(pipeline::CreateShaderModuleError::NotCompiledForBackend);
2870                }
2871            }
2872            wgt::Backend::Gl => hal::ShaderInput::Glsl {
2873                shader: descriptor
2874                    .glsl
2875                    .as_ref()
2876                    .ok_or(pipeline::CreateShaderModuleError::NotCompiledForBackend)?,
2877            },
2878            wgt::Backend::Noop => {
2879                return Err(pipeline::CreateShaderModuleError::NotCompiledForBackend)
2880            }
2881            wgt::Backend::BrowserWebGpu => unreachable!(),
2882        };
2883
2884        let hal_desc = hal::ShaderModuleDescriptor {
2885            label: descriptor.label.to_hal(self.instance_flags),
2886            runtime_checks: wgt::ShaderRuntimeChecks::unchecked(),
2887        };
2888
2889        let raw = match unsafe { self.raw().create_shader_module(&hal_desc, hal_shader) } {
2890            Ok(raw) => raw,
2891            Err(error) => {
2892                return Err(match error {
2893                    hal::ShaderError::Device(error) => {
2894                        pipeline::CreateShaderModuleError::Device(self.handle_hal_error(error))
2895                    }
2896                    hal::ShaderError::Compilation(ref msg) => {
2897                        log::error!("Shader error: {msg}");
2898                        pipeline::CreateShaderModuleError::Generation
2899                    }
2900                })
2901            }
2902        };
2903
2904        let module = pipeline::ShaderModule {
2905            state: ResourceState::Valid(pipeline::ShaderModuleState::Passthrough {
2906                raw,
2907                interface: PassthroughInterface {
2908                    entry_point_names: descriptor
2909                        .entry_points
2910                        .iter()
2911                        .map(|e| e.name.to_string())
2912                        .collect(),
2913                },
2914            }),
2915            device: self.clone(),
2916            label: descriptor.label.to_string(),
2917            compilation_info: wgt::CompilationInfo::default(),
2918        };
2919
2920        Ok(Arc::new(module))
2921    }
2922
2923    pub fn create_command_encoder(
2924        self: &Arc<Self>,
2925        desc: &wgt::CommandEncoderDescriptor<crate::Label>,
2926    ) -> Arc<command::CommandEncoder> {
2927        profiling::scope!("Device::create_command_encoder");
2928
2929        let cmd_enc = self
2930            .create_command_encoder_inner(&desc.label)
2931            .unwrap_or_else(|err| {
2932                let error = err.clone().into();
2933                self.handle_error(
2934                    err,
2935                    desc.label.as_ref().map(|l| l.as_ref()),
2936                    "Device::create_command_encoder",
2937                );
2938                command::CommandEncoder::new_invalid(self, &desc.label, error)
2939            });
2940
2941        api_log!(
2942            "Device::create_command_encoder -> {:?}",
2943            Arc::as_ptr(&cmd_enc)
2944        );
2945
2946        cmd_enc
2947    }
2948
2949    pub(crate) fn create_command_encoder_inner(
2950        self: &Arc<Self>,
2951        label: &crate::Label,
2952    ) -> Result<Arc<command::CommandEncoder>, DeviceError> {
2953        self.check_is_valid()?;
2954
2955        let queue = self.get_queue().unwrap();
2956
2957        let encoder = self
2958            .command_allocator
2959            .acquire_encoder(self.raw(), queue.raw())
2960            .map_err(|e| self.handle_hal_error(e))?;
2961
2962        let cmd_enc = command::CommandEncoder::new(encoder, self, label);
2963
2964        let cmd_enc = Arc::new(cmd_enc);
2965
2966        Ok(cmd_enc)
2967    }
2968
2969    pub fn create_render_bundle_encoder(
2970        self: &Arc<Self>,
2971        desc: &command::RenderBundleEncoderDescriptor,
2972    ) -> Box<command::RenderBundleEncoder> {
2973        profiling::scope!("Device::create_render_bundle_encoder");
2974        api_log!("Device::create_render_bundle_encoder");
2975        Box::new(
2976            command::RenderBundleEncoder::new(self, desc).unwrap_or_else(|err| {
2977                self.handle_error(
2978                    err,
2979                    desc.label.as_deref(),
2980                    "Device::create_render_bundle_encoder",
2981                );
2982                command::RenderBundleEncoder::dummy(self)
2983            }),
2984        )
2985    }
2986
2987    /// Generate information about late-validated buffer bindings for pipelines.
2988    pub(super) fn make_late_sized_buffer_groups(
2989        shader_binding_sizes: &FastHashMap<naga::ResourceBinding, wgt::BufferSize>,
2990        layout: &binding_model::PipelineLayout,
2991    ) -> ArrayVec<pipeline::LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }> {
2992        layout
2993            .bind_group_layouts
2994            .iter()
2995            .enumerate()
2996            .map(|(group_index, bgl)| {
2997                let Some(bgl) = bgl else {
2998                    return pipeline::LateSizedBufferGroup::default();
2999                };
3000
3001                let shader_sizes = bgl
3002                    .late_sized_bindings
3003                    .iter()
3004                    .map(|&binding| {
3005                        let rb = naga::ResourceBinding {
3006                            group: group_index as u32,
3007                            binding,
3008                        };
3009                        shader_binding_sizes.get(&rb).map_or(0, |nz| nz.get())
3010                    })
3011                    .collect();
3012                pipeline::LateSizedBufferGroup { shader_sizes }
3013            })
3014            .collect()
3015    }
3016
3017    pub fn create_bind_group_layout<BGLE>(
3018        self: &Arc<Self>,
3019        desc: &binding_model::BindGroupLayoutDescriptor<BGLE>,
3020    ) -> Arc<BindGroupLayout>
3021    where
3022        BGLE: TryInto<wgt::BindGroupLayoutEntry> + Copy,
3023        CreateBindGroupLayoutError: From<<BGLE as TryInto<wgt::BindGroupLayoutEntry>>::Error>,
3024        BGLE: Into<binding_model::BindGroupLayoutEntry>,
3025    {
3026        profiling::scope!("Device::create_bind_group_layout");
3027
3028        let bgl = self
3029            .create_bind_group_layout_inner(desc)
3030            .unwrap_or_else(|err| {
3031                self.handle_error(
3032                    err,
3033                    desc.label.as_deref(),
3034                    "Device::create_bind_group_layout",
3035                );
3036                BindGroupLayout::invalid(self, desc.label.to_string())
3037            });
3038
3039        #[cfg(feature = "trace")]
3040        if let Some(ref mut trace) = *self.trace.lock() {
3041            use crate::device::trace::IntoTrace;
3042
3043            trace.add(trace::Action::CreateBindGroupLayout(
3044                bgl.to_trace(),
3045                desc.to_trace(),
3046            ));
3047        }
3048        api_log!(
3049            "Device::create_bind_group_layout -> {:?}",
3050            Arc::as_ptr(&bgl)
3051        );
3052        bgl
3053    }
3054
3055    fn create_bind_group_layout_inner<BGLE>(
3056        self: &Arc<Device>,
3057        desc: &binding_model::BindGroupLayoutDescriptor<BGLE>,
3058    ) -> Result<Arc<BindGroupLayout>, CreateBindGroupLayoutError>
3059    where
3060        BGLE: TryInto<wgt::BindGroupLayoutEntry> + Copy,
3061        CreateBindGroupLayoutError: From<<BGLE as TryInto<wgt::BindGroupLayoutEntry>>::Error>,
3062    {
3063        self.check_is_valid()?;
3064
3065        let entry_map = bgl::EntryMap::from_entries(&desc.entries)?;
3066
3067        let bgl_result = self.bgl_pool.get_or_init(entry_map, |entry_map| {
3068            let bgl =
3069                self.create_bind_group_layout_impl(&desc.label, entry_map, bgl::Origin::Pool)?;
3070            bgl.exclusive_pipeline
3071                .set(binding_model::ExclusivePipeline::None)
3072                .unwrap();
3073            Ok(bgl)
3074        });
3075
3076        match bgl_result {
3077            Ok(layout) => Ok(layout),
3078            Err(e) => Err(e),
3079        }
3080    }
3081
3082    fn create_bind_group_layout_impl(
3083        self: &Arc<Self>,
3084        label: &crate::Label,
3085        entry_map: bgl::EntryMap,
3086        origin: bgl::Origin,
3087    ) -> Result<Arc<BindGroupLayout>, CreateBindGroupLayoutError> {
3088        #[derive(PartialEq)]
3089        enum WritableStorage {
3090            Yes,
3091            No,
3092        }
3093
3094        for entry in entry_map.values() {
3095            if entry.binding >= self.limits.max_bindings_per_bind_group {
3096                return Err(CreateBindGroupLayoutError::InvalidBindingIndex {
3097                    binding: entry.binding,
3098                    maximum: self.limits.max_bindings_per_bind_group,
3099                });
3100            }
3101
3102            use wgt::BindingType as Bt;
3103
3104            let mut required_features = wgt::Features::empty();
3105            let mut required_downlevel_flags = wgt::DownlevelFlags::empty();
3106            let (array_feature, writable_storage) = match entry.ty {
3107                Bt::Buffer {
3108                    ty: wgt::BufferBindingType::Uniform,
3109                    has_dynamic_offset: false,
3110                    min_binding_size: _,
3111                } => (
3112                    Some(wgt::Features::BUFFER_BINDING_ARRAY),
3113                    WritableStorage::No,
3114                ),
3115                Bt::Buffer {
3116                    ty: wgt::BufferBindingType::Uniform,
3117                    has_dynamic_offset: true,
3118                    min_binding_size: _,
3119                } => (
3120                    Some(wgt::Features::BUFFER_BINDING_ARRAY),
3121                    WritableStorage::No,
3122                ),
3123                Bt::Buffer {
3124                    ty: wgt::BufferBindingType::Storage { read_only },
3125                    ..
3126                } => (
3127                    Some(
3128                        wgt::Features::BUFFER_BINDING_ARRAY
3129                            | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
3130                    ),
3131                    match read_only {
3132                        true => WritableStorage::No,
3133                        false => WritableStorage::Yes,
3134                    },
3135                ),
3136                Bt::Sampler { .. } => (
3137                    Some(wgt::Features::TEXTURE_BINDING_ARRAY),
3138                    WritableStorage::No,
3139                ),
3140                Bt::Texture {
3141                    multisampled: true,
3142                    sample_type: TextureSampleType::Float { filterable: true },
3143                    ..
3144                } => {
3145                    return Err(CreateBindGroupLayoutError::Entry {
3146                        binding: entry.binding,
3147                        error:
3148                            BindGroupLayoutEntryError::SampleTypeFloatFilterableBindingMultisampled,
3149                    });
3150                }
3151                Bt::Texture {
3152                    multisampled,
3153                    view_dimension,
3154                    ..
3155                } => {
3156                    if multisampled && view_dimension != TextureViewDimension::D2 {
3157                        return Err(CreateBindGroupLayoutError::Entry {
3158                            binding: entry.binding,
3159                            error: BindGroupLayoutEntryError::Non2DMultisampled(view_dimension),
3160                        });
3161                    }
3162
3163                    (
3164                        Some(wgt::Features::TEXTURE_BINDING_ARRAY),
3165                        WritableStorage::No,
3166                    )
3167                }
3168                Bt::StorageTexture {
3169                    access,
3170                    view_dimension,
3171                    format,
3172                } => {
3173                    use wgt::{StorageTextureAccess as Access, TextureFormatFeatureFlags as Flags};
3174
3175                    match view_dimension {
3176                        TextureViewDimension::Cube | TextureViewDimension::CubeArray => {
3177                            return Err(CreateBindGroupLayoutError::Entry {
3178                                binding: entry.binding,
3179                                error: BindGroupLayoutEntryError::StorageTextureCube,
3180                            })
3181                        }
3182                        _ => (),
3183                    }
3184                    match access {
3185                        wgt::StorageTextureAccess::Atomic
3186                            if !self.features.contains(wgt::Features::TEXTURE_ATOMIC) =>
3187                        {
3188                            return Err(CreateBindGroupLayoutError::Entry {
3189                                binding: entry.binding,
3190                                error: BindGroupLayoutEntryError::StorageTextureAtomic,
3191                            });
3192                        }
3193                        _ => (),
3194                    }
3195
3196                    let format_features =
3197                        self.describe_format_features(format).map_err(|error| {
3198                            CreateBindGroupLayoutError::Entry {
3199                                binding: entry.binding,
3200                                error: BindGroupLayoutEntryError::MissingFeatures(error),
3201                            }
3202                        })?;
3203
3204                    let required_feature_flag = match access {
3205                        Access::WriteOnly => Flags::STORAGE_WRITE_ONLY,
3206                        Access::ReadOnly => Flags::STORAGE_READ_ONLY,
3207                        Access::ReadWrite => Flags::STORAGE_READ_WRITE,
3208                        Access::Atomic => Flags::STORAGE_ATOMIC,
3209                    };
3210
3211                    if !format_features.flags.contains(required_feature_flag) {
3212                        return Err(
3213                            CreateBindGroupLayoutError::UnsupportedStorageTextureAccess {
3214                                binding: entry.binding,
3215                                access,
3216                                format,
3217                            },
3218                        );
3219                    }
3220
3221                    (
3222                        Some(
3223                            wgt::Features::TEXTURE_BINDING_ARRAY
3224                                | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY,
3225                        ),
3226                        match access {
3227                            wgt::StorageTextureAccess::WriteOnly => WritableStorage::Yes,
3228                            wgt::StorageTextureAccess::ReadOnly => WritableStorage::No,
3229                            wgt::StorageTextureAccess::ReadWrite => WritableStorage::Yes,
3230                            wgt::StorageTextureAccess::Atomic => {
3231                                required_features |= wgt::Features::TEXTURE_ATOMIC;
3232                                WritableStorage::Yes
3233                            }
3234                        },
3235                    )
3236                }
3237                Bt::AccelerationStructure { vertex_return } => {
3238                    self.require_acceleration_structures().map_err(|e| {
3239                        CreateBindGroupLayoutError::Entry {
3240                            binding: entry.binding,
3241                            error: e.into(),
3242                        }
3243                    })?;
3244                    if vertex_return {
3245                        self.require_features(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN)
3246                            .map_err(|e| CreateBindGroupLayoutError::Entry {
3247                                binding: entry.binding,
3248                                error: e.into(),
3249                            })?;
3250                    }
3251                    (
3252                        Some(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
3253                        WritableStorage::No,
3254                    )
3255                }
3256                Bt::ExternalTexture => {
3257                    self.require_features(wgt::Features::EXTERNAL_TEXTURE)
3258                        .map_err(|e| CreateBindGroupLayoutError::Entry {
3259                            binding: entry.binding,
3260                            error: e.into(),
3261                        })?;
3262                    (None, WritableStorage::No)
3263                }
3264            };
3265
3266            // Validate the count parameter
3267            if entry.count.is_some() {
3268                required_features |= array_feature
3269                    .ok_or(BindGroupLayoutEntryError::ArrayUnsupported)
3270                    .map_err(|error| CreateBindGroupLayoutError::Entry {
3271                        binding: entry.binding,
3272                        error,
3273                    })?;
3274            }
3275
3276            if entry.visibility.contains_unknown_bits() {
3277                return Err(CreateBindGroupLayoutError::InvalidVisibility(
3278                    entry.visibility,
3279                ));
3280            }
3281
3282            if entry
3283                .visibility
3284                .intersects(wgt::ShaderStages::TASK | wgt::ShaderStages::MESH)
3285            {
3286                required_features |= wgt::Features::EXPERIMENTAL_MESH_SHADER;
3287            }
3288
3289            if entry.visibility.intersects(
3290                wgt::ShaderStages::RAY_GENERATION
3291                    | wgt::ShaderStages::ANY_HIT
3292                    | wgt::ShaderStages::CLOSEST_HIT
3293                    | wgt::ShaderStages::MISS,
3294            ) {
3295                required_features |= wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES;
3296            }
3297
3298            if entry.visibility.contains(wgt::ShaderStages::VERTEX) {
3299                if writable_storage == WritableStorage::Yes {
3300                    required_features |= wgt::Features::VERTEX_WRITABLE_STORAGE;
3301                }
3302                if let Bt::Buffer {
3303                    ty: wgt::BufferBindingType::Storage { .. },
3304                    ..
3305                } = entry.ty
3306                {
3307                    required_downlevel_flags |= wgt::DownlevelFlags::VERTEX_STORAGE;
3308                }
3309            }
3310            if writable_storage == WritableStorage::Yes
3311                && entry.visibility.contains(wgt::ShaderStages::FRAGMENT)
3312            {
3313                required_downlevel_flags |= wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE;
3314            }
3315
3316            self.require_features(required_features)
3317                .map_err(BindGroupLayoutEntryError::MissingFeatures)
3318                .map_err(|error| CreateBindGroupLayoutError::Entry {
3319                    binding: entry.binding,
3320                    error,
3321                })?;
3322            self.require_downlevel_flags(required_downlevel_flags)
3323                .map_err(BindGroupLayoutEntryError::MissingDownlevelFlags)
3324                .map_err(|error| CreateBindGroupLayoutError::Entry {
3325                    binding: entry.binding,
3326                    error,
3327                })?;
3328        }
3329
3330        let bgl_flags = conv::bind_group_layout_flags(self.features);
3331
3332        let hal_bindings = entry_map.values().copied().collect::<Vec<_>>();
3333        let hal_desc = hal::BindGroupLayoutDescriptor {
3334            label: label.to_hal(self.instance_flags),
3335            flags: bgl_flags,
3336            entries: &hal_bindings,
3337        };
3338
3339        let mut count_validator = binding_model::BindingTypeMaxCountValidator::default();
3340        for entry in entry_map.values() {
3341            count_validator.add_binding(entry);
3342        }
3343        // If a single bind group layout violates limits, the pipeline layout is
3344        // definitely going to violate limits too, lets catch it now.
3345        count_validator
3346            .validate(&self.limits, self.instance_flags)
3347            .map_err(CreateBindGroupLayoutError::TooManyBindings)?;
3348
3349        // Validate that binding arrays don't conflict with dynamic offsets.
3350        count_validator.validate_binding_arrays()?;
3351
3352        let raw = unsafe { self.raw().create_bind_group_layout(&hal_desc) }
3353            .map_err(|e| self.handle_hal_error(e))?;
3354
3355        let late_sized_bindings = entry_map
3356            .values()
3357            .filter(|entry| {
3358                matches!(
3359                    entry.ty,
3360                    wgt::BindingType::Buffer {
3361                        min_binding_size: None,
3362                        ..
3363                    }
3364                )
3365            })
3366            .map(|entry| entry.binding)
3367            .collect();
3368
3369        let bgl = BindGroupLayout {
3370            state: ResourceState::Valid(BindGroupLayoutState {
3371                raw: binding_model::RawBindGroupLayout::Owning(ManuallyDrop::new(raw)),
3372                origin,
3373                binding_count_validator: count_validator,
3374            }),
3375            device: self.clone(),
3376            entries: entry_map,
3377            late_sized_bindings,
3378            exclusive_pipeline: OnceCell::new(),
3379            label: label.to_string(),
3380        };
3381
3382        let bgl = Arc::new(bgl);
3383
3384        Ok(bgl)
3385    }
3386
3387    fn create_buffer_binding<'a>(
3388        &self,
3389        bb: &'a binding_model::BufferBinding,
3390        binding: u32,
3391        decl: &wgt::BindGroupLayoutEntry,
3392        buffer_init_actions: &mut Vec<BufferInitTrackerAction>,
3393        dynamic_binding_info: &mut Vec<binding_model::BindGroupDynamicBindingData>,
3394        late_sizes_by_binding: &mut FastHashMap<u32, wgt::BufferSize>,
3395        used: &mut BindGroupStates,
3396        snatch_guard: &'a SnatchGuard<'a>,
3397    ) -> Result<hal::BufferBinding<'a, dyn hal::DynBuffer, NonZeroU64>, CreateBindGroupError> {
3398        use crate::binding_model::CreateBindGroupError as Error;
3399
3400        let (binding_ty, dynamic, min_size) = match decl.ty {
3401            wgt::BindingType::Buffer {
3402                ty,
3403                has_dynamic_offset,
3404                min_binding_size,
3405            } => (ty, has_dynamic_offset, min_binding_size),
3406            _ => {
3407                return Err(Error::WrongBindingType {
3408                    binding,
3409                    actual: decl.ty,
3410                    expected: "UniformBuffer, StorageBuffer or ReadonlyStorageBuffer",
3411                })
3412            }
3413        };
3414
3415        let (pub_usage, internal_use, range_limit) = match binding_ty {
3416            wgt::BufferBindingType::Uniform => (
3417                wgt::BufferUsages::UNIFORM,
3418                wgt::BufferUses::UNIFORM,
3419                self.limits.max_uniform_buffer_binding_size,
3420            ),
3421            wgt::BufferBindingType::Storage { read_only } => (
3422                wgt::BufferUsages::STORAGE,
3423                if read_only {
3424                    wgt::BufferUses::STORAGE_READ_ONLY
3425                } else {
3426                    wgt::BufferUses::STORAGE_READ_WRITE
3427                },
3428                self.limits.max_storage_buffer_binding_size,
3429            ),
3430        };
3431
3432        let (align, align_limit_name) =
3433            binding_model::buffer_binding_type_alignment(&self.limits, binding_ty);
3434        if !bb.offset.is_multiple_of(align as u64) {
3435            return Err(Error::UnalignedBufferOffset(
3436                bb.offset,
3437                align_limit_name,
3438                align,
3439            ));
3440        }
3441
3442        let buffer = &bb.buffer;
3443
3444        used.buffers.insert_single(buffer.clone(), internal_use);
3445
3446        buffer.check_is_valid()?;
3447        buffer.same_device(self)?;
3448
3449        buffer.check_usage(pub_usage)?;
3450
3451        let req_size = match bb.size.map(wgt::BufferSize::new) {
3452            // Requested a non-zero size
3453            Some(non_zero @ Some(_)) => non_zero,
3454            // Requested size not specified
3455            None => None,
3456            // Requested zero size
3457            Some(None) => return Err(CreateBindGroupError::BindingZeroSize(buffer.error_ident())),
3458        };
3459        let bb = buffer.binding(bb.offset, req_size, snatch_guard)?;
3460        let bind_size = bb.size.get();
3461
3462        if matches!(binding_ty, wgt::BufferBindingType::Storage { .. })
3463            && bind_size % u64::from(wgt::STORAGE_BINDING_SIZE_ALIGNMENT) != 0
3464        {
3465            return Err(Error::UnalignedEffectiveBufferBindingSizeForStorage {
3466                alignment: wgt::STORAGE_BINDING_SIZE_ALIGNMENT,
3467                size: bind_size,
3468            });
3469        }
3470
3471        let bind_end = bb.offset + bind_size;
3472
3473        if bind_size > range_limit {
3474            return Err(Error::BufferRangeTooLarge {
3475                binding,
3476                given: bind_size,
3477                limit: range_limit,
3478            });
3479        }
3480
3481        // Record binding info for validating dynamic offsets
3482        if dynamic {
3483            dynamic_binding_info.push(binding_model::BindGroupDynamicBindingData {
3484                binding_idx: binding,
3485                buffer_size: buffer.size,
3486                binding_range: bb.offset..bind_end,
3487                maximum_dynamic_offset: buffer.size - bind_end,
3488                binding_type: binding_ty,
3489            });
3490        }
3491
3492        if let Some(non_zero) = min_size {
3493            let min_size = non_zero.get();
3494            if min_size > bind_size {
3495                return Err(Error::BindingSizeTooSmall {
3496                    buffer: buffer.error_ident(),
3497                    actual: bind_size,
3498                    min: min_size,
3499                });
3500            }
3501        } else {
3502            let late_size = wgt::BufferSize::new(bind_size)
3503                .ok_or_else(|| Error::BindingZeroSize(buffer.error_ident()))?;
3504            late_sizes_by_binding.insert(binding, late_size);
3505        }
3506
3507        // This was checked against the device's alignment requirements above,
3508        // which should always be a multiple of `COPY_BUFFER_ALIGNMENT`.
3509        assert_eq!(bb.offset % wgt::COPY_BUFFER_ALIGNMENT, 0);
3510
3511        let init_range = if dynamic {
3512            // We don't know what part of the buffer will be bound, so require that it
3513            // is fully initialized.
3514            0..buffer.size
3515        } else {
3516            // `wgpu_hal` only restricts shader access to bound buffer regions with
3517            // a certain resolution. For the sake of lazy initialization, round up
3518            // the size of the bound range to reflect how much of the buffer is
3519            // actually going to be visible to the shader.
3520            let bounds_check_alignment = binding_model::buffer_binding_type_bounds_check_alignment(
3521                &self.alignments,
3522                binding_ty,
3523            );
3524            let visible_size = align_to(bind_size, bounds_check_alignment);
3525
3526            bb.offset..bb.offset + visible_size
3527        };
3528
3529        // Once a buffer is initialized, nothing can cause the contents to revert to an
3530        // unknown state, so we do not record an init action in the bind group when that is
3531        // the case. (The same is not true of textures.)
3532        buffer_init_actions.extend(buffer.initialization_status.read().create_action(
3533            buffer,
3534            init_range,
3535            MemoryInitKind::NeedsInitializedMemory,
3536        ));
3537
3538        Ok(bb)
3539    }
3540
3541    fn create_sampler_binding<'a>(
3542        &self,
3543        used: &mut BindGroupStates,
3544        binding: u32,
3545        decl: &wgt::BindGroupLayoutEntry,
3546        sampler: &'a Arc<Sampler>,
3547    ) -> Result<&'a dyn hal::DynSampler, CreateBindGroupError> {
3548        use crate::binding_model::CreateBindGroupError as Error;
3549
3550        used.samplers.insert_single(sampler.clone());
3551
3552        sampler.same_device(self)?;
3553
3554        match decl.ty {
3555            wgt::BindingType::Sampler(ty) => {
3556                let (allowed_filtering, allowed_comparison) = match ty {
3557                    wgt::SamplerBindingType::Filtering => (None, false),
3558                    wgt::SamplerBindingType::NonFiltering => (Some(false), false),
3559                    wgt::SamplerBindingType::Comparison => (None, true),
3560                };
3561                if let Some(allowed_filtering) = allowed_filtering {
3562                    if allowed_filtering != sampler.filtering {
3563                        return Err(Error::WrongSamplerFiltering {
3564                            binding,
3565                            layout_flt: allowed_filtering,
3566                            sampler_flt: sampler.filtering,
3567                        });
3568                    }
3569                }
3570                if allowed_comparison != sampler.comparison {
3571                    return Err(Error::WrongSamplerComparison {
3572                        binding,
3573                        layout_cmp: allowed_comparison,
3574                        sampler_cmp: sampler.comparison,
3575                    });
3576                }
3577            }
3578            _ => {
3579                return Err(Error::WrongBindingType {
3580                    binding,
3581                    actual: decl.ty,
3582                    expected: "Sampler",
3583                })
3584            }
3585        }
3586
3587        Ok(sampler.raw()?)
3588    }
3589
3590    fn create_texture_binding<'a>(
3591        &self,
3592        binding: u32,
3593        decl: &wgt::BindGroupLayoutEntry,
3594        view: &'a Arc<TextureView>,
3595        used: &mut BindGroupStates,
3596        texture_init_actions: &mut Vec<TextureInitTrackerAction>,
3597        snatch_guard: &'a SnatchGuard<'a>,
3598    ) -> Result<hal::TextureBinding<'a, dyn hal::DynTextureView>, CreateBindGroupError> {
3599        view.check_valid()?;
3600        view.same_device(self)?;
3601
3602        let internal_use = self.texture_use_parameters(
3603            binding,
3604            decl,
3605            view,
3606            "SampledTexture, ReadonlyStorageTexture or WriteonlyStorageTexture",
3607        )?;
3608
3609        used.views.insert_single(view.clone(), internal_use);
3610
3611        let texture = &view.parent;
3612
3613        // Unlike buffers, textures contents can revert to being undefined if used as a
3614        // render attachment with `StoreOp::Discard`. Therefore, we must always register
3615        // the init action in the bind group, and check the initialization state every
3616        // time the binding is used.
3617        texture_init_actions.push(TextureInitTrackerAction {
3618            texture: texture.clone(),
3619            range: TextureInitRange {
3620                mip_range: view.desc.range.mip_range(texture.desc.mip_level_count),
3621                layer_range: view
3622                    .desc
3623                    .range
3624                    .layer_range(texture.desc.array_layer_count()),
3625            },
3626            kind: MemoryInitKind::NeedsInitializedMemory,
3627        });
3628
3629        Ok(hal::TextureBinding {
3630            view: view.try_raw(snatch_guard)?,
3631            usage: internal_use,
3632        })
3633    }
3634
3635    fn create_tlas_binding<'a>(
3636        self: &Arc<Self>,
3637        used: &mut BindGroupStates,
3638        binding: u32,
3639        decl: &wgt::BindGroupLayoutEntry,
3640        tlas: &'a Arc<Tlas>,
3641        snatch_guard: &'a SnatchGuard<'a>,
3642    ) -> Result<&'a dyn hal::DynAccelerationStructure, CreateBindGroupError> {
3643        use crate::binding_model::CreateBindGroupError as Error;
3644
3645        used.acceleration_structures.insert_single(tlas.clone());
3646
3647        tlas.check_is_valid()?;
3648        tlas.same_device(self)?;
3649
3650        match decl.ty {
3651            wgt::BindingType::AccelerationStructure { vertex_return } => {
3652                if vertex_return
3653                    && !tlas.flags.contains(
3654                        wgpu_types::AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN,
3655                    )
3656                {
3657                    return Err(Error::MissingTLASVertexReturn { binding });
3658                }
3659            }
3660            _ => {
3661                return Err(Error::WrongBindingType {
3662                    binding,
3663                    actual: decl.ty,
3664                    expected: "Tlas",
3665                });
3666            }
3667        }
3668
3669        Ok(tlas.try_raw(snatch_guard)?)
3670    }
3671
3672    fn create_external_texture_binding<'a>(
3673        &'a self,
3674        binding: u32,
3675        decl: &wgt::BindGroupLayoutEntry,
3676        external_texture: &'a Arc<ExternalTexture>,
3677        texture_init_actions: &mut Vec<TextureInitTrackerAction>,
3678        used: &mut BindGroupStates,
3679        snatch_guard: &'a SnatchGuard,
3680    ) -> Result<
3681        hal::ExternalTextureBinding<'a, dyn hal::DynBuffer, dyn hal::DynTextureView>,
3682        CreateBindGroupError,
3683    > {
3684        use crate::binding_model::CreateBindGroupError as Error;
3685
3686        let external_texture_state = external_texture.state()?;
3687        external_texture.same_device(self)?;
3688
3689        used.external_textures
3690            .insert_single(external_texture.clone());
3691
3692        match decl.ty {
3693            wgt::BindingType::ExternalTexture => {}
3694            _ => {
3695                return Err(Error::WrongBindingType {
3696                    binding,
3697                    actual: decl.ty,
3698                    expected: "ExternalTexture",
3699                });
3700            }
3701        }
3702
3703        let planes = (0..3)
3704            .map(|i| {
3705                // We always need 3 bindings. If we have fewer than 3 planes
3706                // just bind plane 0 multiple times. The shader will only
3707                // sample from valid planes anyway.
3708                let plane = external_texture
3709                    .planes
3710                    .get(i)
3711                    .unwrap_or(&external_texture.planes[0]);
3712                let internal_use = wgt::TextureUses::RESOURCE;
3713                used.views.insert_single(plane.clone(), internal_use);
3714                let view = plane.try_raw(snatch_guard)?;
3715                Ok(hal::TextureBinding {
3716                    view,
3717                    usage: internal_use,
3718                })
3719            })
3720            // We can remove this intermediate Vec by using
3721            // array::try_from_fn() above, once it stabilizes.
3722            .collect::<Result<Vec<_>, Error>>()?;
3723        let planes = planes.try_into().unwrap();
3724
3725        // Iterate over the distinct planes, rather than the three bindings produced
3726        // above, so that a plane repeated to fill the bindings is only recorded once.
3727        for plane in external_texture.planes.iter() {
3728            let texture = &plane.parent;
3729            texture_init_actions.push(TextureInitTrackerAction {
3730                texture: texture.clone(),
3731                range: TextureInitRange {
3732                    mip_range: plane.desc.range.mip_range(texture.desc.mip_level_count),
3733                    layer_range: plane
3734                        .desc
3735                        .range
3736                        .layer_range(texture.desc.array_layer_count()),
3737                },
3738                kind: MemoryInitKind::NeedsInitializedMemory,
3739            });
3740        }
3741
3742        used.buffers.insert_single(
3743            external_texture_state.params.clone(),
3744            wgt::BufferUses::UNIFORM,
3745        );
3746        let params = external_texture_state
3747            .params
3748            .binding(0, None, snatch_guard)?;
3749
3750        Ok(hal::ExternalTextureBinding { planes, params })
3751    }
3752
3753    fn create_external_texture_binding_from_view<'a>(
3754        &'a self,
3755        binding: u32,
3756        decl: &wgt::BindGroupLayoutEntry,
3757        view: &'a Arc<TextureView>,
3758        texture_init_actions: &mut Vec<TextureInitTrackerAction>,
3759        used: &mut BindGroupStates,
3760        snatch_guard: &'a SnatchGuard,
3761    ) -> Result<
3762        hal::ExternalTextureBinding<'a, dyn hal::DynBuffer, dyn hal::DynTextureView>,
3763        CreateBindGroupError,
3764    > {
3765        use crate::binding_model::CreateBindGroupError as Error;
3766
3767        view.same_device(self)?;
3768        view.check_valid()?;
3769
3770        let internal_use = self.texture_use_parameters(binding, decl, view, "SampledTexture")?;
3771        used.views.insert_single(view.clone(), internal_use);
3772
3773        match decl.ty {
3774            wgt::BindingType::ExternalTexture => {}
3775            _ => {
3776                return Err(Error::WrongBindingType {
3777                    binding,
3778                    actual: decl.ty,
3779                    expected: "ExternalTexture",
3780                });
3781            }
3782        }
3783
3784        // We need 3 bindings, so just repeat the same texture view 3 times.
3785        let planes = [
3786            hal::TextureBinding {
3787                view: view.try_raw(snatch_guard)?,
3788                usage: internal_use,
3789            },
3790            hal::TextureBinding {
3791                view: view.try_raw(snatch_guard)?,
3792                usage: internal_use,
3793            },
3794            hal::TextureBinding {
3795                view: view.try_raw(snatch_guard)?,
3796                usage: internal_use,
3797            },
3798        ];
3799        let params = hal::BufferBinding::new_unchecked(
3800            self.default_external_texture_params_buffer.as_ref(),
3801            0,
3802            NonZeroU64::new(size_of::<ExternalTextureParams>() as u64).unwrap(),
3803        );
3804
3805        texture_init_actions.push(TextureInitTrackerAction {
3806            texture: view.parent.clone(),
3807            range: TextureInitRange {
3808                mip_range: view.desc.range.mip_range(view.parent.desc.mip_level_count),
3809                layer_range: view
3810                    .desc
3811                    .range
3812                    .layer_range(view.parent.desc.array_layer_count()),
3813            },
3814            kind: MemoryInitKind::NeedsInitializedMemory,
3815        });
3816
3817        Ok(hal::ExternalTextureBinding { planes, params })
3818    }
3819
3820    pub fn create_bind_group(
3821        self: &Arc<Self>,
3822        desc: &binding_model::BindGroupDescriptor,
3823    ) -> Arc<BindGroup> {
3824        profiling::scope!("Device::create_bind_group");
3825        #[cfg(feature = "trace")]
3826        let trace_desc = (&desc).to_trace();
3827
3828        let bind_group = self.create_bind_group_inner(desc).unwrap_or_else(|err| {
3829            self.handle_error(err, desc.label.as_deref(), "Device::create_bind_group");
3830            BindGroup::invalid(self.clone(), desc.label.to_string(), desc.layout.clone())
3831        });
3832
3833        #[cfg(feature = "trace")]
3834        if let Some(ref mut trace) = *self.trace.lock() {
3835            trace.add(trace::Action::CreateBindGroup(
3836                bind_group.to_trace(),
3837                trace_desc,
3838            ));
3839        }
3840
3841        api_log!(
3842            "Device::create_bind_group -> {:?}",
3843            Arc::as_ptr(&bind_group)
3844        );
3845
3846        bind_group
3847    }
3848
3849    // This function expects the provided bind group layout to be resolved
3850    // (not passing a duplicate) beforehand.
3851    pub fn create_bind_group_inner(
3852        self: &Arc<Self>,
3853        desc: &binding_model::BindGroupDescriptor,
3854    ) -> Result<Arc<BindGroup>, CreateBindGroupError> {
3855        use crate::binding_model::{BindingResource as Br, CreateBindGroupError as Error};
3856
3857        self.check_is_valid()?;
3858
3859        let layout = desc.layout.clone();
3860
3861        layout.same_device(self)?;
3862        layout.check_is_valid()?;
3863
3864        {
3865            // Check that the number of entries in the descriptor matches
3866            // the number of entries in the layout.
3867            let actual = desc.entries.len();
3868            let expected = layout.entries.len();
3869            if actual != expected {
3870                return Err(Error::BindingsNumMismatch { expected, actual });
3871            }
3872        }
3873
3874        // Record binding info for dynamic offset validation
3875        let mut dynamic_binding_info = Vec::new();
3876        // Bound sizes of late-sized buffer bindings, collected in `layout.late_sized_bindings`
3877        // order once all entries are processed.
3878        let mut late_sizes_by_binding = FastHashMap::default();
3879        // fill out the descriptors
3880        let mut used = BindGroupStates::new();
3881
3882        let mut buffer_init_actions = Vec::new();
3883        let mut texture_init_actions = Vec::new();
3884        let snatch_guard = self.snatchable_lock.read();
3885        let mut hal_entries = SmallVec::<[_; 4]>::with_capacity(desc.entries.len());
3886        let mut hal_buffers = SmallVec::<[_; 4]>::new();
3887        let mut hal_samplers = SmallVec::<[_; 4]>::new();
3888        let mut hal_textures = SmallVec::<[_; 8]>::new();
3889        let mut hal_tlas_s = SmallVec::<[_; 1]>::new();
3890        let mut hal_external_textures = SmallVec::<[_; 1]>::new();
3891        for entry in desc.entries.iter() {
3892            let binding = entry.binding;
3893            // Find the corresponding declaration in the layout
3894            let decl = layout
3895                .entries
3896                .get(binding)
3897                .ok_or(Error::MissingBindingDeclaration(binding))?;
3898            let (res_index, count) = match entry.resource {
3899                Br::Buffer(ref bb) => {
3900                    let bb = self.create_buffer_binding(
3901                        bb,
3902                        binding,
3903                        decl,
3904                        &mut buffer_init_actions,
3905                        &mut dynamic_binding_info,
3906                        &mut late_sizes_by_binding,
3907                        &mut used,
3908                        &snatch_guard,
3909                    )?;
3910
3911                    let res_index = hal_buffers.len();
3912                    hal_buffers.push(bb);
3913                    (res_index, 1)
3914                }
3915                Br::BufferArray(ref bindings_array) => {
3916                    let num_bindings = bindings_array.len();
3917                    Self::check_array_binding(self.features, decl.count, num_bindings)?;
3918
3919                    let res_index = hal_buffers.len();
3920                    for bb in bindings_array.iter() {
3921                        let bb = self.create_buffer_binding(
3922                            bb,
3923                            binding,
3924                            decl,
3925                            &mut buffer_init_actions,
3926                            &mut dynamic_binding_info,
3927                            &mut late_sizes_by_binding,
3928                            &mut used,
3929                            &snatch_guard,
3930                        )?;
3931                        hal_buffers.push(bb);
3932                    }
3933                    (res_index, num_bindings)
3934                }
3935                Br::Sampler(ref sampler) => {
3936                    let sampler = self.create_sampler_binding(&mut used, binding, decl, sampler)?;
3937
3938                    let res_index = hal_samplers.len();
3939                    hal_samplers.push(sampler);
3940                    (res_index, 1)
3941                }
3942                Br::SamplerArray(ref samplers) => {
3943                    let num_bindings = samplers.len();
3944                    Self::check_array_binding(self.features, decl.count, num_bindings)?;
3945
3946                    let res_index = hal_samplers.len();
3947                    for sampler in samplers.iter() {
3948                        let sampler =
3949                            self.create_sampler_binding(&mut used, binding, decl, sampler)?;
3950
3951                        hal_samplers.push(sampler);
3952                    }
3953
3954                    (res_index, num_bindings)
3955                }
3956                Br::TextureView(ref view) => match decl.ty {
3957                    wgt::BindingType::ExternalTexture => {
3958                        let et = self.create_external_texture_binding_from_view(
3959                            binding,
3960                            decl,
3961                            view,
3962                            &mut texture_init_actions,
3963                            &mut used,
3964                            &snatch_guard,
3965                        )?;
3966                        let res_index = hal_external_textures.len();
3967                        hal_external_textures.push(et);
3968                        (res_index, 1)
3969                    }
3970                    _ => {
3971                        let tb = self.create_texture_binding(
3972                            binding,
3973                            decl,
3974                            view,
3975                            &mut used,
3976                            &mut texture_init_actions,
3977                            &snatch_guard,
3978                        )?;
3979                        let res_index = hal_textures.len();
3980                        hal_textures.push(tb);
3981                        (res_index, 1)
3982                    }
3983                },
3984                Br::TextureViewArray(ref views) => {
3985                    let num_bindings = views.len();
3986                    Self::check_array_binding(self.features, decl.count, num_bindings)?;
3987
3988                    let res_index = hal_textures.len();
3989                    for view in views.iter() {
3990                        let tb = self.create_texture_binding(
3991                            binding,
3992                            decl,
3993                            view,
3994                            &mut used,
3995                            &mut texture_init_actions,
3996                            &snatch_guard,
3997                        )?;
3998
3999                        hal_textures.push(tb);
4000                    }
4001
4002                    (res_index, num_bindings)
4003                }
4004                Br::AccelerationStructure(ref tlas) => {
4005                    let tlas =
4006                        self.create_tlas_binding(&mut used, binding, decl, tlas, &snatch_guard)?;
4007                    let res_index = hal_tlas_s.len();
4008                    hal_tlas_s.push(tlas);
4009                    (res_index, 1)
4010                }
4011                Br::AccelerationStructureArray(ref tlas_array) => {
4012                    // Feature validation for TLAS binding arrays happens at bind group layout
4013                    // creation time (mirroring other binding-array resource types). By the time we
4014                    // get here, `decl.count` has already been validated against device features.
4015                    let num_bindings = tlas_array.len();
4016                    Self::check_array_binding(self.features, decl.count, num_bindings)?;
4017
4018                    let res_index = hal_tlas_s.len();
4019                    for tlas in tlas_array.iter() {
4020                        let tlas = self.create_tlas_binding(
4021                            &mut used,
4022                            binding,
4023                            decl,
4024                            tlas,
4025                            &snatch_guard,
4026                        )?;
4027                        hal_tlas_s.push(tlas);
4028                    }
4029                    (res_index, num_bindings)
4030                }
4031                Br::ExternalTexture(ref et) => {
4032                    let et = self.create_external_texture_binding(
4033                        binding,
4034                        decl,
4035                        et,
4036                        &mut texture_init_actions,
4037                        &mut used,
4038                        &snatch_guard,
4039                    )?;
4040                    let res_index = hal_external_textures.len();
4041                    hal_external_textures.push(et);
4042                    (res_index, 1)
4043                }
4044            };
4045
4046            hal_entries.push(hal::BindGroupEntry {
4047                binding,
4048                resource_index: res_index as u32,
4049                count: count as u32,
4050            });
4051        }
4052
4053        used.optimize();
4054
4055        hal_entries.sort_by_key(|entry| entry.binding);
4056        for (a, b) in hal_entries.iter().zip(hal_entries.iter().skip(1)) {
4057            if a.binding == b.binding {
4058                return Err(Error::DuplicateBinding(a.binding));
4059            }
4060        }
4061
4062        dynamic_binding_info.sort_by_key(|i| i.binding_idx);
4063
4064        let hal_desc = hal::BindGroupDescriptor {
4065            label: desc.label.to_hal(self.instance_flags),
4066            layout: layout.try_raw()?,
4067            entries: &hal_entries,
4068            buffers: &hal_buffers,
4069            samplers: &hal_samplers,
4070            textures: &hal_textures,
4071            acceleration_structures: &hal_tlas_s,
4072            external_textures: &hal_external_textures,
4073        };
4074        let raw = unsafe { self.raw().create_bind_group(&hal_desc) }
4075            .map_err(|e| self.handle_hal_error(e))?;
4076
4077        // Every layout entry has a descriptor entry by now, so every late-sized binding has a size.
4078        let late_buffer_binding_sizes = layout
4079            .late_sized_bindings
4080            .iter()
4081            .map(|binding| late_sizes_by_binding[binding])
4082            .collect();
4083
4084        let bind_group = BindGroup {
4085            state: ResourceState::Valid(BindGroupState {
4086                raw: Snatchable::new(raw),
4087            }),
4088            device: self.clone(),
4089            layout,
4090            label: desc.label.to_string(),
4091            tracking_data: TrackingData::new(self.tracker_indices.bind_groups.clone()),
4092            used,
4093            buffer_init_actions,
4094            texture_init_actions,
4095            dynamic_binding_info,
4096            late_buffer_binding_sizes,
4097        };
4098
4099        let bind_group = Arc::new(bind_group);
4100
4101        let weak_ref = Arc::downgrade(&bind_group);
4102        for texture in bind_group.used.views.used_textures() {
4103            let mut bind_groups = texture.bind_groups.lock();
4104            bind_groups.push(weak_ref.clone());
4105        }
4106        for buffer in bind_group.used.buffers.used_resources() {
4107            let mut bind_groups = buffer.bind_groups.lock();
4108            bind_groups.push(weak_ref.clone());
4109        }
4110
4111        Ok(bind_group)
4112    }
4113
4114    fn check_array_binding(
4115        features: wgt::Features,
4116        count: Option<NonZeroU32>,
4117        num_bindings: usize,
4118    ) -> Result<(), CreateBindGroupError> {
4119        use super::binding_model::CreateBindGroupError as Error;
4120
4121        if let Some(count) = count {
4122            let count = count.get() as usize;
4123            if count < num_bindings {
4124                return Err(Error::BindingArrayPartialLengthMismatch {
4125                    actual: num_bindings,
4126                    expected: count,
4127                });
4128            }
4129            if count != num_bindings
4130                && !features.contains(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY)
4131            {
4132                return Err(Error::BindingArrayLengthMismatch {
4133                    actual: num_bindings,
4134                    expected: count,
4135                });
4136            }
4137            if num_bindings == 0 {
4138                return Err(Error::BindingArrayZeroLength);
4139            }
4140        } else {
4141            return Err(Error::SingleBindingExpected);
4142        };
4143
4144        Ok(())
4145    }
4146
4147    fn texture_use_parameters(
4148        &self,
4149        binding: u32,
4150        decl: &wgt::BindGroupLayoutEntry,
4151        view: &TextureView,
4152        expected: &'static str,
4153    ) -> Result<wgt::TextureUses, CreateBindGroupError> {
4154        use crate::binding_model::CreateBindGroupError as Error;
4155        if view
4156            .desc
4157            .aspects()
4158            .contains(hal::FormatAspects::DEPTH | hal::FormatAspects::STENCIL)
4159        {
4160            return Err(Error::DepthStencilAspect);
4161        }
4162        match decl.ty {
4163            wgt::BindingType::Texture {
4164                sample_type,
4165                view_dimension,
4166                multisampled,
4167            } => {
4168                use wgt::TextureSampleType as Tst;
4169                if multisampled != (view.samples != 1) {
4170                    return Err(Error::InvalidTextureMultisample {
4171                        binding,
4172                        layout_multisampled: multisampled,
4173                        view_samples: view.samples,
4174                    });
4175                }
4176                let compat_sample_type = view
4177                    .desc
4178                    .format
4179                    .sample_type(Some(view.desc.range.aspect), Some(self.features))
4180                    .unwrap();
4181                match (sample_type, compat_sample_type) {
4182                    (Tst::Uint, Tst::Uint) |
4183                        (Tst::Sint, Tst::Sint) |
4184                        (Tst::Depth, Tst::Depth) |
4185                        // if we expect non-filterable, accept anything float
4186                        (Tst::Float { filterable: false }, Tst::Float { .. }) |
4187                        // if we expect filterable, require it
4188                        (Tst::Float { filterable: true }, Tst::Float { filterable: true }) |
4189                        // if we expect non-filterable, also accept depth
4190                        (Tst::Float { filterable: false }, Tst::Depth) => {}
4191                    // if we expect filterable, also accept Float that is defined as
4192                    // unfilterable if filterable feature is explicitly enabled (only hit
4193                    // if wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES is
4194                    // enabled)
4195                    (Tst::Float { filterable: true }, Tst::Float { .. })
4196                        if view.format_features.flags
4197                            .contains(wgt::TextureFormatFeatureFlags::FILTERABLE) => {}
4198                    _ => {
4199                        return Err(Error::InvalidTextureSampleType {
4200                            binding,
4201                            layout_sample_type: sample_type,
4202                            view_format: view.desc.format,
4203                            view_sample_type: compat_sample_type,
4204                        })
4205                    }
4206                }
4207                if view_dimension != view.desc.dimension {
4208                    return Err(Error::InvalidTextureDimension {
4209                        binding,
4210                        layout_dimension: view_dimension,
4211                        view_dimension: view.desc.dimension,
4212                    });
4213                }
4214                if let Some(texture_binding_view_dimension) =
4215                    view.parent.texture_binding_view_dimension()
4216                {
4217                    if texture_binding_view_dimension != view.desc.dimension {
4218                        return Err(Error::InvalidTextureBindingViewDimension {
4219                            binding,
4220                            view_dimension: view.desc.dimension,
4221                            texture_binding_view_dimension,
4222                        });
4223                    }
4224                }
4225                view.check_usage(wgt::TextureUsages::TEXTURE_BINDING)?;
4226                let depth_stencil_uses = if view.desc.aspects() == hal::FormatAspects::DEPTH {
4227                    wgt::TextureUses::DEPTH_SAMPLED
4228                } else if view.desc.aspects() == hal::FormatAspects::STENCIL {
4229                    wgt::TextureUses::STENCIL_SAMPLED
4230                } else {
4231                    wgt::TextureUses::empty()
4232                };
4233                Ok(wgt::TextureUses::RESOURCE | depth_stencil_uses)
4234            }
4235            wgt::BindingType::StorageTexture {
4236                access,
4237                format,
4238                view_dimension,
4239            } => {
4240                if format != view.desc.format {
4241                    return Err(Error::InvalidStorageTextureFormat {
4242                        binding,
4243                        layout_format: format,
4244                        view_format: view.desc.format,
4245                    });
4246                }
4247                if view_dimension != view.desc.dimension {
4248                    return Err(Error::InvalidTextureDimension {
4249                        binding,
4250                        layout_dimension: view_dimension,
4251                        view_dimension: view.desc.dimension,
4252                    });
4253                }
4254                if let Some(texture_binding_view_dimension) =
4255                    view.parent.texture_binding_view_dimension()
4256                {
4257                    if texture_binding_view_dimension != view.desc.dimension {
4258                        return Err(Error::InvalidTextureBindingViewDimension {
4259                            binding,
4260                            view_dimension: view.desc.dimension,
4261                            texture_binding_view_dimension,
4262                        });
4263                    }
4264                }
4265
4266                let mip_level_count = view.selector.mips.end - view.selector.mips.start;
4267                if mip_level_count != 1 {
4268                    return Err(Error::InvalidStorageTextureMipLevelCount {
4269                        binding,
4270                        mip_level_count,
4271                    });
4272                }
4273
4274                if view.desc.swizzle != wgt::TextureComponentSwizzle::default() {
4275                    return Err(Error::InvalidStorageTextureSwizzle {
4276                        swizzle: view.desc.swizzle,
4277                    });
4278                }
4279
4280                view.check_usage(wgt::TextureUsages::STORAGE_BINDING)?;
4281
4282                Ok(match access {
4283                    wgt::StorageTextureAccess::ReadOnly => wgt::TextureUses::STORAGE_READ_ONLY,
4284                    wgt::StorageTextureAccess::WriteOnly => wgt::TextureUses::STORAGE_WRITE_ONLY,
4285                    wgt::StorageTextureAccess::ReadWrite => wgt::TextureUses::STORAGE_READ_WRITE,
4286                    wgt::StorageTextureAccess::Atomic => wgt::TextureUses::STORAGE_ATOMIC,
4287                })
4288            }
4289            wgt::BindingType::ExternalTexture => {
4290                if view.desc.dimension != TextureViewDimension::D2 {
4291                    return Err(Error::InvalidTextureDimension {
4292                        binding,
4293                        layout_dimension: TextureViewDimension::D2,
4294                        view_dimension: view.desc.dimension,
4295                    });
4296                }
4297                let mip_level_count = view.selector.mips.end - view.selector.mips.start;
4298                if mip_level_count != 1 {
4299                    return Err(Error::InvalidExternalTextureMipLevelCount {
4300                        binding,
4301                        mip_level_count,
4302                    });
4303                }
4304                if view.desc.format != TextureFormat::Rgba8Unorm
4305                    && view.desc.format != TextureFormat::Bgra8Unorm
4306                    && view.desc.format != TextureFormat::Rgba16Float
4307                {
4308                    return Err(Error::InvalidExternalTextureFormat {
4309                        binding,
4310                        format: view.desc.format,
4311                    });
4312                }
4313                if view.samples != 1 {
4314                    return Err(Error::InvalidTextureMultisample {
4315                        binding,
4316                        layout_multisampled: false,
4317                        view_samples: view.samples,
4318                    });
4319                }
4320
4321                view.check_usage(wgt::TextureUsages::TEXTURE_BINDING)?;
4322                Ok(wgt::TextureUses::RESOURCE)
4323            }
4324            _ => Err(Error::WrongBindingType {
4325                binding,
4326                actual: decl.ty,
4327                expected,
4328            }),
4329        }
4330    }
4331
4332    pub fn create_pipeline_layout(
4333        self: &Arc<Self>,
4334        desc: &binding_model::PipelineLayoutDescriptor,
4335    ) -> Arc<binding_model::PipelineLayout> {
4336        profiling::scope!("Device::create_pipeline_layout");
4337        let layout = self
4338            .create_pipeline_layout_impl(desc, false)
4339            .unwrap_or_else(|err| {
4340                self.handle_error(err, desc.label.as_deref(), "Device::create_pipeline_layout");
4341                binding_model::PipelineLayout::invalid(Arc::clone(self), desc.label.to_string())
4342            });
4343        #[cfg(feature = "trace")]
4344        if let Some(ref mut trace) = *self.trace.lock() {
4345            use crate::device::trace::IntoTrace;
4346            trace.add(trace::Action::CreatePipelineLayout(
4347                layout.to_trace(),
4348                desc.to_trace(),
4349            ));
4350        }
4351        api_log!(
4352            "Device::create_pipeline_layout -> {:?}",
4353            Arc::as_ptr(&layout)
4354        );
4355        layout
4356    }
4357
4358    fn create_pipeline_layout_impl(
4359        self: &Arc<Self>,
4360        desc: &binding_model::PipelineLayoutDescriptor,
4361        ignore_exclusive_pipeline_check: bool,
4362    ) -> Result<Arc<binding_model::PipelineLayout>, binding_model::CreatePipelineLayoutError> {
4363        use crate::binding_model::CreatePipelineLayoutError as Error;
4364
4365        self.check_is_valid()?;
4366
4367        let bind_group_layouts_count = desc.bind_group_layouts.len();
4368        let device_max_bind_groups = self.limits.max_bind_groups as usize;
4369        if bind_group_layouts_count > device_max_bind_groups {
4370            return Err(Error::TooManyGroups {
4371                actual: bind_group_layouts_count,
4372                max: device_max_bind_groups,
4373            });
4374        }
4375
4376        if desc.immediate_size != 0 {
4377            self.require_features(wgt::Features::IMMEDIATES)?;
4378        }
4379        if self.limits.max_immediate_size < desc.immediate_size {
4380            return Err(Error::ImmediateRangeTooLarge {
4381                size: desc.immediate_size,
4382                max: self.limits.max_immediate_size,
4383            });
4384        }
4385        if !desc
4386            .immediate_size
4387            .is_multiple_of(wgt::IMMEDIATE_DATA_ALIGNMENT)
4388        {
4389            return Err(Error::MisalignedImmediateSize {
4390                size: desc.immediate_size,
4391            });
4392        }
4393
4394        let mut count_validator = binding_model::BindingTypeMaxCountValidator::default();
4395
4396        for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
4397            let Some(bgl) = bgl else {
4398                continue;
4399            };
4400
4401            bgl.same_device(self)?;
4402
4403            if !ignore_exclusive_pipeline_check {
4404                let exclusive_pipeline = bgl.exclusive_pipeline.get().unwrap();
4405                if !matches!(exclusive_pipeline, binding_model::ExclusivePipeline::None) {
4406                    return Err(Error::BglHasExclusivePipeline {
4407                        index,
4408                        pipeline: alloc::format!("{exclusive_pipeline}"),
4409                    });
4410                }
4411            }
4412
4413            count_validator.merge(&bgl.state()?.binding_count_validator);
4414        }
4415
4416        count_validator
4417            .validate(&self.limits, self.instance_flags)
4418            .map_err(Error::TooManyBindings)?;
4419
4420        let buffers_and_acceleration_structures_in_vertex_stage =
4421            count_validator.buffers_and_acceleration_structures_in_vertex_stage();
4422
4423        let get_bgl_iter = || {
4424            desc.bind_group_layouts
4425                .iter()
4426                .map(|bgl| bgl.as_ref().filter(|bgl| !bgl.entries.is_empty()))
4427        };
4428
4429        let bind_group_layouts = get_bgl_iter()
4430            .map(|bgl| bgl.cloned())
4431            .collect::<ArrayVec<_, { hal::MAX_BIND_GROUPS }>>();
4432
4433        let raw_bind_group_layouts = get_bgl_iter()
4434            .map(|bgl| bgl.map(|bgl| bgl.try_raw()).transpose())
4435            .collect::<Result<ArrayVec<_, { hal::MAX_BIND_GROUPS }>, _>>()?;
4436
4437        let additional_flags = if self.indirect_validation.is_some() {
4438            hal::PipelineLayoutFlags::INDIRECT_BUILTIN_UPDATE
4439        } else {
4440            hal::PipelineLayoutFlags::empty()
4441        };
4442
4443        let hal_desc = hal::PipelineLayoutDescriptor {
4444            label: desc.label.to_hal(self.instance_flags),
4445            flags: hal::PipelineLayoutFlags::FIRST_VERTEX_INSTANCE
4446                | hal::PipelineLayoutFlags::NUM_WORK_GROUPS
4447                | additional_flags,
4448            bind_group_layouts: &raw_bind_group_layouts,
4449            immediate_size: desc.immediate_size,
4450        };
4451
4452        let raw = unsafe { self.raw().create_pipeline_layout(&hal_desc) }
4453            .map_err(|e| self.handle_hal_error(e))?;
4454
4455        drop(raw_bind_group_layouts);
4456
4457        let layout = binding_model::PipelineLayout {
4458            raw: ResourceState::Valid(raw),
4459            device: self.clone(),
4460            label: desc.label.to_string(),
4461            bind_group_layouts,
4462            immediate_size: desc.immediate_size,
4463            buffers_and_acceleration_structures_in_vertex_stage,
4464        };
4465
4466        let layout = Arc::new(layout);
4467
4468        Ok(layout)
4469    }
4470
4471    pub(super) fn create_derived_pipeline_layout(
4472        self: &Arc<Self>,
4473        mut derived_group_layouts: Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>,
4474        immediate_size: u32,
4475    ) -> Result<Arc<binding_model::PipelineLayout>, pipeline::ImplicitLayoutError> {
4476        // <https://gpuweb.github.io/gpuweb/#abstract-opdef-default-pipeline-layout>
4477        // Round up the immediate size for pipeline layout as it is required to be a multiple of 4
4478        let immediate_size = align_to(immediate_size, wgt::IMMEDIATE_DATA_ALIGNMENT);
4479
4480        while derived_group_layouts
4481            .last()
4482            .is_some_and(|map| map.is_empty())
4483        {
4484            derived_group_layouts.pop();
4485        }
4486
4487        let mut unique_bind_group_layouts = FastHashMap::default();
4488
4489        let bind_group_layouts = derived_group_layouts
4490            .into_iter()
4491            .map(|mut bgl_entry_map| {
4492                if bgl_entry_map.is_empty() {
4493                    return Ok(None);
4494                }
4495
4496                bgl_entry_map.sort();
4497                match unique_bind_group_layouts.entry(bgl_entry_map) {
4498                    hashbrown::hash_map::Entry::Occupied(v) => Ok(Some(Arc::clone(v.get()))),
4499                    hashbrown::hash_map::Entry::Vacant(e) => {
4500                        match self.create_bind_group_layout_impl(
4501                            &None,
4502                            e.key().clone(),
4503                            bgl::Origin::Derived,
4504                        ) {
4505                            Ok(bgl) => {
4506                                e.insert(bgl.clone());
4507                                Ok(Some(bgl))
4508                            }
4509                            Err(e) => Err(e),
4510                        }
4511                    }
4512                }
4513            })
4514            .collect::<Result<Vec<_>, _>>()?;
4515
4516        let layout_desc = binding_model::PipelineLayoutDescriptor {
4517            label: None,
4518            bind_group_layouts: Cow::Owned(bind_group_layouts),
4519            immediate_size,
4520        };
4521
4522        let layout = self.create_pipeline_layout_impl(&layout_desc, true)?;
4523        Ok(layout)
4524    }
4525
4526    /// Creates a compute pipeline. If the creation fails,
4527    /// it will handle error in device and return an invalid compute pipeline.
4528    ///
4529    /// Corresponds to [GPUDevice.createComputePipeline](https://www.w3.org/TR/webgpu/#dom-gpudevice-createcomputepipeline)
4530    pub fn create_compute_pipeline(
4531        self: &Arc<Self>,
4532        desc: pipeline::ComputePipelineDescriptor,
4533    ) -> Arc<pipeline::ComputePipeline> {
4534        profiling::scope!("Device::create_compute_pipeline");
4535        let compute_pipeline = self
4536            .create_compute_pipeline_or_error_inner(desc.clone())
4537            .unwrap_or_else(|err| {
4538                if let pipeline::CreatePipelineError::Internal { stage, ref message } = err {
4539                    log::error!("Shader translation error for stage {stage:?}: {message}");
4540                    log::error!("Please report it to https://github.com/gfx-rs/wgpu");
4541                }
4542                self.handle_error(
4543                    err,
4544                    desc.label.as_deref(),
4545                    "Device::create_compute_pipeline",
4546                );
4547
4548                pipeline::ComputePipeline::invalid(self.clone(), desc.label.to_string())
4549            });
4550        #[cfg(feature = "trace")]
4551        if let Some(ref mut trace) = *self.trace.lock() {
4552            use crate::device::trace;
4553            use crate::device::trace::IntoTrace;
4554            trace.add(trace::Action::CreateComputePipeline {
4555                id: compute_pipeline.to_trace(),
4556                desc: desc.to_trace(),
4557            });
4558        }
4559        api_log!(
4560            "Device::create_compute_pipeline -> {:?}",
4561            Arc::as_ptr(&compute_pipeline)
4562        );
4563        compute_pipeline
4564    }
4565
4566    /// Creates a compute pipeline without raising any error to device.
4567    /// Device lost errors will be mapped to invalid compute pipeline
4568    /// as required by specification.
4569    ///
4570    /// Corresponds to [GPUDevice.createComputePipelineAsync](https://www.w3.org/TR/webgpu/#dom-gpudevice-createcomputepipelineasync)
4571    pub fn create_compute_pipeline_or_error(
4572        self: &Arc<Self>,
4573        desc: pipeline::ComputePipelineDescriptor,
4574    ) -> Result<Arc<pipeline::ComputePipeline>, pipeline::CreatePipelineError> {
4575        let label = desc.label.to_string();
4576        match self.create_compute_pipeline_or_error_inner(desc) {
4577            Err(err) if err.webgpu_error_type() == wgt::error::ErrorType::DeviceLost => {
4578                Ok(pipeline::ComputePipeline::invalid(self.clone(), label))
4579            }
4580            result => result,
4581        }
4582    }
4583
4584    fn create_compute_pipeline_or_error_inner(
4585        self: &Arc<Self>,
4586        desc: pipeline::ComputePipelineDescriptor,
4587    ) -> Result<Arc<pipeline::ComputePipeline>, pipeline::CreatePipelineError> {
4588        self.check_is_valid()?;
4589
4590        self.require_downlevel_flags(wgt::DownlevelFlags::COMPUTE_SHADERS)?;
4591
4592        let is_auto_layout = desc.layout.is_none();
4593
4594        // Get the pipeline layout from the desc if it is provided.
4595        let pipeline_layout = match desc.layout {
4596            Some(pipeline_layout) => {
4597                pipeline_layout.same_device(self)?;
4598                pipeline_layout.check_valid()?;
4599                Some(pipeline_layout)
4600            }
4601            None => None,
4602        };
4603
4604        let mut compiler =
4605            StageCompiler::new(self, pipeline_layout, validation::StageIo::default(), None);
4606        let compute_stage =
4607            compiler.compile(&desc.stage, validation::ShaderStageForValidation::Compute)?;
4608
4609        let resources = compiler.resources;
4610
4611        let pipeline_layout = match resources.layout {
4612            validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
4613            validation::BindingLayoutSource::Derived(entries) => {
4614                self.create_derived_pipeline_layout(entries, resources.immediates.size())?
4615            }
4616        };
4617
4618        let naga::valid::ImmediateUsage::Valid {
4619            slots: immediate_slots_required,
4620            size: _,
4621        } = resources.immediates
4622        else {
4623            unreachable!("Immediates exceeding maxImmediateSize should have been rejected");
4624        };
4625
4626        let late_sized_buffer_groups = Device::make_late_sized_buffer_groups(
4627            &resources.minimum_binding_sizes,
4628            &pipeline_layout,
4629        );
4630
4631        let cache = match desc.cache {
4632            Some(cache) => {
4633                cache.check_is_valid()?;
4634                cache.same_device(self)?;
4635                Some(cache)
4636            }
4637            None => None,
4638        };
4639
4640        let pipeline_desc = hal::ComputePipelineDescriptor {
4641            label: desc.label.to_hal(self.instance_flags),
4642            layout: pipeline_layout.raw()?,
4643            stage: compute_stage.to_hal(),
4644            cache: cache.as_ref().map(|it| it.raw()).transpose()?,
4645        };
4646
4647        let raw = unsafe { self.raw().create_compute_pipeline(&pipeline_desc) }
4648            .map_err(|error| self.handle_hal_pipeline_error(error))?;
4649        drop(compute_stage);
4650
4651        let pipeline = pipeline::ComputePipeline {
4652            state: ResourceState::Valid(pipeline::ComputePipelineState {
4653                raw: ManuallyDrop::new(raw),
4654                layout: pipeline_layout.clone(),
4655                _shader_module: desc.stage.module,
4656            }),
4657            device: self.clone(),
4658            late_sized_buffer_groups,
4659            immediate_slots_required,
4660            label: desc.label.to_string(),
4661            tracking_data: TrackingData::new(self.tracker_indices.compute_pipelines.clone()),
4662        };
4663
4664        let pipeline = Arc::new(pipeline);
4665
4666        if is_auto_layout {
4667            for bgl in pipeline_layout.bind_group_layouts.iter() {
4668                let Some(bgl) = bgl else {
4669                    continue;
4670                };
4671
4672                // `bind_group_layouts` might contain duplicate entries, so we need to ignore the
4673                // result.
4674                let _ = bgl.exclusive_pipeline.set((&pipeline).into());
4675            }
4676        }
4677
4678        Ok(pipeline)
4679    }
4680
4681    /// Creates a render pipeline. If the creation fails,
4682    /// it will handle error in device and return an invalid render pipeline.
4683    ///
4684    /// Corresponds to [GPUDevice.createRenderPipeline](https://www.w3.org/TR/webgpu/#dom-gpudevice-createrenderpipeline)
4685    pub fn create_render_pipeline(
4686        self: &Arc<Self>,
4687        desc: pipeline::ResolvedGeneralRenderPipelineDescriptor,
4688    ) -> Arc<pipeline::RenderPipeline> {
4689        profiling::scope!("Device::create_render_pipeline");
4690
4691        let render_pipeline = self
4692            .create_render_pipeline_or_error_inner(desc.clone())
4693            .unwrap_or_else(|err| {
4694                if let pipeline::CreatePipelineError::Internal { stage, ref message } = err {
4695                    log::error!("Shader translation error for stage {stage:?}: {message}");
4696                    log::error!("Please report it to https://github.com/gfx-rs/wgpu");
4697                }
4698                self.handle_error(err, desc.label.as_deref(), "Device::create_render_pipeline");
4699                pipeline::RenderPipeline::invalid(self.clone(), desc.label.to_string())
4700            });
4701        #[cfg(feature = "trace")]
4702        if let Some(ref mut trace) = *self.trace.lock() {
4703            use crate::device::trace::IntoTrace;
4704            trace.add(trace::Action::CreateGeneralRenderPipeline {
4705                id: render_pipeline.to_trace(),
4706                desc: desc.to_trace(),
4707            });
4708        }
4709        api_log!(
4710            "Device::create_render_pipeline -> {:?}",
4711            Arc::as_ptr(&render_pipeline)
4712        );
4713        render_pipeline
4714    }
4715
4716    /// Creates a render pipeline without raising any error to device.
4717    /// Device lost errors will be mapped to invalid render pipeline
4718    /// as required by specification.
4719    ///
4720    /// Corresponds to [GPUDevice.createRenderPipelineAsync](https://www.w3.org/TR/webgpu/#dom-gpudevice-createrenderpipelineasync)
4721    pub fn create_render_pipeline_or_error(
4722        self: &Arc<Self>,
4723        desc: pipeline::ResolvedGeneralRenderPipelineDescriptor,
4724    ) -> Result<Arc<pipeline::RenderPipeline>, pipeline::CreatePipelineError> {
4725        let label = desc.label.to_string();
4726        match self.create_render_pipeline_or_error_inner(desc) {
4727            Err(e) if e.webgpu_error_type() == wgt::error::ErrorType::DeviceLost => Ok(
4728                pipeline::RenderPipeline::invalid(self.clone(), label.to_string()),
4729            ),
4730            result => result,
4731        }
4732    }
4733
4734    fn create_render_pipeline_or_error_inner(
4735        self: &Arc<Self>,
4736        desc: pipeline::ResolvedGeneralRenderPipelineDescriptor,
4737    ) -> Result<Arc<pipeline::RenderPipeline>, pipeline::CreatePipelineError> {
4738        use wgt::TextureFormatFeatureFlags as Tfff;
4739
4740        self.check_is_valid()?;
4741
4742        let color_targets = desc
4743            .fragment
4744            .as_ref()
4745            .map_or(&[][..], |fragment| &fragment.targets);
4746        let depth_stencil_state = desc.depth_stencil.as_ref();
4747
4748        check_color_attachment_count(color_targets.len(), self.limits.max_color_attachments)?;
4749
4750        {
4751            let cts: ArrayVec<_, { hal::MAX_COLOR_ATTACHMENTS }> =
4752                color_targets.iter().filter_map(|x| x.as_ref()).collect();
4753            if !cts.is_empty() && {
4754                let first = &cts[0];
4755                cts[1..]
4756                    .iter()
4757                    .any(|ct| ct.write_mask != first.write_mask || ct.blend != first.blend)
4758            } {
4759                self.require_downlevel_flags(wgt::DownlevelFlags::INDEPENDENT_BLEND)?;
4760            }
4761        }
4762
4763        let mut io = validation::StageIo::default();
4764
4765        let mut vertex_steps;
4766        let mut hal_vertex_buffer_layouts;
4767        let mut total_attributes;
4768        let mut dual_source_blending = false;
4769        let mut has_depth_attachment = false;
4770        if let pipeline::RenderPipelineVertexProcessor::Vertex(ref vertex) = desc.vertex {
4771            if vertex.buffers.len() > self.limits.max_vertex_buffers as usize {
4772                return Err(pipeline::RenderError::TooManyVertexBuffers {
4773                    given: vertex.buffers.len() as u32,
4774                    limit: self.limits.max_vertex_buffers,
4775                }
4776                .into());
4777            }
4778
4779            vertex_steps = Vec::with_capacity(vertex.buffers.len());
4780            hal_vertex_buffer_layouts = Vec::with_capacity(vertex.buffers.len());
4781            total_attributes = 0;
4782            for (i, vb_state) in vertex.buffers.iter().enumerate() {
4783                let Some(vb_state) = vb_state else {
4784                    vertex_steps.push(None);
4785                    hal_vertex_buffer_layouts.push(None);
4786                    continue;
4787                };
4788
4789                // https://gpuweb.github.io/gpuweb/#abstract-opdef-validating-gpuvertexbufferlayout
4790
4791                if vb_state.array_stride > self.limits.max_vertex_buffer_array_stride as u64 {
4792                    return Err(pipeline::RenderError::VertexStrideTooLarge {
4793                        index: i as u32,
4794                        given: vb_state.array_stride as u32,
4795                        limit: self.limits.max_vertex_buffer_array_stride,
4796                    }
4797                    .into());
4798                }
4799                if vb_state.array_stride % wgt::VERTEX_ALIGNMENT != 0 {
4800                    return Err(pipeline::RenderError::UnalignedVertexStride {
4801                        index: i as u32,
4802                        stride: vb_state.array_stride,
4803                    }
4804                    .into());
4805                }
4806
4807                let max_stride = if vb_state.array_stride == 0 {
4808                    self.limits.max_vertex_buffer_array_stride as u64
4809                } else {
4810                    vb_state.array_stride
4811                };
4812                let mut last_stride = 0;
4813                for attribute in vb_state.attributes.iter() {
4814                    let attribute_stride = attribute.offset + attribute.format.size();
4815                    if attribute_stride > max_stride {
4816                        return Err(pipeline::RenderError::VertexAttributeStrideTooLarge {
4817                            location: attribute.shader_location,
4818                            given: attribute_stride as u32,
4819                            limit: max_stride as u32,
4820                        }
4821                        .into());
4822                    }
4823
4824                    let required_offset_alignment = attribute.format.size().min(4);
4825                    if attribute.offset % required_offset_alignment != 0 {
4826                        return Err(pipeline::RenderError::InvalidVertexAttributeOffset {
4827                            location: attribute.shader_location,
4828                            offset: attribute.offset,
4829                        }
4830                        .into());
4831                    }
4832
4833                    if attribute.shader_location >= self.limits.max_vertex_attributes {
4834                        return Err(pipeline::RenderError::VertexAttributeLocationTooLarge {
4835                            given: attribute.shader_location,
4836                            limit: self.limits.max_vertex_attributes,
4837                        }
4838                        .into());
4839                    }
4840
4841                    last_stride = last_stride.max(attribute_stride);
4842                }
4843
4844                vertex_steps.push(Some(pipeline::VertexStep {
4845                    stride: vb_state.array_stride,
4846                    last_stride,
4847                    mode: vb_state.step_mode,
4848                }));
4849                hal_vertex_buffer_layouts.push(if vb_state.attributes.is_empty() {
4850                    None
4851                } else {
4852                    Some(hal::VertexBufferLayout {
4853                        array_stride: vb_state.array_stride,
4854                        step_mode: vb_state.step_mode,
4855                        attributes: vb_state.attributes.as_ref(),
4856                    })
4857                });
4858
4859                for attribute in vb_state.attributes.iter() {
4860                    if attribute.offset >= 0x10000000 {
4861                        return Err(pipeline::RenderError::InvalidVertexAttributeOffset {
4862                            location: attribute.shader_location,
4863                            offset: attribute.offset,
4864                        }
4865                        .into());
4866                    }
4867
4868                    if let wgt::VertexFormat::Float64
4869                    | wgt::VertexFormat::Float64x2
4870                    | wgt::VertexFormat::Float64x3
4871                    | wgt::VertexFormat::Float64x4 = attribute.format
4872                    {
4873                        self.require_features(wgt::Features::VERTEX_ATTRIBUTE_64BIT)?;
4874                    }
4875
4876                    let previous = io.varyings.insert(
4877                        attribute.shader_location,
4878                        validation::InterfaceVar::vertex_attribute(attribute.format),
4879                    );
4880
4881                    if previous.is_some() {
4882                        return Err(pipeline::RenderError::ShaderLocationClash(
4883                            attribute.shader_location,
4884                        )
4885                        .into());
4886                    }
4887                }
4888                total_attributes += vb_state.attributes.len();
4889            }
4890
4891            if total_attributes > self.limits.max_vertex_attributes as usize {
4892                return Err(pipeline::RenderError::TooManyVertexAttributes {
4893                    given: total_attributes as u32,
4894                    limit: self.limits.max_vertex_attributes,
4895                }
4896                .into());
4897            }
4898        } else {
4899            vertex_steps = Vec::new();
4900            hal_vertex_buffer_layouts = Vec::new();
4901        };
4902
4903        if desc.primitive.strip_index_format.is_some() && !desc.primitive.topology.is_strip() {
4904            return Err(pipeline::RenderError::StripIndexFormatForNonStripTopology {
4905                strip_index_format: desc.primitive.strip_index_format,
4906                topology: desc.primitive.topology,
4907            }
4908            .into());
4909        }
4910
4911        if desc.primitive.unclipped_depth {
4912            self.require_features(wgt::Features::DEPTH_CLIP_CONTROL)?;
4913        }
4914
4915        if desc.primitive.polygon_mode == wgt::PolygonMode::Line {
4916            self.require_features(wgt::Features::POLYGON_MODE_LINE)?;
4917        }
4918        if desc.primitive.polygon_mode == wgt::PolygonMode::Point {
4919            self.require_features(wgt::Features::POLYGON_MODE_POINT)?;
4920        }
4921
4922        if desc.primitive.conservative {
4923            self.require_features(wgt::Features::CONSERVATIVE_RASTERIZATION)?;
4924        }
4925
4926        if desc.primitive.conservative && desc.primitive.polygon_mode != wgt::PolygonMode::Fill {
4927            return Err(pipeline::RenderError::ConservativeRasterizationNonFillPolygonMode.into());
4928        }
4929
4930        let mut target_specified = false;
4931        let mut required_color_outputs = 0u64;
4932        const _: () = {
4933            assert!(hal::MAX_COLOR_ATTACHMENTS <= 64);
4934        };
4935
4936        for (i, cs) in color_targets.iter().enumerate() {
4937            if let Some(cs) = cs.as_ref() {
4938                target_specified = true;
4939                let error = 'error: {
4940                    // This is expected to be the operative check for illegal write mask
4941                    // values (larger than 15), because WebGPU requires that it be validated
4942                    // on the device timeline.
4943                    if cs.write_mask.contains_unknown_bits() {
4944                        break 'error Some(ColorStateError::InvalidWriteMask(cs.write_mask));
4945                    } else if cs.write_mask != ColorWrites::NONE {
4946                        required_color_outputs |= 1 << i;
4947                    }
4948
4949                    let format_features = self.describe_format_features(cs.format)?;
4950                    if !format_features
4951                        .allowed_usages
4952                        .contains(wgt::TextureUsages::RENDER_ATTACHMENT)
4953                    {
4954                        break 'error Some(ColorStateError::FormatNotRenderable(cs.format));
4955                    }
4956                    if cs.blend.is_some() && !format_features.flags.contains(Tfff::BLENDABLE) {
4957                        break 'error Some(ColorStateError::FormatNotBlendable(cs.format));
4958                    }
4959                    if !hal::FormatAspects::from(cs.format).contains(hal::FormatAspects::COLOR) {
4960                        break 'error Some(ColorStateError::FormatNotColor(cs.format));
4961                    }
4962
4963                    if desc.multisample.count > 1
4964                        && !format_features
4965                            .flags
4966                            .sample_count_supported(desc.multisample.count)
4967                    {
4968                        break 'error Some(ColorStateError::InvalidSampleCount(
4969                            desc.multisample.count,
4970                            cs.format,
4971                            cs.format
4972                                .guaranteed_format_features(self.features)
4973                                .flags
4974                                .supported_sample_counts(),
4975                            self.adapter
4976                                .get_texture_format_features(cs.format)
4977                                .flags
4978                                .supported_sample_counts(),
4979                        ));
4980                    }
4981
4982                    if let Some(blend_mode) = cs.blend {
4983                        for component in [&blend_mode.color, &blend_mode.alpha] {
4984                            for factor in [component.src_factor, component.dst_factor] {
4985                                if factor.uses_second_blend_source() {
4986                                    self.require_features(wgt::Features::DUAL_SOURCE_BLENDING)?;
4987                                    if i == 0 {
4988                                        dual_source_blending = true;
4989                                    } else {
4990                                        break 'error Some(
4991                                            ColorStateError::BlendFactorOnUnsupportedTarget {
4992                                                factor,
4993                                                target: i as u32,
4994                                            },
4995                                        );
4996                                    }
4997                                }
4998
4999                                if [wgt::BlendOperation::Min, wgt::BlendOperation::Max]
5000                                    .contains(&component.operation)
5001                                    && factor != wgt::BlendFactor::One
5002                                {
5003                                    break 'error Some(ColorStateError::InvalidMinMaxBlendFactor {
5004                                        factor,
5005                                        target: i as u32,
5006                                    });
5007                                }
5008                            }
5009                        }
5010                    }
5011
5012                    break 'error None;
5013                };
5014                if let Some(e) = error {
5015                    return Err(pipeline::RenderError::ColorState(i as u8, e).into());
5016                }
5017            }
5018        }
5019
5020        if dual_source_blending && color_targets.len() > 1 {
5021            return Err(
5022                pipeline::RenderError::DualSourceBlendingWithMultipleColorTargets {
5023                    count: color_targets.len(),
5024                }
5025                .into(),
5026            );
5027        }
5028
5029        validation::validate_color_attachment_bytes_per_sample(
5030            color_targets.iter().flatten().map(|cs| cs.format),
5031            self.limits.max_color_attachment_bytes_per_sample,
5032        )
5033        .map_err(pipeline::RenderError::ColorAttachment)?;
5034
5035        if let Some(ds) = depth_stencil_state {
5036            // See <https://gpuweb.github.io/gpuweb/#abstract-opdef-validating-gpudepthstencilstate>.
5037            target_specified = true;
5038            let error = 'error: {
5039                if !ds.format.is_depth_stencil_format() {
5040                    // This error case is not redundant with the aspect check below when
5041                    // neither depth nor stencil is enabled at all.
5042                    break 'error Some(pipeline::DepthStencilStateError::FormatNotDepthOrStencil(
5043                        ds.format,
5044                    ));
5045                }
5046
5047                let format_features = self.describe_format_features(ds.format)?;
5048                if !format_features
5049                    .allowed_usages
5050                    .contains(wgt::TextureUsages::RENDER_ATTACHMENT)
5051                {
5052                    break 'error Some(pipeline::DepthStencilStateError::FormatNotRenderable(
5053                        ds.format,
5054                    ));
5055                }
5056
5057                let aspect = hal::FormatAspects::from(ds.format);
5058                if aspect.contains(hal::FormatAspects::DEPTH) {
5059                    has_depth_attachment = true;
5060                } else if ds.is_depth_enabled() {
5061                    break 'error Some(pipeline::DepthStencilStateError::FormatNotDepth(ds.format));
5062                }
5063                if has_depth_attachment {
5064                    let Some(depth_write_enabled) = ds.depth_write_enabled else {
5065                        break 'error Some(
5066                            pipeline::DepthStencilStateError::MissingDepthWriteEnabled(ds.format),
5067                        );
5068                    };
5069
5070                    let depth_compare_required = depth_write_enabled
5071                        || ds.stencil.front.depth_fail_op != wgt::StencilOperation::Keep
5072                        || ds.stencil.back.depth_fail_op != wgt::StencilOperation::Keep;
5073                    if depth_compare_required && ds.depth_compare.is_none() {
5074                        break 'error Some(pipeline::DepthStencilStateError::MissingDepthCompare(
5075                            ds.format,
5076                        ));
5077                    }
5078                }
5079
5080                if ds.stencil.is_enabled() && !aspect.contains(hal::FormatAspects::STENCIL) {
5081                    break 'error Some(pipeline::DepthStencilStateError::FormatNotStencil(
5082                        ds.format,
5083                    ));
5084                }
5085                if desc.multisample.count > 1
5086                    && !format_features
5087                        .flags
5088                        .sample_count_supported(desc.multisample.count)
5089                {
5090                    break 'error Some(pipeline::DepthStencilStateError::InvalidSampleCount(
5091                        desc.multisample.count,
5092                        ds.format,
5093                        ds.format
5094                            .guaranteed_format_features(self.features)
5095                            .flags
5096                            .supported_sample_counts(),
5097                        self.adapter
5098                            .get_texture_format_features(ds.format)
5099                            .flags
5100                            .supported_sample_counts(),
5101                    ));
5102                }
5103
5104                break 'error None;
5105            };
5106            if let Some(e) = error {
5107                return Err(pipeline::RenderError::DepthStencilState(e).into());
5108            }
5109
5110            if ds.bias.clamp != 0.0 {
5111                self.require_downlevel_flags(wgt::DownlevelFlags::DEPTH_BIAS_CLAMP)?;
5112            }
5113
5114            if (ds.bias.is_enabled() || ds.bias.clamp != 0.0)
5115                && !desc.primitive.topology.is_triangles()
5116            {
5117                return Err(pipeline::RenderError::DepthStencilState(
5118                    pipeline::DepthStencilStateError::DepthBiasWithIncompatibleTopology(
5119                        desc.primitive.topology,
5120                    ),
5121                )
5122                .into());
5123            }
5124        }
5125
5126        if !target_specified {
5127            return Err(pipeline::RenderError::NoTargetSpecified.into());
5128        }
5129
5130        let is_auto_layout = desc.layout.is_none();
5131
5132        // Get the pipeline layout from the desc if it is provided.
5133        let pipeline_layout = match desc.layout {
5134            Some(pipeline_layout) => {
5135                pipeline_layout.same_device(self)?;
5136                pipeline_layout.check_valid()?;
5137                Some(pipeline_layout)
5138            }
5139            None => None,
5140        };
5141
5142        let samples = {
5143            let sc = desc.multisample.count;
5144            if sc == 0 || sc > 32 || !sc.is_power_of_two() {
5145                return Err(pipeline::RenderError::InvalidSampleCount(sc).into());
5146            }
5147            sc
5148        };
5149
5150        // Validate and compile each programmable shader stage.
5151        let mut compiler =
5152            StageCompiler::new(self, pipeline_layout, io, Some(desc.primitive.topology));
5153        let vertex_stage;
5154        let task_stage;
5155        let mesh_stage;
5156
5157        match desc.vertex {
5158            pipeline::RenderPipelineVertexProcessor::Vertex(ref vertex) => {
5159                let stage = validation::ShaderStageForValidation::Vertex {
5160                    topology: desc.primitive.topology,
5161                    compare_function: desc.depth_stencil.as_ref().and_then(|d| d.depth_compare),
5162                };
5163                vertex_stage = Some(compiler.compile(&vertex.stage, stage)?);
5164                task_stage = None;
5165                mesh_stage = None;
5166            }
5167            pipeline::RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => {
5168                self.require_features(wgt::Features::EXPERIMENTAL_MESH_SHADER)?;
5169
5170                vertex_stage = None;
5171                task_stage = match task {
5172                    Some(task) => Some(
5173                        compiler
5174                            .compile(&task.stage, validation::ShaderStageForValidation::Task)?,
5175                    ),
5176                    None => None,
5177                };
5178                mesh_stage = Some(
5179                    compiler.compile(&mesh.stage, validation::ShaderStageForValidation::Mesh)?,
5180                );
5181            }
5182        }
5183
5184        let fragment_stage = match desc.fragment {
5185            Some(ref fragment) => {
5186                let stage = validation::ShaderStageForValidation::Fragment {
5187                    dual_source_blending,
5188                    has_depth_attachment,
5189                };
5190                Some(compiler.compile(&fragment.stage, stage)?)
5191            }
5192            None => None,
5193        };
5194
5195        // Extract the information the `StageCompiler` has accumulated about the
5196        // overall pipeline.
5197        let StageCompiler {
5198            resources,
5199            io,
5200            validated: validated_stages,
5201            ..
5202        } = compiler;
5203
5204        let mut active_color_outputs = 0u64;
5205        if validated_stages.contains(wgt::ShaderStages::FRAGMENT) {
5206            for (i, output) in io.varyings.iter() {
5207                active_color_outputs |= 1 << i;
5208                match color_targets.get(*i as usize) {
5209                    Some(Some(state)) => {
5210                        validation::check_color_attachment_compatibility(state, output.ty)
5211                            .map_err(|err| pipeline::RenderError::ColorState(*i as u8, err))?;
5212                    }
5213                    _ => {
5214                        log::debug!(
5215                            "The fragment stage {:?} output @location({}) values are ignored",
5216                            fragment_stage
5217                                .as_ref()
5218                                .map_or("", |stage| stage.entry_point.as_str()),
5219                            i
5220                        );
5221                    }
5222                }
5223            }
5224
5225            let missing_color_outputs = required_color_outputs & !active_color_outputs;
5226            if missing_color_outputs != 0 {
5227                return Err(pipeline::RenderError::ColorState(
5228                    missing_color_outputs.trailing_zeros() as u8,
5229                    ColorStateError::OutputNotPresent,
5230                )
5231                .into());
5232            }
5233        }
5234
5235        let pipeline_layout = match resources.layout {
5236            validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
5237            validation::BindingLayoutSource::Derived(entries) => {
5238                self.create_derived_pipeline_layout(entries, resources.immediates.size())?
5239            }
5240        };
5241
5242        let naga::valid::ImmediateUsage::Valid {
5243            slots: immediate_slots_required,
5244            size: _,
5245        } = resources.immediates
5246        else {
5247            unreachable!("Immediates exceeding maxImmediateSize should have been rejected");
5248        };
5249
5250        if let pipeline::RenderPipelineVertexProcessor::Vertex(ref vertex) = desc.vertex {
5251            let bind_groups_plus_vertex_buffers =
5252                u32::try_from(pipeline_layout.bind_group_layouts.len() + vertex.buffers.len())
5253                    .unwrap();
5254            if bind_groups_plus_vertex_buffers > self.limits.max_bind_groups_plus_vertex_buffers {
5255                return Err(pipeline::RenderError::TooManyBindGroupsPlusVertexBuffers {
5256                    given: bind_groups_plus_vertex_buffers,
5257                    limit: self.limits.max_bind_groups_plus_vertex_buffers,
5258                }
5259                .into());
5260            }
5261
5262            let given = pipeline_layout
5263                .buffers_and_acceleration_structures_in_vertex_stage
5264                .saturating_add(vertex.buffers.len() as u32);
5265            if !self
5266                .instance_flags
5267                .contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE)
5268            {
5269                let limit = self
5270                    .limits
5271                    .max_buffers_and_acceleration_structures_per_shader_stage;
5272                if given > limit {
5273                    return Err(
5274                        pipeline::RenderError::TooManyBuffersAndAccelerationStructuresInVertexStage {
5275                            given,
5276                            limit,
5277                        }
5278                        .into(),
5279                    );
5280                }
5281            }
5282        }
5283
5284        // Multiview is only supported if the feature is enabled
5285        if let Some(mv_mask) = desc.multiview_mask {
5286            self.require_features(wgt::Features::MULTIVIEW)?;
5287            if !(mv_mask.get() + 1).is_power_of_two() {
5288                self.require_features(wgt::Features::SELECTIVE_MULTIVIEW)?;
5289            }
5290        }
5291
5292        if !self
5293            .downlevel
5294            .flags
5295            .contains(wgt::DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED)
5296        {
5297            for (binding, size) in resources.minimum_binding_sizes.iter() {
5298                if size.get() % 16 != 0 {
5299                    return Err(pipeline::RenderError::UnalignedShader {
5300                        binding: binding.binding,
5301                        group: binding.group,
5302                        size: size.get(),
5303                    }
5304                    .into());
5305                }
5306            }
5307        }
5308
5309        let late_sized_buffer_groups = Device::make_late_sized_buffer_groups(
5310            &resources.minimum_binding_sizes,
5311            &pipeline_layout,
5312        );
5313
5314        let cache = match desc.cache {
5315            Some(cache) => {
5316                cache.check_is_valid()?;
5317                cache.same_device(self)?;
5318                Some(cache)
5319            }
5320            None => None,
5321        };
5322
5323        let is_mesh = mesh_stage.is_some();
5324        let has_task_shader = task_stage.is_some();
5325        let raw = {
5326            let pipeline_desc = hal::RenderPipelineDescriptor {
5327                label: desc.label.to_hal(self.instance_flags),
5328                layout: pipeline_layout.raw()?,
5329                vertex_processor: match vertex_stage {
5330                    Some(ref vertex_stage) => hal::VertexProcessor::Standard {
5331                        vertex_buffers: &hal_vertex_buffer_layouts,
5332                        vertex_stage: vertex_stage.to_hal(),
5333                    },
5334                    None => hal::VertexProcessor::Mesh {
5335                        task_stage: task_stage.as_ref().map(|stage| stage.to_hal()),
5336                        mesh_stage: mesh_stage.as_ref().unwrap().to_hal(),
5337                    },
5338                },
5339                primitive: desc.primitive,
5340                depth_stencil: desc.depth_stencil.clone(),
5341                multisample: desc.multisample,
5342                fragment_stage: fragment_stage.as_ref().map(|stage| stage.to_hal()),
5343                color_targets,
5344                multiview_mask: desc.multiview_mask,
5345                cache: cache.as_ref().map(|it| it.raw()).transpose()?,
5346            };
5347            unsafe { self.raw().create_render_pipeline(&pipeline_desc) }
5348                .map_err(|err| self.handle_hal_pipeline_error(err))?
5349        };
5350        drop((vertex_stage, task_stage, mesh_stage, fragment_stage));
5351
5352        let pass_context = RenderPassContext {
5353            attachments: AttachmentData {
5354                colors: color_targets
5355                    .iter()
5356                    .map(|state| state.as_ref().map(|s| s.format))
5357                    .collect(),
5358                resolves: ArrayVec::new(),
5359                depth_stencil: depth_stencil_state.as_ref().map(|state| state.format),
5360            },
5361            sample_count: samples,
5362            multiview_mask: desc.multiview_mask,
5363        };
5364
5365        let mut flags = pipeline::PipelineFlags::empty();
5366        for state in color_targets.iter().filter_map(|s| s.as_ref()) {
5367            if let Some(ref bs) = state.blend {
5368                if bs.color.uses_constant() | bs.alpha.uses_constant() {
5369                    flags |= pipeline::PipelineFlags::BLEND_CONSTANT;
5370                }
5371            }
5372        }
5373        if let Some(ds) = depth_stencil_state.as_ref() {
5374            if ds.stencil.is_enabled() && ds.stencil.needs_ref_value() {
5375                flags |= pipeline::PipelineFlags::STENCIL_REFERENCE;
5376            }
5377            if !ds.is_depth_read_only() {
5378                flags |= pipeline::PipelineFlags::WRITES_DEPTH;
5379            }
5380            if !ds.is_stencil_read_only(desc.primitive.cull_mode) {
5381                flags |= pipeline::PipelineFlags::WRITES_STENCIL;
5382            }
5383        }
5384        let shader_modules = {
5385            let mut shader_modules = ArrayVec::new();
5386            match desc.vertex {
5387                pipeline::RenderPipelineVertexProcessor::Vertex(vertex) => {
5388                    shader_modules.push(vertex.stage.module)
5389                }
5390                pipeline::RenderPipelineVertexProcessor::Mesh(task, mesh) => {
5391                    if let Some(task) = task {
5392                        shader_modules.push(task.stage.module);
5393                    }
5394                    shader_modules.push(mesh.stage.module);
5395                }
5396            }
5397            shader_modules.extend(desc.fragment.map(|f| f.stage.module));
5398            shader_modules
5399        };
5400
5401        let pipeline = pipeline::RenderPipeline {
5402            state: ResourceState::Valid(pipeline::RenderPipelineState {
5403                raw: ManuallyDrop::new(raw),
5404                layout: pipeline_layout.clone(),
5405            }),
5406            device: self.clone(),
5407            pass_context,
5408            _shader_modules: shader_modules,
5409            flags,
5410            topology: desc.primitive.topology,
5411            strip_index_format: desc.primitive.strip_index_format,
5412            vertex_steps,
5413            late_sized_buffer_groups,
5414            immediate_slots_required,
5415            label: desc.label.to_string(),
5416            tracking_data: TrackingData::new(self.tracker_indices.render_pipelines.clone()),
5417            is_mesh,
5418            has_task_shader,
5419        };
5420
5421        let pipeline = Arc::new(pipeline);
5422
5423        if is_auto_layout {
5424            for bgl in pipeline_layout.bind_group_layouts.iter() {
5425                let Some(bgl) = bgl else {
5426                    continue;
5427                };
5428
5429                // `bind_group_layouts` might contain duplicate entries, so we need to ignore the
5430                // result.
5431                let _ = bgl.exclusive_pipeline.set((&pipeline).into());
5432            }
5433        }
5434
5435        Ok(pipeline)
5436    }
5437
5438    /// Handle a [`hal::PipelineError`].
5439    ///
5440    /// Turn `error` into a [`CreatePipelineError`] and return it.
5441    ///
5442    /// Pass all [`hal::DeviceError`]s through [`Device::handle_hal_error`],
5443    /// so that `self` is marked as lost when appropriate.
5444    ///
5445    /// [`CreatePipelineError`]: pipeline::CreatePipelineError
5446    #[track_caller]
5447    pub(crate) fn handle_hal_pipeline_error(
5448        &self,
5449        error: hal::PipelineError,
5450    ) -> pipeline::CreatePipelineError {
5451        match error {
5452            hal::PipelineError::Device(error) => {
5453                pipeline::CreatePipelineError::Device(self.handle_hal_error(error))
5454            }
5455            other => pipeline::CreatePipelineError::from_hal_without_device_loss(other),
5456        }
5457    }
5458
5459    /// # Safety
5460    /// The `data` field on `desc` must have previously been returned from
5461    /// [`pipeline::PipelineCache::get_data`]
5462    pub unsafe fn create_pipeline_cache(
5463        self: &Arc<Self>,
5464        desc: &pipeline::PipelineCacheDescriptor,
5465    ) -> (
5466        Arc<pipeline::PipelineCache>,
5467        Option<pipeline::CreatePipelineCacheError>,
5468    ) {
5469        profiling::scope!("Device::create_pipeline_cache");
5470        let (cache, error) = match unsafe { self.create_pipeline_cache_inner(desc) } {
5471            Ok(cache) => (cache, None),
5472            Err(e) => (
5473                pipeline::PipelineCache::invalid(self.clone(), desc),
5474                Some(e),
5475            ),
5476        };
5477        #[cfg(feature = "trace")]
5478        if let Some(ref mut trace) = *self.trace.lock() {
5479            use trace::IntoTrace;
5480            trace.add(trace::Action::CreatePipelineCache {
5481                id: cache.to_trace(),
5482                desc: desc.clone(),
5483            });
5484        }
5485        api_log!("Device::create_pipeline_cache -> {:?}", Arc::as_ptr(&cache));
5486        (cache, error)
5487    }
5488
5489    /// # Safety
5490    /// The `data` field on `desc` must have previously been returned from
5491    /// [`pipeline::PipelineCache::get_data`]
5492    pub(crate) unsafe fn create_pipeline_cache_inner(
5493        self: &Arc<Self>,
5494        desc: &pipeline::PipelineCacheDescriptor,
5495    ) -> Result<Arc<pipeline::PipelineCache>, pipeline::CreatePipelineCacheError> {
5496        use crate::pipeline_cache;
5497
5498        self.check_is_valid()?;
5499
5500        self.require_features(wgt::Features::PIPELINE_CACHE)?;
5501        let data = if let Some((data, validation_key)) = desc
5502            .data
5503            .as_ref()
5504            .zip(self.raw().pipeline_cache_validation_key())
5505        {
5506            let data = pipeline_cache::validate_pipeline_cache(
5507                data,
5508                &self.adapter.raw.info,
5509                validation_key,
5510            );
5511            match data {
5512                Ok(data) => Some(data),
5513                Err(e) if e.was_avoidable() || !desc.fallback => return Err(e.into()),
5514                // If the error was unavoidable and we are asked to fallback, do so
5515                Err(_) => None,
5516            }
5517        } else {
5518            None
5519        };
5520        let cache_desc = hal::PipelineCacheDescriptor {
5521            data,
5522            label: desc.label.to_hal(self.instance_flags),
5523        };
5524        let raw = match unsafe { self.raw().create_pipeline_cache(&cache_desc) } {
5525            Ok(raw) => raw,
5526            Err(e) => match e {
5527                hal::PipelineCacheError::Device(e) => return Err(self.handle_hal_error(e).into()),
5528            },
5529        };
5530        let cache = pipeline::PipelineCache {
5531            device: self.clone(),
5532            label: desc.label.to_string(),
5533            // This would be none in the error condition, which we don't implement yet
5534            raw: ResourceState::Valid(raw),
5535        };
5536
5537        let cache = Arc::new(cache);
5538
5539        Ok(cache)
5540    }
5541
5542    fn get_texture_format_features(&self, format: TextureFormat) -> wgt::TextureFormatFeatures {
5543        // Variant of adapter.get_texture_format_features that takes device features into account
5544        use wgt::TextureFormatFeatureFlags as tfsc;
5545        let mut format_features = self.adapter.get_texture_format_features(format);
5546        if (format == TextureFormat::R32Float
5547            || format == TextureFormat::Rg32Float
5548            || format == TextureFormat::Rgba32Float)
5549            && !self.features.contains(wgt::Features::FLOAT32_FILTERABLE)
5550        {
5551            format_features.flags.set(tfsc::FILTERABLE, false);
5552        }
5553        format_features
5554    }
5555
5556    pub(crate) fn describe_format_features(
5557        &self,
5558        format: TextureFormat,
5559    ) -> Result<wgt::TextureFormatFeatures, MissingFeatures> {
5560        self.require_features(format.required_features())?;
5561
5562        let using_device_features = self
5563            .features
5564            .contains(wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES);
5565        // If we're running downlevel, we need to manually ask the backend what
5566        // we can use as we can't trust WebGPU.
5567        let downlevel = !self
5568            .downlevel
5569            .flags
5570            .contains(wgt::DownlevelFlags::WEBGPU_TEXTURE_FORMAT_SUPPORT);
5571
5572        if using_device_features || downlevel {
5573            Ok(self.get_texture_format_features(format))
5574        } else {
5575            Ok(format.guaranteed_format_features(self.features))
5576        }
5577    }
5578
5579    #[cfg(feature = "replay")]
5580    pub(crate) fn wait_for_submit(
5581        &self,
5582        submission_index: crate::SubmissionIndex,
5583    ) -> Result<(), DeviceError> {
5584        let last_done_index = unsafe { self.raw().get_fence_value(self.fence.as_ref()) }
5585            .map_err(|e| self.handle_hal_error(e))?;
5586        if last_done_index < submission_index {
5587            unsafe { self.raw().wait(self.fence.as_ref(), submission_index, None) }
5588                .map_err(|e| self.handle_hal_error(e))?;
5589            if let Some(queue) = self.get_queue() {
5590                let closures = queue.lock_life().triage_submissions(submission_index);
5591                assert!(
5592                    closures.is_empty(),
5593                    "wait_for_submit is not expected to work with closures"
5594                );
5595            }
5596        }
5597        Ok(())
5598    }
5599
5600    pub fn create_query_set(
5601        self: &Arc<Self>,
5602        desc: &resource::QuerySetDescriptor,
5603    ) -> Arc<QuerySet> {
5604        profiling::scope!("Device::create_query_set");
5605        let query_set = self.create_query_set_inner(desc).unwrap_or_else(|err| {
5606            self.handle_error(err, desc.label.as_deref(), "Device::create_query_set");
5607            QuerySet::invalid(Arc::clone(self), desc)
5608        });
5609        #[cfg(feature = "trace")]
5610        if let Some(ref mut trace) = *self.trace.lock() {
5611            use trace::IntoTrace;
5612            trace.add(trace::Action::CreateQuerySet {
5613                id: query_set.to_trace(),
5614                desc: desc.clone(),
5615            });
5616        }
5617        api_log!("Device::create_query_set -> {:?}", Arc::as_ptr(&query_set));
5618        query_set
5619    }
5620
5621    pub(crate) fn create_query_set_inner(
5622        self: &Arc<Self>,
5623        desc: &resource::QuerySetDescriptor,
5624    ) -> Result<Arc<QuerySet>, resource::CreateQuerySetError> {
5625        use resource::CreateQuerySetError as Error;
5626
5627        self.check_is_valid()?;
5628
5629        match desc.ty {
5630            wgt::QueryType::Occlusion => {}
5631            wgt::QueryType::Timestamp => {
5632                self.require_features(wgt::Features::TIMESTAMP_QUERY)?;
5633            }
5634            wgt::QueryType::PipelineStatistics(..) => {
5635                self.require_features(wgt::Features::PIPELINE_STATISTICS_QUERY)?;
5636            }
5637        }
5638
5639        if desc.count == 0 {
5640            return Err(Error::ZeroCount);
5641        }
5642
5643        if desc.count > wgt::QUERY_SET_MAX_QUERIES {
5644            return Err(Error::TooManyQueries {
5645                count: desc.count,
5646                maximum: wgt::QUERY_SET_MAX_QUERIES,
5647            });
5648        }
5649
5650        let hal_desc = desc.map_label(|label| label.to_hal(self.instance_flags));
5651
5652        let raw = unsafe { self.raw().create_query_set(&hal_desc) }
5653            .map_err(|e| self.handle_hal_error_with_nonfatal_oom(e))?;
5654
5655        let query_set = QuerySet {
5656            state: ResourceState::Valid(QuerySetState {
5657                raw: Snatchable::new(raw),
5658            }),
5659            device: self.clone(),
5660            tracking_data: TrackingData::new(self.tracker_indices.query_sets.clone()),
5661            desc: desc.map_label(|l| l.to_string()),
5662            initialized_slots: Mutex::new(
5663                rank::QUERY_SET_INITIALIZED_SLOTS,
5664                bit_vec::BitVec::from_elem(desc.count as usize, false),
5665            ),
5666        };
5667
5668        let query_set = Arc::new(query_set);
5669
5670        Ok(query_set)
5671    }
5672
5673    #[track_caller]
5674    pub(crate) fn lose(&self, message: &str) {
5675        // Follow the steps at https://gpuweb.github.io/gpuweb/#lose-the-device.
5676
5677        // Mark the device explicitly as invalid. This is checked in various
5678        // places to prevent new work from being submitted.
5679        let was_valid = self.valid.swap(false, Ordering::AcqRel);
5680
5681        if was_valid {
5682            // `message` rarely identifies the cause on its own ("Device is
5683            // lost"), so say which operation failed and on which driver.
5684            // This is only logged: the message below may reach web content.
5685            let info = &self.adapter.raw.info;
5686            log::error!(
5687                "{} lost at {}: {message}. Adapter: {:?} ({:?}, vendor {:#06x}, device {:#06x}), \
5688                 driver: {:?} {:?}",
5689                self.error_ident(),
5690                core::panic::Location::caller(),
5691                info.name,
5692                info.backend,
5693                info.vendor,
5694                info.device,
5695                info.driver,
5696                info.driver_info,
5697            );
5698        }
5699
5700        // 1) Resolve the GPUDevice device.lost promise.
5701        if let Some(device_lost_closure) = self.device_lost_closure.lock().take() {
5702            device_lost_closure(DeviceLostReason::Unknown, message.to_string());
5703        }
5704
5705        // 2) Complete any outstanding mapAsync() steps.
5706        // 3) Complete any outstanding onSubmittedWorkDone() steps.
5707
5708        // These parts are passively accomplished by setting valid to false,
5709        // since that will prevent any new work from being added to the queues.
5710        // Future calls to poll_devices will continue to check the work queues
5711        // until they are cleared, and then drop the device.
5712    }
5713
5714    fn release_gpu_resources(&self) {
5715        // This is called when the device is lost, which makes every associated
5716        // resource invalid and unusable. This is an opportunity to release all of
5717        // the underlying gpu resources, even though the objects remain visible to
5718        // the user agent. We purge this memory naturally when resources have been
5719        // moved into the appropriate buckets, so this function just needs to
5720        // initiate movement into those buckets, and it can do that by calling
5721        // "destroy" on all the resources we know about.
5722
5723        let trackers = self.trackers.lock();
5724        let buffers = trackers
5725            .buffers
5726            .used_resources()
5727            .flat_map(Weak::upgrade)
5728            .collect::<Vec<_>>();
5729        let textures = trackers
5730            .textures
5731            .used_resources()
5732            .flat_map(Weak::upgrade)
5733            .collect::<Vec<_>>();
5734        drop(trackers);
5735
5736        for buffer in buffers {
5737            buffer.destroy();
5738        }
5739        for texture in textures {
5740            texture.destroy();
5741        }
5742    }
5743
5744    pub(crate) fn new_usage_scope(&self) -> UsageScope<'_> {
5745        UsageScope::new_pooled(
5746            &self.usage_scopes,
5747            &self.tracker_indices,
5748            self.ordered_buffer_usages,
5749            self.ordered_texture_usages,
5750        )
5751    }
5752
5753    /// `device_lost_closure` might never be called.
5754    pub fn set_device_lost_closure(&self, device_lost_closure: DeviceLostClosure) {
5755        self.device_lost_closure.lock().replace(device_lost_closure);
5756    }
5757
5758    pub fn destroy(self: &Arc<Self>) {
5759        api_log!("Device::destroy {:?}", Arc::as_ptr(self));
5760
5761        // Follow the steps at
5762        // https://gpuweb.github.io/gpuweb/#dom-gpudevice-destroy.
5763        // It's legal to call destroy multiple times, but if the device
5764        // is already invalid, there's nothing more to do. There's also
5765        // no need to return an error.
5766        if !self.is_valid() {
5767            return;
5768        }
5769
5770        // The last part of destroy is to lose the device. The spec says
5771        // delay that until all "currently-enqueued operations on any
5772        // queue on this device are completed." This is accomplished by
5773        // setting valid to false, and then relying upon maintain to
5774        // check for empty queues and a DeviceLostClosure. At that time,
5775        // the DeviceLostClosure will be called with "destroyed" as the
5776        // reason.
5777        self.valid.store(false, Ordering::Release);
5778    }
5779
5780    pub fn get_internal_counters(&self) -> wgt::InternalCounters {
5781        wgt::InternalCounters {
5782            hal: self.get_hal_counters(),
5783            core: wgt::CoreCounters {},
5784        }
5785    }
5786
5787    pub fn get_hal_counters(&self) -> wgt::HalCounters {
5788        self.raw().get_internal_counters()
5789    }
5790
5791    pub fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
5792        self.raw().generate_allocator_report()
5793    }
5794}
5795
5796crate::impl_resource_type!(Device);
5797crate::impl_labeled!(Device);
5798crate::impl_storage_item!(Device);