wgpu_hal/noop/
mod.rs

1#![allow(unused_variables)]
2
3use alloc::{string::String, vec, vec::Vec};
4use core::{ptr, sync::atomic::Ordering, time::Duration};
5
6#[cfg(supports_64bit_atomics)]
7use core::sync::atomic::AtomicU64;
8#[cfg(not(supports_64bit_atomics))]
9use portable_atomic::AtomicU64;
10
11use crate::TlasInstance;
12
13mod buffer;
14pub use buffer::Buffer;
15mod command;
16pub use command::CommandBuffer;
17
18#[derive(Clone, Debug)]
19pub struct Api;
20pub struct Context;
21#[derive(Debug)]
22pub struct Encoder;
23#[derive(Debug)]
24pub struct Resource;
25
26#[derive(Debug)]
27pub struct Fence {
28    value: AtomicU64,
29}
30
31type DeviceResult<T> = Result<T, crate::DeviceError>;
32
33impl crate::Api for Api {
34    const VARIANT: wgt::Backend = wgt::Backend::Noop;
35
36    type Instance = Context;
37    type Surface = Context;
38    type Adapter = Context;
39    type Device = Context;
40
41    type Queue = Context;
42    type CommandEncoder = CommandBuffer;
43    type CommandBuffer = CommandBuffer;
44
45    type Buffer = Buffer;
46    type Texture = Resource;
47    type SurfaceTexture = Resource;
48    type TextureView = Resource;
49    type Sampler = Resource;
50    type QuerySet = Resource;
51    type Fence = Fence;
52    type AccelerationStructure = Resource;
53    type PipelineCache = Resource;
54
55    type BindGroupLayout = Resource;
56    type BindGroup = Resource;
57    type PipelineLayout = Resource;
58    type ShaderModule = Resource;
59    type RenderPipeline = Resource;
60    type ComputePipeline = Resource;
61}
62
63crate::impl_dyn_resource!(Buffer, CommandBuffer, Context, Fence, Resource);
64
65impl crate::DynAccelerationStructure for Resource {}
66impl crate::DynBindGroup for Resource {}
67impl crate::DynBindGroupLayout for Resource {}
68impl crate::DynBuffer for Buffer {}
69impl crate::DynCommandBuffer for CommandBuffer {}
70impl crate::DynComputePipeline for Resource {}
71impl crate::DynFence for Fence {}
72impl crate::DynPipelineCache for Resource {}
73impl crate::DynPipelineLayout for Resource {}
74impl crate::DynQuerySet for Resource {}
75impl crate::DynRenderPipeline for Resource {}
76impl crate::DynSampler for Resource {}
77impl crate::DynShaderModule for Resource {}
78impl crate::DynSurfaceTexture for Resource {}
79impl crate::DynTexture for Resource {}
80impl crate::DynTextureView for Resource {}
81
82impl core::borrow::Borrow<dyn crate::DynTexture> for Resource {
83    fn borrow(&self) -> &dyn crate::DynTexture {
84        self
85    }
86}
87
88impl crate::Instance for Context {
89    type A = Api;
90
91    unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
92        let crate::InstanceDescriptor {
93            backend_options:
94                wgt::BackendOptions {
95                    noop: wgt::NoopBackendOptions { enable },
96                    ..
97                },
98            name: _,
99            flags: _,
100            memory_budget_thresholds: _,
101            telemetry: _,
102        } = *desc;
103        if enable {
104            Ok(Context)
105        } else {
106            Err(crate::InstanceError::new(String::from(
107                "noop backend disabled because NoopBackendOptions::enable is false",
108            )))
109        }
110    }
111    unsafe fn create_surface(
112        &self,
113        _display_handle: raw_window_handle::RawDisplayHandle,
114        _window_handle: raw_window_handle::RawWindowHandle,
115    ) -> Result<Context, crate::InstanceError> {
116        Ok(Context)
117    }
118    unsafe fn enumerate_adapters(
119        &self,
120        _surface_hint: Option<&Context>,
121    ) -> Vec<crate::ExposedAdapter<Api>> {
122        vec![crate::ExposedAdapter {
123            adapter: Context,
124            info: adapter_info(),
125            features: wgt::Features::all(),
126            capabilities: CAPABILITIES,
127        }]
128    }
129}
130
131/// Returns the adapter info for the noop backend.
132///
133/// This is used in the test harness to construct info about
134/// the noop backend adapter without actually initializing wgpu.
135pub fn adapter_info() -> wgt::AdapterInfo {
136    wgt::AdapterInfo {
137        name: String::from("noop wgpu backend"),
138        vendor: 0,
139        device: 0,
140        device_type: wgt::DeviceType::Cpu,
141        device_pci_bus_id: String::new(),
142        driver: String::from("wgpu"),
143        driver_info: String::new(),
144        backend: wgt::Backend::Noop,
145        subgroup_min_size: wgt::MINIMUM_SUBGROUP_MIN_SIZE,
146        subgroup_max_size: wgt::MAXIMUM_SUBGROUP_MAX_SIZE,
147        transient_saves_memory: false,
148    }
149}
150
151/// The capabilities of the noop backend.
152///
153/// This is used in the test harness to construct capabilities
154/// of the noop backend without actually initializing wgpu.
155pub const CAPABILITIES: crate::Capabilities = {
156    /// Guaranteed to be no bigger than isize::MAX which is the maximum size of an allocation,
157    /// except on 16-bit platforms which we certainly don’t fit in.
158    const ALLOC_MAX_U32: u32 = i32::MAX as u32;
159
160    crate::Capabilities {
161        limits: wgt::Limits {
162            // All maximally permissive
163            max_texture_dimension_1d: ALLOC_MAX_U32,
164            max_texture_dimension_2d: ALLOC_MAX_U32,
165            max_texture_dimension_3d: ALLOC_MAX_U32,
166            max_texture_array_layers: ALLOC_MAX_U32,
167            max_bind_groups: ALLOC_MAX_U32,
168            max_bindings_per_bind_group: ALLOC_MAX_U32,
169            max_dynamic_uniform_buffers_per_pipeline_layout: ALLOC_MAX_U32,
170            max_dynamic_storage_buffers_per_pipeline_layout: ALLOC_MAX_U32,
171            max_sampled_textures_per_shader_stage: ALLOC_MAX_U32,
172            max_samplers_per_shader_stage: ALLOC_MAX_U32,
173            max_storage_buffers_per_shader_stage: ALLOC_MAX_U32,
174            max_storage_textures_per_shader_stage: ALLOC_MAX_U32,
175            max_uniform_buffers_per_shader_stage: ALLOC_MAX_U32,
176            max_binding_array_elements_per_shader_stage: ALLOC_MAX_U32,
177            max_binding_array_sampler_elements_per_shader_stage: ALLOC_MAX_U32,
178            max_uniform_buffer_binding_size: ALLOC_MAX_U32,
179            max_storage_buffer_binding_size: ALLOC_MAX_U32,
180            max_vertex_buffers: ALLOC_MAX_U32,
181            max_buffer_size: ALLOC_MAX_U32 as u64,
182            max_vertex_attributes: ALLOC_MAX_U32,
183            max_vertex_buffer_array_stride: ALLOC_MAX_U32,
184            min_uniform_buffer_offset_alignment: 1,
185            min_storage_buffer_offset_alignment: 1,
186            max_inter_stage_shader_components: ALLOC_MAX_U32,
187            max_color_attachments: ALLOC_MAX_U32,
188            max_color_attachment_bytes_per_sample: ALLOC_MAX_U32,
189            max_compute_workgroup_storage_size: ALLOC_MAX_U32,
190            max_compute_invocations_per_workgroup: ALLOC_MAX_U32,
191            max_compute_workgroup_size_x: ALLOC_MAX_U32,
192            max_compute_workgroup_size_y: ALLOC_MAX_U32,
193            max_compute_workgroup_size_z: ALLOC_MAX_U32,
194            max_compute_workgroups_per_dimension: ALLOC_MAX_U32,
195            max_immediate_size: ALLOC_MAX_U32,
196            max_non_sampler_bindings: ALLOC_MAX_U32,
197
198            max_task_mesh_workgroup_total_count: ALLOC_MAX_U32,
199            max_task_mesh_workgroups_per_dimension: ALLOC_MAX_U32,
200            max_task_invocations_per_workgroup: ALLOC_MAX_U32,
201            max_task_invocations_per_dimension: ALLOC_MAX_U32,
202            max_mesh_invocations_per_workgroup: ALLOC_MAX_U32,
203            max_mesh_invocations_per_dimension: ALLOC_MAX_U32,
204            max_task_payload_size: ALLOC_MAX_U32,
205            max_mesh_output_vertices: ALLOC_MAX_U32,
206            max_mesh_output_primitives: ALLOC_MAX_U32,
207            max_mesh_output_layers: ALLOC_MAX_U32,
208            max_mesh_multiview_view_count: ALLOC_MAX_U32,
209
210            max_blas_primitive_count: ALLOC_MAX_U32,
211            max_blas_geometry_count: ALLOC_MAX_U32,
212            max_tlas_instance_count: ALLOC_MAX_U32,
213            max_acceleration_structures_per_shader_stage: ALLOC_MAX_U32,
214
215            max_multiview_view_count: ALLOC_MAX_U32,
216        },
217        alignments: crate::Alignments {
218            // All maximally permissive
219            buffer_copy_offset: wgt::BufferSize::MIN,
220            buffer_copy_pitch: wgt::BufferSize::MIN,
221            uniform_bounds_check_alignment: wgt::BufferSize::MIN,
222            raw_tlas_instance_size: 0,
223            ray_tracing_scratch_buffer_alignment: 1,
224        },
225        downlevel: wgt::DownlevelCapabilities {
226            flags: wgt::DownlevelFlags::all(),
227            limits: wgt::DownlevelLimits {},
228            shader_model: wgt::ShaderModel::Sm5,
229        },
230    }
231};
232
233impl crate::Surface for Context {
234    type A = Api;
235
236    unsafe fn configure(
237        &self,
238        device: &Context,
239        config: &crate::SurfaceConfiguration,
240    ) -> Result<(), crate::SurfaceError> {
241        Ok(())
242    }
243
244    unsafe fn unconfigure(&self, device: &Context) {}
245
246    unsafe fn acquire_texture(
247        &self,
248        timeout: Option<Duration>,
249        fence: &Fence,
250    ) -> Result<Option<crate::AcquiredSurfaceTexture<Api>>, crate::SurfaceError> {
251        Ok(None)
252    }
253    unsafe fn discard_texture(&self, texture: Resource) {}
254}
255
256impl crate::Adapter for Context {
257    type A = Api;
258
259    unsafe fn open(
260        &self,
261        features: wgt::Features,
262        _limits: &wgt::Limits,
263        _memory_hints: &wgt::MemoryHints,
264    ) -> DeviceResult<crate::OpenDevice<Api>> {
265        Ok(crate::OpenDevice {
266            device: Context,
267            queue: Context,
268        })
269    }
270    unsafe fn texture_format_capabilities(
271        &self,
272        format: wgt::TextureFormat,
273    ) -> crate::TextureFormatCapabilities {
274        crate::TextureFormatCapabilities::empty()
275    }
276
277    unsafe fn surface_capabilities(&self, surface: &Context) -> Option<crate::SurfaceCapabilities> {
278        None
279    }
280
281    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
282        wgt::PresentationTimestamp::INVALID_TIMESTAMP
283    }
284}
285
286impl crate::Queue for Context {
287    type A = Api;
288
289    unsafe fn submit(
290        &self,
291        command_buffers: &[&CommandBuffer],
292        surface_textures: &[&Resource],
293        (fence, fence_value): (&mut Fence, crate::FenceValue),
294    ) -> DeviceResult<()> {
295        // All commands are executed synchronously.
296        for cb in command_buffers {
297            // SAFETY: Caller is responsible for ensuring synchronization between commands and
298            // other mutations.
299            unsafe {
300                cb.execute();
301            }
302        }
303        fence.value.store(fence_value, Ordering::Release);
304        Ok(())
305    }
306    unsafe fn present(
307        &self,
308        surface: &Context,
309        texture: Resource,
310    ) -> Result<(), crate::SurfaceError> {
311        Ok(())
312    }
313
314    unsafe fn get_timestamp_period(&self) -> f32 {
315        1.0
316    }
317}
318
319impl crate::Device for Context {
320    type A = Api;
321
322    unsafe fn create_buffer(&self, desc: &crate::BufferDescriptor) -> DeviceResult<Buffer> {
323        Buffer::new(desc)
324    }
325
326    unsafe fn destroy_buffer(&self, buffer: Buffer) {}
327    unsafe fn add_raw_buffer(&self, _buffer: &Buffer) {}
328
329    unsafe fn map_buffer(
330        &self,
331        buffer: &Buffer,
332        range: crate::MemoryRange,
333    ) -> DeviceResult<crate::BufferMapping> {
334        // Safety: the `wgpu-core` validation layer will prevent any user-accessible aliasing
335        // mappings from being created, so we don’t need to perform any checks here, except for
336        // bounds checks on the range which are built into `get_slice_ptr()`.
337        Ok(crate::BufferMapping {
338            ptr: ptr::NonNull::new(buffer.get_slice_ptr(range).cast::<u8>()).unwrap(),
339            is_coherent: true,
340        })
341    }
342    unsafe fn unmap_buffer(&self, buffer: &Buffer) {}
343    unsafe fn flush_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {}
344    unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {}
345
346    unsafe fn create_texture(&self, desc: &crate::TextureDescriptor) -> DeviceResult<Resource> {
347        Ok(Resource)
348    }
349    unsafe fn destroy_texture(&self, texture: Resource) {}
350    unsafe fn add_raw_texture(&self, _texture: &Resource) {}
351
352    unsafe fn create_texture_view(
353        &self,
354        texture: &Resource,
355        desc: &crate::TextureViewDescriptor,
356    ) -> DeviceResult<Resource> {
357        Ok(Resource)
358    }
359    unsafe fn destroy_texture_view(&self, view: Resource) {}
360    unsafe fn create_sampler(&self, desc: &crate::SamplerDescriptor) -> DeviceResult<Resource> {
361        Ok(Resource)
362    }
363    unsafe fn destroy_sampler(&self, sampler: Resource) {}
364
365    unsafe fn create_command_encoder(
366        &self,
367        desc: &crate::CommandEncoderDescriptor<Context>,
368    ) -> DeviceResult<CommandBuffer> {
369        Ok(CommandBuffer::new())
370    }
371
372    unsafe fn create_bind_group_layout(
373        &self,
374        desc: &crate::BindGroupLayoutDescriptor,
375    ) -> DeviceResult<Resource> {
376        Ok(Resource)
377    }
378    unsafe fn destroy_bind_group_layout(&self, bg_layout: Resource) {}
379    unsafe fn create_pipeline_layout(
380        &self,
381        desc: &crate::PipelineLayoutDescriptor<Resource>,
382    ) -> DeviceResult<Resource> {
383        Ok(Resource)
384    }
385    unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Resource) {}
386    unsafe fn create_bind_group(
387        &self,
388        desc: &crate::BindGroupDescriptor<Resource, Buffer, Resource, Resource, Resource>,
389    ) -> DeviceResult<Resource> {
390        Ok(Resource)
391    }
392    unsafe fn destroy_bind_group(&self, group: Resource) {}
393
394    unsafe fn create_shader_module(
395        &self,
396        desc: &crate::ShaderModuleDescriptor,
397        shader: crate::ShaderInput,
398    ) -> Result<Resource, crate::ShaderError> {
399        Ok(Resource)
400    }
401    unsafe fn destroy_shader_module(&self, module: Resource) {}
402    unsafe fn create_render_pipeline(
403        &self,
404        desc: &crate::RenderPipelineDescriptor<Resource, Resource, Resource>,
405    ) -> Result<Resource, crate::PipelineError> {
406        Ok(Resource)
407    }
408    unsafe fn destroy_render_pipeline(&self, pipeline: Resource) {}
409    unsafe fn create_compute_pipeline(
410        &self,
411        desc: &crate::ComputePipelineDescriptor<Resource, Resource, Resource>,
412    ) -> Result<Resource, crate::PipelineError> {
413        Ok(Resource)
414    }
415    unsafe fn destroy_compute_pipeline(&self, pipeline: Resource) {}
416    unsafe fn create_pipeline_cache(
417        &self,
418        desc: &crate::PipelineCacheDescriptor<'_>,
419    ) -> Result<Resource, crate::PipelineCacheError> {
420        Ok(Resource)
421    }
422    unsafe fn destroy_pipeline_cache(&self, cache: Resource) {}
423
424    unsafe fn create_query_set(
425        &self,
426        desc: &wgt::QuerySetDescriptor<crate::Label>,
427    ) -> DeviceResult<Resource> {
428        Ok(Resource)
429    }
430    unsafe fn destroy_query_set(&self, set: Resource) {}
431    unsafe fn create_fence(&self) -> DeviceResult<Fence> {
432        Ok(Fence {
433            value: AtomicU64::new(0),
434        })
435    }
436    unsafe fn destroy_fence(&self, fence: Fence) {}
437    unsafe fn get_fence_value(&self, fence: &Fence) -> DeviceResult<crate::FenceValue> {
438        Ok(fence.value.load(Ordering::Acquire))
439    }
440    unsafe fn wait(
441        &self,
442        fence: &Fence,
443        value: crate::FenceValue,
444        timeout: Option<Duration>,
445    ) -> DeviceResult<bool> {
446        // The relevant commands must have already been submitted, and noop-backend commands are
447        // executed synchronously, so there is no waiting — either it is already done,
448        // or this method was called incorrectly.
449        assert!(
450            fence.value.load(Ordering::Acquire) >= value,
451            "submission must have already been done"
452        );
453        Ok(true)
454    }
455
456    unsafe fn start_graphics_debugger_capture(&self) -> bool {
457        false
458    }
459    unsafe fn stop_graphics_debugger_capture(&self) {}
460    unsafe fn create_acceleration_structure(
461        &self,
462        desc: &crate::AccelerationStructureDescriptor,
463    ) -> DeviceResult<Resource> {
464        Ok(Resource)
465    }
466    unsafe fn get_acceleration_structure_build_sizes<'a>(
467        &self,
468        _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, Buffer>,
469    ) -> crate::AccelerationStructureBuildSizes {
470        Default::default()
471    }
472    unsafe fn get_acceleration_structure_device_address(
473        &self,
474        _acceleration_structure: &Resource,
475    ) -> wgt::BufferAddress {
476        Default::default()
477    }
478    unsafe fn destroy_acceleration_structure(&self, _acceleration_structure: Resource) {}
479
480    fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> {
481        vec![]
482    }
483
484    fn get_internal_counters(&self) -> wgt::HalCounters {
485        Default::default()
486    }
487
488    fn check_if_oom(&self) -> DeviceResult<()> {
489        Ok(())
490    }
491}