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