Skip to main content

wgpu/
dispatch.rs

1//! Infrastructure for dispatching calls to the appropriate "backend". The "backends" are:
2//!
3//! - `wgpu_core`: An implementation of the the wgpu api on top of various native graphics APIs.
4//! - `webgpu`: An implementation of the wgpu api which calls WebGPU directly.
5//!
6//! The interface traits are all object safe and listed in the `InterfaceTypes` trait.
7//!
8//! The method for dispatching should optimize well if only one backend is
9//! compiled in, as-if there was no dispatching at all. See the comments on
10//! [`dispatch_types`] for details.
11//!
12//! [`dispatch_types`]: macro.dispatch_types.html
13
14#![allow(
15    drop_bounds,
16    reason = "This exists to remind implementors to impl drop."
17)]
18#![allow(clippy::too_many_arguments, reason = "It's fine.")]
19#![allow(
20    missing_docs,
21    clippy::missing_safety_doc,
22    reason = "Interfaces are not documented"
23)]
24#![allow(
25    clippy::len_without_is_empty,
26    reason = "trait is minimal, not ergonomic"
27)]
28
29use crate::{Blas, Tlas, WasmNotSend, WasmNotSendSync, WriteOnly};
30
31use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
32use core::{any::Any, fmt::Debug, future::Future, hash::Hash, ops::Range, pin::Pin};
33
34#[cfg(custom)]
35use crate::backend::custom::*;
36#[cfg(webgpu)]
37use crate::backend::webgpu::*;
38#[cfg(wgpu_core)]
39use crate::backend::wgpu_core::*;
40
41/// Create a single trait with the given supertraits and a blanket impl for all types that implement them.
42///
43/// This is useful for creating a trait alias as a shorthand.
44macro_rules! trait_alias {
45    ($name:ident: $($bound:tt)+) => {
46        pub trait $name: $($bound)+ {}
47        impl<T: $($bound)+> $name for T {}
48    };
49}
50
51// Various return futures in the API.
52trait_alias!(RequestAdapterFuture: Future<Output = Result<DispatchAdapter, wgt::RequestAdapterError>> + WasmNotSend + 'static);
53trait_alias!(RequestDeviceFuture: Future<Output = Result<(DispatchDevice, DispatchQueue), crate::RequestDeviceError>> + WasmNotSend + 'static);
54trait_alias!(PopErrorScopeFuture: Future<Output = Option<crate::Error>> + WasmNotSend + 'static);
55trait_alias!(ShaderCompilationInfoFuture: Future<Output = crate::CompilationInfo> + WasmNotSend + 'static);
56trait_alias!(EnumerateAdapterFuture: Future<Output = Vec<DispatchAdapter>> + WasmNotSend + 'static);
57
58// We can't use trait aliases here, as you can't convert from a dyn Trait to dyn Supertrait _yet_.
59#[cfg(send_sync)]
60pub type BoxDeviceLostCallback = Box<dyn FnOnce(crate::DeviceLostReason, String) + Send + 'static>;
61#[cfg(not(send_sync))]
62pub type BoxDeviceLostCallback = Box<dyn FnOnce(crate::DeviceLostReason, String) + 'static>;
63#[cfg(send_sync)]
64pub type BoxSubmittedWorkDoneCallback = Box<dyn FnOnce() + Send + 'static>;
65#[cfg(not(send_sync))]
66pub type BoxSubmittedWorkDoneCallback = Box<dyn FnOnce() + 'static>;
67#[cfg(send_sync)]
68pub type BufferMapCallback = Box<dyn FnOnce(Result<(), crate::BufferAsyncError>) + Send + 'static>;
69#[cfg(not(send_sync))]
70pub type BufferMapCallback = Box<dyn FnOnce(Result<(), crate::BufferAsyncError>) + 'static>;
71
72#[cfg(send_sync)]
73pub type BlasCompactCallback = Box<dyn FnOnce(Result<(), crate::BlasAsyncError>) + Send + 'static>;
74#[cfg(not(send_sync))]
75pub type BlasCompactCallback = Box<dyn FnOnce(Result<(), crate::BlasAsyncError>) + 'static>;
76
77// remove when rust 1.86
78#[cfg_attr(not(custom), expect(dead_code))]
79pub trait AsAny {
80    fn as_any(&self) -> &dyn Any;
81}
82
83impl<T: 'static> AsAny for T {
84    fn as_any(&self) -> &dyn Any {
85        self
86    }
87}
88
89// Common traits on all the interface traits
90trait_alias!(CommonTraits: AsAny + Any + Debug + WasmNotSendSync);
91
92pub trait InstanceInterface: CommonTraits {
93    fn new(desc: crate::InstanceDescriptor) -> Self
94    where
95        Self: Sized;
96
97    unsafe fn create_surface(
98        &self,
99        target: crate::SurfaceTargetUnsafe,
100    ) -> Result<DispatchSurface, crate::CreateSurfaceError>;
101
102    fn request_adapter(
103        &self,
104        options: &crate::RequestAdapterOptions<'_, '_>,
105    ) -> Pin<Box<dyn RequestAdapterFuture>>;
106
107    fn poll_all_devices(&self, force_wait: bool) -> bool;
108
109    #[cfg(feature = "wgsl")]
110    fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures;
111
112    fn enumerate_adapters(&self, backends: crate::Backends)
113        -> Pin<Box<dyn EnumerateAdapterFuture>>;
114}
115
116pub trait AdapterInterface: CommonTraits {
117    fn request_device(
118        &self,
119        desc: &crate::DeviceDescriptor<'_>,
120    ) -> Pin<Box<dyn RequestDeviceFuture>>;
121
122    fn is_surface_supported(&self, surface: &DispatchSurface) -> bool;
123
124    fn features(&self) -> crate::Features;
125
126    fn limits(&self) -> crate::Limits;
127
128    fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities;
129
130    fn get_info(&self) -> crate::AdapterInfo;
131
132    fn get_texture_format_features(
133        &self,
134        format: crate::TextureFormat,
135    ) -> crate::TextureFormatFeatures;
136
137    fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp;
138
139    fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties>;
140}
141
142pub trait DeviceInterface: CommonTraits {
143    fn features(&self) -> crate::Features;
144    fn limits(&self) -> crate::Limits;
145    fn adapter_info(&self) -> crate::AdapterInfo;
146
147    fn create_shader_module(
148        &self,
149        desc: crate::ShaderModuleDescriptor<'_>,
150        shader_bound_checks: crate::ShaderRuntimeChecks,
151    ) -> DispatchShaderModule;
152
153    unsafe fn create_shader_module_passthrough(
154        &self,
155        desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
156    ) -> DispatchShaderModule;
157
158    fn create_bind_group_layout(
159        &self,
160        desc: &crate::BindGroupLayoutDescriptor<'_>,
161    ) -> DispatchBindGroupLayout;
162    fn create_bind_group(&self, desc: &crate::BindGroupDescriptor<'_>) -> DispatchBindGroup;
163    fn create_pipeline_layout(
164        &self,
165        desc: &crate::PipelineLayoutDescriptor<'_>,
166    ) -> DispatchPipelineLayout;
167    fn create_render_pipeline(
168        &self,
169        desc: &crate::RenderPipelineDescriptor<'_>,
170    ) -> DispatchRenderPipeline;
171    fn create_mesh_pipeline(
172        &self,
173        desc: &crate::MeshPipelineDescriptor<'_>,
174    ) -> DispatchRenderPipeline;
175    fn create_compute_pipeline(
176        &self,
177        desc: &crate::ComputePipelineDescriptor<'_>,
178    ) -> DispatchComputePipeline;
179    unsafe fn create_pipeline_cache(
180        &self,
181        desc: &crate::PipelineCacheDescriptor<'_>,
182    ) -> DispatchPipelineCache;
183    fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> DispatchBuffer;
184    fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> DispatchTexture;
185    fn create_external_texture(
186        &self,
187        desc: &crate::ExternalTextureDescriptor<'_>,
188        planes: &[&crate::TextureView],
189    ) -> DispatchExternalTexture;
190    fn create_blas(
191        &self,
192        desc: &crate::CreateBlasDescriptor<'_>,
193        sizes: crate::BlasGeometrySizeDescriptors,
194    ) -> (Option<u64>, DispatchBlas);
195    fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> DispatchTlas;
196    fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> DispatchSampler;
197    fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> DispatchQuerySet;
198    fn create_command_encoder(
199        &self,
200        desc: &crate::CommandEncoderDescriptor<'_>,
201    ) -> DispatchCommandEncoder;
202    fn create_render_bundle_encoder(
203        &self,
204        desc: &crate::RenderBundleEncoderDescriptor<'_>,
205    ) -> DispatchRenderBundleEncoder;
206
207    fn set_device_lost_callback(&self, device_lost_callback: BoxDeviceLostCallback);
208
209    fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>);
210    // Returns index on the stack of the pushed error scope.
211    fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32;
212    fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn PopErrorScopeFuture>>;
213
214    unsafe fn start_graphics_debugger_capture(&self);
215    unsafe fn stop_graphics_debugger_capture(&self);
216
217    fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError>;
218
219    fn get_internal_counters(&self) -> crate::InternalCounters;
220    fn generate_allocator_report(&self) -> Option<crate::AllocatorReport>;
221
222    fn destroy(&self);
223}
224
225pub trait QueueInterface: CommonTraits {
226    fn write_buffer(&self, buffer: &DispatchBuffer, offset: crate::BufferAddress, data: &[u8]);
227
228    fn create_staging_buffer(&self, size: crate::BufferSize) -> Option<DispatchQueueWriteBuffer>;
229    fn validate_write_buffer(
230        &self,
231        buffer: &DispatchBuffer,
232        offset: crate::BufferAddress,
233        size: crate::BufferSize,
234    ) -> Option<()>;
235    fn write_staging_buffer(
236        &self,
237        buffer: &DispatchBuffer,
238        offset: crate::BufferAddress,
239        staging_buffer: &DispatchQueueWriteBuffer,
240    );
241
242    fn write_texture(
243        &self,
244        texture: crate::TexelCopyTextureInfo<'_>,
245        data: &[u8],
246        data_layout: crate::TexelCopyBufferLayout,
247        size: crate::Extent3d,
248    );
249    #[cfg(web)]
250    fn copy_external_image_to_texture(
251        &self,
252        source: &crate::CopyExternalImageSourceInfo,
253        dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
254        size: crate::Extent3d,
255    );
256
257    /// Submit must always drain the iterator, even in the case of error.
258    fn submit(&self, command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>) -> u64;
259
260    fn get_timestamp_period(&self) -> f32;
261    fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback);
262
263    fn compact_blas(&self, blas: &DispatchBlas) -> (Option<u64>, DispatchBlas);
264
265    fn present(&self, detail: &DispatchSurfaceOutputDetail);
266}
267
268pub trait ShaderModuleInterface: CommonTraits {
269    fn get_compilation_info(&self) -> Pin<Box<dyn ShaderCompilationInfoFuture>>;
270}
271pub trait BindGroupLayoutInterface: CommonTraits {}
272pub trait BindGroupInterface: CommonTraits {}
273pub trait TextureViewInterface: CommonTraits {}
274pub trait SamplerInterface: CommonTraits {}
275pub trait BufferInterface: CommonTraits {
276    fn map_async(
277        &self,
278        mode: crate::MapMode,
279        range: Range<crate::BufferAddress>,
280        callback: BufferMapCallback,
281    );
282    fn get_mapped_range(
283        &self,
284        sub_range: Range<crate::BufferAddress>,
285    ) -> Result<DispatchBufferMappedRange, crate::MapRangeError>;
286
287    fn unmap(&self);
288
289    fn destroy(&self);
290}
291pub trait TextureInterface: CommonTraits {
292    fn create_view(&self, desc: &crate::TextureViewDescriptor<'_>) -> DispatchTextureView;
293
294    fn destroy(&self);
295}
296pub trait ExternalTextureInterface: CommonTraits {
297    fn destroy(&self);
298}
299pub trait BlasInterface: CommonTraits {
300    fn prepare_compact_async(&self, callback: BlasCompactCallback);
301    fn ready_for_compaction(&self) -> bool;
302}
303pub trait TlasInterface: CommonTraits {}
304pub trait QuerySetInterface: CommonTraits {
305    fn destroy(&self);
306}
307pub trait PipelineLayoutInterface: CommonTraits {}
308pub trait RenderPipelineInterface: CommonTraits {
309    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
310}
311pub trait ComputePipelineInterface: CommonTraits {
312    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
313}
314pub trait PipelineCacheInterface: CommonTraits {
315    fn get_data(&self) -> Option<Vec<u8>>;
316}
317pub trait CommandEncoderInterface: CommonTraits {
318    fn copy_buffer_to_buffer(
319        &self,
320        source: &DispatchBuffer,
321        source_offset: crate::BufferAddress,
322        destination: &DispatchBuffer,
323        destination_offset: crate::BufferAddress,
324        copy_size: Option<crate::BufferAddress>,
325    );
326    fn copy_buffer_to_texture(
327        &self,
328        source: crate::TexelCopyBufferInfo<'_>,
329        destination: crate::TexelCopyTextureInfo<'_>,
330        copy_size: crate::Extent3d,
331    );
332    fn copy_texture_to_buffer(
333        &self,
334        source: crate::TexelCopyTextureInfo<'_>,
335        destination: crate::TexelCopyBufferInfo<'_>,
336        copy_size: crate::Extent3d,
337    );
338    fn copy_texture_to_texture(
339        &self,
340        source: crate::TexelCopyTextureInfo<'_>,
341        destination: crate::TexelCopyTextureInfo<'_>,
342        copy_size: crate::Extent3d,
343    );
344
345    fn begin_compute_pass(&self, desc: &crate::ComputePassDescriptor<'_>) -> DispatchComputePass;
346    fn begin_render_pass(&self, desc: &crate::RenderPassDescriptor<'_>) -> DispatchRenderPass;
347    fn finish(&mut self) -> DispatchCommandBuffer;
348
349    fn clear_texture(
350        &self,
351        texture: &DispatchTexture,
352        subresource_range: &crate::ImageSubresourceRange,
353    );
354    fn clear_buffer(
355        &self,
356        buffer: &DispatchBuffer,
357        offset: crate::BufferAddress,
358        size: Option<crate::BufferAddress>,
359    );
360
361    fn insert_debug_marker(&self, label: &str);
362    fn push_debug_group(&self, label: &str);
363    fn pop_debug_group(&self);
364
365    fn write_timestamp(&self, query_set: &DispatchQuerySet, query_index: u32);
366    fn resolve_query_set(
367        &self,
368        query_set: &DispatchQuerySet,
369        first_query: u32,
370        query_count: u32,
371        destination: &DispatchBuffer,
372        destination_offset: crate::BufferAddress,
373    );
374    fn mark_acceleration_structures_built<'a>(
375        &self,
376        blas: &mut dyn Iterator<Item = &'a Blas>,
377        tlas: &mut dyn Iterator<Item = &'a Tlas>,
378    );
379
380    fn build_acceleration_structures<'a>(
381        &self,
382        blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
383        tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
384    );
385
386    fn transition_resources<'a>(
387        &mut self,
388        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
389        texture_transitions: &mut dyn Iterator<Item = wgt::TextureTransition<&'a DispatchTexture>>,
390    );
391}
392pub trait ComputePassInterface: CommonTraits + Drop {
393    fn set_pipeline(&mut self, pipeline: &DispatchComputePipeline);
394    fn set_bind_group(
395        &mut self,
396        index: u32,
397        bind_group: Option<&DispatchBindGroup>,
398        offsets: &[crate::DynamicOffset],
399    );
400    fn set_immediates(&mut self, offset: u32, data: &[u8]);
401
402    fn insert_debug_marker(&mut self, label: &str);
403    fn push_debug_group(&mut self, group_label: &str);
404    fn pop_debug_group(&mut self);
405
406    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
407    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
408    fn end_pipeline_statistics_query(&mut self);
409
410    fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32);
411    fn dispatch_workgroups_indirect(
412        &mut self,
413        indirect_buffer: &DispatchBuffer,
414        indirect_offset: crate::BufferAddress,
415    );
416
417    fn transition_resources<'a>(
418        &mut self,
419        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
420        texture_transitions: &mut dyn Iterator<
421            Item = wgt::TextureTransition<&'a DispatchTextureView>,
422        >,
423    );
424}
425pub trait RenderPassInterface: CommonTraits + Drop {
426    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
427    fn set_bind_group(
428        &mut self,
429        index: u32,
430        bind_group: Option<&DispatchBindGroup>,
431        offsets: &[crate::DynamicOffset],
432    );
433    fn set_index_buffer(
434        &mut self,
435        buffer: &DispatchBuffer,
436        index_format: crate::IndexFormat,
437        offset: crate::BufferAddress,
438        size: Option<crate::BufferSize>,
439    );
440    fn set_vertex_buffer(
441        &mut self,
442        slot: u32,
443        buffer: Option<&DispatchBuffer>,
444        offset: crate::BufferAddress,
445        size: Option<crate::BufferSize>,
446    );
447    fn set_immediates(&mut self, offset: u32, data: &[u8]);
448    fn set_blend_constant(&mut self, color: crate::Color);
449    fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32);
450    fn set_viewport(
451        &mut self,
452        x: f32,
453        y: f32,
454        width: f32,
455        height: f32,
456        min_depth: f32,
457        max_depth: f32,
458    );
459    fn set_stencil_reference(&mut self, reference: u32);
460
461    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
462    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
463    fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32);
464    fn draw_indirect(
465        &mut self,
466        indirect_buffer: &DispatchBuffer,
467        indirect_offset: crate::BufferAddress,
468    );
469    fn draw_indexed_indirect(
470        &mut self,
471        indirect_buffer: &DispatchBuffer,
472        indirect_offset: crate::BufferAddress,
473    );
474    fn draw_mesh_tasks_indirect(
475        &mut self,
476        indirect_buffer: &DispatchBuffer,
477        indirect_offset: crate::BufferAddress,
478    );
479
480    fn multi_draw_indirect(
481        &mut self,
482        indirect_buffer: &DispatchBuffer,
483        indirect_offset: crate::BufferAddress,
484        count: u32,
485    );
486    fn multi_draw_indexed_indirect(
487        &mut self,
488        indirect_buffer: &DispatchBuffer,
489        indirect_offset: crate::BufferAddress,
490        count: u32,
491    );
492    fn multi_draw_indirect_count(
493        &mut self,
494        indirect_buffer: &DispatchBuffer,
495        indirect_offset: crate::BufferAddress,
496        count_buffer: &DispatchBuffer,
497        count_buffer_offset: crate::BufferAddress,
498        max_count: u32,
499    );
500    fn multi_draw_mesh_tasks_indirect(
501        &mut self,
502        indirect_buffer: &DispatchBuffer,
503        indirect_offset: crate::BufferAddress,
504        count: u32,
505    );
506    fn multi_draw_indexed_indirect_count(
507        &mut self,
508        indirect_buffer: &DispatchBuffer,
509        indirect_offset: crate::BufferAddress,
510        count_buffer: &DispatchBuffer,
511        count_buffer_offset: crate::BufferAddress,
512        max_count: u32,
513    );
514    fn multi_draw_mesh_tasks_indirect_count(
515        &mut self,
516        indirect_buffer: &DispatchBuffer,
517        indirect_offset: crate::BufferAddress,
518        count_buffer: &DispatchBuffer,
519        count_buffer_offset: crate::BufferAddress,
520        max_count: u32,
521    );
522
523    fn insert_debug_marker(&mut self, label: &str);
524    fn push_debug_group(&mut self, group_label: &str);
525    fn pop_debug_group(&mut self);
526
527    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
528    fn begin_occlusion_query(&mut self, query_index: u32);
529    fn end_occlusion_query(&mut self);
530    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
531    fn end_pipeline_statistics_query(&mut self);
532
533    fn execute_bundles(&mut self, render_bundles: &mut dyn Iterator<Item = &DispatchRenderBundle>);
534}
535
536pub trait RenderBundleEncoderInterface: CommonTraits {
537    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
538    fn set_bind_group(
539        &mut self,
540        index: u32,
541        bind_group: Option<&DispatchBindGroup>,
542        offsets: &[crate::DynamicOffset],
543    );
544    fn set_index_buffer(
545        &mut self,
546        buffer: &DispatchBuffer,
547        index_format: crate::IndexFormat,
548        offset: crate::BufferAddress,
549        size: Option<crate::BufferSize>,
550    );
551    fn set_vertex_buffer(
552        &mut self,
553        slot: u32,
554        buffer: Option<&DispatchBuffer>,
555        offset: crate::BufferAddress,
556        size: Option<crate::BufferSize>,
557    );
558    fn set_immediates(&mut self, offset: u32, data: &[u8]);
559
560    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
561    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
562    fn draw_indirect(
563        &mut self,
564        indirect_buffer: &DispatchBuffer,
565        indirect_offset: crate::BufferAddress,
566    );
567    fn draw_indexed_indirect(
568        &mut self,
569        indirect_buffer: &DispatchBuffer,
570        indirect_offset: crate::BufferAddress,
571    );
572
573    fn finish(self, desc: &crate::RenderBundleDescriptor<'_>) -> DispatchRenderBundle
574    where
575        Self: Sized;
576
577    /// Object-safe version of `finish` for dyn dispatch through `Box<dyn RenderBundleEncoderInterface>`.
578    ///
579    /// A default implementation cannot be provided here: a default that calls `finish` would
580    /// require `Self: Sized` (to move out of the box), which would remove the method from the
581    /// vtable and break object safety. Every concrete backend must implement this as:
582    /// ```ignore
583    /// fn finish_boxed(self: Box<Self>, desc: &RenderBundleDescriptor<'_>) -> DispatchRenderBundle {
584    ///     (*self).finish(desc)
585    /// }
586    /// ```
587    #[cfg(custom)]
588    fn finish_boxed(
589        self: Box<Self>,
590        desc: &crate::RenderBundleDescriptor<'_>,
591    ) -> DispatchRenderBundle;
592}
593
594pub trait CommandBufferInterface: CommonTraits {}
595pub trait RenderBundleInterface: CommonTraits {}
596
597pub trait SurfaceInterface: CommonTraits {
598    fn get_capabilities(&self, adapter: &DispatchAdapter) -> crate::SurfaceCapabilities;
599
600    /// The backing display's current HDR / luminance characteristics.
601    ///
602    /// Defaults to [`crate::DisplayHdrInfo::default`] (all fields `None`) so
603    /// custom backends without a display query need not override it.
604    fn display_hdr_info(&self, adapter: &DispatchAdapter) -> crate::DisplayHdrInfo {
605        let _ = adapter;
606        crate::DisplayHdrInfo::default()
607    }
608
609    fn configure(&self, device: &DispatchDevice, config: &crate::SurfaceConfiguration);
610    fn get_current_texture(
611        &self,
612    ) -> (
613        Option<DispatchTexture>,
614        crate::SurfaceStatus,
615        DispatchSurfaceOutputDetail,
616    );
617
618    /// See [`crate::Surface::keep_presented_images`]; a backend whose
619    /// images are not numbered does nothing.
620    fn keep_presented_images(&self, keep: bool) {
621        let _ = keep;
622    }
623}
624
625pub trait SurfaceOutputDetailInterface: CommonTraits {
626    fn texture_discard(&self);
627    fn texture_release(&self);
628
629    /// See [`crate::SurfaceTexture::image`].
630    fn image(&self) -> Option<crate::SurfaceImage> {
631        None
632    }
633}
634
635pub trait QueueWriteBufferInterface: CommonTraits {
636    fn len(&self) -> usize;
637
638    /// # Safety
639    ///
640    /// Must only be used on write, not read, mappings.
641    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
642}
643
644pub trait BufferMappedRangeInterface: CommonTraits {
645    // Used only in wgpu_core's `impl QueueWriteBufferInterface`
646    #[cfg_attr(not(wgpu_core), expect(unused))]
647    fn len(&self) -> usize;
648
649    /// # Safety
650    ///
651    /// Must only be used on read, not write, mappings.
652    unsafe fn read_slice(&self) -> &[u8];
653
654    /// # Safety
655    ///
656    /// Must only be used on write, not read, mappings.
657    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
658
659    #[cfg(webgpu)]
660    fn as_uint8array(&self) -> &js_sys::Uint8Array;
661}
662
663/// Generates a dispatch type for some `wgpu` API type.
664///
665/// Invocations of this macro take one of the following forms:
666///
667/// ```ignore
668/// dispatch_types! {mut type D: I = Core, Web, Dyn }
669/// dispatch_types! {ref type D: I = Core, Web, Dyn }
670/// ```
671///
672/// This defines `D` as a type that dereferences to a `dyn I` trait object. Most uses of
673/// `D` in the rest of this crate just call the methods from the `dyn I` object, not from
674/// `D` itself.
675///
676/// Internally, `D` is an enum with up to three variants holding values of type `Core`,
677/// `Web`, and `Dyn`, all of which must implement `I`. `Core`, `Web` and `Dyn` are the
678/// types from the `wgpu_core`, `webgpu`, and `custom` submodules of `wgpu::backend` that
679/// correspond to `D`. The macro generates `Deref` and `DerefMut` implementations that
680/// match on this enum and produce a `dyn I` reference for each variant.
681///
682/// The macro's `mut type` form defines `D` as the unique owner of the backend type, with
683/// a `DerefMut` implementation, and `as_*_mut` methods that return `&mut` references.
684/// This `D` does not implement `Clone`.
685///
686/// The macro's `ref type` form defines `D` to hold an `Arc` pointing to the backend type,
687/// permitting `Clone` and `Deref`, but losing exclusive, mutable access.
688///
689/// For example:
690///
691/// ```ignore
692/// dispatch_types! {ref type DispatchBuffer: BufferInterface =
693///                  CoreBuffer, WebBuffer, DynBuffer}
694/// ```
695///
696/// This defines `DispatchBuffer` as a type that dereferences to `&dyn BufferInterface`,
697/// which has methods like `map_async` and `destroy`. The enum would be:
698///
699/// ```ignore
700/// pub enum DispatchBuffer {
701///     #[cfg(wgpu_core)]
702///     Core(Arc<CoreBuffer>),
703///     #[cfg(webgpu)]
704///     WebGPU(WebBuffer),
705///     #[cfg(custom)]
706///     Custom(DynBuffer),
707/// }
708/// ```
709///
710/// This macro also defines `as_*` methods so that the backend implementations can
711/// dereference other arguments.
712///
713/// ## Devirtualization
714///
715/// The dispatch types generated by this macro are carefully designed to allow the
716/// compiler to completely devirtualize calls in most circumstances.
717///
718/// Note that every variant of the enum generated by this macro is under a `#[cfg]`.
719/// Naturally, the `match` expressions in the `Deref` and `DerefMut` implementations have
720/// matching `#[cfg]` attributes on each match arm.
721///
722/// In practice, when `wgpu`'s `"custom"` feature is not enabled, there is usually only
723/// one variant in the `enum`, making it effectively a newtype around the sole variant's
724/// data: it has no discriminant to branch on, and the `match` expressions are removed
725/// entirely by the compiler.
726///
727/// In this case, when we invoke a method from the interface trait `I` on a dispatch type,
728/// the `Deref` and `DerefMut` implementations' `match` statements build a `&dyn I` for
729/// the data, on which we immediately invoke a method. The vtable is a constant, allowing
730/// the Rust compiler to turn the `dyn` method call into an ordinary method call. This
731/// creates opportunities for inlining.
732///
733/// Similarly, the `as_*` methods are free when there is only one backend.
734macro_rules! dispatch_types {
735    (
736        ref type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
737    ) => {
738        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
739        pub enum $name {
740            #[cfg(wgpu_core)]
741            Core(Arc<$core_type>),
742            #[cfg(webgpu)]
743            WebGPU($webgpu_type),
744            #[allow(clippy::allow_attributes, private_interfaces)]
745            #[cfg(custom)]
746            Custom($custom_type),
747        }
748
749        impl $name {
750            #[cfg(wgpu_core)]
751            #[inline]
752            #[allow(clippy::allow_attributes, unused)]
753            pub fn as_core(&self) -> &$core_type {
754                match self {
755                    Self::Core(value) => value,
756                    _ => panic!(concat!(stringify!($name), " is not core")),
757                }
758            }
759
760            #[cfg(wgpu_core)]
761            #[inline]
762            #[allow(clippy::allow_attributes, unused)]
763            pub fn as_core_opt(&self) -> Option<&$core_type> {
764                match self {
765                    Self::Core(value) => Some(value),
766                    _ => None,
767                }
768            }
769
770            #[cfg(custom)]
771            #[inline]
772            #[allow(clippy::allow_attributes, unused)]
773            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
774                match self {
775                    Self::Custom(value) => value.downcast(),
776                    _ => None,
777                }
778            }
779
780            #[cfg(webgpu)]
781            #[inline]
782            #[allow(clippy::allow_attributes, unused)]
783            pub fn as_webgpu(&self) -> &$webgpu_type {
784                match self {
785                    Self::WebGPU(value) => value,
786                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
787                }
788            }
789
790            #[cfg(webgpu)]
791            #[inline]
792            #[allow(clippy::allow_attributes, unused)]
793            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
794                match self {
795                    Self::WebGPU(value) => Some(value),
796                    _ => None,
797                }
798            }
799
800            #[cfg(custom)]
801            #[inline]
802            pub fn custom<T: $interface>(t: T) -> Self {
803                Self::Custom($custom_type::new(t))
804            }
805        }
806
807        #[cfg(wgpu_core)]
808        impl From<$core_type> for $name {
809            #[inline]
810            fn from(value: $core_type) -> Self {
811                Self::Core(Arc::new(value))
812            }
813        }
814
815        #[cfg(webgpu)]
816        impl From<$webgpu_type> for $name {
817            #[inline]
818            fn from(value: $webgpu_type) -> Self {
819                Self::WebGPU(value)
820            }
821        }
822
823        impl core::ops::Deref for $name {
824            type Target = dyn $interface;
825
826            #[inline]
827            fn deref(&self) -> &Self::Target {
828                match self {
829                    #[cfg(wgpu_core)]
830                    Self::Core(value) => value.as_ref(),
831                    #[cfg(webgpu)]
832                    Self::WebGPU(value) => value,
833                    #[cfg(custom)]
834                    Self::Custom(value) => value.deref(),
835                    #[cfg(not(any(wgpu_core, webgpu)))]
836                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
837                }
838            }
839        }
840    };
841    (
842        mut type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
843    ) => {
844        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
845        pub enum $name {
846            #[cfg(wgpu_core)]
847            Core($core_type),
848            #[cfg(webgpu)]
849            WebGPU($webgpu_type),
850            #[allow(clippy::allow_attributes, private_interfaces)]
851            #[cfg(custom)]
852            Custom($custom_type),
853        }
854
855        impl $name {
856            #[cfg(wgpu_core)]
857            #[inline]
858            #[allow(clippy::allow_attributes, unused)]
859            pub fn as_core(&self) -> &$core_type {
860                match self {
861                    Self::Core(value) => value,
862                    _ => panic!(concat!(stringify!($name), " is not core")),
863                }
864            }
865
866            #[cfg(wgpu_core)]
867            #[inline]
868            #[allow(clippy::allow_attributes, unused)]
869            pub fn as_core_mut(&mut self) -> &mut $core_type {
870                match self {
871                    Self::Core(value) => value,
872                    _ => panic!(concat!(stringify!($name), " is not core")),
873                }
874            }
875
876            #[cfg(wgpu_core)]
877            #[inline]
878            #[allow(clippy::allow_attributes, unused)]
879            pub fn as_core_opt(&self) -> Option<&$core_type> {
880                match self {
881                    Self::Core(value) => Some(value),
882                    _ => None,
883                }
884            }
885
886            #[cfg(wgpu_core)]
887            #[inline]
888            #[allow(clippy::allow_attributes, unused)]
889            pub fn as_core_mut_opt(
890                &mut self,
891            ) -> Option<&mut $core_type> {
892                match self {
893                    Self::Core(value) => Some(value),
894                    _ => None,
895                }
896            }
897
898            #[cfg(custom)]
899            #[inline]
900            #[allow(clippy::allow_attributes, unused)]
901            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
902                match self {
903                    Self::Custom(value) => value.downcast(),
904                    _ => None,
905                }
906            }
907
908            #[cfg(webgpu)]
909            #[inline]
910            #[allow(clippy::allow_attributes, unused)]
911            pub fn as_webgpu(&self) -> &$webgpu_type {
912                match self {
913                    Self::WebGPU(value) => value,
914                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
915                }
916            }
917
918            #[cfg(webgpu)]
919            #[inline]
920            #[allow(clippy::allow_attributes, unused)]
921            pub fn as_webgpu_mut(&mut self) -> &mut $webgpu_type {
922                match self {
923                    Self::WebGPU(value) => value,
924                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
925                }
926            }
927
928            #[cfg(webgpu)]
929            #[inline]
930            #[allow(clippy::allow_attributes, unused)]
931            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
932                match self {
933                    Self::WebGPU(value) => Some(value),
934                    _ => None,
935                }
936            }
937
938            #[cfg(webgpu)]
939            #[inline]
940            #[allow(clippy::allow_attributes, unused)]
941            pub fn as_webgpu_mut_opt(
942                &mut self,
943            ) -> Option<&mut $webgpu_type> {
944                match self {
945                    Self::WebGPU(value) => Some(value),
946                    _ => None,
947                }
948            }
949
950            #[cfg(custom)]
951            #[inline]
952            pub fn custom<T: $interface>(t: T) -> Self {
953                Self::Custom($custom_type::new(t))
954            }
955        }
956
957        #[cfg(wgpu_core)]
958        impl From<$core_type> for $name {
959            #[inline]
960            fn from(value: $core_type) -> Self {
961                Self::Core(value)
962            }
963        }
964
965        #[cfg(webgpu)]
966        impl From<$webgpu_type> for $name {
967            #[inline]
968            fn from(value: $webgpu_type) -> Self {
969                Self::WebGPU(value)
970            }
971        }
972
973        impl core::ops::Deref for $name {
974            type Target = dyn $interface;
975
976            #[inline]
977            fn deref(&self) -> &Self::Target {
978                match self {
979                    #[cfg(wgpu_core)]
980                    Self::Core(value) => value,
981                    #[cfg(webgpu)]
982                    Self::WebGPU(value) => value,
983                    #[cfg(custom)]
984                    Self::Custom(value) => value.deref(),
985                    #[cfg(not(any(wgpu_core, webgpu)))]
986                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
987                }
988            }
989        }
990
991        impl core::ops::DerefMut for $name {
992            #[inline]
993            fn deref_mut(&mut self) -> &mut Self::Target {
994                match self {
995                    #[cfg(wgpu_core)]
996                    Self::Core(value) => value,
997                    #[cfg(webgpu)]
998                    Self::WebGPU(value) => value,
999                    #[cfg(custom)]
1000                    Self::Custom(value) => value.deref_mut(),
1001                    #[cfg(not(any(wgpu_core, webgpu)))]
1002                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
1003                }
1004            }
1005        }
1006    };
1007}
1008
1009dispatch_types! {ref type DispatchInstance: InstanceInterface = ContextWgpuCore, ContextWebGpu, DynContext}
1010dispatch_types! {ref type DispatchAdapter: AdapterInterface = CoreAdapter, WebAdapter, DynAdapter}
1011dispatch_types! {ref type DispatchDevice: DeviceInterface = CoreDevice, WebDevice, DynDevice}
1012dispatch_types! {ref type DispatchQueue: QueueInterface = CoreQueue, WebQueue, DynQueue}
1013dispatch_types! {ref type DispatchShaderModule: ShaderModuleInterface = CoreShaderModule, WebShaderModule, DynShaderModule}
1014dispatch_types! {ref type DispatchBindGroupLayout: BindGroupLayoutInterface = CoreBindGroupLayout, WebBindGroupLayout, DynBindGroupLayout}
1015dispatch_types! {ref type DispatchBindGroup: BindGroupInterface = CoreBindGroup, WebBindGroup, DynBindGroup}
1016dispatch_types! {ref type DispatchTextureView: TextureViewInterface = CoreTextureView, WebTextureView, DynTextureView}
1017dispatch_types! {ref type DispatchSampler: SamplerInterface = CoreSampler, WebSampler, DynSampler}
1018dispatch_types! {ref type DispatchBuffer: BufferInterface = CoreBuffer, WebBuffer, DynBuffer}
1019dispatch_types! {ref type DispatchTexture: TextureInterface = CoreTexture, WebTexture, DynTexture}
1020dispatch_types! {ref type DispatchExternalTexture: ExternalTextureInterface = CoreExternalTexture, WebExternalTexture, DynExternalTexture}
1021dispatch_types! {ref type DispatchBlas: BlasInterface = CoreBlas, WebBlas, DynBlas}
1022dispatch_types! {ref type DispatchTlas: TlasInterface = CoreTlas, WebTlas, DynTlas}
1023dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, WebQuerySet, DynQuerySet}
1024dispatch_types! {ref type DispatchPipelineLayout: PipelineLayoutInterface = CorePipelineLayout, WebPipelineLayout, DynPipelineLayout}
1025dispatch_types! {ref type DispatchRenderPipeline: RenderPipelineInterface = CoreRenderPipeline, WebRenderPipeline, DynRenderPipeline}
1026dispatch_types! {ref type DispatchComputePipeline: ComputePipelineInterface = CoreComputePipeline, WebComputePipeline, DynComputePipeline}
1027dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePipelineCache, WebPipelineCache, DynPipelineCache}
1028dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder}
1029dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass}
1030dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass}
1031dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer}
1032dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder}
1033dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle}
1034dispatch_types! {ref type DispatchSurface: SurfaceInterface = CoreSurface, WebSurface, DynSurface}
1035dispatch_types! {ref type DispatchSurfaceOutputDetail: SurfaceOutputDetailInterface = CoreSurfaceOutputDetail, WebSurfaceOutputDetail, DynSurfaceOutputDetail}
1036dispatch_types! {mut type DispatchQueueWriteBuffer: QueueWriteBufferInterface = CoreQueueWriteBuffer, WebQueueWriteBuffer, DynQueueWriteBuffer}
1037dispatch_types! {mut type DispatchBufferMappedRange: BufferMappedRangeInterface = CoreBufferMappedRange, WebBufferMappedRange, DynBufferMappedRange}