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    fn ray_tracing_invocation_reorder_mode(&self) -> crate::wgt::RayTracingInvocationReorderMode;
142}
143
144pub trait DeviceInterface: CommonTraits {
145    fn features(&self) -> crate::Features;
146    fn limits(&self) -> crate::Limits;
147    fn is_surface_supported(&self, surface: &DispatchSurface) -> bool;
148    fn adapter_info(&self) -> crate::AdapterInfo;
149    fn queue(&self) -> DispatchQueue;
150
151    fn create_shader_module(
152        &self,
153        desc: crate::ShaderModuleDescriptor<'_>,
154        shader_bound_checks: crate::ShaderRuntimeChecks,
155    ) -> DispatchShaderModule;
156
157    unsafe fn create_shader_module_passthrough(
158        &self,
159        desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
160    ) -> DispatchShaderModule;
161
162    fn create_bind_group_layout(
163        &self,
164        desc: &crate::BindGroupLayoutDescriptor<'_>,
165    ) -> DispatchBindGroupLayout;
166    fn create_bind_group(&self, desc: &crate::BindGroupDescriptor<'_>) -> DispatchBindGroup;
167    fn create_pipeline_layout(
168        &self,
169        desc: &crate::PipelineLayoutDescriptor<'_>,
170    ) -> DispatchPipelineLayout;
171    fn create_render_pipeline(
172        &self,
173        desc: &crate::RenderPipelineDescriptor<'_>,
174    ) -> DispatchRenderPipeline;
175    fn create_mesh_pipeline(
176        &self,
177        desc: &crate::MeshPipelineDescriptor<'_>,
178    ) -> DispatchRenderPipeline;
179    fn create_compute_pipeline(
180        &self,
181        desc: &crate::ComputePipelineDescriptor<'_>,
182    ) -> DispatchComputePipeline;
183    fn create_ray_tracing_pipeline(
184        &self,
185        desc: &crate::RayTracingPipelineDescriptor<'_>,
186    ) -> DispatchRayTracingPipeline;
187    unsafe fn create_pipeline_cache(
188        &self,
189        desc: &crate::PipelineCacheDescriptor<'_>,
190    ) -> DispatchPipelineCache;
191    fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> DispatchBuffer;
192    fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> DispatchTexture;
193    fn create_external_texture(
194        &self,
195        desc: &crate::ExternalTextureDescriptor<'_>,
196        planes: &[&crate::TextureView],
197    ) -> DispatchExternalTexture;
198    fn create_blas(
199        &self,
200        desc: &crate::CreateBlasDescriptor<'_>,
201        sizes: crate::BlasGeometrySizeDescriptors,
202    ) -> (Option<u64>, DispatchBlas);
203    fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> DispatchTlas;
204    fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> DispatchSampler;
205    fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> DispatchQuerySet;
206    fn create_command_encoder(
207        &self,
208        desc: &crate::CommandEncoderDescriptor<'_>,
209    ) -> DispatchCommandEncoder;
210    fn create_render_bundle_encoder(
211        &self,
212        desc: &crate::RenderBundleEncoderDescriptor<'_>,
213    ) -> DispatchRenderBundleEncoder;
214
215    fn set_device_lost_callback(&self, device_lost_callback: BoxDeviceLostCallback);
216
217    fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>);
218    // Returns index on the stack of the pushed error scope.
219    fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32;
220    fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn PopErrorScopeFuture>>;
221
222    unsafe fn start_graphics_debugger_capture(&self);
223    unsafe fn stop_graphics_debugger_capture(&self);
224
225    fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError>;
226
227    fn get_internal_counters(&self) -> crate::InternalCounters;
228    fn generate_allocator_report(&self) -> Option<crate::AllocatorReport>;
229
230    fn destroy(&self);
231}
232
233pub trait QueueInterface: CommonTraits {
234    fn write_buffer(&self, buffer: &DispatchBuffer, offset: crate::BufferAddress, data: &[u8]);
235
236    fn create_staging_buffer(&self, size: crate::BufferSize) -> Option<DispatchQueueWriteBuffer>;
237    fn validate_write_buffer(
238        &self,
239        buffer: &DispatchBuffer,
240        offset: crate::BufferAddress,
241        size: crate::BufferSize,
242    ) -> Option<()>;
243    fn write_staging_buffer(
244        &self,
245        buffer: &DispatchBuffer,
246        offset: crate::BufferAddress,
247        staging_buffer: DispatchQueueWriteBuffer,
248    );
249
250    fn write_texture(
251        &self,
252        texture: crate::TexelCopyTextureInfo<'_>,
253        data: &[u8],
254        data_layout: crate::TexelCopyBufferLayout,
255        size: crate::Extent3d,
256    );
257    #[cfg(web)]
258    fn copy_external_image_to_texture(
259        &self,
260        source: &crate::CopyExternalImageSourceInfo,
261        dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
262        size: crate::Extent3d,
263    );
264
265    /// Submit must always drain the iterator, even in the case of error.
266    fn submit(
267        &self,
268        command_buffers: &mut dyn Iterator<Item = DispatchCommandBuffer>,
269    ) -> Option<u64>;
270
271    fn get_timestamp_period(&self) -> f32;
272    fn on_submitted_work_done(&self, callback: BoxSubmittedWorkDoneCallback);
273
274    fn compact_blas(&self, blas: &DispatchBlas) -> (Option<u64>, DispatchBlas);
275
276    fn present(&self, detail: &DispatchSurfaceOutputDetail);
277
278    fn present_with_damage(
279        &self,
280        detail: &DispatchSurfaceOutputDetail,
281        _damage_rects: &[wgt::Rect<u32>],
282    ) {
283        self.present(detail);
284    }
285}
286
287pub trait ShaderModuleInterface: CommonTraits {
288    fn get_compilation_info(&self) -> Pin<Box<dyn ShaderCompilationInfoFuture>>;
289}
290pub trait BindGroupLayoutInterface: CommonTraits {}
291pub trait BindGroupInterface: CommonTraits {}
292pub trait TextureViewInterface: CommonTraits {}
293pub trait SamplerInterface: CommonTraits {}
294pub trait BufferInterface: CommonTraits {
295    fn map_async(
296        &self,
297        mode: crate::MapMode,
298        range: Range<crate::BufferAddress>,
299        callback: BufferMapCallback,
300    );
301    fn get_mapped_range(
302        &self,
303        sub_range: Range<crate::BufferAddress>,
304    ) -> Result<DispatchBufferMappedRange, crate::MapRangeError>;
305
306    fn unmap(&self);
307
308    fn destroy(&self);
309
310    fn size(&self) -> crate::BufferAddress;
311
312    fn usage(&self) -> crate::BufferUsages;
313}
314pub trait TextureInterface: CommonTraits {
315    fn create_view(&self, desc: &crate::TextureViewDescriptor<'_>) -> DispatchTextureView;
316
317    fn destroy(&self);
318
319    fn size(&self) -> wgt::Extent3d;
320
321    fn mip_level_count(&self) -> u32;
322
323    fn sample_count(&self) -> u32;
324
325    fn dimension(&self) -> wgt::TextureDimension;
326
327    fn format(&self) -> wgt::TextureFormat;
328
329    fn usage(&self) -> wgt::TextureUsages;
330
331    /// Marks this texture's contents as already initialized, skipping wgpu's
332    /// lazy zero-initialization of it.
333    ///
334    /// Defaults to a no-op, which is a valid implementation for backends
335    /// (such as WebGPU) that have no concept of lazy zero-initialization.
336    ///
337    /// # Safety
338    ///
339    /// The entire contents of the texture must already be initialized.
340    unsafe fn mark_externally_initialized(&self) {}
341
342    fn texture_binding_view_dimension(&self) -> Option<crate::TextureViewDimension>;
343}
344pub trait ExternalTextureInterface: CommonTraits {
345    fn destroy(&self);
346}
347pub trait BlasInterface: CommonTraits {
348    fn prepare_compact_async(&self, callback: BlasCompactCallback);
349    fn ready_for_compaction(&self) -> bool;
350}
351pub trait TlasInterface: CommonTraits {}
352pub trait QuerySetInterface: CommonTraits {
353    fn destroy(&self);
354
355    fn ty(&self) -> crate::QueryType;
356
357    fn count(&self) -> u32;
358}
359pub trait PipelineLayoutInterface: CommonTraits {}
360pub trait RenderPipelineInterface: CommonTraits {
361    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
362}
363pub trait ComputePipelineInterface: CommonTraits {
364    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
365}
366pub trait RayTracingPipelineInterface: CommonTraits {
367    fn get_bind_group_layout(&self, index: u32) -> DispatchBindGroupLayout;
368}
369pub trait PipelineCacheInterface: CommonTraits {
370    fn get_data(&self) -> Option<Vec<u8>>;
371}
372pub trait CommandEncoderInterface: CommonTraits {
373    fn copy_buffer_to_buffer(
374        &self,
375        source: &DispatchBuffer,
376        source_offset: crate::BufferAddress,
377        destination: &DispatchBuffer,
378        destination_offset: crate::BufferAddress,
379        copy_size: Option<crate::BufferAddress>,
380    );
381    fn copy_buffer_to_texture(
382        &self,
383        source: crate::TexelCopyBufferInfo<'_>,
384        destination: crate::TexelCopyTextureInfo<'_>,
385        copy_size: crate::Extent3d,
386    );
387    fn copy_texture_to_buffer(
388        &self,
389        source: crate::TexelCopyTextureInfo<'_>,
390        destination: crate::TexelCopyBufferInfo<'_>,
391        copy_size: crate::Extent3d,
392    );
393    fn copy_texture_to_texture(
394        &self,
395        source: crate::TexelCopyTextureInfo<'_>,
396        destination: crate::TexelCopyTextureInfo<'_>,
397        copy_size: crate::Extent3d,
398    );
399
400    fn begin_compute_pass(&self, desc: &crate::ComputePassDescriptor<'_>) -> DispatchComputePass;
401    fn begin_render_pass(&self, desc: &crate::RenderPassDescriptor<'_>) -> DispatchRenderPass;
402    fn begin_ray_tracing_pass(
403        &self,
404        desc: &crate::RayTracingPassDescriptor<'_>,
405    ) -> DispatchRayTracingPass;
406    fn finish(&mut self) -> DispatchCommandBuffer;
407
408    fn clear_texture(
409        &self,
410        texture: &DispatchTexture,
411        subresource_range: &crate::ImageSubresourceRange,
412    );
413    fn clear_buffer(
414        &self,
415        buffer: &DispatchBuffer,
416        offset: crate::BufferAddress,
417        size: Option<crate::BufferAddress>,
418    );
419
420    fn insert_debug_marker(&self, label: &str);
421    fn push_debug_group(&self, label: &str);
422    fn pop_debug_group(&self);
423
424    fn write_timestamp(&self, query_set: &DispatchQuerySet, query_index: u32);
425    fn resolve_query_set(
426        &self,
427        query_set: &DispatchQuerySet,
428        first_query: u32,
429        query_count: u32,
430        destination: &DispatchBuffer,
431        destination_offset: crate::BufferAddress,
432    );
433    fn mark_acceleration_structures_built<'a>(
434        &self,
435        blas: &mut dyn Iterator<Item = &'a Blas>,
436        tlas: &mut dyn Iterator<Item = &'a Tlas>,
437    );
438
439    fn build_acceleration_structures<'a>(
440        &self,
441        blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
442        tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
443    );
444
445    fn transition_resources<'a>(
446        &mut self,
447        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
448        texture_transitions: &mut dyn Iterator<Item = wgt::TextureTransition<&'a DispatchTexture>>,
449    );
450}
451pub trait ComputePassInterface: CommonTraits + Drop {
452    fn set_pipeline(&mut self, pipeline: &DispatchComputePipeline);
453    fn set_bind_group(
454        &mut self,
455        index: u32,
456        bind_group: Option<&DispatchBindGroup>,
457        offsets: &[crate::DynamicOffset],
458    );
459    fn set_immediates(&mut self, offset: u32, data: &[u8]);
460
461    fn insert_debug_marker(&mut self, label: &str);
462    fn push_debug_group(&mut self, group_label: &str);
463    fn pop_debug_group(&mut self);
464
465    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
466    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
467    fn end_pipeline_statistics_query(&mut self);
468
469    fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32);
470    fn dispatch_workgroups_indirect(
471        &mut self,
472        indirect_buffer: &DispatchBuffer,
473        indirect_offset: crate::BufferAddress,
474    );
475
476    fn transition_resources<'a>(
477        &mut self,
478        buffer_transitions: &mut dyn Iterator<Item = wgt::BufferTransition<&'a DispatchBuffer>>,
479        texture_transitions: &mut dyn Iterator<
480            Item = wgt::TextureTransition<&'a DispatchTextureView>,
481        >,
482    );
483}
484pub trait RenderPassInterface: CommonTraits + Drop {
485    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
486    fn set_bind_group(
487        &mut self,
488        index: u32,
489        bind_group: Option<&DispatchBindGroup>,
490        offsets: &[crate::DynamicOffset],
491    );
492    fn set_index_buffer(
493        &mut self,
494        buffer: &DispatchBuffer,
495        index_format: crate::IndexFormat,
496        offset: crate::BufferAddress,
497        size: Option<crate::BufferAddress>,
498    );
499    fn set_vertex_buffer(
500        &mut self,
501        slot: u32,
502        buffer: Option<&DispatchBuffer>,
503        offset: crate::BufferAddress,
504        size: Option<crate::BufferAddress>,
505    );
506    fn set_immediates(&mut self, offset: u32, data: &[u8]);
507    fn set_blend_constant(&mut self, color: crate::Color);
508    fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32);
509    fn set_viewport(
510        &mut self,
511        x: f32,
512        y: f32,
513        width: f32,
514        height: f32,
515        min_depth: f32,
516        max_depth: f32,
517    );
518    fn set_stencil_reference(&mut self, reference: u32);
519
520    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
521    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
522    fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32);
523    fn draw_indirect(
524        &mut self,
525        indirect_buffer: &DispatchBuffer,
526        indirect_offset: crate::BufferAddress,
527    );
528    fn draw_indexed_indirect(
529        &mut self,
530        indirect_buffer: &DispatchBuffer,
531        indirect_offset: crate::BufferAddress,
532    );
533    fn draw_mesh_tasks_indirect(
534        &mut self,
535        indirect_buffer: &DispatchBuffer,
536        indirect_offset: crate::BufferAddress,
537    );
538
539    fn multi_draw_indirect(
540        &mut self,
541        indirect_buffer: &DispatchBuffer,
542        indirect_offset: crate::BufferAddress,
543        count: u32,
544    );
545    fn multi_draw_indexed_indirect(
546        &mut self,
547        indirect_buffer: &DispatchBuffer,
548        indirect_offset: crate::BufferAddress,
549        count: u32,
550    );
551    fn multi_draw_indirect_count(
552        &mut self,
553        indirect_buffer: &DispatchBuffer,
554        indirect_offset: crate::BufferAddress,
555        count_buffer: &DispatchBuffer,
556        count_buffer_offset: crate::BufferAddress,
557        max_count: u32,
558    );
559    fn multi_draw_mesh_tasks_indirect(
560        &mut self,
561        indirect_buffer: &DispatchBuffer,
562        indirect_offset: crate::BufferAddress,
563        count: u32,
564    );
565    fn multi_draw_indexed_indirect_count(
566        &mut self,
567        indirect_buffer: &DispatchBuffer,
568        indirect_offset: crate::BufferAddress,
569        count_buffer: &DispatchBuffer,
570        count_buffer_offset: crate::BufferAddress,
571        max_count: u32,
572    );
573    fn multi_draw_mesh_tasks_indirect_count(
574        &mut self,
575        indirect_buffer: &DispatchBuffer,
576        indirect_offset: crate::BufferAddress,
577        count_buffer: &DispatchBuffer,
578        count_buffer_offset: crate::BufferAddress,
579        max_count: u32,
580    );
581
582    fn insert_debug_marker(&mut self, label: &str);
583    fn push_debug_group(&mut self, group_label: &str);
584    fn pop_debug_group(&mut self);
585
586    fn write_timestamp(&mut self, query_set: &DispatchQuerySet, query_index: u32);
587    fn begin_occlusion_query(&mut self, query_index: u32);
588    fn end_occlusion_query(&mut self);
589    fn begin_pipeline_statistics_query(&mut self, query_set: &DispatchQuerySet, query_index: u32);
590    fn end_pipeline_statistics_query(&mut self);
591
592    fn execute_bundles(&mut self, render_bundles: &mut dyn Iterator<Item = &DispatchRenderBundle>);
593}
594pub trait RayTracingPassInterface: CommonTraits + Drop {
595    fn set_pipeline(&mut self, pipeline: &DispatchRayTracingPipeline);
596    fn set_bind_group(
597        &mut self,
598        index: u32,
599        bind_group: Option<&DispatchBindGroup>,
600        offsets: &[crate::DynamicOffset],
601    );
602    fn set_immediates(&mut self, offset: u32, data: &[u8]);
603
604    fn insert_debug_marker(&mut self, label: &str);
605    fn push_debug_group(&mut self, group_label: &str);
606    fn pop_debug_group(&mut self);
607
608    fn trace_rays(&mut self, x: u32, y: u32, z: u32);
609}
610
611pub trait RenderBundleEncoderInterface: CommonTraits {
612    fn set_pipeline(&mut self, pipeline: &DispatchRenderPipeline);
613    fn set_bind_group(
614        &mut self,
615        index: u32,
616        bind_group: Option<&DispatchBindGroup>,
617        offsets: &[crate::DynamicOffset],
618    );
619    fn set_index_buffer(
620        &mut self,
621        buffer: &DispatchBuffer,
622        index_format: crate::IndexFormat,
623        offset: crate::BufferAddress,
624        size: Option<crate::BufferAddress>,
625    );
626    fn set_vertex_buffer(
627        &mut self,
628        slot: u32,
629        buffer: Option<&DispatchBuffer>,
630        offset: crate::BufferAddress,
631        size: Option<crate::BufferAddress>,
632    );
633    fn set_immediates(&mut self, offset: u32, data: &[u8]);
634
635    fn insert_debug_marker(&mut self, label: &str);
636    fn push_debug_group(&mut self, group_label: &str);
637    fn pop_debug_group(&mut self);
638
639    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
640    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
641    fn draw_indirect(
642        &mut self,
643        indirect_buffer: &DispatchBuffer,
644        indirect_offset: crate::BufferAddress,
645    );
646    fn draw_indexed_indirect(
647        &mut self,
648        indirect_buffer: &DispatchBuffer,
649        indirect_offset: crate::BufferAddress,
650    );
651
652    fn finish(self, desc: &crate::RenderBundleDescriptor<'_>) -> DispatchRenderBundle
653    where
654        Self: Sized;
655
656    /// Object-safe version of `finish` for dyn dispatch through `Box<dyn RenderBundleEncoderInterface>`.
657    ///
658    /// A default implementation cannot be provided here: a default that calls `finish` would
659    /// require `Self: Sized` (to move out of the box), which would remove the method from the
660    /// vtable and break object safety. Every concrete backend must implement this as:
661    /// ```ignore
662    /// fn finish_boxed(self: Box<Self>, desc: &RenderBundleDescriptor<'_>) -> DispatchRenderBundle {
663    ///     (*self).finish(desc)
664    /// }
665    /// ```
666    #[cfg(custom)]
667    fn finish_boxed(
668        self: Box<Self>,
669        desc: &crate::RenderBundleDescriptor<'_>,
670    ) -> DispatchRenderBundle;
671}
672
673pub trait CommandBufferInterface: CommonTraits {}
674pub trait RenderBundleInterface: CommonTraits {}
675
676pub trait SurfaceInterface: CommonTraits {
677    fn get_capabilities(&self, adapter: &DispatchAdapter) -> crate::SurfaceCapabilities;
678
679    /// The backing display's current HDR / luminance characteristics.
680    ///
681    /// Defaults to [`crate::DisplayHdrInfo::default`] (all fields `None`) so
682    /// custom backends without a display query need not override it.
683    fn display_hdr_info(&self, adapter: &DispatchAdapter) -> crate::DisplayHdrInfo {
684        let _ = adapter;
685        crate::DisplayHdrInfo::default()
686    }
687
688    fn configure(&self, device: &DispatchDevice, config: &crate::SurfaceConfiguration);
689    fn get_current_texture(
690        &self,
691        desc: Option<crate::TextureDescriptor<'static>>,
692    ) -> (
693        Option<DispatchTexture>,
694        crate::SurfaceStatus,
695        DispatchSurfaceOutputDetail,
696    );
697}
698
699pub trait SurfaceOutputDetailInterface: CommonTraits {
700    fn texture_discard(&self);
701    fn texture_release(&self);
702}
703
704pub trait QueueWriteBufferInterface: CommonTraits {
705    fn len(&self) -> usize;
706
707    /// # Safety
708    ///
709    /// Must only be used on write, not read, mappings.
710    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
711}
712
713pub trait BufferMappedRangeInterface: CommonTraits {
714    /// # Safety
715    ///
716    /// Must only be used on read, not write, mappings.
717    unsafe fn read_slice(&self) -> &[u8];
718
719    /// # Safety
720    ///
721    /// Must only be used on write, not read, mappings.
722    unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]>;
723
724    #[cfg(webgpu)]
725    fn as_uint8array(&self) -> &js_sys::Uint8Array;
726}
727
728/// Generates a `Send` and `Sync` implementation for a dispatch enum generated by `dispatch_types!`.
729macro_rules! explicit_send_sync_impl {
730    ($name:ident) => {
731        /// Implement [`Send`] + [`Sync`] for the dispatch type, and check that all of its fields
732        /// are [`Send`] + [`Sync`] so that that implementation is sound.
733        ///
734        /// This is identical to the “auto trait” implementation that Rust would provide, except
735        /// that it is eager rather than lazy: its requirements are checked now (in
736        /// `_fields_are_send_sync`), when this crate is compiled, rather than whenever a dependent
737        /// wants to know whether `$name: Send` holds.
738        ///
739        /// This improves compilation performance and avoids a risk of dependents running into the
740        /// default [`recursion_limit`] when checking types containing wgpu API types. This risk
741        /// will become greater when Rust’s “next solver” is stabilized.
742        ///
743        /// The effectiveness of this strategy is tested by
744        ///     ../tests/send_sync_recursion.rs.
745        #[cfg(send_sync)]
746        const _: () = {
747            // SAFETY: Bounds checked below
748            unsafe impl Send for $name {}
749            // SAFETY: Bounds checked below
750            unsafe impl Sync for $name {}
751
752            /// This code will fail to compile if any field is not `Send + Sync`, or if a new field
753            /// is added to the dispatch type.
754            ///
755            /// This technique is modeled after the macro library `non_structural_derive`, with
756            /// permission (see <https://github.com/fee1-dead/non_structural_derive/issues/1#issuecomment-5250905440>).
757            /// We only need it in this very narrow situation, so we can use a simpler macro.
758            fn _fields_are_send_sync(dispatch_enum: &$name) {
759                fn _check_bound<T: Send + Sync>(_: &T) {}
760                // Must dereference to handle the case where there are no enabled variants.
761                match *dispatch_enum {
762                    #[cfg(wgpu_core)]
763                    $name::Core(ref value) => _check_bound(value),
764                    #[cfg(webgpu)]
765                    $name::WebGPU(ref value) => _check_bound(value),
766                    #[cfg(custom)]
767                    $name::Custom(ref value) => _check_bound(value),
768                }
769            }
770        };
771    };
772}
773
774/// Generates a dispatch type for some `wgpu` API type.
775///
776/// Invocations of this macro take one of the following forms:
777///
778/// ```ignore
779/// dispatch_types! {mut type D: I = Core, Web, Dyn }
780/// dispatch_types! {ref type D: I = Core, Web, Dyn }
781/// ```
782///
783/// This defines `D` as a type that dereferences to a `dyn I` trait object. Most uses of
784/// `D` in the rest of this crate just call the methods from the `dyn I` object, not from
785/// `D` itself.
786///
787/// Internally, `D` is an enum with up to three variants holding values of type `Core`,
788/// `Web`, and `Dyn`, all of which must implement `I`. `Core`, `Web` and `Dyn` are the
789/// types from the `wgpu_core`, `webgpu`, and `custom` submodules of `wgpu::backend` that
790/// correspond to `D`. The macro generates `Deref` and `DerefMut` implementations that
791/// match on this enum and produce a `dyn I` reference for each variant.
792///
793/// The macro's `mut type` form defines `D` as the unique owner of the backend type, with
794/// a `DerefMut` implementation, and `as_*_mut` methods that return `&mut` references.
795/// This `D` does not implement `Clone`.
796///
797/// The macro's `ref type` form defines `D` to be `Clone` and `Deref`, but losing exclusive, mutable access.
798///
799/// For example:
800///
801/// ```ignore
802/// dispatch_types! {ref type DispatchBuffer: BufferInterface =
803///                  CoreBuffer, WebBuffer, DynBuffer}
804/// ```
805///
806/// This defines `DispatchBuffer` as a type that dereferences to `&dyn BufferInterface`,
807/// which has methods like `map_async` and `destroy`. The enum would be:
808///
809/// ```ignore
810/// pub enum DispatchBuffer {
811///     #[cfg(wgpu_core)]
812///     Core(CoreBuffer),
813///     #[cfg(webgpu)]
814///     WebGPU(WebBuffer),
815///     #[cfg(custom)]
816///     Custom(DynBuffer),
817/// }
818/// ```
819///
820/// This macro also defines `as_*` methods so that the backend implementations can
821/// dereference other arguments.
822///
823/// ## Devirtualization
824///
825/// The dispatch types generated by this macro are carefully designed to allow the
826/// compiler to completely devirtualize calls in most circumstances.
827///
828/// Note that every variant of the enum generated by this macro is under a `#[cfg]`.
829/// Naturally, the `match` expressions in the `Deref` and `DerefMut` implementations have
830/// matching `#[cfg]` attributes on each match arm.
831///
832/// In practice, when `wgpu`'s `"custom"` feature is not enabled, there is usually only
833/// one variant in the `enum`, making it effectively a newtype around the sole variant's
834/// data: it has no discriminant to branch on, and the `match` expressions are removed
835/// entirely by the compiler.
836///
837/// In this case, when we invoke a method from the interface trait `I` on a dispatch type,
838/// the `Deref` and `DerefMut` implementations' `match` statements build a `&dyn I` for
839/// the data, on which we immediately invoke a method. The vtable is a constant, allowing
840/// the Rust compiler to turn the `dyn` method call into an ordinary method call. This
841/// creates opportunities for inlining.
842///
843/// Similarly, the `as_*` methods are free when there is only one backend.
844macro_rules! dispatch_types {
845    (
846        ref type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
847    ) => {
848        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
849        pub enum $name {
850            #[cfg(wgpu_core)]
851            Core($core_type),
852            #[cfg(webgpu)]
853            WebGPU($webgpu_type),
854            #[allow(clippy::allow_attributes, private_interfaces)]
855            #[cfg(custom)]
856            Custom($custom_type),
857        }
858
859        impl $name {
860            #[cfg(wgpu_core)]
861            #[inline]
862            #[allow(clippy::allow_attributes, unused)]
863            pub fn as_core(&self) -> &$core_type {
864                match self {
865                    Self::Core(value) => value,
866                    _ => panic!(concat!(stringify!($name), " is not core")),
867                }
868            }
869
870            #[cfg(wgpu_core)]
871            #[inline]
872            #[allow(clippy::allow_attributes, unused)]
873            pub fn as_core_opt(&self) -> Option<&$core_type> {
874                match self {
875                    Self::Core(value) => Some(value),
876                    _ => None,
877                }
878            }
879
880            #[cfg(custom)]
881            #[inline]
882            #[allow(clippy::allow_attributes, unused)]
883            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
884                match self {
885                    Self::Custom(value) => value.downcast(),
886                    _ => None,
887                }
888            }
889
890            #[cfg(webgpu)]
891            #[inline]
892            #[allow(clippy::allow_attributes, unused)]
893            pub fn as_webgpu(&self) -> &$webgpu_type {
894                match self {
895                    Self::WebGPU(value) => value,
896                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
897                }
898            }
899
900            #[cfg(webgpu)]
901            #[inline]
902            #[allow(clippy::allow_attributes, unused)]
903            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
904                match self {
905                    Self::WebGPU(value) => Some(value),
906                    _ => None,
907                }
908            }
909
910            #[cfg(custom)]
911            #[inline]
912            pub fn custom<T: $interface>(t: T) -> Self {
913                Self::Custom($custom_type::new(t))
914            }
915        }
916
917        #[cfg(wgpu_core)]
918        impl From<$core_type> for $name {
919            #[inline]
920            fn from(value: $core_type) -> Self {
921                Self::Core(value)
922            }
923        }
924
925        #[cfg(webgpu)]
926        impl From<$webgpu_type> for $name {
927            #[inline]
928            fn from(value: $webgpu_type) -> Self {
929                Self::WebGPU(value)
930            }
931        }
932
933        impl core::ops::Deref for $name {
934            type Target = dyn $interface;
935
936            #[inline]
937            fn deref(&self) -> &Self::Target {
938                match self {
939                    #[cfg(wgpu_core)]
940                    Self::Core(value) => value,
941                    #[cfg(webgpu)]
942                    Self::WebGPU(value) => value,
943                    #[cfg(custom)]
944                    Self::Custom(value) => value.deref(),
945                    #[cfg(not(any(wgpu_core, webgpu)))]
946                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
947                }
948            }
949        }
950
951        explicit_send_sync_impl!($name);
952    };
953    (
954        mut type $name:ident: $interface:ident = $core_type:ident,$webgpu_type:ident,$custom_type:ident
955    ) => {
956        #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
957        pub enum $name {
958            #[cfg(wgpu_core)]
959            Core($core_type),
960            #[cfg(webgpu)]
961            WebGPU($webgpu_type),
962            #[allow(clippy::allow_attributes, private_interfaces)]
963            #[cfg(custom)]
964            Custom($custom_type),
965        }
966
967        impl $name {
968            #[cfg(wgpu_core)]
969            #[inline]
970            #[allow(clippy::allow_attributes, unused)]
971            pub fn as_core(&self) -> &$core_type {
972                match self {
973                    Self::Core(value) => value,
974                    _ => panic!(concat!(stringify!($name), " is not core")),
975                }
976            }
977
978            #[cfg(wgpu_core)]
979            #[inline]
980            #[allow(clippy::allow_attributes, unused)]
981            pub fn as_core_mut(&mut self) -> &mut $core_type {
982                match self {
983                    Self::Core(value) => value,
984                    _ => panic!(concat!(stringify!($name), " is not core")),
985                }
986            }
987
988            #[cfg(wgpu_core)]
989            #[inline]
990            #[allow(clippy::allow_attributes, unused)]
991            pub fn as_core_opt(&self) -> Option<&$core_type> {
992                match self {
993                    Self::Core(value) => Some(value),
994                    _ => None,
995                }
996            }
997
998            #[cfg(wgpu_core)]
999            #[inline]
1000            #[allow(clippy::allow_attributes, unused)]
1001            pub fn as_core_mut_opt(
1002                &mut self,
1003            ) -> Option<&mut $core_type> {
1004                match self {
1005                    Self::Core(value) => Some(value),
1006                    _ => None,
1007                }
1008            }
1009
1010            #[cfg(custom)]
1011            #[inline]
1012            #[allow(clippy::allow_attributes, unused)]
1013            pub fn as_custom<T: $interface>(&self) -> Option<&T> {
1014                match self {
1015                    Self::Custom(value) => value.downcast(),
1016                    _ => None,
1017                }
1018            }
1019
1020            #[cfg(webgpu)]
1021            #[inline]
1022            #[allow(clippy::allow_attributes, unused)]
1023            pub fn as_webgpu(&self) -> &$webgpu_type {
1024                match self {
1025                    Self::WebGPU(value) => value,
1026                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
1027                }
1028            }
1029
1030            #[cfg(webgpu)]
1031            #[inline]
1032            #[allow(clippy::allow_attributes, unused)]
1033            pub fn as_webgpu_mut(&mut self) -> &mut $webgpu_type {
1034                match self {
1035                    Self::WebGPU(value) => value,
1036                    _ => panic!(concat!(stringify!($name), " is not webgpu")),
1037                }
1038            }
1039
1040            #[cfg(webgpu)]
1041            #[inline]
1042            #[allow(clippy::allow_attributes, unused)]
1043            pub fn as_webgpu_opt(&self) -> Option<&$webgpu_type> {
1044                match self {
1045                    Self::WebGPU(value) => Some(value),
1046                    _ => None,
1047                }
1048            }
1049
1050            #[cfg(webgpu)]
1051            #[inline]
1052            #[allow(clippy::allow_attributes, unused)]
1053            pub fn as_webgpu_mut_opt(
1054                &mut self,
1055            ) -> Option<&mut $webgpu_type> {
1056                match self {
1057                    Self::WebGPU(value) => Some(value),
1058                    _ => None,
1059                }
1060            }
1061
1062            #[cfg(custom)]
1063            #[inline]
1064            pub fn custom<T: $interface>(t: T) -> Self {
1065                Self::Custom($custom_type::new(t))
1066            }
1067        }
1068
1069        #[cfg(wgpu_core)]
1070        impl From<$core_type> for $name {
1071            #[inline]
1072            fn from(value: $core_type) -> Self {
1073                Self::Core(value)
1074            }
1075        }
1076
1077        #[cfg(webgpu)]
1078        impl From<$webgpu_type> for $name {
1079            #[inline]
1080            fn from(value: $webgpu_type) -> Self {
1081                Self::WebGPU(value)
1082            }
1083        }
1084
1085        impl core::ops::Deref for $name {
1086            type Target = dyn $interface;
1087
1088            #[inline]
1089            fn deref(&self) -> &Self::Target {
1090                match self {
1091                    #[cfg(wgpu_core)]
1092                    Self::Core(value) => value,
1093                    #[cfg(webgpu)]
1094                    Self::WebGPU(value) => value,
1095                    #[cfg(custom)]
1096                    Self::Custom(value) => value.deref(),
1097                    #[cfg(not(any(wgpu_core, webgpu)))]
1098                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
1099                }
1100            }
1101        }
1102
1103        impl core::ops::DerefMut for $name {
1104            #[inline]
1105            fn deref_mut(&mut self) -> &mut Self::Target {
1106                match self {
1107                    #[cfg(wgpu_core)]
1108                    Self::Core(value) => value,
1109                    #[cfg(webgpu)]
1110                    Self::WebGPU(value) => value,
1111                    #[cfg(custom)]
1112                    Self::Custom(value) => value.deref_mut(),
1113                    #[cfg(not(any(wgpu_core, webgpu)))]
1114                    _ => panic!("No context available. You need to enable one of wgpu's backend feature build flags."),
1115                }
1116            }
1117        }
1118
1119        explicit_send_sync_impl!($name);
1120    };
1121}
1122
1123dispatch_types! {ref type DispatchInstance: InstanceInterface = ContextWgpuCore, ContextWebGpu, DynContext}
1124dispatch_types! {ref type DispatchAdapter: AdapterInterface = CoreAdapter, WebAdapter, DynAdapter}
1125dispatch_types! {ref type DispatchDevice: DeviceInterface = CoreDevice, WebDevice, DynDevice}
1126dispatch_types! {ref type DispatchQueue: QueueInterface = CoreQueue, WebQueue, DynQueue}
1127dispatch_types! {ref type DispatchShaderModule: ShaderModuleInterface = CoreShaderModule, WebShaderModule, DynShaderModule}
1128dispatch_types! {ref type DispatchBindGroupLayout: BindGroupLayoutInterface = CoreBindGroupLayout, WebBindGroupLayout, DynBindGroupLayout}
1129dispatch_types! {ref type DispatchBindGroup: BindGroupInterface = CoreBindGroup, WebBindGroup, DynBindGroup}
1130dispatch_types! {ref type DispatchTextureView: TextureViewInterface = CoreTextureView, WebTextureView, DynTextureView}
1131dispatch_types! {ref type DispatchSampler: SamplerInterface = CoreSampler, WebSampler, DynSampler}
1132dispatch_types! {ref type DispatchBuffer: BufferInterface = CoreBuffer, WebBuffer, DynBuffer}
1133dispatch_types! {ref type DispatchTexture: TextureInterface = CoreTexture, WebTexture, DynTexture}
1134dispatch_types! {ref type DispatchExternalTexture: ExternalTextureInterface = CoreExternalTexture, WebExternalTexture, DynExternalTexture}
1135dispatch_types! {ref type DispatchBlas: BlasInterface = CoreBlas, WebBlas, DynBlas}
1136dispatch_types! {ref type DispatchTlas: TlasInterface = CoreTlas, WebTlas, DynTlas}
1137dispatch_types! {ref type DispatchQuerySet: QuerySetInterface = CoreQuerySet, WebQuerySet, DynQuerySet}
1138dispatch_types! {ref type DispatchPipelineLayout: PipelineLayoutInterface = CorePipelineLayout, WebPipelineLayout, DynPipelineLayout}
1139dispatch_types! {ref type DispatchRenderPipeline: RenderPipelineInterface = CoreRenderPipeline, WebRenderPipeline, DynRenderPipeline}
1140dispatch_types! {ref type DispatchComputePipeline: ComputePipelineInterface = CoreComputePipeline, WebComputePipeline, DynComputePipeline}
1141dispatch_types! {ref type DispatchRayTracingPipeline: RayTracingPipelineInterface = CoreRayTracingPipeline, WebRayTracingPipeline, DynRayTracingPipeline}
1142dispatch_types! {ref type DispatchPipelineCache: PipelineCacheInterface = CorePipelineCache, WebPipelineCache, DynPipelineCache}
1143dispatch_types! {mut type DispatchCommandEncoder: CommandEncoderInterface = CoreCommandEncoder, WebCommandEncoder, DynCommandEncoder}
1144dispatch_types! {mut type DispatchComputePass: ComputePassInterface = CoreComputePass, WebComputePassEncoder, DynComputePass}
1145dispatch_types! {mut type DispatchRenderPass: RenderPassInterface = CoreRenderPass, WebRenderPassEncoder, DynRenderPass}
1146dispatch_types! {mut type DispatchRayTracingPass: RayTracingPassInterface = CoreRayTracingPass, WebRayTracingPassEncoder, DynRayTracingPass}
1147dispatch_types! {mut type DispatchCommandBuffer: CommandBufferInterface = CoreCommandBuffer, WebCommandBuffer, DynCommandBuffer}
1148dispatch_types! {mut type DispatchRenderBundleEncoder: RenderBundleEncoderInterface = CoreRenderBundleEncoder, WebRenderBundleEncoder, DynRenderBundleEncoder}
1149dispatch_types! {ref type DispatchRenderBundle: RenderBundleInterface = CoreRenderBundle, WebRenderBundle, DynRenderBundle}
1150dispatch_types! {ref type DispatchSurface: SurfaceInterface = CoreSurface, WebSurface, DynSurface}
1151dispatch_types! {ref type DispatchSurfaceOutputDetail: SurfaceOutputDetailInterface = CoreSurfaceOutputDetail, WebSurfaceOutputDetail, DynSurfaceOutputDetail}
1152dispatch_types! {mut type DispatchQueueWriteBuffer: QueueWriteBufferInterface = CoreQueueWriteBuffer, WebQueueWriteBuffer, DynQueueWriteBuffer}
1153dispatch_types! {mut type DispatchBufferMappedRange: BufferMappedRangeInterface = CoreBufferMappedRange, WebBufferMappedRange, DynBufferMappedRange}