Skip to main content

wgpu/backend/
wgpu_core.rs

1use alloc::{
2    borrow::Cow::{self, Borrowed},
3    boxed::Box,
4    format,
5    string::{String, ToString as _},
6    sync::Arc,
7    vec,
8    vec::Vec,
9};
10use core::{
11    error::Error,
12    fmt,
13    future::ready,
14    ops::{Deref, Range},
15    pin::Pin,
16    ptr::NonNull,
17    slice,
18};
19use hashbrown::HashMap;
20
21use arrayvec::ArrayVec;
22use smallvec::SmallVec;
23use wgc::{
24    command::bundle_ffi::*, error::ContextErrorSource, pipeline::CreateShaderModuleError,
25    resource::BlasPrepareCompactResult,
26};
27use wgt::{
28    error::{ErrorType, WebGpuError},
29    WasmNotSendSync,
30};
31
32use crate::{
33    api,
34    dispatch::{self, BlasCompactCallback, BufferMappedRangeInterface},
35    BindingResource, Blas, BufferBinding, BufferDescriptor, CompilationInfo, CompilationMessage,
36    CompilationMessageType, ErrorSource, Features, Label, LoadOp, MapMode, Operations,
37    ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, Tlas, WriteOnly,
38};
39use crate::{dispatch::DispatchAdapter, util::Mutex};
40
41mod thread_id;
42
43#[derive(Clone)]
44pub struct ContextWgpuCore(Arc<wgc::global::Global>);
45
46impl Drop for ContextWgpuCore {
47    fn drop(&mut self) {
48        //nothing
49    }
50}
51
52impl fmt::Debug for ContextWgpuCore {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        f.debug_struct("ContextWgpuCore")
55            .field("type", &"Native")
56            .finish()
57    }
58}
59
60impl ContextWgpuCore {
61    pub unsafe fn from_hal_instance<A: hal::Api>(hal_instance: A::Instance) -> Self {
62        Self(unsafe {
63            Arc::new(wgc::global::Global::from_hal_instance::<A>(
64                "wgpu",
65                hal_instance,
66            ))
67        })
68    }
69
70    /// # Safety
71    ///
72    /// - The raw instance handle returned must not be manually destroyed.
73    pub unsafe fn instance_as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
74        unsafe { self.0.instance_as_hal::<A>() }
75    }
76
77    pub unsafe fn from_core_instance(core_instance: wgc::instance::Instance) -> Self {
78        Self(unsafe { Arc::new(wgc::global::Global::from_instance(core_instance)) })
79    }
80
81    #[cfg(wgpu_core)]
82    pub fn enumerate_adapters(&self, backends: wgt::Backends) -> Vec<wgc::id::AdapterId> {
83        self.0.enumerate_adapters(backends)
84    }
85
86    pub unsafe fn create_adapter_from_hal<A: hal::Api>(
87        &self,
88        hal_adapter: hal::ExposedAdapter<A>,
89    ) -> wgc::id::AdapterId {
90        unsafe { self.0.create_adapter_from_hal(hal_adapter.into(), None) }
91    }
92
93    pub unsafe fn adapter_as_hal<A: hal::Api>(
94        &self,
95        adapter: &CoreAdapter,
96    ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
97        unsafe { self.0.adapter_as_hal::<A>(adapter.id) }
98    }
99
100    pub unsafe fn buffer_as_hal<A: hal::Api>(
101        &self,
102        buffer: &CoreBuffer,
103    ) -> Option<impl Deref<Target = A::Buffer>> {
104        unsafe { self.0.buffer_as_hal::<A>(buffer.id) }
105    }
106
107    pub unsafe fn create_device_from_hal<A: hal::Api>(
108        &self,
109        adapter: &CoreAdapter,
110        hal_device: hal::OpenDevice<A>,
111        desc: &crate::DeviceDescriptor<'_>,
112    ) -> Result<(CoreDevice, CoreQueue), crate::RequestDeviceError> {
113        let (device_id, queue_id) = unsafe {
114            self.0.create_device_from_hal(
115                adapter.id,
116                hal_device.into(),
117                &desc.map_label(|l| l.map(Borrowed)),
118                None,
119                None,
120            )
121        }?;
122        let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
123        let device = CoreDevice {
124            context: self.clone(),
125            id: device_id,
126            error_sink: error_sink.clone(),
127            features: desc.required_features,
128        };
129        let queue = CoreQueue {
130            context: self.clone(),
131            id: queue_id,
132            error_sink,
133        };
134        Ok((device, queue))
135    }
136
137    pub unsafe fn create_texture_from_hal<A: hal::Api>(
138        &self,
139        hal_texture: A::Texture,
140        device: &CoreDevice,
141        desc: &TextureDescriptor<'_>,
142    ) -> CoreTexture {
143        let descriptor = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
144        let (id, error) = unsafe {
145            self.0
146                .create_texture_from_hal(Box::new(hal_texture), device.id, &descriptor, None)
147        };
148        if let Some(cause) = error {
149            self.handle_error(
150                &device.error_sink,
151                cause,
152                desc.label,
153                "Device::create_texture_from_hal",
154            );
155        }
156        CoreTexture {
157            context: self.clone(),
158            id,
159            error_sink: Arc::clone(&device.error_sink),
160        }
161    }
162
163    /// # Safety
164    ///
165    /// - `hal_buffer` must be created from `device`.
166    /// - `hal_buffer` must be created respecting `desc`
167    /// - `hal_buffer` must be initialized
168    /// - `hal_buffer` must not have zero size.
169    pub unsafe fn create_buffer_from_hal<A: hal::Api>(
170        &self,
171        hal_buffer: A::Buffer,
172        device: &CoreDevice,
173        desc: &BufferDescriptor<'_>,
174    ) -> CoreBuffer {
175        let (id, error) = unsafe {
176            self.0.create_buffer_from_hal::<A>(
177                hal_buffer,
178                device.id,
179                &desc.map_label(|l| l.map(Borrowed)),
180                None,
181            )
182        };
183        if let Some(cause) = error {
184            self.handle_error(
185                &device.error_sink,
186                cause,
187                desc.label,
188                "Device::create_buffer_from_hal",
189            );
190        }
191        CoreBuffer {
192            context: self.clone(),
193            id,
194            error_sink: Arc::clone(&device.error_sink),
195        }
196    }
197
198    pub unsafe fn device_as_hal<A: hal::Api>(
199        &self,
200        device: &CoreDevice,
201    ) -> Option<impl Deref<Target = A::Device>> {
202        unsafe { self.0.device_as_hal::<A>(device.id) }
203    }
204
205    pub unsafe fn surface_as_hal<A: hal::Api>(
206        &self,
207        surface: &CoreSurface,
208    ) -> Option<impl Deref<Target = A::Surface>> {
209        unsafe { self.0.surface_as_hal::<A>(surface.id) }
210    }
211
212    pub unsafe fn texture_as_hal<A: hal::Api>(
213        &self,
214        texture: &CoreTexture,
215    ) -> Option<impl Deref<Target = A::Texture>> {
216        unsafe { self.0.texture_as_hal::<A>(texture.id) }
217    }
218
219    pub unsafe fn texture_view_as_hal<A: hal::Api>(
220        &self,
221        texture_view: &CoreTextureView,
222    ) -> Option<impl Deref<Target = A::TextureView>> {
223        unsafe { self.0.texture_view_as_hal::<A>(texture_view.id) }
224    }
225
226    /// This method will start the wgpu_core level command recording.
227    pub unsafe fn command_encoder_as_hal_mut<
228        A: hal::Api,
229        F: FnOnce(Option<&mut A::CommandEncoder>) -> R,
230        R,
231    >(
232        &self,
233        command_encoder: &CoreCommandEncoder,
234        hal_command_encoder_callback: F,
235    ) -> R {
236        unsafe {
237            self.0.command_encoder_as_hal_mut::<A, F, R>(
238                command_encoder.id,
239                hal_command_encoder_callback,
240            )
241        }
242    }
243
244    pub unsafe fn blas_as_hal<A: hal::Api>(
245        &self,
246        blas: &CoreBlas,
247    ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
248        unsafe { self.0.blas_as_hal::<A>(blas.id) }
249    }
250
251    pub unsafe fn tlas_as_hal<A: hal::Api>(
252        &self,
253        tlas: &CoreTlas,
254    ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
255        unsafe { self.0.tlas_as_hal::<A>(tlas.id) }
256    }
257
258    pub fn generate_report(&self) -> wgc::global::GlobalReport {
259        self.0.generate_report()
260    }
261
262    #[cold]
263    #[track_caller]
264    #[inline(never)]
265    fn handle_error_inner(
266        &self,
267        sink_mutex: &Mutex<ErrorSinkRaw>,
268        error_type: ErrorType,
269        source: ContextErrorSource,
270        label: Label<'_>,
271        fn_ident: &'static str,
272    ) {
273        let source: ErrorSource = Box::new(wgc::error::ContextError {
274            fn_ident,
275            source,
276            label: label.unwrap_or_default().to_string(),
277        });
278        let final_error_handling = {
279            let mut sink = sink_mutex.lock();
280            let description = || self.format_error(&*source);
281            let error = match error_type {
282                ErrorType::Internal => {
283                    let description = description();
284                    crate::Error::Internal {
285                        source,
286                        description,
287                    }
288                }
289                ErrorType::OutOfMemory => crate::Error::OutOfMemory { source },
290                ErrorType::Validation => {
291                    let description = description();
292                    crate::Error::Validation {
293                        source,
294                        description,
295                    }
296                }
297                ErrorType::DeviceLost => return, // will be surfaced via callback
298            };
299            sink.handle_error_or_return_handler(error)
300        };
301
302        if let Some(f) = final_error_handling {
303            // If the user has provided their own `uncaptured_handler` callback, invoke it now,
304            // having released our lock on `sink_mutex`. See the comments on
305            // `handle_error_or_return_handler` for details.
306            f();
307        }
308    }
309
310    #[inline]
311    #[track_caller]
312    fn handle_error(
313        &self,
314        sink_mutex: &Mutex<ErrorSinkRaw>,
315        source: impl WebGpuError + WasmNotSendSync + 'static,
316        label: Label<'_>,
317        fn_ident: &'static str,
318    ) {
319        let error_type = source.webgpu_error_type();
320        self.handle_error_inner(sink_mutex, error_type, Box::new(source), label, fn_ident)
321    }
322
323    #[inline]
324    #[track_caller]
325    fn handle_error_nolabel(
326        &self,
327        sink_mutex: &Mutex<ErrorSinkRaw>,
328        source: impl WebGpuError + WasmNotSendSync + 'static,
329        fn_ident: &'static str,
330    ) {
331        let error_type = source.webgpu_error_type();
332        self.handle_error_inner(sink_mutex, error_type, Box::new(source), None, fn_ident)
333    }
334
335    #[track_caller]
336    #[cold]
337    fn handle_error_fatal(
338        &self,
339        cause: impl Error + WasmNotSendSync + 'static,
340        operation: &'static str,
341    ) -> ! {
342        panic!("Error in {operation}: {f}", f = self.format_error(&cause));
343    }
344
345    #[inline(never)]
346    fn format_error(&self, err: &(dyn Error + 'static)) -> String {
347        let mut output = String::new();
348        let mut level = 1;
349
350        fn print_tree(output: &mut String, level: &mut usize, e: &(dyn Error + 'static)) {
351            let mut print = |e: &(dyn Error + 'static)| {
352                use core::fmt::Write;
353                writeln!(output, "{}{}", " ".repeat(*level * 2), e).unwrap();
354
355                if let Some(e) = e.source() {
356                    *level += 1;
357                    print_tree(output, level, e);
358                    *level -= 1;
359                }
360            };
361            if let Some(multi) = e.downcast_ref::<wgc::error::MultiError>() {
362                for e in multi.errors() {
363                    print(e);
364                }
365            } else {
366                print(e);
367            }
368        }
369
370        print_tree(&mut output, &mut level, err);
371
372        format!("Validation Error\n\nCaused by:\n{output}")
373    }
374
375    pub unsafe fn queue_as_hal<A: hal::Api>(
376        &self,
377        queue: &CoreQueue,
378    ) -> Option<impl Deref<Target = A::Queue> + WasmNotSendSync> {
379        unsafe { self.0.queue_as_hal::<A>(queue.id) }
380    }
381}
382
383fn map_buffer_copy_view(
384    view: crate::TexelCopyBufferInfo<'_>,
385) -> wgt::TexelCopyBufferInfo<wgc::id::BufferId> {
386    wgt::TexelCopyBufferInfo {
387        buffer: view.buffer.inner.as_core().id,
388        layout: view.layout,
389    }
390}
391
392fn map_texture_copy_view(
393    view: crate::TexelCopyTextureInfo<'_>,
394) -> wgt::TexelCopyTextureInfo<wgc::id::TextureId> {
395    wgt::TexelCopyTextureInfo {
396        texture: view.texture.inner.as_core().id,
397        mip_level: view.mip_level,
398        origin: view.origin,
399        aspect: view.aspect,
400    }
401}
402
403#[cfg_attr(not(webgl), expect(unused))]
404fn map_texture_tagged_copy_view(
405    view: crate::CopyExternalImageDestInfo<&api::Texture>,
406) -> wgt::CopyExternalImageDestInfo<wgc::id::TextureId> {
407    wgt::CopyExternalImageDestInfo {
408        texture: view.texture.inner.as_core().id,
409        mip_level: view.mip_level,
410        origin: view.origin,
411        aspect: view.aspect,
412        color_space: view.color_space,
413        premultiplied_alpha: view.premultiplied_alpha,
414    }
415}
416
417fn map_load_op<V: Copy>(load: &LoadOp<V>) -> LoadOp<Option<V>> {
418    match *load {
419        LoadOp::Clear(clear_value) => LoadOp::Clear(Some(clear_value)),
420        LoadOp::DontCare(token) => LoadOp::DontCare(token),
421        LoadOp::Load => LoadOp::Load,
422    }
423}
424
425fn map_pass_channel<V: Copy>(ops: Option<&Operations<V>>) -> wgc::command::PassChannel<Option<V>> {
426    match ops {
427        Some(&Operations { load, store }) => wgc::command::PassChannel {
428            load_op: Some(map_load_op(&load)),
429            store_op: Some(store),
430            read_only: false,
431        },
432        None => wgc::command::PassChannel {
433            load_op: None,
434            store_op: None,
435            read_only: true,
436        },
437    }
438}
439
440#[derive(Debug)]
441pub struct CoreSurface {
442    pub(crate) context: ContextWgpuCore,
443    id: wgc::id::SurfaceId,
444    /// Configured device is needed to know which backend
445    /// code to execute when acquiring a new frame.
446    configured_device: Mutex<Option<wgc::id::DeviceId>>,
447    /// The error sink with which to report errors.
448    /// `None` if the surface has not been configured.
449    error_sink: Mutex<Option<ErrorSink>>,
450}
451
452#[derive(Debug)]
453pub struct CoreAdapter {
454    pub(crate) context: ContextWgpuCore,
455    pub(crate) id: wgc::id::AdapterId,
456}
457
458#[derive(Debug)]
459pub struct CoreDevice {
460    pub(crate) context: ContextWgpuCore,
461    id: wgc::id::DeviceId,
462    error_sink: ErrorSink,
463    features: Features,
464}
465
466#[derive(Debug)]
467pub struct CoreBuffer {
468    pub(crate) context: ContextWgpuCore,
469    id: wgc::id::BufferId,
470    error_sink: ErrorSink,
471}
472
473#[derive(Debug)]
474pub struct CoreShaderModule {
475    pub(crate) context: ContextWgpuCore,
476    id: wgc::id::ShaderModuleId,
477    compilation_info: CompilationInfo,
478}
479
480#[derive(Debug)]
481pub struct CoreBindGroupLayout {
482    pub(crate) context: ContextWgpuCore,
483    id: wgc::id::BindGroupLayoutId,
484}
485
486#[derive(Debug)]
487pub struct CoreBindGroup {
488    pub(crate) context: ContextWgpuCore,
489    id: wgc::id::BindGroupId,
490}
491
492#[derive(Debug)]
493pub struct CoreTexture {
494    pub(crate) context: ContextWgpuCore,
495    id: wgc::id::TextureId,
496    error_sink: ErrorSink,
497}
498
499#[derive(Debug)]
500pub struct CoreTextureView {
501    pub(crate) context: ContextWgpuCore,
502    id: wgc::id::TextureViewId,
503}
504
505#[derive(Debug)]
506pub struct CoreExternalTexture {
507    pub(crate) context: ContextWgpuCore,
508    id: wgc::id::ExternalTextureId,
509}
510
511#[derive(Debug)]
512pub struct CoreSampler {
513    pub(crate) context: ContextWgpuCore,
514    id: wgc::id::SamplerId,
515}
516
517#[derive(Debug)]
518pub struct CoreQuerySet {
519    pub(crate) context: ContextWgpuCore,
520    id: wgc::id::QuerySetId,
521}
522
523#[derive(Debug)]
524pub struct CorePipelineLayout {
525    pub(crate) context: ContextWgpuCore,
526    id: wgc::id::PipelineLayoutId,
527}
528
529#[derive(Debug)]
530pub struct CorePipelineCache {
531    pub(crate) context: ContextWgpuCore,
532    id: wgc::id::PipelineCacheId,
533}
534
535#[derive(Debug)]
536pub struct CoreCommandBuffer {
537    pub(crate) context: ContextWgpuCore,
538    id: wgc::id::CommandBufferId,
539}
540
541#[derive(Debug)]
542pub struct CoreRenderBundleEncoder {
543    pub(crate) context: ContextWgpuCore,
544    encoder: wgc::command::RenderBundleEncoder,
545    id: crate::cmp::Identifier,
546}
547
548#[derive(Debug)]
549pub struct CoreRenderBundle {
550    context: ContextWgpuCore,
551    id: wgc::id::RenderBundleId,
552}
553
554#[derive(Debug)]
555pub struct CoreQueue {
556    pub(crate) context: ContextWgpuCore,
557    id: wgc::id::QueueId,
558    error_sink: ErrorSink,
559}
560
561#[derive(Debug)]
562pub struct CoreComputePipeline {
563    pub(crate) context: ContextWgpuCore,
564    id: wgc::id::ComputePipelineId,
565    error_sink: ErrorSink,
566}
567
568#[derive(Debug)]
569pub struct CoreRenderPipeline {
570    pub(crate) context: ContextWgpuCore,
571    id: wgc::id::RenderPipelineId,
572    error_sink: ErrorSink,
573}
574
575#[derive(Debug)]
576pub struct CoreComputePass {
577    pub(crate) context: ContextWgpuCore,
578    pass: wgc::command::ComputePass,
579    error_sink: ErrorSink,
580    id: crate::cmp::Identifier,
581}
582
583#[derive(Debug)]
584pub struct CoreRenderPass {
585    pub(crate) context: ContextWgpuCore,
586    pass: wgc::command::RenderPass,
587    error_sink: ErrorSink,
588    id: crate::cmp::Identifier,
589}
590
591#[derive(Debug)]
592pub struct CoreCommandEncoder {
593    pub(crate) context: ContextWgpuCore,
594    id: wgc::id::CommandEncoderId,
595    error_sink: ErrorSink,
596}
597
598#[derive(Debug)]
599pub struct CoreBlas {
600    pub(crate) context: ContextWgpuCore,
601    id: wgc::id::BlasId,
602    error_sink: ErrorSink,
603}
604
605#[derive(Debug)]
606pub struct CoreTlas {
607    pub(crate) context: ContextWgpuCore,
608    id: wgc::id::TlasId,
609    // error_sink: ErrorSink,
610}
611
612#[derive(Debug)]
613pub struct CoreSurfaceOutputDetail {
614    context: ContextWgpuCore,
615    surface_id: wgc::id::SurfaceId,
616    error_sink: ErrorSink,
617}
618
619type ErrorSink = Arc<Mutex<ErrorSinkRaw>>;
620
621struct ErrorScope {
622    error: Option<crate::Error>,
623    filter: crate::ErrorFilter,
624}
625
626struct ErrorSinkRaw {
627    scopes: HashMap<thread_id::ThreadId, Vec<ErrorScope>>,
628    uncaptured_handler: Option<Arc<dyn crate::UncapturedErrorHandler>>,
629}
630
631impl ErrorSinkRaw {
632    fn new() -> ErrorSinkRaw {
633        ErrorSinkRaw {
634            scopes: HashMap::new(),
635            uncaptured_handler: None,
636        }
637    }
638
639    /// Deliver the error to
640    ///
641    /// * the innermost error scope, if any, or
642    /// * the uncaptured error handler, if there is one, or
643    /// * [`default_error_handler()`].
644    ///
645    /// If a closure is returned, the caller should call it immediately after dropping the
646    /// [`ErrorSink`] mutex guard. This makes sure that the user callback is not called with
647    /// a wgpu mutex held.
648    #[track_caller]
649    #[must_use]
650    fn handle_error_or_return_handler(&mut self, err: crate::Error) -> Option<impl FnOnce()> {
651        let filter = match err {
652            crate::Error::OutOfMemory { .. } => crate::ErrorFilter::OutOfMemory,
653            crate::Error::Validation { .. } => crate::ErrorFilter::Validation,
654            crate::Error::Internal { .. } => crate::ErrorFilter::Internal,
655        };
656        let thread_id = thread_id::ThreadId::current();
657        let scopes = self.scopes.entry(thread_id).or_default();
658        match scopes.iter_mut().rev().find(|scope| scope.filter == filter) {
659            Some(scope) => {
660                if scope.error.is_none() {
661                    scope.error = Some(err);
662                }
663                None
664            }
665            None => {
666                if let Some(custom_handler) = &self.uncaptured_handler {
667                    let custom_handler = Arc::clone(custom_handler);
668                    Some(move || (custom_handler)(err))
669                } else {
670                    // direct call preserves #[track_caller] where dyn can't
671                    default_error_handler(err)
672                }
673            }
674        }
675    }
676}
677
678impl fmt::Debug for ErrorSinkRaw {
679    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
680        write!(f, "ErrorSink")
681    }
682}
683
684#[track_caller]
685fn default_error_handler(err: crate::Error) -> ! {
686    log::error!("Handling wgpu errors as fatal by default");
687    panic!("wgpu error: {err}\n");
688}
689
690impl From<CreateShaderModuleError> for CompilationInfo {
691    fn from(value: CreateShaderModuleError) -> Self {
692        match value {
693            #[cfg(feature = "wgsl")]
694            CreateShaderModuleError::Parsing(v) => v.into(),
695            #[cfg(feature = "glsl")]
696            CreateShaderModuleError::ParsingGlsl(v) => v.into(),
697            #[cfg(feature = "spirv")]
698            CreateShaderModuleError::ParsingSpirV(v) => v.into(),
699            CreateShaderModuleError::Validation(v) => v.into(),
700            // Device errors are reported through the error sink, and are not compilation errors.
701            // Same goes for native shader module generation errors.
702            CreateShaderModuleError::Device(_) | CreateShaderModuleError::Generation => {
703                CompilationInfo {
704                    messages: Vec::new(),
705                }
706            }
707            // Everything else is an error message without location information.
708            _ => CompilationInfo {
709                messages: vec![CompilationMessage {
710                    message: value.to_string(),
711                    message_type: CompilationMessageType::Error,
712                    location: None,
713                }],
714            },
715        }
716    }
717}
718
719#[derive(Debug)]
720pub struct CoreQueueWriteBuffer {
721    buffer_id: wgc::id::StagingBufferId,
722    mapping: CoreBufferMappedRange,
723}
724
725#[derive(Debug)]
726pub struct CoreBufferMappedRange {
727    ptr: NonNull<u8>,
728    size: usize,
729}
730
731#[cfg(send_sync)]
732unsafe impl Send for CoreBufferMappedRange {}
733#[cfg(send_sync)]
734unsafe impl Sync for CoreBufferMappedRange {}
735
736impl Drop for CoreBufferMappedRange {
737    fn drop(&mut self) {
738        // Intentionally left blank so that `BufferMappedRange` still
739        // implements `Drop`, to match the web backend
740    }
741}
742
743crate::cmp::impl_eq_ord_hash_arc_address!(ContextWgpuCore => .0);
744crate::cmp::impl_eq_ord_hash_proxy!(CoreAdapter => .id);
745crate::cmp::impl_eq_ord_hash_proxy!(CoreDevice => .id);
746crate::cmp::impl_eq_ord_hash_proxy!(CoreQueue => .id);
747crate::cmp::impl_eq_ord_hash_proxy!(CoreShaderModule => .id);
748crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroupLayout => .id);
749crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroup => .id);
750crate::cmp::impl_eq_ord_hash_proxy!(CoreTextureView => .id);
751crate::cmp::impl_eq_ord_hash_proxy!(CoreSampler => .id);
752crate::cmp::impl_eq_ord_hash_proxy!(CoreBuffer => .id);
753crate::cmp::impl_eq_ord_hash_proxy!(CoreTexture => .id);
754crate::cmp::impl_eq_ord_hash_proxy!(CoreExternalTexture => .id);
755crate::cmp::impl_eq_ord_hash_proxy!(CoreBlas => .id);
756crate::cmp::impl_eq_ord_hash_proxy!(CoreTlas => .id);
757crate::cmp::impl_eq_ord_hash_proxy!(CoreQuerySet => .id);
758crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineLayout => .id);
759crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPipeline => .id);
760crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePipeline => .id);
761crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineCache => .id);
762crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandEncoder => .id);
763crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id);
764crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id);
765crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandBuffer => .id);
766crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundleEncoder => .id);
767crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundle => .id);
768crate::cmp::impl_eq_ord_hash_proxy!(CoreSurface => .id);
769crate::cmp::impl_eq_ord_hash_proxy!(CoreSurfaceOutputDetail => .surface_id);
770crate::cmp::impl_eq_ord_hash_proxy!(CoreQueueWriteBuffer => .mapping.ptr);
771crate::cmp::impl_eq_ord_hash_proxy!(CoreBufferMappedRange => .ptr);
772
773impl dispatch::InstanceInterface for ContextWgpuCore {
774    fn new(desc: wgt::InstanceDescriptor) -> Self
775    where
776        Self: Sized,
777    {
778        Self(Arc::new(wgc::global::Global::new("wgpu", desc, None)))
779    }
780
781    unsafe fn create_surface(
782        &self,
783        target: crate::api::SurfaceTargetUnsafe,
784    ) -> Result<dispatch::DispatchSurface, crate::CreateSurfaceError> {
785        let id = match target {
786            SurfaceTargetUnsafe::RawHandle {
787                raw_display_handle,
788                raw_window_handle,
789            } => unsafe {
790                self.0
791                    .instance_create_surface(raw_display_handle, raw_window_handle, None)
792            },
793
794            #[cfg(all(
795                unix,
796                not(target_vendor = "apple"),
797                not(target_family = "wasm"),
798                not(target_os = "netbsd")
799            ))]
800            SurfaceTargetUnsafe::Drm {
801                fd,
802                plane,
803                connector_id,
804                width,
805                height,
806                refresh_rate,
807            } => unsafe {
808                self.0.instance_create_surface_from_drm(
809                    fd,
810                    plane,
811                    connector_id,
812                    width,
813                    height,
814                    refresh_rate,
815                    None,
816                )
817            },
818
819            #[cfg(metal)]
820            SurfaceTargetUnsafe::CoreAnimationLayer(layer) => unsafe {
821                self.0.instance_create_surface_metal(layer, None)
822            },
823
824            #[cfg(target_os = "netbsd")]
825            SurfaceTargetUnsafe::Drm { .. } => Err(
826                wgc::instance::CreateSurfaceError::BackendNotEnabled(wgt::Backend::Vulkan),
827            ),
828
829            #[cfg(dx12)]
830            SurfaceTargetUnsafe::CompositionVisual(visual) => unsafe {
831                self.0.instance_create_surface_from_visual(visual, None)
832            },
833
834            #[cfg(dx12)]
835            SurfaceTargetUnsafe::SurfaceHandle(surface_handle) => unsafe {
836                self.0
837                    .instance_create_surface_from_surface_handle(surface_handle, None)
838            },
839
840            #[cfg(dx12)]
841            SurfaceTargetUnsafe::SwapChainPanel(swap_chain_panel) => unsafe {
842                self.0
843                    .instance_create_surface_from_swap_chain_panel(swap_chain_panel, None)
844            },
845        }?;
846
847        Ok(CoreSurface {
848            context: self.clone(),
849            id,
850            configured_device: Mutex::default(),
851            error_sink: Mutex::default(),
852        }
853        .into())
854    }
855
856    fn request_adapter(
857        &self,
858        options: &crate::api::RequestAdapterOptions<'_, '_>,
859    ) -> Pin<Box<dyn dispatch::RequestAdapterFuture>> {
860        let id = self.0.request_adapter(
861            &wgc::instance::RequestAdapterOptions {
862                power_preference: options.power_preference,
863                force_fallback_adapter: options.force_fallback_adapter,
864                compatible_surface: options
865                    .compatible_surface
866                    .map(|surface| surface.inner.as_core().id),
867            },
868            wgt::Backends::all(),
869            None,
870        );
871        let adapter = id.map(|id| {
872            let core = CoreAdapter {
873                context: self.clone(),
874                id,
875            };
876            let generic: dispatch::DispatchAdapter = core.into();
877            generic
878        });
879        Box::pin(ready(adapter))
880    }
881
882    fn poll_all_devices(&self, force_wait: bool) -> bool {
883        match self.0.poll_all_devices(force_wait) {
884            Ok(all_queue_empty) => all_queue_empty,
885            // Tilo: as in `Device::poll`, a lost device reports itself through its callback.
886            Err(wgc::device::WaitIdleError::Device(_)) => false,
887            Err(err) => self.handle_error_fatal(err, "Instance::poll_all_devices"),
888        }
889    }
890
891    #[cfg(feature = "wgsl")]
892    fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures {
893        use wgc::naga::front::wgsl::ImplementedLanguageExtension;
894        ImplementedLanguageExtension::all().iter().copied().fold(
895            crate::WgslLanguageFeatures::empty(),
896            |acc, wle| {
897                acc | match wle {
898                    ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => {
899                        crate::WgslLanguageFeatures::ReadOnlyAndReadWriteStorageTextures
900                    }
901                    ImplementedLanguageExtension::Packed4x8IntegerDotProduct => {
902                        crate::WgslLanguageFeatures::Packed4x8IntegerDotProduct
903                    }
904                    ImplementedLanguageExtension::PointerCompositeAccess => {
905                        crate::WgslLanguageFeatures::PointerCompositeAccess
906                    }
907                }
908            },
909        )
910    }
911
912    fn enumerate_adapters(
913        &self,
914        backends: crate::Backends,
915    ) -> Pin<Box<dyn dispatch::EnumerateAdapterFuture>> {
916        let adapters: Vec<DispatchAdapter> = self
917            .enumerate_adapters(backends)
918            .into_iter()
919            .map(|adapter| {
920                let core = crate::backend::wgpu_core::CoreAdapter {
921                    context: self.clone(),
922                    id: adapter,
923                };
924                core.into()
925            })
926            .collect();
927        Box::pin(ready(adapters))
928    }
929}
930
931impl dispatch::AdapterInterface for CoreAdapter {
932    fn request_device(
933        &self,
934        desc: &crate::DeviceDescriptor<'_>,
935    ) -> Pin<Box<dyn dispatch::RequestDeviceFuture>> {
936        let res = self.context.0.adapter_request_device(
937            self.id,
938            &desc.map_label(|l| l.map(Borrowed)),
939            None,
940            None,
941        );
942        let (device_id, queue_id) = match res {
943            Ok(ids) => ids,
944            Err(err) => {
945                return Box::pin(ready(Err(err.into())));
946            }
947        };
948        let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
949        let device = CoreDevice {
950            context: self.context.clone(),
951            id: device_id,
952            error_sink: error_sink.clone(),
953            features: desc.required_features,
954        };
955        let queue = CoreQueue {
956            context: self.context.clone(),
957            id: queue_id,
958            error_sink,
959        };
960        Box::pin(ready(Ok((device.into(), queue.into()))))
961    }
962
963    fn is_surface_supported(&self, surface: &dispatch::DispatchSurface) -> bool {
964        let surface = surface.as_core();
965
966        self.context
967            .0
968            .adapter_is_surface_supported(self.id, surface.id)
969    }
970
971    fn features(&self) -> crate::Features {
972        self.context.0.adapter_features(self.id)
973    }
974
975    fn limits(&self) -> crate::Limits {
976        self.context.0.adapter_limits(self.id)
977    }
978
979    fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities {
980        self.context.0.adapter_downlevel_capabilities(self.id)
981    }
982
983    fn get_info(&self) -> crate::AdapterInfo {
984        self.context.0.adapter_get_info(self.id)
985    }
986
987    fn get_texture_format_features(
988        &self,
989        format: crate::TextureFormat,
990    ) -> crate::TextureFormatFeatures {
991        self.context
992            .0
993            .adapter_get_texture_format_features(self.id, format)
994    }
995
996    fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp {
997        self.context.0.adapter_get_presentation_timestamp(self.id)
998    }
999
1000    fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties> {
1001        self.context
1002            .0
1003            .adapter_cooperative_matrix_properties(self.id)
1004    }
1005}
1006
1007impl Drop for CoreAdapter {
1008    fn drop(&mut self) {
1009        self.context.0.adapter_drop(self.id)
1010    }
1011}
1012
1013impl dispatch::DeviceInterface for CoreDevice {
1014    fn features(&self) -> crate::Features {
1015        self.context.0.device_features(self.id)
1016    }
1017
1018    fn limits(&self) -> crate::Limits {
1019        self.context.0.device_limits(self.id)
1020    }
1021
1022    fn adapter_info(&self) -> crate::AdapterInfo {
1023        self.context.0.device_adapter_info(self.id)
1024    }
1025
1026    // If we have no way to create a shader module, we can't return one, and so most of the function is unreachable.
1027    #[cfg_attr(
1028        not(any(
1029            feature = "spirv",
1030            feature = "glsl",
1031            feature = "wgsl",
1032            feature = "naga-ir"
1033        )),
1034        expect(unused)
1035    )]
1036    fn create_shader_module(
1037        &self,
1038        desc: crate::ShaderModuleDescriptor<'_>,
1039        shader_bound_checks: wgt::ShaderRuntimeChecks,
1040    ) -> dispatch::DispatchShaderModule {
1041        let descriptor = wgc::pipeline::ShaderModuleDescriptor {
1042            label: desc.label.map(Borrowed),
1043            runtime_checks: shader_bound_checks,
1044        };
1045        let source = match desc.source {
1046            #[cfg(feature = "spirv")]
1047            ShaderSource::SpirV(ref spv) => {
1048                // Parse the given shader code and store its representation.
1049                let options = naga::front::spv::Options {
1050                    adjust_coordinate_space: false, // we require NDC_Y_UP feature
1051                    strict_capabilities: true,
1052                    block_ctx_dump_prefix: None,
1053                };
1054                wgc::pipeline::ShaderModuleSource::SpirV(Borrowed(spv), options)
1055            }
1056            #[cfg(feature = "glsl")]
1057            ShaderSource::Glsl {
1058                ref shader,
1059                stage,
1060                defines,
1061            } => {
1062                let options = naga::front::glsl::Options {
1063                    stage,
1064                    defines: defines
1065                        .iter()
1066                        .map(|&(key, value)| (String::from(key), String::from(value)))
1067                        .collect(),
1068                };
1069                wgc::pipeline::ShaderModuleSource::Glsl(Borrowed(shader), options)
1070            }
1071            #[cfg(feature = "wgsl")]
1072            ShaderSource::Wgsl(ref code) => wgc::pipeline::ShaderModuleSource::Wgsl(Borrowed(code)),
1073            #[cfg(feature = "naga-ir")]
1074            ShaderSource::Naga(module) => wgc::pipeline::ShaderModuleSource::Naga(module),
1075            ShaderSource::Dummy(_) => panic!("found `ShaderSource::Dummy`"),
1076        };
1077        let (id, error) =
1078            self.context
1079                .0
1080                .device_create_shader_module(self.id, &descriptor, source, None);
1081        let compilation_info = match error {
1082            Some(cause) => {
1083                self.context.handle_error(
1084                    &self.error_sink,
1085                    cause.clone(),
1086                    desc.label,
1087                    "Device::create_shader_module",
1088                );
1089                CompilationInfo::from(cause)
1090            }
1091            None => CompilationInfo { messages: vec![] },
1092        };
1093
1094        CoreShaderModule {
1095            context: self.context.clone(),
1096            id,
1097            compilation_info,
1098        }
1099        .into()
1100    }
1101
1102    unsafe fn create_shader_module_passthrough(
1103        &self,
1104        desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
1105    ) -> dispatch::DispatchShaderModule {
1106        let desc = desc.map_label(|l| l.map(Cow::from));
1107        let (id, error) = unsafe {
1108            self.context
1109                .0
1110                .device_create_shader_module_passthrough(self.id, &desc, None)
1111        };
1112
1113        let compilation_info = match error {
1114            Some(cause) => {
1115                self.context.handle_error(
1116                    &self.error_sink,
1117                    cause.clone(),
1118                    desc.label.as_deref(),
1119                    "Device::create_shader_module_passthrough",
1120                );
1121                CompilationInfo::from(cause)
1122            }
1123            None => CompilationInfo { messages: vec![] },
1124        };
1125
1126        CoreShaderModule {
1127            context: self.context.clone(),
1128            id,
1129            compilation_info,
1130        }
1131        .into()
1132    }
1133
1134    fn create_bind_group_layout(
1135        &self,
1136        desc: &crate::BindGroupLayoutDescriptor<'_>,
1137    ) -> dispatch::DispatchBindGroupLayout {
1138        let descriptor = wgc::binding_model::BindGroupLayoutDescriptor {
1139            label: desc.label.map(Borrowed),
1140            entries: Borrowed(desc.entries),
1141        };
1142        let (id, error) =
1143            self.context
1144                .0
1145                .device_create_bind_group_layout(self.id, &descriptor, None);
1146        if let Some(cause) = error {
1147            self.context.handle_error(
1148                &self.error_sink,
1149                cause,
1150                desc.label,
1151                "Device::create_bind_group_layout",
1152            );
1153        }
1154        CoreBindGroupLayout {
1155            context: self.context.clone(),
1156            id,
1157        }
1158        .into()
1159    }
1160
1161    fn create_bind_group(
1162        &self,
1163        desc: &crate::BindGroupDescriptor<'_>,
1164    ) -> dispatch::DispatchBindGroup {
1165        use wgc::binding_model as bm;
1166
1167        let mut arrayed_texture_views = Vec::new();
1168        let mut arrayed_samplers = Vec::new();
1169        if self.features.contains(Features::TEXTURE_BINDING_ARRAY) {
1170            // gather all the array view IDs first
1171            for entry in desc.entries.iter() {
1172                if let BindingResource::TextureViewArray(array) = entry.resource {
1173                    arrayed_texture_views.extend(array.iter().map(|view| view.inner.as_core().id));
1174                }
1175                if let BindingResource::SamplerArray(array) = entry.resource {
1176                    arrayed_samplers.extend(array.iter().map(|sampler| sampler.inner.as_core().id));
1177                }
1178            }
1179        }
1180        let mut remaining_arrayed_texture_views = &arrayed_texture_views[..];
1181        let mut remaining_arrayed_samplers = &arrayed_samplers[..];
1182
1183        let mut arrayed_buffer_bindings = Vec::new();
1184        if self.features.contains(Features::BUFFER_BINDING_ARRAY) {
1185            // gather all the buffers first
1186            for entry in desc.entries.iter() {
1187                if let BindingResource::BufferArray(array) = entry.resource {
1188                    arrayed_buffer_bindings.extend(array.iter().map(|binding| bm::BufferBinding {
1189                        buffer: binding.buffer.inner.as_core().id,
1190                        offset: binding.offset,
1191                        size: binding.size.map(wgt::BufferSize::get),
1192                    }));
1193                }
1194            }
1195        }
1196        let mut remaining_arrayed_buffer_bindings = &arrayed_buffer_bindings[..];
1197
1198        let mut arrayed_acceleration_structures = Vec::new();
1199        if self
1200            .features
1201            .contains(Features::ACCELERATION_STRUCTURE_BINDING_ARRAY)
1202        {
1203            // Gather all the TLAS IDs used by TLAS arrays first (same pattern as other arrayed resources).
1204            for entry in desc.entries.iter() {
1205                if let BindingResource::AccelerationStructureArray(array) = entry.resource {
1206                    arrayed_acceleration_structures
1207                        .extend(array.iter().map(|tlas| tlas.inner.as_core().id));
1208                }
1209            }
1210        }
1211        let mut remaining_arrayed_acceleration_structures = &arrayed_acceleration_structures[..];
1212
1213        let entries = desc
1214            .entries
1215            .iter()
1216            .map(|entry| bm::BindGroupEntry {
1217                binding: entry.binding,
1218                resource: match entry.resource {
1219                    BindingResource::Buffer(BufferBinding {
1220                        buffer,
1221                        offset,
1222                        size,
1223                    }) => bm::BindingResource::Buffer(bm::BufferBinding {
1224                        buffer: buffer.inner.as_core().id,
1225                        offset,
1226                        size: size.map(wgt::BufferSize::get),
1227                    }),
1228                    BindingResource::BufferArray(array) => {
1229                        let slice = &remaining_arrayed_buffer_bindings[..array.len()];
1230                        remaining_arrayed_buffer_bindings =
1231                            &remaining_arrayed_buffer_bindings[array.len()..];
1232                        bm::BindingResource::BufferArray(Borrowed(slice))
1233                    }
1234                    BindingResource::Sampler(sampler) => {
1235                        bm::BindingResource::Sampler(sampler.inner.as_core().id)
1236                    }
1237                    BindingResource::SamplerArray(array) => {
1238                        let slice = &remaining_arrayed_samplers[..array.len()];
1239                        remaining_arrayed_samplers = &remaining_arrayed_samplers[array.len()..];
1240                        bm::BindingResource::SamplerArray(Borrowed(slice))
1241                    }
1242                    BindingResource::TextureView(texture_view) => {
1243                        bm::BindingResource::TextureView(texture_view.inner.as_core().id)
1244                    }
1245                    BindingResource::TextureViewArray(array) => {
1246                        let slice = &remaining_arrayed_texture_views[..array.len()];
1247                        remaining_arrayed_texture_views =
1248                            &remaining_arrayed_texture_views[array.len()..];
1249                        bm::BindingResource::TextureViewArray(Borrowed(slice))
1250                    }
1251                    BindingResource::AccelerationStructure(acceleration_structure) => {
1252                        bm::BindingResource::AccelerationStructure(
1253                            acceleration_structure.inner.as_core().id,
1254                        )
1255                    }
1256                    BindingResource::AccelerationStructureArray(array) => {
1257                        let slice = &remaining_arrayed_acceleration_structures[..array.len()];
1258                        remaining_arrayed_acceleration_structures =
1259                            &remaining_arrayed_acceleration_structures[array.len()..];
1260                        bm::BindingResource::AccelerationStructureArray(Borrowed(slice))
1261                    }
1262                    BindingResource::ExternalTexture(external_texture) => {
1263                        bm::BindingResource::ExternalTexture(external_texture.inner.as_core().id)
1264                    }
1265                },
1266            })
1267            .collect::<Vec<_>>();
1268        let descriptor = bm::BindGroupDescriptor {
1269            label: desc.label.as_ref().map(|label| Borrowed(&label[..])),
1270            layout: desc.layout.inner.as_core().id,
1271            entries: Borrowed(&entries),
1272        };
1273
1274        let (id, error) = self
1275            .context
1276            .0
1277            .device_create_bind_group(self.id, &descriptor, None);
1278        if let Some(cause) = error {
1279            self.context.handle_error(
1280                &self.error_sink,
1281                cause,
1282                desc.label,
1283                "Device::create_bind_group",
1284            );
1285        }
1286        CoreBindGroup {
1287            context: self.context.clone(),
1288            id,
1289        }
1290        .into()
1291    }
1292
1293    fn create_pipeline_layout(
1294        &self,
1295        desc: &crate::PipelineLayoutDescriptor<'_>,
1296    ) -> dispatch::DispatchPipelineLayout {
1297        // Limit is always less or equal to hal::MAX_BIND_GROUPS, so this is always right
1298        // Guards following ArrayVec
1299        assert!(
1300            desc.bind_group_layouts.len() <= wgc::MAX_BIND_GROUPS,
1301            "Bind group layout count {} exceeds device bind group limit {}",
1302            desc.bind_group_layouts.len(),
1303            wgc::MAX_BIND_GROUPS
1304        );
1305
1306        let temp_layouts = desc
1307            .bind_group_layouts
1308            .iter()
1309            .map(|bgl| bgl.map(|bgl| bgl.inner.as_core().id))
1310            .collect::<ArrayVec<_, { wgc::MAX_BIND_GROUPS }>>();
1311        let descriptor = wgc::binding_model::PipelineLayoutDescriptor {
1312            label: desc.label.map(Borrowed),
1313            bind_group_layouts: Borrowed(&temp_layouts),
1314            immediate_size: desc.immediate_size,
1315        };
1316
1317        let (id, error) = self
1318            .context
1319            .0
1320            .device_create_pipeline_layout(self.id, &descriptor, None);
1321        if let Some(cause) = error {
1322            self.context.handle_error(
1323                &self.error_sink,
1324                cause,
1325                desc.label,
1326                "Device::create_pipeline_layout",
1327            );
1328        }
1329        CorePipelineLayout {
1330            context: self.context.clone(),
1331            id,
1332        }
1333        .into()
1334    }
1335
1336    fn create_render_pipeline(
1337        &self,
1338        desc: &crate::RenderPipelineDescriptor<'_>,
1339    ) -> dispatch::DispatchRenderPipeline {
1340        use wgc::pipeline as pipe;
1341
1342        let vertex_buffers: ArrayVec<_, { wgc::MAX_VERTEX_BUFFERS }> = desc
1343            .vertex
1344            .buffers
1345            .iter()
1346            .map(|vbuf| pipe::VertexBufferLayout {
1347                array_stride: vbuf.array_stride,
1348                step_mode: vbuf.step_mode,
1349                attributes: Borrowed(vbuf.attributes),
1350            })
1351            .collect();
1352
1353        let vert_constants = desc
1354            .vertex
1355            .compilation_options
1356            .constants
1357            .iter()
1358            .map(|&(key, value)| (String::from(key), value))
1359            .collect();
1360
1361        let descriptor = pipe::RenderPipelineDescriptor {
1362            label: desc.label.map(Borrowed),
1363            layout: desc.layout.map(|layout| layout.inner.as_core().id),
1364            vertex: pipe::VertexState {
1365                stage: pipe::ProgrammableStageDescriptor {
1366                    module: desc.vertex.module.inner.as_core().id,
1367                    entry_point: desc.vertex.entry_point.map(Borrowed),
1368                    constants: vert_constants,
1369                    zero_initialize_workgroup_memory: desc
1370                        .vertex
1371                        .compilation_options
1372                        .zero_initialize_workgroup_memory,
1373                },
1374                buffers: Borrowed(&vertex_buffers),
1375            },
1376            primitive: desc.primitive,
1377            depth_stencil: desc.depth_stencil.clone(),
1378            multisample: desc.multisample,
1379            fragment: desc.fragment.as_ref().map(|frag| {
1380                let frag_constants = frag
1381                    .compilation_options
1382                    .constants
1383                    .iter()
1384                    .map(|&(key, value)| (String::from(key), value))
1385                    .collect();
1386                pipe::FragmentState {
1387                    stage: pipe::ProgrammableStageDescriptor {
1388                        module: frag.module.inner.as_core().id,
1389                        entry_point: frag.entry_point.map(Borrowed),
1390                        constants: frag_constants,
1391                        zero_initialize_workgroup_memory: frag
1392                            .compilation_options
1393                            .zero_initialize_workgroup_memory,
1394                    },
1395                    targets: Borrowed(frag.targets),
1396                }
1397            }),
1398            multiview_mask: desc.multiview_mask,
1399            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1400        };
1401
1402        let (id, error) = self
1403            .context
1404            .0
1405            .device_create_render_pipeline(self.id, &descriptor, None);
1406        if let Some(cause) = error {
1407            if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1408                log::error!("Shader translation error for stage {stage:?}: {error}");
1409                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1410            }
1411            self.context.handle_error(
1412                &self.error_sink,
1413                cause,
1414                desc.label,
1415                "Device::create_render_pipeline",
1416            );
1417        }
1418        CoreRenderPipeline {
1419            context: self.context.clone(),
1420            id,
1421            error_sink: Arc::clone(&self.error_sink),
1422        }
1423        .into()
1424    }
1425
1426    fn create_mesh_pipeline(
1427        &self,
1428        desc: &crate::MeshPipelineDescriptor<'_>,
1429    ) -> dispatch::DispatchRenderPipeline {
1430        use wgc::pipeline as pipe;
1431
1432        let mesh_constants = desc
1433            .mesh
1434            .compilation_options
1435            .constants
1436            .iter()
1437            .map(|&(key, value)| (String::from(key), value))
1438            .collect();
1439        let descriptor = pipe::MeshPipelineDescriptor {
1440            label: desc.label.map(Borrowed),
1441            task: desc.task.as_ref().map(|task| {
1442                let task_constants = task
1443                    .compilation_options
1444                    .constants
1445                    .iter()
1446                    .map(|&(key, value)| (String::from(key), value))
1447                    .collect();
1448                pipe::TaskState {
1449                    stage: pipe::ProgrammableStageDescriptor {
1450                        module: task.module.inner.as_core().id,
1451                        entry_point: task.entry_point.map(Borrowed),
1452                        constants: task_constants,
1453                        zero_initialize_workgroup_memory: desc
1454                            .mesh
1455                            .compilation_options
1456                            .zero_initialize_workgroup_memory,
1457                    },
1458                }
1459            }),
1460            mesh: pipe::MeshState {
1461                stage: pipe::ProgrammableStageDescriptor {
1462                    module: desc.mesh.module.inner.as_core().id,
1463                    entry_point: desc.mesh.entry_point.map(Borrowed),
1464                    constants: mesh_constants,
1465                    zero_initialize_workgroup_memory: desc
1466                        .mesh
1467                        .compilation_options
1468                        .zero_initialize_workgroup_memory,
1469                },
1470            },
1471            layout: desc.layout.map(|layout| layout.inner.as_core().id),
1472            primitive: desc.primitive,
1473            depth_stencil: desc.depth_stencil.clone(),
1474            multisample: desc.multisample,
1475            fragment: desc.fragment.as_ref().map(|frag| {
1476                let frag_constants = frag
1477                    .compilation_options
1478                    .constants
1479                    .iter()
1480                    .map(|&(key, value)| (String::from(key), value))
1481                    .collect();
1482                pipe::FragmentState {
1483                    stage: pipe::ProgrammableStageDescriptor {
1484                        module: frag.module.inner.as_core().id,
1485                        entry_point: frag.entry_point.map(Borrowed),
1486                        constants: frag_constants,
1487                        zero_initialize_workgroup_memory: frag
1488                            .compilation_options
1489                            .zero_initialize_workgroup_memory,
1490                    },
1491                    targets: Borrowed(frag.targets),
1492                }
1493            }),
1494            multiview: desc.multiview,
1495            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1496        };
1497
1498        let (id, error) = self
1499            .context
1500            .0
1501            .device_create_mesh_pipeline(self.id, &descriptor, None);
1502        if let Some(cause) = error {
1503            if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1504                log::error!("Shader translation error for stage {stage:?}: {error}");
1505                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1506            }
1507            self.context.handle_error(
1508                &self.error_sink,
1509                cause,
1510                desc.label,
1511                "Device::create_render_pipeline",
1512            );
1513        }
1514        CoreRenderPipeline {
1515            context: self.context.clone(),
1516            id,
1517            error_sink: Arc::clone(&self.error_sink),
1518        }
1519        .into()
1520    }
1521
1522    fn create_compute_pipeline(
1523        &self,
1524        desc: &crate::ComputePipelineDescriptor<'_>,
1525    ) -> dispatch::DispatchComputePipeline {
1526        use wgc::pipeline as pipe;
1527
1528        let constants = desc
1529            .compilation_options
1530            .constants
1531            .iter()
1532            .map(|&(key, value)| (String::from(key), value))
1533            .collect();
1534
1535        let descriptor = pipe::ComputePipelineDescriptor {
1536            label: desc.label.map(Borrowed),
1537            layout: desc.layout.map(|pll| pll.inner.as_core().id),
1538            stage: pipe::ProgrammableStageDescriptor {
1539                module: desc.module.inner.as_core().id,
1540                entry_point: desc.entry_point.map(Borrowed),
1541                constants,
1542                zero_initialize_workgroup_memory: desc
1543                    .compilation_options
1544                    .zero_initialize_workgroup_memory,
1545            },
1546            cache: desc.cache.map(|cache| cache.inner.as_core().id),
1547        };
1548
1549        let (id, error) = self
1550            .context
1551            .0
1552            .device_create_compute_pipeline(self.id, &descriptor, None);
1553        if let Some(cause) = error {
1554            if let wgc::pipeline::CreateComputePipelineError::Internal(ref error) = cause {
1555                log::error!(
1556                    "Shader translation error for stage {:?}: {}",
1557                    wgt::ShaderStages::COMPUTE,
1558                    error
1559                );
1560                log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1561            }
1562            self.context.handle_error(
1563                &self.error_sink,
1564                cause,
1565                desc.label,
1566                "Device::create_compute_pipeline",
1567            );
1568        }
1569        CoreComputePipeline {
1570            context: self.context.clone(),
1571            id,
1572            error_sink: Arc::clone(&self.error_sink),
1573        }
1574        .into()
1575    }
1576
1577    unsafe fn create_pipeline_cache(
1578        &self,
1579        desc: &crate::PipelineCacheDescriptor<'_>,
1580    ) -> dispatch::DispatchPipelineCache {
1581        use wgc::pipeline as pipe;
1582
1583        let descriptor = pipe::PipelineCacheDescriptor {
1584            label: desc.label.map(Borrowed),
1585            data: desc.data.map(Borrowed),
1586            fallback: desc.fallback,
1587        };
1588        let (id, error) = unsafe {
1589            self.context
1590                .0
1591                .device_create_pipeline_cache(self.id, &descriptor, None)
1592        };
1593        if let Some(cause) = error {
1594            self.context.handle_error(
1595                &self.error_sink,
1596                cause,
1597                desc.label,
1598                "Device::device_create_pipeline_cache_init",
1599            );
1600        }
1601        CorePipelineCache {
1602            context: self.context.clone(),
1603            id,
1604        }
1605        .into()
1606    }
1607
1608    fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> dispatch::DispatchBuffer {
1609        let (id, error) = self.context.0.device_create_buffer(
1610            self.id,
1611            &desc.map_label(|l| l.map(Borrowed)),
1612            None,
1613        );
1614        if let Some(cause) = error {
1615            self.context
1616                .handle_error(&self.error_sink, cause, desc.label, "Device::create_buffer");
1617        }
1618
1619        CoreBuffer {
1620            context: self.context.clone(),
1621            id,
1622            error_sink: Arc::clone(&self.error_sink),
1623        }
1624        .into()
1625    }
1626
1627    fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> dispatch::DispatchTexture {
1628        let wgt_desc = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
1629        let (id, error) = self
1630            .context
1631            .0
1632            .device_create_texture(self.id, &wgt_desc, None);
1633        if let Some(cause) = error {
1634            self.context.handle_error(
1635                &self.error_sink,
1636                cause,
1637                desc.label,
1638                "Device::create_texture",
1639            );
1640        }
1641
1642        CoreTexture {
1643            context: self.context.clone(),
1644            id,
1645            error_sink: Arc::clone(&self.error_sink),
1646        }
1647        .into()
1648    }
1649
1650    fn create_external_texture(
1651        &self,
1652        desc: &crate::ExternalTextureDescriptor<'_>,
1653        planes: &[&crate::TextureView],
1654    ) -> dispatch::DispatchExternalTexture {
1655        let wgt_desc = desc.map_label(|l| l.map(Borrowed));
1656        let planes = planes
1657            .iter()
1658            .map(|plane| plane.inner.as_core().id)
1659            .collect::<Vec<_>>();
1660        let (id, error) = self
1661            .context
1662            .0
1663            .device_create_external_texture(self.id, &wgt_desc, &planes, None);
1664        if let Some(cause) = error {
1665            self.context.handle_error(
1666                &self.error_sink,
1667                cause,
1668                desc.label,
1669                "Device::create_external_texture",
1670            );
1671        }
1672
1673        CoreExternalTexture {
1674            context: self.context.clone(),
1675            id,
1676        }
1677        .into()
1678    }
1679
1680    fn create_blas(
1681        &self,
1682        desc: &crate::CreateBlasDescriptor<'_>,
1683        sizes: crate::BlasGeometrySizeDescriptors,
1684    ) -> (Option<u64>, dispatch::DispatchBlas) {
1685        let global = &self.context.0;
1686        let (id, handle, error) =
1687            global.device_create_blas(self.id, &desc.map_label(|l| l.map(Borrowed)), sizes, None);
1688        if let Some(cause) = error {
1689            self.context
1690                .handle_error(&self.error_sink, cause, desc.label, "Device::create_blas");
1691        }
1692        (
1693            handle,
1694            CoreBlas {
1695                context: self.context.clone(),
1696                id,
1697                error_sink: Arc::clone(&self.error_sink),
1698            }
1699            .into(),
1700        )
1701    }
1702
1703    fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> dispatch::DispatchTlas {
1704        let global = &self.context.0;
1705        let (id, error) =
1706            global.device_create_tlas(self.id, &desc.map_label(|l| l.map(Borrowed)), None);
1707        if let Some(cause) = error {
1708            self.context
1709                .handle_error(&self.error_sink, cause, desc.label, "Device::create_tlas");
1710        }
1711        CoreTlas {
1712            context: self.context.clone(),
1713            id,
1714            // error_sink: Arc::clone(&self.error_sink),
1715        }
1716        .into()
1717    }
1718
1719    fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> dispatch::DispatchSampler {
1720        let descriptor = wgc::resource::SamplerDescriptor {
1721            label: desc.label.map(Borrowed),
1722            address_modes: [
1723                desc.address_mode_u,
1724                desc.address_mode_v,
1725                desc.address_mode_w,
1726            ],
1727            mag_filter: desc.mag_filter,
1728            min_filter: desc.min_filter,
1729            mipmap_filter: desc.mipmap_filter,
1730            lod_min_clamp: desc.lod_min_clamp,
1731            lod_max_clamp: desc.lod_max_clamp,
1732            compare: desc.compare,
1733            anisotropy_clamp: desc.anisotropy_clamp,
1734            border_color: desc.border_color,
1735        };
1736
1737        let (id, error) = self
1738            .context
1739            .0
1740            .device_create_sampler(self.id, &descriptor, None);
1741        if let Some(cause) = error {
1742            self.context.handle_error(
1743                &self.error_sink,
1744                cause,
1745                desc.label,
1746                "Device::create_sampler",
1747            );
1748        }
1749        CoreSampler {
1750            context: self.context.clone(),
1751            id,
1752        }
1753        .into()
1754    }
1755
1756    fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> dispatch::DispatchQuerySet {
1757        let (id, error) = self.context.0.device_create_query_set(
1758            self.id,
1759            &desc.map_label(|l| l.map(Borrowed)),
1760            None,
1761        );
1762        if let Some(cause) = error {
1763            self.context
1764                .handle_error_nolabel(&self.error_sink, cause, "Device::create_query_set");
1765        }
1766        CoreQuerySet {
1767            context: self.context.clone(),
1768            id,
1769        }
1770        .into()
1771    }
1772
1773    fn create_command_encoder(
1774        &self,
1775        desc: &crate::CommandEncoderDescriptor<'_>,
1776    ) -> dispatch::DispatchCommandEncoder {
1777        let (id, error) = self.context.0.device_create_command_encoder(
1778            self.id,
1779            &desc.map_label(|l| l.map(Borrowed)),
1780            None,
1781        );
1782        if let Some(cause) = error {
1783            self.context.handle_error(
1784                &self.error_sink,
1785                cause,
1786                desc.label,
1787                "Device::create_command_encoder",
1788            );
1789        }
1790
1791        CoreCommandEncoder {
1792            context: self.context.clone(),
1793            id,
1794            error_sink: Arc::clone(&self.error_sink),
1795        }
1796        .into()
1797    }
1798
1799    fn create_render_bundle_encoder(
1800        &self,
1801        desc: &crate::RenderBundleEncoderDescriptor<'_>,
1802    ) -> dispatch::DispatchRenderBundleEncoder {
1803        let descriptor = wgc::command::RenderBundleEncoderDescriptor {
1804            label: desc.label.map(Borrowed),
1805            color_formats: Borrowed(desc.color_formats),
1806            depth_stencil: desc.depth_stencil,
1807            sample_count: desc.sample_count,
1808            multiview: desc.multiview,
1809        };
1810        let encoder = match wgc::command::RenderBundleEncoder::new(&descriptor, self.id) {
1811            Ok(encoder) => encoder,
1812            Err(e) => panic!("Error in Device::create_render_bundle_encoder: {e}"),
1813        };
1814
1815        CoreRenderBundleEncoder {
1816            context: self.context.clone(),
1817            encoder,
1818            id: crate::cmp::Identifier::create(),
1819        }
1820        .into()
1821    }
1822
1823    fn set_device_lost_callback(&self, device_lost_callback: dispatch::BoxDeviceLostCallback) {
1824        self.context
1825            .0
1826            .device_set_device_lost_closure(self.id, device_lost_callback);
1827    }
1828
1829    fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>) {
1830        let mut error_sink = self.error_sink.lock();
1831        error_sink.uncaptured_handler = Some(handler);
1832    }
1833
1834    fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32 {
1835        let mut error_sink = self.error_sink.lock();
1836        let thread_id = thread_id::ThreadId::current();
1837        let scopes = error_sink.scopes.entry(thread_id).or_default();
1838        let index = scopes
1839            .len()
1840            .try_into()
1841            .expect("Greater than 2^32 nested error scopes");
1842        scopes.push(ErrorScope {
1843            error: None,
1844            filter,
1845        });
1846        index
1847    }
1848
1849    fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn dispatch::PopErrorScopeFuture>> {
1850        let mut error_sink = self.error_sink.lock();
1851
1852        // We go out of our way to avoid panicking while unwinding, because that would abort the process,
1853        // and we are supposed to just drop the error scope on the floor.
1854        let is_panicking = crate::util::is_panicking();
1855        let thread_id = thread_id::ThreadId::current();
1856        let err = "Mismatched pop_error_scope call: no error scope for this thread. Error scopes are thread-local.";
1857        let scopes = match error_sink.scopes.get_mut(&thread_id) {
1858            Some(s) => s,
1859            None => {
1860                if !is_panicking {
1861                    panic!("{err}");
1862                } else {
1863                    return Box::pin(ready(None));
1864                }
1865            }
1866        };
1867        if scopes.is_empty() && !is_panicking {
1868            panic!("{err}");
1869        }
1870        if index as usize != scopes.len() - 1 && !is_panicking {
1871            panic!(
1872                "Mismatched pop_error_scope call: error scopes must be popped in reverse order."
1873            );
1874        }
1875
1876        // It would be more correct in this case to use `remove` here so that when unwinding is occurring
1877        // we would remove the correct error scope, but we don't have such a primitive on the web
1878        // and having consistent behavior here is more important. If you are unwinding and it unwinds
1879        // the guards in the wrong order, it's totally reasonable to have incorrect behavior.
1880        let scope = match scopes.pop() {
1881            Some(s) => s,
1882            None if !is_panicking => unreachable!(),
1883            None => return Box::pin(ready(None)),
1884        };
1885
1886        Box::pin(ready(scope.error))
1887    }
1888
1889    unsafe fn start_graphics_debugger_capture(&self) {
1890        unsafe {
1891            self.context
1892                .0
1893                .device_start_graphics_debugger_capture(self.id)
1894        };
1895    }
1896
1897    unsafe fn stop_graphics_debugger_capture(&self) {
1898        unsafe {
1899            self.context
1900                .0
1901                .device_stop_graphics_debugger_capture(self.id)
1902        };
1903    }
1904
1905    fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
1906        match self.context.0.device_poll(self.id, poll_type) {
1907            Ok(status) => Ok(status),
1908            Err(err) => {
1909                if let Some(poll_error) = err.to_poll_error() {
1910                    return Err(poll_error);
1911                }
1912                // Tilo: a lost device is not a programming error. wgpu-core has already marked
1913                // the device invalid and run its device-lost callback, which is where the
1914                // caller learns why; the work it waited for will never finish, so say so.
1915                if let wgc::device::WaitIdleError::Device(_) = err {
1916                    return Err(crate::PollError::Timeout);
1917                }
1918
1919                self.context.handle_error_fatal(err, "Device::poll")
1920            }
1921        }
1922    }
1923
1924    fn get_internal_counters(&self) -> crate::InternalCounters {
1925        self.context.0.device_get_internal_counters(self.id)
1926    }
1927
1928    fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1929        self.context.0.device_generate_allocator_report(self.id)
1930    }
1931
1932    fn destroy(&self) {
1933        self.context.0.device_destroy(self.id);
1934    }
1935}
1936
1937impl Drop for CoreDevice {
1938    fn drop(&mut self) {
1939        self.context.0.device_drop(self.id)
1940    }
1941}
1942
1943impl dispatch::QueueInterface for CoreQueue {
1944    fn write_buffer(
1945        &self,
1946        buffer: &dispatch::DispatchBuffer,
1947        offset: crate::BufferAddress,
1948        data: &[u8],
1949    ) {
1950        let buffer = buffer.as_core();
1951
1952        match self
1953            .context
1954            .0
1955            .queue_write_buffer(self.id, buffer.id, offset, data)
1956        {
1957            Ok(()) => (),
1958            Err(err) => {
1959                self.context
1960                    .handle_error_nolabel(&self.error_sink, err, "Queue::write_buffer")
1961            }
1962        }
1963    }
1964
1965    fn create_staging_buffer(
1966        &self,
1967        size: crate::BufferSize,
1968    ) -> Option<dispatch::DispatchQueueWriteBuffer> {
1969        match self
1970            .context
1971            .0
1972            .queue_create_staging_buffer(self.id, size, None)
1973        {
1974            Ok((buffer_id, ptr)) => Some(
1975                CoreQueueWriteBuffer {
1976                    buffer_id,
1977                    mapping: CoreBufferMappedRange {
1978                        ptr,
1979                        size: size.get() as usize,
1980                    },
1981                }
1982                .into(),
1983            ),
1984            Err(err) => {
1985                self.context.handle_error_nolabel(
1986                    &self.error_sink,
1987                    err,
1988                    "Queue::write_buffer_with",
1989                );
1990                None
1991            }
1992        }
1993    }
1994
1995    fn validate_write_buffer(
1996        &self,
1997        buffer: &dispatch::DispatchBuffer,
1998        offset: wgt::BufferAddress,
1999        size: wgt::BufferSize,
2000    ) -> Option<()> {
2001        let buffer = buffer.as_core();
2002
2003        match self
2004            .context
2005            .0
2006            .queue_validate_write_buffer(self.id, buffer.id, offset, size)
2007        {
2008            Ok(()) => Some(()),
2009            Err(err) => {
2010                self.context.handle_error_nolabel(
2011                    &self.error_sink,
2012                    err,
2013                    "Queue::write_buffer_with",
2014                );
2015                None
2016            }
2017        }
2018    }
2019
2020    fn write_staging_buffer(
2021        &self,
2022        buffer: &dispatch::DispatchBuffer,
2023        offset: crate::BufferAddress,
2024        staging_buffer: &dispatch::DispatchQueueWriteBuffer,
2025    ) {
2026        let buffer = buffer.as_core();
2027        let staging_buffer = staging_buffer.as_core();
2028
2029        match self.context.0.queue_write_staging_buffer(
2030            self.id,
2031            buffer.id,
2032            offset,
2033            staging_buffer.buffer_id,
2034        ) {
2035            Ok(()) => (),
2036            Err(err) => {
2037                self.context.handle_error_nolabel(
2038                    &self.error_sink,
2039                    err,
2040                    "Queue::write_buffer_with",
2041                );
2042            }
2043        }
2044    }
2045
2046    fn write_texture(
2047        &self,
2048        texture: crate::TexelCopyTextureInfo<'_>,
2049        data: &[u8],
2050        data_layout: crate::TexelCopyBufferLayout,
2051        size: crate::Extent3d,
2052    ) {
2053        match self.context.0.queue_write_texture(
2054            self.id,
2055            &map_texture_copy_view(texture),
2056            data,
2057            &data_layout,
2058            &size,
2059        ) {
2060            Ok(()) => (),
2061            Err(err) => {
2062                self.context
2063                    .handle_error_nolabel(&self.error_sink, err, "Queue::write_texture")
2064            }
2065        }
2066    }
2067
2068    // This method needs to exist if either webgpu or webgl is enabled,
2069    // but we only actually have an implementation if webgl is enabled.
2070    #[cfg(web)]
2071    #[cfg_attr(not(webgl), expect(unused_variables))]
2072    fn copy_external_image_to_texture(
2073        &self,
2074        source: &crate::CopyExternalImageSourceInfo,
2075        dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
2076        size: crate::Extent3d,
2077    ) {
2078        #[cfg(webgl)]
2079        match self.context.0.queue_copy_external_image_to_texture(
2080            self.id,
2081            source,
2082            map_texture_tagged_copy_view(dest),
2083            size,
2084        ) {
2085            Ok(()) => (),
2086            Err(err) => self.context.handle_error_nolabel(
2087                &self.error_sink,
2088                err,
2089                "Queue::copy_external_image_to_texture",
2090            ),
2091        }
2092    }
2093
2094    fn submit(
2095        &self,
2096        command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
2097    ) -> u64 {
2098        let temp_command_buffers = command_buffers.collect::<SmallVec<[_; 4]>>();
2099        let command_buffer_ids = temp_command_buffers
2100            .iter()
2101            .map(|cmdbuf| cmdbuf.as_core().id)
2102            .collect::<SmallVec<[_; 4]>>();
2103
2104        let index = match self.context.0.queue_submit(self.id, &command_buffer_ids) {
2105            Ok(index) => index,
2106            Err((index, err)) => {
2107                self.context
2108                    .handle_error_nolabel(&self.error_sink, err, "Queue::submit");
2109                index
2110            }
2111        };
2112
2113        drop(temp_command_buffers);
2114
2115        index
2116    }
2117
2118    fn get_timestamp_period(&self) -> f32 {
2119        self.context.0.queue_get_timestamp_period(self.id)
2120    }
2121
2122    fn on_submitted_work_done(&self, callback: dispatch::BoxSubmittedWorkDoneCallback) {
2123        self.context
2124            .0
2125            .queue_on_submitted_work_done(self.id, callback);
2126    }
2127
2128    fn compact_blas(&self, blas: &dispatch::DispatchBlas) -> (Option<u64>, dispatch::DispatchBlas) {
2129        let (id, handle, error) =
2130            self.context
2131                .0
2132                .queue_compact_blas(self.id, blas.as_core().id, None);
2133
2134        if let Some(cause) = error {
2135            self.context
2136                .handle_error_nolabel(&self.error_sink, cause, "Queue::compact_blas");
2137        }
2138        (
2139            handle,
2140            CoreBlas {
2141                context: self.context.clone(),
2142                id,
2143                error_sink: Arc::clone(&self.error_sink),
2144            }
2145            .into(),
2146        )
2147    }
2148}
2149
2150impl Drop for CoreQueue {
2151    fn drop(&mut self) {
2152        self.context.0.queue_drop(self.id)
2153    }
2154}
2155
2156impl dispatch::ShaderModuleInterface for CoreShaderModule {
2157    fn get_compilation_info(&self) -> Pin<Box<dyn dispatch::ShaderCompilationInfoFuture>> {
2158        Box::pin(ready(self.compilation_info.clone()))
2159    }
2160}
2161
2162impl Drop for CoreShaderModule {
2163    fn drop(&mut self) {
2164        self.context.0.shader_module_drop(self.id)
2165    }
2166}
2167
2168impl dispatch::BindGroupLayoutInterface for CoreBindGroupLayout {}
2169
2170impl Drop for CoreBindGroupLayout {
2171    fn drop(&mut self) {
2172        self.context.0.bind_group_layout_drop(self.id)
2173    }
2174}
2175
2176impl dispatch::BindGroupInterface for CoreBindGroup {}
2177
2178impl Drop for CoreBindGroup {
2179    fn drop(&mut self) {
2180        self.context.0.bind_group_drop(self.id)
2181    }
2182}
2183
2184impl dispatch::TextureViewInterface for CoreTextureView {}
2185
2186impl Drop for CoreTextureView {
2187    fn drop(&mut self) {
2188        self.context.0.texture_view_drop(self.id);
2189    }
2190}
2191
2192impl dispatch::ExternalTextureInterface for CoreExternalTexture {
2193    fn destroy(&self) {
2194        self.context.0.external_texture_destroy(self.id);
2195    }
2196}
2197
2198impl Drop for CoreExternalTexture {
2199    fn drop(&mut self) {
2200        self.context.0.external_texture_drop(self.id);
2201    }
2202}
2203
2204impl dispatch::SamplerInterface for CoreSampler {}
2205
2206impl Drop for CoreSampler {
2207    fn drop(&mut self) {
2208        self.context.0.sampler_drop(self.id)
2209    }
2210}
2211
2212impl dispatch::BufferInterface for CoreBuffer {
2213    fn map_async(
2214        &self,
2215        mode: crate::MapMode,
2216        range: Range<crate::BufferAddress>,
2217        callback: dispatch::BufferMapCallback,
2218    ) {
2219        let operation = wgc::resource::BufferMapOperation {
2220            host: match mode {
2221                MapMode::Read => wgc::device::HostMap::Read,
2222                MapMode::Write => wgc::device::HostMap::Write,
2223            },
2224            callback: Some(Box::new(|status| {
2225                let res = status.map_err(|_| crate::BufferAsyncError);
2226                callback(res);
2227            })),
2228        };
2229
2230        match self.context.0.buffer_map_async(
2231            self.id,
2232            range.start,
2233            Some(range.end - range.start),
2234            operation,
2235        ) {
2236            Ok(_) => (),
2237            Err(cause) => {
2238                self.context
2239                    .handle_error_nolabel(&self.error_sink, cause, "Buffer::map_async")
2240            }
2241        }
2242    }
2243
2244    fn get_mapped_range(
2245        &self,
2246        sub_range: Range<crate::BufferAddress>,
2247    ) -> dispatch::DispatchBufferMappedRange {
2248        let size = sub_range.end - sub_range.start;
2249        match self
2250            .context
2251            .0
2252            .buffer_get_mapped_range(self.id, sub_range.start, Some(size))
2253        {
2254            Ok((ptr, size)) => CoreBufferMappedRange {
2255                ptr,
2256                size: size as usize,
2257            }
2258            .into(),
2259            Err(err) => self
2260                .context
2261                .handle_error_fatal(err, "Buffer::get_mapped_range"),
2262        }
2263    }
2264
2265    fn unmap(&self) {
2266        match self.context.0.buffer_unmap(self.id) {
2267            Ok(()) => (),
2268            Err(cause) => {
2269                self.context
2270                    .handle_error_nolabel(&self.error_sink, cause, "Buffer::buffer_unmap")
2271            }
2272        }
2273    }
2274
2275    fn destroy(&self) {
2276        self.context.0.buffer_destroy(self.id);
2277    }
2278}
2279
2280impl Drop for CoreBuffer {
2281    fn drop(&mut self) {
2282        self.context.0.buffer_drop(self.id)
2283    }
2284}
2285
2286impl dispatch::TextureInterface for CoreTexture {
2287    fn create_view(
2288        &self,
2289        desc: &crate::TextureViewDescriptor<'_>,
2290    ) -> dispatch::DispatchTextureView {
2291        let descriptor = wgc::resource::TextureViewDescriptor {
2292            label: desc.label.map(Borrowed),
2293            format: desc.format,
2294            dimension: desc.dimension,
2295            usage: desc.usage,
2296            range: wgt::ImageSubresourceRange {
2297                aspect: desc.aspect,
2298                base_mip_level: desc.base_mip_level,
2299                mip_level_count: desc.mip_level_count,
2300                base_array_layer: desc.base_array_layer,
2301                array_layer_count: desc.array_layer_count,
2302            },
2303        };
2304        let (id, error) = self
2305            .context
2306            .0
2307            .texture_create_view(self.id, &descriptor, None);
2308        if let Some(cause) = error {
2309            self.context
2310                .handle_error(&self.error_sink, cause, desc.label, "Texture::create_view");
2311        }
2312        CoreTextureView {
2313            context: self.context.clone(),
2314            id,
2315        }
2316        .into()
2317    }
2318
2319    fn destroy(&self) {
2320        self.context.0.texture_destroy(self.id);
2321    }
2322}
2323
2324impl Drop for CoreTexture {
2325    fn drop(&mut self) {
2326        self.context.0.texture_drop(self.id)
2327    }
2328}
2329
2330impl dispatch::BlasInterface for CoreBlas {
2331    fn prepare_compact_async(&self, callback: BlasCompactCallback) {
2332        let callback: Option<wgc::resource::BlasCompactCallback> =
2333            Some(Box::new(|status: BlasPrepareCompactResult| {
2334                let res = status.map_err(|_| crate::BlasAsyncError);
2335                callback(res);
2336            }));
2337
2338        match self.context.0.blas_prepare_compact_async(self.id, callback) {
2339            Ok(_) => (),
2340            Err(cause) => self.context.handle_error_nolabel(
2341                &self.error_sink,
2342                cause,
2343                "Blas::prepare_compact_async",
2344            ),
2345        }
2346    }
2347
2348    fn ready_for_compaction(&self) -> bool {
2349        match self.context.0.ready_for_compaction(self.id) {
2350            Ok(ready) => ready,
2351            Err(cause) => {
2352                self.context.handle_error_nolabel(
2353                    &self.error_sink,
2354                    cause,
2355                    "Blas::ready_for_compaction",
2356                );
2357                // A BLAS is definitely not ready for compaction if it's not valid
2358                false
2359            }
2360        }
2361    }
2362}
2363
2364impl Drop for CoreBlas {
2365    fn drop(&mut self) {
2366        self.context.0.blas_drop(self.id)
2367    }
2368}
2369
2370impl dispatch::TlasInterface for CoreTlas {}
2371
2372impl Drop for CoreTlas {
2373    fn drop(&mut self) {
2374        self.context.0.tlas_drop(self.id)
2375    }
2376}
2377
2378impl dispatch::QuerySetInterface for CoreQuerySet {}
2379
2380impl Drop for CoreQuerySet {
2381    fn drop(&mut self) {
2382        self.context.0.query_set_drop(self.id)
2383    }
2384}
2385
2386impl dispatch::PipelineLayoutInterface for CorePipelineLayout {}
2387
2388impl Drop for CorePipelineLayout {
2389    fn drop(&mut self) {
2390        self.context.0.pipeline_layout_drop(self.id)
2391    }
2392}
2393
2394impl dispatch::RenderPipelineInterface for CoreRenderPipeline {
2395    fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2396        let (id, error) = self
2397            .context
2398            .0
2399            .render_pipeline_get_bind_group_layout(self.id, index, None);
2400        if let Some(err) = error {
2401            self.context.handle_error_nolabel(
2402                &self.error_sink,
2403                err,
2404                "RenderPipeline::get_bind_group_layout",
2405            )
2406        }
2407        CoreBindGroupLayout {
2408            context: self.context.clone(),
2409            id,
2410        }
2411        .into()
2412    }
2413}
2414
2415impl Drop for CoreRenderPipeline {
2416    fn drop(&mut self) {
2417        self.context.0.render_pipeline_drop(self.id)
2418    }
2419}
2420
2421impl dispatch::ComputePipelineInterface for CoreComputePipeline {
2422    fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2423        let (id, error) = self
2424            .context
2425            .0
2426            .compute_pipeline_get_bind_group_layout(self.id, index, None);
2427        if let Some(err) = error {
2428            self.context.handle_error_nolabel(
2429                &self.error_sink,
2430                err,
2431                "ComputePipeline::get_bind_group_layout",
2432            )
2433        }
2434        CoreBindGroupLayout {
2435            context: self.context.clone(),
2436            id,
2437        }
2438        .into()
2439    }
2440}
2441
2442impl Drop for CoreComputePipeline {
2443    fn drop(&mut self) {
2444        self.context.0.compute_pipeline_drop(self.id)
2445    }
2446}
2447
2448impl dispatch::PipelineCacheInterface for CorePipelineCache {
2449    fn get_data(&self) -> Option<Vec<u8>> {
2450        self.context.0.pipeline_cache_get_data(self.id)
2451    }
2452}
2453
2454impl Drop for CorePipelineCache {
2455    fn drop(&mut self) {
2456        self.context.0.pipeline_cache_drop(self.id)
2457    }
2458}
2459
2460impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
2461    fn copy_buffer_to_buffer(
2462        &self,
2463        source: &dispatch::DispatchBuffer,
2464        source_offset: crate::BufferAddress,
2465        destination: &dispatch::DispatchBuffer,
2466        destination_offset: crate::BufferAddress,
2467        copy_size: Option<crate::BufferAddress>,
2468    ) {
2469        let source = source.as_core();
2470        let destination = destination.as_core();
2471
2472        if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_buffer(
2473            self.id,
2474            source.id,
2475            source_offset,
2476            destination.id,
2477            destination_offset,
2478            copy_size,
2479        ) {
2480            self.context.handle_error_nolabel(
2481                &self.error_sink,
2482                cause,
2483                "CommandEncoder::copy_buffer_to_buffer",
2484            );
2485        }
2486    }
2487
2488    fn copy_buffer_to_texture(
2489        &self,
2490        source: crate::TexelCopyBufferInfo<'_>,
2491        destination: crate::TexelCopyTextureInfo<'_>,
2492        copy_size: crate::Extent3d,
2493    ) {
2494        if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_texture(
2495            self.id,
2496            &map_buffer_copy_view(source),
2497            &map_texture_copy_view(destination),
2498            &copy_size,
2499        ) {
2500            self.context.handle_error_nolabel(
2501                &self.error_sink,
2502                cause,
2503                "CommandEncoder::copy_buffer_to_texture",
2504            );
2505        }
2506    }
2507
2508    fn copy_texture_to_buffer(
2509        &self,
2510        source: crate::TexelCopyTextureInfo<'_>,
2511        destination: crate::TexelCopyBufferInfo<'_>,
2512        copy_size: crate::Extent3d,
2513    ) {
2514        if let Err(cause) = self.context.0.command_encoder_copy_texture_to_buffer(
2515            self.id,
2516            &map_texture_copy_view(source),
2517            &map_buffer_copy_view(destination),
2518            &copy_size,
2519        ) {
2520            self.context.handle_error_nolabel(
2521                &self.error_sink,
2522                cause,
2523                "CommandEncoder::copy_texture_to_buffer",
2524            );
2525        }
2526    }
2527
2528    fn copy_texture_to_texture(
2529        &self,
2530        source: crate::TexelCopyTextureInfo<'_>,
2531        destination: crate::TexelCopyTextureInfo<'_>,
2532        copy_size: crate::Extent3d,
2533    ) {
2534        if let Err(cause) = self.context.0.command_encoder_copy_texture_to_texture(
2535            self.id,
2536            &map_texture_copy_view(source),
2537            &map_texture_copy_view(destination),
2538            &copy_size,
2539        ) {
2540            self.context.handle_error_nolabel(
2541                &self.error_sink,
2542                cause,
2543                "CommandEncoder::copy_texture_to_texture",
2544            );
2545        }
2546    }
2547
2548    fn begin_compute_pass(
2549        &self,
2550        desc: &crate::ComputePassDescriptor<'_>,
2551    ) -> dispatch::DispatchComputePass {
2552        let timestamp_writes =
2553            desc.timestamp_writes
2554                .as_ref()
2555                .map(|tw| wgc::command::PassTimestampWrites {
2556                    query_set: tw.query_set.inner.as_core().id,
2557                    beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2558                    end_of_pass_write_index: tw.end_of_pass_write_index,
2559                });
2560
2561        let (pass, err) = self.context.0.command_encoder_begin_compute_pass(
2562            self.id,
2563            &wgc::command::ComputePassDescriptor {
2564                label: desc.label.map(Borrowed),
2565                timestamp_writes,
2566            },
2567        );
2568
2569        if let Some(cause) = err {
2570            self.context.handle_error(
2571                &self.error_sink,
2572                cause,
2573                desc.label,
2574                "CommandEncoder::begin_compute_pass",
2575            );
2576        }
2577
2578        CoreComputePass {
2579            context: self.context.clone(),
2580            pass,
2581            error_sink: self.error_sink.clone(),
2582            id: crate::cmp::Identifier::create(),
2583        }
2584        .into()
2585    }
2586
2587    fn begin_render_pass(
2588        &self,
2589        desc: &crate::RenderPassDescriptor<'_>,
2590    ) -> dispatch::DispatchRenderPass {
2591        let colors = desc
2592            .color_attachments
2593            .iter()
2594            .map(|ca| {
2595                ca.as_ref()
2596                    .map(|at| wgc::command::RenderPassColorAttachment {
2597                        view: at.view.inner.as_core().id,
2598                        depth_slice: at.depth_slice,
2599                        resolve_target: at.resolve_target.map(|view| view.inner.as_core().id),
2600                        load_op: at.ops.load,
2601                        store_op: at.ops.store,
2602                    })
2603            })
2604            .collect::<Vec<_>>();
2605
2606        let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
2607            wgc::command::RenderPassDepthStencilAttachment {
2608                view: dsa.view.inner.as_core().id,
2609                depth: map_pass_channel(dsa.depth_ops.as_ref()),
2610                stencil: map_pass_channel(dsa.stencil_ops.as_ref()),
2611            }
2612        });
2613
2614        let timestamp_writes =
2615            desc.timestamp_writes
2616                .as_ref()
2617                .map(|tw| wgc::command::PassTimestampWrites {
2618                    query_set: tw.query_set.inner.as_core().id,
2619                    beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2620                    end_of_pass_write_index: tw.end_of_pass_write_index,
2621                });
2622
2623        let (pass, err) = self.context.0.command_encoder_begin_render_pass(
2624            self.id,
2625            &wgc::command::RenderPassDescriptor {
2626                label: desc.label.map(Borrowed),
2627                timestamp_writes: timestamp_writes.as_ref(),
2628                color_attachments: Borrowed(&colors),
2629                depth_stencil_attachment: depth_stencil.as_ref(),
2630                occlusion_query_set: desc.occlusion_query_set.map(|qs| qs.inner.as_core().id),
2631                multiview_mask: desc.multiview_mask,
2632            },
2633        );
2634
2635        if let Some(cause) = err {
2636            self.context.handle_error(
2637                &self.error_sink,
2638                cause,
2639                desc.label,
2640                "CommandEncoder::begin_render_pass",
2641            );
2642        }
2643
2644        CoreRenderPass {
2645            context: self.context.clone(),
2646            pass,
2647            error_sink: self.error_sink.clone(),
2648            id: crate::cmp::Identifier::create(),
2649        }
2650        .into()
2651    }
2652
2653    fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
2654        let descriptor = wgt::CommandBufferDescriptor::default();
2655        let (id, opt_label_and_error) =
2656            self.context
2657                .0
2658                .command_encoder_finish(self.id, &descriptor, None);
2659        if let Some((label, cause)) = opt_label_and_error {
2660            self.context
2661                .handle_error(&self.error_sink, cause, Some(&label), "a CommandEncoder");
2662        }
2663        CoreCommandBuffer {
2664            context: self.context.clone(),
2665            id,
2666        }
2667        .into()
2668    }
2669
2670    fn clear_texture(
2671        &self,
2672        texture: &dispatch::DispatchTexture,
2673        subresource_range: &crate::ImageSubresourceRange,
2674    ) {
2675        let texture = texture.as_core();
2676
2677        if let Err(cause) =
2678            self.context
2679                .0
2680                .command_encoder_clear_texture(self.id, texture.id, subresource_range)
2681        {
2682            self.context.handle_error_nolabel(
2683                &self.error_sink,
2684                cause,
2685                "CommandEncoder::clear_texture",
2686            );
2687        }
2688    }
2689
2690    fn clear_buffer(
2691        &self,
2692        buffer: &dispatch::DispatchBuffer,
2693        offset: crate::BufferAddress,
2694        size: Option<crate::BufferAddress>,
2695    ) {
2696        let buffer = buffer.as_core();
2697
2698        if let Err(cause) = self
2699            .context
2700            .0
2701            .command_encoder_clear_buffer(self.id, buffer.id, offset, size)
2702        {
2703            self.context.handle_error_nolabel(
2704                &self.error_sink,
2705                cause,
2706                "CommandEncoder::fill_buffer",
2707            );
2708        }
2709    }
2710
2711    fn insert_debug_marker(&self, label: &str) {
2712        if let Err(cause) = self
2713            .context
2714            .0
2715            .command_encoder_insert_debug_marker(self.id, label)
2716        {
2717            self.context.handle_error_nolabel(
2718                &self.error_sink,
2719                cause,
2720                "CommandEncoder::insert_debug_marker",
2721            );
2722        }
2723    }
2724
2725    fn push_debug_group(&self, label: &str) {
2726        if let Err(cause) = self
2727            .context
2728            .0
2729            .command_encoder_push_debug_group(self.id, label)
2730        {
2731            self.context.handle_error_nolabel(
2732                &self.error_sink,
2733                cause,
2734                "CommandEncoder::push_debug_group",
2735            );
2736        }
2737    }
2738
2739    fn pop_debug_group(&self) {
2740        if let Err(cause) = self.context.0.command_encoder_pop_debug_group(self.id) {
2741            self.context.handle_error_nolabel(
2742                &self.error_sink,
2743                cause,
2744                "CommandEncoder::pop_debug_group",
2745            );
2746        }
2747    }
2748
2749    fn write_timestamp(&self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2750        let query_set = query_set.as_core();
2751
2752        if let Err(cause) =
2753            self.context
2754                .0
2755                .command_encoder_write_timestamp(self.id, query_set.id, query_index)
2756        {
2757            self.context.handle_error_nolabel(
2758                &self.error_sink,
2759                cause,
2760                "CommandEncoder::write_timestamp",
2761            );
2762        }
2763    }
2764
2765    fn resolve_query_set(
2766        &self,
2767        query_set: &dispatch::DispatchQuerySet,
2768        first_query: u32,
2769        query_count: u32,
2770        destination: &dispatch::DispatchBuffer,
2771        destination_offset: crate::BufferAddress,
2772    ) {
2773        let query_set = query_set.as_core();
2774        let destination = destination.as_core();
2775
2776        if let Err(cause) = self.context.0.command_encoder_resolve_query_set(
2777            self.id,
2778            query_set.id,
2779            first_query,
2780            query_count,
2781            destination.id,
2782            destination_offset,
2783        ) {
2784            self.context.handle_error_nolabel(
2785                &self.error_sink,
2786                cause,
2787                "CommandEncoder::resolve_query_set",
2788            );
2789        }
2790    }
2791
2792    fn mark_acceleration_structures_built<'a>(
2793        &self,
2794        blas: &mut dyn Iterator<Item = &'a Blas>,
2795        tlas: &mut dyn Iterator<Item = &'a Tlas>,
2796    ) {
2797        let blas = blas
2798            .map(|b| b.inner.as_core().id)
2799            .collect::<SmallVec<[_; 4]>>();
2800        let tlas = tlas
2801            .map(|t| t.inner.as_core().id)
2802            .collect::<SmallVec<[_; 4]>>();
2803        if let Err(cause) = self
2804            .context
2805            .0
2806            .command_encoder_mark_acceleration_structures_built(self.id, &blas, &tlas)
2807        {
2808            self.context.handle_error_nolabel(
2809                &self.error_sink,
2810                cause,
2811                "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2812            );
2813        }
2814    }
2815
2816    fn build_acceleration_structures<'a>(
2817        &self,
2818        blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
2819        tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
2820    ) {
2821        let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| {
2822            let geometries = match e.geometry {
2823                crate::BlasGeometries::TriangleGeometries(ref triangle_geometries) => {
2824                    let iter = triangle_geometries.iter().map(|tg| {
2825                        wgc::ray_tracing::BlasTriangleGeometry {
2826                            vertex_buffer: tg.vertex_buffer.inner.as_core().id,
2827                            index_buffer: tg.index_buffer.map(|buf| buf.inner.as_core().id),
2828                            transform_buffer: tg.transform_buffer.map(|buf| buf.inner.as_core().id),
2829                            size: tg.size,
2830                            transform_buffer_offset: tg.transform_buffer_offset,
2831                            first_vertex: tg.first_vertex,
2832                            vertex_stride: tg.vertex_stride,
2833                            first_index: tg.first_index,
2834                        }
2835                    });
2836                    wgc::ray_tracing::BlasGeometries::TriangleGeometries(Box::new(iter))
2837                }
2838            };
2839            wgc::ray_tracing::BlasBuildEntry {
2840                blas_id: e.blas.inner.as_core().id,
2841                geometries,
2842            }
2843        });
2844
2845        let tlas = tlas.into_iter().map(|e| {
2846            let instances = e
2847                .instances
2848                .iter()
2849                .map(|instance: &Option<crate::TlasInstance>| {
2850                    instance
2851                        .as_ref()
2852                        .map(|instance| wgc::ray_tracing::TlasInstance {
2853                            blas_id: instance.blas.as_core().id,
2854                            transform: &instance.transform,
2855                            custom_data: instance.custom_data,
2856                            mask: instance.mask,
2857                        })
2858                });
2859            wgc::ray_tracing::TlasPackage {
2860                tlas_id: e.inner.as_core().id,
2861                instances: Box::new(instances),
2862                lowest_unmodified: e.lowest_unmodified,
2863            }
2864        });
2865
2866        if let Err(cause) = self
2867            .context
2868            .0
2869            .command_encoder_build_acceleration_structures(self.id, blas, tlas)
2870        {
2871            self.context.handle_error_nolabel(
2872                &self.error_sink,
2873                cause,
2874                "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2875            );
2876        }
2877    }
2878
2879    fn transition_resources<'a>(
2880        &mut self,
2881        buffer_transitions: &mut dyn Iterator<
2882            Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
2883        >,
2884        texture_transitions: &mut dyn Iterator<
2885            Item = wgt::TextureTransition<&'a dispatch::DispatchTexture>,
2886        >,
2887    ) {
2888        let result = self.context.0.command_encoder_transition_resources(
2889            self.id,
2890            buffer_transitions.map(|t| wgt::BufferTransition {
2891                buffer: t.buffer.as_core().id,
2892                state: t.state,
2893            }),
2894            texture_transitions.map(|t| wgt::TextureTransition {
2895                texture: t.texture.as_core().id,
2896                selector: t.selector.clone(),
2897                state: t.state,
2898            }),
2899        );
2900
2901        if let Err(cause) = result {
2902            self.context.handle_error_nolabel(
2903                &self.error_sink,
2904                cause,
2905                "CommandEncoder::transition_resources",
2906            );
2907        }
2908    }
2909}
2910
2911impl Drop for CoreCommandEncoder {
2912    fn drop(&mut self) {
2913        self.context.0.command_encoder_drop(self.id)
2914    }
2915}
2916
2917impl dispatch::CommandBufferInterface for CoreCommandBuffer {}
2918
2919impl Drop for CoreCommandBuffer {
2920    fn drop(&mut self) {
2921        self.context.0.command_buffer_drop(self.id)
2922    }
2923}
2924
2925impl dispatch::ComputePassInterface for CoreComputePass {
2926    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchComputePipeline) {
2927        let pipeline = pipeline.as_core();
2928
2929        if let Err(cause) = self
2930            .context
2931            .0
2932            .compute_pass_set_pipeline(&mut self.pass, pipeline.id)
2933        {
2934            self.context.handle_error(
2935                &self.error_sink,
2936                cause,
2937                self.pass.label(),
2938                "ComputePass::set_pipeline",
2939            );
2940        }
2941    }
2942
2943    fn set_bind_group(
2944        &mut self,
2945        index: u32,
2946        bind_group: Option<&dispatch::DispatchBindGroup>,
2947        offsets: &[crate::DynamicOffset],
2948    ) {
2949        let bg = bind_group.map(|bg| bg.as_core().id);
2950
2951        if let Err(cause) =
2952            self.context
2953                .0
2954                .compute_pass_set_bind_group(&mut self.pass, index, bg, offsets)
2955        {
2956            self.context.handle_error(
2957                &self.error_sink,
2958                cause,
2959                self.pass.label(),
2960                "ComputePass::set_bind_group",
2961            );
2962        }
2963    }
2964
2965    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
2966        if let Err(cause) = self
2967            .context
2968            .0
2969            .compute_pass_set_immediates(&mut self.pass, offset, data)
2970        {
2971            self.context.handle_error(
2972                &self.error_sink,
2973                cause,
2974                self.pass.label(),
2975                "ComputePass::set_immediates",
2976            );
2977        }
2978    }
2979
2980    fn insert_debug_marker(&mut self, label: &str) {
2981        if let Err(cause) =
2982            self.context
2983                .0
2984                .compute_pass_insert_debug_marker(&mut self.pass, label, 0)
2985        {
2986            self.context.handle_error(
2987                &self.error_sink,
2988                cause,
2989                self.pass.label(),
2990                "ComputePass::insert_debug_marker",
2991            );
2992        }
2993    }
2994
2995    fn push_debug_group(&mut self, group_label: &str) {
2996        if let Err(cause) =
2997            self.context
2998                .0
2999                .compute_pass_push_debug_group(&mut self.pass, group_label, 0)
3000        {
3001            self.context.handle_error(
3002                &self.error_sink,
3003                cause,
3004                self.pass.label(),
3005                "ComputePass::push_debug_group",
3006            );
3007        }
3008    }
3009
3010    fn pop_debug_group(&mut self) {
3011        if let Err(cause) = self.context.0.compute_pass_pop_debug_group(&mut self.pass) {
3012            self.context.handle_error(
3013                &self.error_sink,
3014                cause,
3015                self.pass.label(),
3016                "ComputePass::pop_debug_group",
3017            );
3018        }
3019    }
3020
3021    fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3022        let query_set = query_set.as_core();
3023
3024        if let Err(cause) =
3025            self.context
3026                .0
3027                .compute_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3028        {
3029            self.context.handle_error(
3030                &self.error_sink,
3031                cause,
3032                self.pass.label(),
3033                "ComputePass::write_timestamp",
3034            );
3035        }
3036    }
3037
3038    fn begin_pipeline_statistics_query(
3039        &mut self,
3040        query_set: &dispatch::DispatchQuerySet,
3041        query_index: u32,
3042    ) {
3043        let query_set = query_set.as_core();
3044
3045        if let Err(cause) = self.context.0.compute_pass_begin_pipeline_statistics_query(
3046            &mut self.pass,
3047            query_set.id,
3048            query_index,
3049        ) {
3050            self.context.handle_error(
3051                &self.error_sink,
3052                cause,
3053                self.pass.label(),
3054                "ComputePass::begin_pipeline_statistics_query",
3055            );
3056        }
3057    }
3058
3059    fn end_pipeline_statistics_query(&mut self) {
3060        if let Err(cause) = self
3061            .context
3062            .0
3063            .compute_pass_end_pipeline_statistics_query(&mut self.pass)
3064        {
3065            self.context.handle_error(
3066                &self.error_sink,
3067                cause,
3068                self.pass.label(),
3069                "ComputePass::end_pipeline_statistics_query",
3070            );
3071        }
3072    }
3073
3074    fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32) {
3075        if let Err(cause) = self
3076            .context
3077            .0
3078            .compute_pass_dispatch_workgroups(&mut self.pass, x, y, z)
3079        {
3080            self.context.handle_error(
3081                &self.error_sink,
3082                cause,
3083                self.pass.label(),
3084                "ComputePass::dispatch_workgroups",
3085            );
3086        }
3087    }
3088
3089    fn dispatch_workgroups_indirect(
3090        &mut self,
3091        indirect_buffer: &dispatch::DispatchBuffer,
3092        indirect_offset: crate::BufferAddress,
3093    ) {
3094        let indirect_buffer = indirect_buffer.as_core();
3095
3096        if let Err(cause) = self.context.0.compute_pass_dispatch_workgroups_indirect(
3097            &mut self.pass,
3098            indirect_buffer.id,
3099            indirect_offset,
3100        ) {
3101            self.context.handle_error(
3102                &self.error_sink,
3103                cause,
3104                self.pass.label(),
3105                "ComputePass::dispatch_workgroups_indirect",
3106            );
3107        }
3108    }
3109}
3110
3111impl Drop for CoreComputePass {
3112    fn drop(&mut self) {
3113        if let Err(cause) = self.context.0.compute_pass_end(&mut self.pass) {
3114            self.context.handle_error(
3115                &self.error_sink,
3116                cause,
3117                self.pass.label(),
3118                "ComputePass::end",
3119            );
3120        }
3121    }
3122}
3123
3124impl dispatch::RenderPassInterface for CoreRenderPass {
3125    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3126        let pipeline = pipeline.as_core();
3127
3128        if let Err(cause) = self
3129            .context
3130            .0
3131            .render_pass_set_pipeline(&mut self.pass, pipeline.id)
3132        {
3133            self.context.handle_error(
3134                &self.error_sink,
3135                cause,
3136                self.pass.label(),
3137                "RenderPass::set_pipeline",
3138            );
3139        }
3140    }
3141
3142    fn set_bind_group(
3143        &mut self,
3144        index: u32,
3145        bind_group: Option<&dispatch::DispatchBindGroup>,
3146        offsets: &[crate::DynamicOffset],
3147    ) {
3148        let bg = bind_group.map(|bg| bg.as_core().id);
3149
3150        if let Err(cause) =
3151            self.context
3152                .0
3153                .render_pass_set_bind_group(&mut self.pass, index, bg, offsets)
3154        {
3155            self.context.handle_error(
3156                &self.error_sink,
3157                cause,
3158                self.pass.label(),
3159                "RenderPass::set_bind_group",
3160            );
3161        }
3162    }
3163
3164    fn set_index_buffer(
3165        &mut self,
3166        buffer: &dispatch::DispatchBuffer,
3167        index_format: crate::IndexFormat,
3168        offset: crate::BufferAddress,
3169        size: Option<crate::BufferSize>,
3170    ) {
3171        let buffer = buffer.as_core();
3172
3173        if let Err(cause) = self.context.0.render_pass_set_index_buffer(
3174            &mut self.pass,
3175            buffer.id,
3176            index_format,
3177            offset,
3178            size,
3179        ) {
3180            self.context.handle_error(
3181                &self.error_sink,
3182                cause,
3183                self.pass.label(),
3184                "RenderPass::set_index_buffer",
3185            );
3186        }
3187    }
3188
3189    fn set_vertex_buffer(
3190        &mut self,
3191        slot: u32,
3192        buffer: &dispatch::DispatchBuffer,
3193        offset: crate::BufferAddress,
3194        size: Option<crate::BufferSize>,
3195    ) {
3196        let buffer = buffer.as_core();
3197
3198        if let Err(cause) = self.context.0.render_pass_set_vertex_buffer(
3199            &mut self.pass,
3200            slot,
3201            buffer.id,
3202            offset,
3203            size,
3204        ) {
3205            self.context.handle_error(
3206                &self.error_sink,
3207                cause,
3208                self.pass.label(),
3209                "RenderPass::set_vertex_buffer",
3210            );
3211        }
3212    }
3213
3214    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3215        if let Err(cause) = self
3216            .context
3217            .0
3218            .render_pass_set_immediates(&mut self.pass, offset, data)
3219        {
3220            self.context.handle_error(
3221                &self.error_sink,
3222                cause,
3223                self.pass.label(),
3224                "RenderPass::set_immediates",
3225            );
3226        }
3227    }
3228
3229    fn set_blend_constant(&mut self, color: crate::Color) {
3230        if let Err(cause) = self
3231            .context
3232            .0
3233            .render_pass_set_blend_constant(&mut self.pass, color)
3234        {
3235            self.context.handle_error(
3236                &self.error_sink,
3237                cause,
3238                self.pass.label(),
3239                "RenderPass::set_blend_constant",
3240            );
3241        }
3242    }
3243
3244    fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) {
3245        if let Err(cause) =
3246            self.context
3247                .0
3248                .render_pass_set_scissor_rect(&mut self.pass, x, y, width, height)
3249        {
3250            self.context.handle_error(
3251                &self.error_sink,
3252                cause,
3253                self.pass.label(),
3254                "RenderPass::set_scissor_rect",
3255            );
3256        }
3257    }
3258
3259    fn set_viewport(
3260        &mut self,
3261        x: f32,
3262        y: f32,
3263        width: f32,
3264        height: f32,
3265        min_depth: f32,
3266        max_depth: f32,
3267    ) {
3268        if let Err(cause) = self.context.0.render_pass_set_viewport(
3269            &mut self.pass,
3270            x,
3271            y,
3272            width,
3273            height,
3274            min_depth,
3275            max_depth,
3276        ) {
3277            self.context.handle_error(
3278                &self.error_sink,
3279                cause,
3280                self.pass.label(),
3281                "RenderPass::set_viewport",
3282            );
3283        }
3284    }
3285
3286    fn set_stencil_reference(&mut self, reference: u32) {
3287        if let Err(cause) = self
3288            .context
3289            .0
3290            .render_pass_set_stencil_reference(&mut self.pass, reference)
3291        {
3292            self.context.handle_error(
3293                &self.error_sink,
3294                cause,
3295                self.pass.label(),
3296                "RenderPass::set_stencil_reference",
3297            );
3298        }
3299    }
3300
3301    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3302        if let Err(cause) = self.context.0.render_pass_draw(
3303            &mut self.pass,
3304            vertices.end - vertices.start,
3305            instances.end - instances.start,
3306            vertices.start,
3307            instances.start,
3308        ) {
3309            self.context.handle_error(
3310                &self.error_sink,
3311                cause,
3312                self.pass.label(),
3313                "RenderPass::draw",
3314            );
3315        }
3316    }
3317
3318    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3319        if let Err(cause) = self.context.0.render_pass_draw_indexed(
3320            &mut self.pass,
3321            indices.end - indices.start,
3322            instances.end - instances.start,
3323            indices.start,
3324            base_vertex,
3325            instances.start,
3326        ) {
3327            self.context.handle_error(
3328                &self.error_sink,
3329                cause,
3330                self.pass.label(),
3331                "RenderPass::draw_indexed",
3332            );
3333        }
3334    }
3335
3336    fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
3337        if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks(
3338            &mut self.pass,
3339            group_count_x,
3340            group_count_y,
3341            group_count_z,
3342        ) {
3343            self.context.handle_error(
3344                &self.error_sink,
3345                cause,
3346                self.pass.label(),
3347                "RenderPass::draw_mesh_tasks",
3348            );
3349        }
3350    }
3351
3352    fn draw_indirect(
3353        &mut self,
3354        indirect_buffer: &dispatch::DispatchBuffer,
3355        indirect_offset: crate::BufferAddress,
3356    ) {
3357        let indirect_buffer = indirect_buffer.as_core();
3358
3359        if let Err(cause) = self.context.0.render_pass_draw_indirect(
3360            &mut self.pass,
3361            indirect_buffer.id,
3362            indirect_offset,
3363        ) {
3364            self.context.handle_error(
3365                &self.error_sink,
3366                cause,
3367                self.pass.label(),
3368                "RenderPass::draw_indirect",
3369            );
3370        }
3371    }
3372
3373    fn draw_indexed_indirect(
3374        &mut self,
3375        indirect_buffer: &dispatch::DispatchBuffer,
3376        indirect_offset: crate::BufferAddress,
3377    ) {
3378        let indirect_buffer = indirect_buffer.as_core();
3379
3380        if let Err(cause) = self.context.0.render_pass_draw_indexed_indirect(
3381            &mut self.pass,
3382            indirect_buffer.id,
3383            indirect_offset,
3384        ) {
3385            self.context.handle_error(
3386                &self.error_sink,
3387                cause,
3388                self.pass.label(),
3389                "RenderPass::draw_indexed_indirect",
3390            );
3391        }
3392    }
3393
3394    fn draw_mesh_tasks_indirect(
3395        &mut self,
3396        indirect_buffer: &dispatch::DispatchBuffer,
3397        indirect_offset: crate::BufferAddress,
3398    ) {
3399        let indirect_buffer = indirect_buffer.as_core();
3400
3401        if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks_indirect(
3402            &mut self.pass,
3403            indirect_buffer.id,
3404            indirect_offset,
3405        ) {
3406            self.context.handle_error(
3407                &self.error_sink,
3408                cause,
3409                self.pass.label(),
3410                "RenderPass::draw_mesh_tasks_indirect",
3411            );
3412        }
3413    }
3414
3415    fn multi_draw_indirect(
3416        &mut self,
3417        indirect_buffer: &dispatch::DispatchBuffer,
3418        indirect_offset: crate::BufferAddress,
3419        count: u32,
3420    ) {
3421        let indirect_buffer = indirect_buffer.as_core();
3422
3423        if let Err(cause) = self.context.0.render_pass_multi_draw_indirect(
3424            &mut self.pass,
3425            indirect_buffer.id,
3426            indirect_offset,
3427            count,
3428        ) {
3429            self.context.handle_error(
3430                &self.error_sink,
3431                cause,
3432                self.pass.label(),
3433                "RenderPass::multi_draw_indirect",
3434            );
3435        }
3436    }
3437
3438    fn multi_draw_indexed_indirect(
3439        &mut self,
3440        indirect_buffer: &dispatch::DispatchBuffer,
3441        indirect_offset: crate::BufferAddress,
3442        count: u32,
3443    ) {
3444        let indirect_buffer = indirect_buffer.as_core();
3445
3446        if let Err(cause) = self.context.0.render_pass_multi_draw_indexed_indirect(
3447            &mut self.pass,
3448            indirect_buffer.id,
3449            indirect_offset,
3450            count,
3451        ) {
3452            self.context.handle_error(
3453                &self.error_sink,
3454                cause,
3455                self.pass.label(),
3456                "RenderPass::multi_draw_indexed_indirect",
3457            );
3458        }
3459    }
3460
3461    fn multi_draw_mesh_tasks_indirect(
3462        &mut self,
3463        indirect_buffer: &dispatch::DispatchBuffer,
3464        indirect_offset: crate::BufferAddress,
3465        count: u32,
3466    ) {
3467        let indirect_buffer = indirect_buffer.as_core();
3468
3469        if let Err(cause) = self.context.0.render_pass_multi_draw_mesh_tasks_indirect(
3470            &mut self.pass,
3471            indirect_buffer.id,
3472            indirect_offset,
3473            count,
3474        ) {
3475            self.context.handle_error(
3476                &self.error_sink,
3477                cause,
3478                self.pass.label(),
3479                "RenderPass::multi_draw_mesh_tasks_indirect",
3480            );
3481        }
3482    }
3483
3484    fn multi_draw_indirect_count(
3485        &mut self,
3486        indirect_buffer: &dispatch::DispatchBuffer,
3487        indirect_offset: crate::BufferAddress,
3488        count_buffer: &dispatch::DispatchBuffer,
3489        count_buffer_offset: crate::BufferAddress,
3490        max_count: u32,
3491    ) {
3492        let indirect_buffer = indirect_buffer.as_core();
3493        let count_buffer = count_buffer.as_core();
3494
3495        if let Err(cause) = self.context.0.render_pass_multi_draw_indirect_count(
3496            &mut self.pass,
3497            indirect_buffer.id,
3498            indirect_offset,
3499            count_buffer.id,
3500            count_buffer_offset,
3501            max_count,
3502        ) {
3503            self.context.handle_error(
3504                &self.error_sink,
3505                cause,
3506                self.pass.label(),
3507                "RenderPass::multi_draw_indirect_count",
3508            );
3509        }
3510    }
3511
3512    fn multi_draw_indexed_indirect_count(
3513        &mut self,
3514        indirect_buffer: &dispatch::DispatchBuffer,
3515        indirect_offset: crate::BufferAddress,
3516        count_buffer: &dispatch::DispatchBuffer,
3517        count_buffer_offset: crate::BufferAddress,
3518        max_count: u32,
3519    ) {
3520        let indirect_buffer = indirect_buffer.as_core();
3521        let count_buffer = count_buffer.as_core();
3522
3523        if let Err(cause) = self
3524            .context
3525            .0
3526            .render_pass_multi_draw_indexed_indirect_count(
3527                &mut self.pass,
3528                indirect_buffer.id,
3529                indirect_offset,
3530                count_buffer.id,
3531                count_buffer_offset,
3532                max_count,
3533            )
3534        {
3535            self.context.handle_error(
3536                &self.error_sink,
3537                cause,
3538                self.pass.label(),
3539                "RenderPass::multi_draw_indexed_indirect_count",
3540            );
3541        }
3542    }
3543
3544    fn multi_draw_mesh_tasks_indirect_count(
3545        &mut self,
3546        indirect_buffer: &dispatch::DispatchBuffer,
3547        indirect_offset: crate::BufferAddress,
3548        count_buffer: &dispatch::DispatchBuffer,
3549        count_buffer_offset: crate::BufferAddress,
3550        max_count: u32,
3551    ) {
3552        let indirect_buffer = indirect_buffer.as_core();
3553        let count_buffer = count_buffer.as_core();
3554
3555        if let Err(cause) = self
3556            .context
3557            .0
3558            .render_pass_multi_draw_mesh_tasks_indirect_count(
3559                &mut self.pass,
3560                indirect_buffer.id,
3561                indirect_offset,
3562                count_buffer.id,
3563                count_buffer_offset,
3564                max_count,
3565            )
3566        {
3567            self.context.handle_error(
3568                &self.error_sink,
3569                cause,
3570                self.pass.label(),
3571                "RenderPass::multi_draw_mesh_tasks_indirect_count",
3572            );
3573        }
3574    }
3575
3576    fn insert_debug_marker(&mut self, label: &str) {
3577        if let Err(cause) = self
3578            .context
3579            .0
3580            .render_pass_insert_debug_marker(&mut self.pass, label, 0)
3581        {
3582            self.context.handle_error(
3583                &self.error_sink,
3584                cause,
3585                self.pass.label(),
3586                "RenderPass::insert_debug_marker",
3587            );
3588        }
3589    }
3590
3591    fn push_debug_group(&mut self, group_label: &str) {
3592        if let Err(cause) =
3593            self.context
3594                .0
3595                .render_pass_push_debug_group(&mut self.pass, group_label, 0)
3596        {
3597            self.context.handle_error(
3598                &self.error_sink,
3599                cause,
3600                self.pass.label(),
3601                "RenderPass::push_debug_group",
3602            );
3603        }
3604    }
3605
3606    fn pop_debug_group(&mut self) {
3607        if let Err(cause) = self.context.0.render_pass_pop_debug_group(&mut self.pass) {
3608            self.context.handle_error(
3609                &self.error_sink,
3610                cause,
3611                self.pass.label(),
3612                "RenderPass::pop_debug_group",
3613            );
3614        }
3615    }
3616
3617    fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3618        let query_set = query_set.as_core();
3619
3620        if let Err(cause) =
3621            self.context
3622                .0
3623                .render_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3624        {
3625            self.context.handle_error(
3626                &self.error_sink,
3627                cause,
3628                self.pass.label(),
3629                "RenderPass::write_timestamp",
3630            );
3631        }
3632    }
3633
3634    fn begin_occlusion_query(&mut self, query_index: u32) {
3635        if let Err(cause) = self
3636            .context
3637            .0
3638            .render_pass_begin_occlusion_query(&mut self.pass, query_index)
3639        {
3640            self.context.handle_error(
3641                &self.error_sink,
3642                cause,
3643                self.pass.label(),
3644                "RenderPass::begin_occlusion_query",
3645            );
3646        }
3647    }
3648
3649    fn end_occlusion_query(&mut self) {
3650        if let Err(cause) = self
3651            .context
3652            .0
3653            .render_pass_end_occlusion_query(&mut self.pass)
3654        {
3655            self.context.handle_error(
3656                &self.error_sink,
3657                cause,
3658                self.pass.label(),
3659                "RenderPass::end_occlusion_query",
3660            );
3661        }
3662    }
3663
3664    fn begin_pipeline_statistics_query(
3665        &mut self,
3666        query_set: &dispatch::DispatchQuerySet,
3667        query_index: u32,
3668    ) {
3669        let query_set = query_set.as_core();
3670
3671        if let Err(cause) = self.context.0.render_pass_begin_pipeline_statistics_query(
3672            &mut self.pass,
3673            query_set.id,
3674            query_index,
3675        ) {
3676            self.context.handle_error(
3677                &self.error_sink,
3678                cause,
3679                self.pass.label(),
3680                "RenderPass::begin_pipeline_statistics_query",
3681            );
3682        }
3683    }
3684
3685    fn end_pipeline_statistics_query(&mut self) {
3686        if let Err(cause) = self
3687            .context
3688            .0
3689            .render_pass_end_pipeline_statistics_query(&mut self.pass)
3690        {
3691            self.context.handle_error(
3692                &self.error_sink,
3693                cause,
3694                self.pass.label(),
3695                "RenderPass::end_pipeline_statistics_query",
3696            );
3697        }
3698    }
3699
3700    fn execute_bundles(
3701        &mut self,
3702        render_bundles: &mut dyn Iterator<Item = &dispatch::DispatchRenderBundle>,
3703    ) {
3704        let temp_render_bundles = render_bundles
3705            .map(|rb| rb.as_core().id)
3706            .collect::<SmallVec<[_; 4]>>();
3707        if let Err(cause) = self
3708            .context
3709            .0
3710            .render_pass_execute_bundles(&mut self.pass, &temp_render_bundles)
3711        {
3712            self.context.handle_error(
3713                &self.error_sink,
3714                cause,
3715                self.pass.label(),
3716                "RenderPass::execute_bundles",
3717            );
3718        }
3719    }
3720}
3721
3722impl Drop for CoreRenderPass {
3723    fn drop(&mut self) {
3724        if let Err(cause) = self.context.0.render_pass_end(&mut self.pass) {
3725            self.context.handle_error(
3726                &self.error_sink,
3727                cause,
3728                self.pass.label(),
3729                "RenderPass::end",
3730            );
3731        }
3732    }
3733}
3734
3735impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder {
3736    fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3737        let pipeline = pipeline.as_core();
3738
3739        wgpu_render_bundle_set_pipeline(&mut self.encoder, pipeline.id)
3740    }
3741
3742    fn set_bind_group(
3743        &mut self,
3744        index: u32,
3745        bind_group: Option<&dispatch::DispatchBindGroup>,
3746        offsets: &[crate::DynamicOffset],
3747    ) {
3748        let bg = bind_group.map(|bg| bg.as_core().id);
3749
3750        unsafe {
3751            wgpu_render_bundle_set_bind_group(
3752                &mut self.encoder,
3753                index,
3754                bg,
3755                offsets.as_ptr(),
3756                offsets.len(),
3757            )
3758        }
3759    }
3760
3761    fn set_index_buffer(
3762        &mut self,
3763        buffer: &dispatch::DispatchBuffer,
3764        index_format: crate::IndexFormat,
3765        offset: crate::BufferAddress,
3766        size: Option<crate::BufferSize>,
3767    ) {
3768        let buffer = buffer.as_core();
3769
3770        self.encoder
3771            .set_index_buffer(buffer.id, index_format, offset, size)
3772    }
3773
3774    fn set_vertex_buffer(
3775        &mut self,
3776        slot: u32,
3777        buffer: &dispatch::DispatchBuffer,
3778        offset: crate::BufferAddress,
3779        size: Option<crate::BufferSize>,
3780    ) {
3781        let buffer = buffer.as_core();
3782
3783        wgpu_render_bundle_set_vertex_buffer(&mut self.encoder, slot, buffer.id, offset, size)
3784    }
3785
3786    fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3787        unsafe {
3788            wgpu_render_bundle_set_immediates(
3789                &mut self.encoder,
3790                offset,
3791                data.len().try_into().unwrap(),
3792                data.as_ptr(),
3793            )
3794        }
3795    }
3796
3797    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3798        wgpu_render_bundle_draw(
3799            &mut self.encoder,
3800            vertices.end - vertices.start,
3801            instances.end - instances.start,
3802            vertices.start,
3803            instances.start,
3804        )
3805    }
3806
3807    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3808        wgpu_render_bundle_draw_indexed(
3809            &mut self.encoder,
3810            indices.end - indices.start,
3811            instances.end - instances.start,
3812            indices.start,
3813            base_vertex,
3814            instances.start,
3815        )
3816    }
3817
3818    fn draw_indirect(
3819        &mut self,
3820        indirect_buffer: &dispatch::DispatchBuffer,
3821        indirect_offset: crate::BufferAddress,
3822    ) {
3823        let indirect_buffer = indirect_buffer.as_core();
3824
3825        wgpu_render_bundle_draw_indirect(&mut self.encoder, indirect_buffer.id, indirect_offset)
3826    }
3827
3828    fn draw_indexed_indirect(
3829        &mut self,
3830        indirect_buffer: &dispatch::DispatchBuffer,
3831        indirect_offset: crate::BufferAddress,
3832    ) {
3833        let indirect_buffer = indirect_buffer.as_core();
3834
3835        wgpu_render_bundle_draw_indexed_indirect(
3836            &mut self.encoder,
3837            indirect_buffer.id,
3838            indirect_offset,
3839        )
3840    }
3841
3842    fn finish(self, desc: &crate::RenderBundleDescriptor<'_>) -> dispatch::DispatchRenderBundle
3843    where
3844        Self: Sized,
3845    {
3846        let (id, error) = self.context.0.render_bundle_encoder_finish(
3847            self.encoder,
3848            &desc.map_label(|l| l.map(Borrowed)),
3849            None,
3850        );
3851        if let Some(err) = error {
3852            self.context
3853                .handle_error_fatal(err, "RenderBundleEncoder::finish");
3854        }
3855        CoreRenderBundle {
3856            context: self.context.clone(),
3857            id,
3858        }
3859        .into()
3860    }
3861}
3862
3863impl dispatch::RenderBundleInterface for CoreRenderBundle {}
3864
3865impl Drop for CoreRenderBundle {
3866    fn drop(&mut self) {
3867        self.context.0.render_bundle_drop(self.id)
3868    }
3869}
3870
3871impl dispatch::SurfaceInterface for CoreSurface {
3872    fn get_capabilities(&self, adapter: &dispatch::DispatchAdapter) -> wgt::SurfaceCapabilities {
3873        let adapter = adapter.as_core();
3874
3875        self.context
3876            .0
3877            .surface_get_capabilities(self.id, adapter.id)
3878            .unwrap_or_default()
3879    }
3880
3881    fn configure(&self, device: &dispatch::DispatchDevice, config: &crate::SurfaceConfiguration) {
3882        let device = device.as_core();
3883
3884        let error = self.context.0.surface_configure(self.id, device.id, config);
3885        if let Some(e) = error {
3886            self.context
3887                .handle_error_nolabel(&device.error_sink, e, "Surface::configure");
3888        } else {
3889            *self.configured_device.lock() = Some(device.id);
3890            *self.error_sink.lock() = Some(device.error_sink.clone());
3891        }
3892    }
3893
3894    fn get_current_texture(
3895        &self,
3896    ) -> (
3897        Option<dispatch::DispatchTexture>,
3898        crate::SurfaceStatus,
3899        dispatch::DispatchSurfaceOutputDetail,
3900    ) {
3901        let error_sink = if let Some(error_sink) = self.error_sink.lock().as_ref() {
3902            error_sink.clone()
3903        } else {
3904            Arc::new(Mutex::new(ErrorSinkRaw::new()))
3905        };
3906
3907        let output_detail = CoreSurfaceOutputDetail {
3908            context: self.context.clone(),
3909            surface_id: self.id,
3910            error_sink: error_sink.clone(),
3911        }
3912        .into();
3913
3914        match self.context.0.surface_get_current_texture(self.id, None) {
3915            Ok(wgc::present::SurfaceOutput {
3916                status,
3917                texture: texture_id,
3918            }) => {
3919                let data = texture_id
3920                    .map(|id| CoreTexture {
3921                        context: self.context.clone(),
3922                        id,
3923                        error_sink,
3924                    })
3925                    .map(Into::into);
3926
3927                (data, status, output_detail)
3928            }
3929            Err(err) => {
3930                let error_sink = self.error_sink.lock();
3931                match error_sink.as_ref() {
3932                    Some(error_sink) => {
3933                        self.context.handle_error_nolabel(
3934                            error_sink,
3935                            err,
3936                            "Surface::get_current_texture_view",
3937                        );
3938                        (None, crate::SurfaceStatus::Validation, output_detail)
3939                    }
3940                    None => self
3941                        .context
3942                        .handle_error_fatal(err, "Surface::get_current_texture_view"),
3943                }
3944            }
3945        }
3946    }
3947}
3948
3949impl Drop for CoreSurface {
3950    fn drop(&mut self) {
3951        self.context.0.surface_drop(self.id)
3952    }
3953}
3954
3955impl dispatch::SurfaceOutputDetailInterface for CoreSurfaceOutputDetail {
3956    fn present(&self) {
3957        match self.context.0.surface_present(self.surface_id) {
3958            Ok(_status) => (),
3959            Err(err) => {
3960                self.context
3961                    .handle_error_nolabel(&self.error_sink, err, "Surface::present");
3962            }
3963        }
3964    }
3965
3966    fn texture_discard(&self) {
3967        match self.context.0.surface_texture_discard(self.surface_id) {
3968            Ok(_status) => (),
3969            Err(err) => self
3970                .context
3971                .handle_error_fatal(err, "Surface::discard_texture"),
3972        }
3973    }
3974}
3975impl Drop for CoreSurfaceOutputDetail {
3976    fn drop(&mut self) {
3977        // Discard gets called by the api struct
3978
3979        // no-op
3980    }
3981}
3982
3983impl dispatch::QueueWriteBufferInterface for CoreQueueWriteBuffer {
3984    #[inline]
3985    fn len(&self) -> usize {
3986        self.mapping.len()
3987    }
3988
3989    #[inline]
3990    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
3991        unsafe { self.mapping.write_slice() }
3992    }
3993}
3994impl Drop for CoreQueueWriteBuffer {
3995    fn drop(&mut self) {
3996        // The api struct calls queue.write_staging_buffer
3997
3998        // no-op
3999    }
4000}
4001
4002impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange {
4003    #[inline]
4004    fn len(&self) -> usize {
4005        self.size
4006    }
4007
4008    #[inline]
4009    unsafe fn read_slice(&self) -> &[u8] {
4010        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.size) }
4011    }
4012
4013    #[inline]
4014    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
4015        unsafe { WriteOnly::new(NonNull::slice_from_raw_parts(self.ptr, self.size)) }
4016    }
4017
4018    #[cfg(webgpu)]
4019    fn as_uint8array(&self) -> &js_sys::Uint8Array {
4020        panic!("Only available on WebGPU")
4021    }
4022}