Skip to main content

wgpu/util/
mod.rs

1//! Utility structures and functions that are built on top of the main `wgpu` API.
2//!
3//! Nothing in this module is a part of the WebGPU API specification;
4//! they are unique to the `wgpu` library.
5
6mod belt;
7mod device;
8mod encoder;
9mod init;
10#[cfg(webgpu)]
11mod panicking;
12mod spirv;
13mod texture_blitter;
14
15use alloc::{format, string::String};
16
17pub use belt::StagingBelt;
18pub use device::{BufferInitDescriptor, DeviceExt};
19pub use encoder::RenderEncoder;
20pub use init::*;
21pub use spirv::*;
22#[cfg(feature = "wgsl")]
23pub use texture_blitter::{TextureBlitter, TextureBlitterBuilder};
24pub use wgt::{
25    math::*, DispatchIndirectArgs, DrawIndexedIndirectArgs, DrawIndirectArgs, TextureDataOrder,
26};
27
28#[cfg(webgpu)]
29pub(crate) use panicking::is_panicking;
30pub(crate) use wgpu_sync::Mutex;
31
32use crate::BufferUsages;
33
34/// CPU-accessible buffer used to retrieve data from buffers that cannot or must not be mapped.
35///
36/// This utility is a convenience wrapper around creating and mapping a temporary
37/// [`Buffer`][crate::Buffer].
38#[derive(Debug)]
39pub struct DownloadBuffer {
40    view: crate::BufferView,
41}
42
43impl DownloadBuffer {
44    /// Asynchronously read the contents of a buffer by copying it to a staging buffer.
45    ///
46    /// `buffer_slice`’s buffer must have been created with [`BufferUsages::COPY_SRC`].
47    /// The slice’s size must be a multiple of 4.
48    ///
49    /// `callback` will be called when the data is available.
50    /// If you are not submitting further work, you must call
51    /// [`Device::poll()`][crate::Device::poll] repeatedly until the callback completes.
52    pub fn read_buffer(
53        device: &super::Device,
54        queue: &super::Queue,
55        buffer_slice: &super::BufferSlice<'_>,
56        callback: impl FnOnce(Result<Self, super::BufferAsyncError>) + Send + 'static,
57    ) {
58        let size = buffer_slice.size;
59
60        let temporary_buffer = device.create_buffer(&super::BufferDescriptor {
61            size,
62            usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
63            mapped_at_creation: false,
64            label: None,
65        });
66
67        let mut encoder =
68            device.create_command_encoder(&super::CommandEncoderDescriptor { label: None });
69        encoder.copy_buffer_to_buffer(
70            buffer_slice.buffer,
71            buffer_slice.offset,
72            &temporary_buffer,
73            0,
74            size,
75        );
76        queue.submit([encoder.finish()]);
77
78        temporary_buffer
79            .clone()
80            .map_async(super::MapMode::Read, .., move |result| {
81                if let Err(e) = result {
82                    callback(Err(e));
83                    return;
84                }
85
86                let view = match temporary_buffer.get_mapped_range(0..size) {
87                    Ok(range) => range,
88                    Err(e) => {
89                        callback(Err(super::BufferAsyncError));
90                        log::error!("Failed to get mapped range: {e}");
91                        return;
92                    }
93                };
94                callback(Ok(Self { view }));
95            });
96    }
97}
98
99impl core::ops::Deref for DownloadBuffer {
100    type Target = [u8];
101    fn deref(&self) -> &[u8] {
102        &self.view
103    }
104}
105
106/// A recommended key for storing [`PipelineCache`]s for the adapter
107/// associated with the given [`AdapterInfo`](wgt::AdapterInfo)
108/// This key will define a class of adapters for which the same cache
109/// might be valid.
110///
111/// If this returns `None`, the adapter doesn't support [`PipelineCache`].
112/// This may be because the API doesn't support application managed caches
113/// (such as browser WebGPU), or that `wgpu` hasn't implemented it for
114/// that API yet.
115///
116/// This key could be used as a filename, as seen in the example below.
117///
118/// # Examples
119///
120/// ```no_run
121/// # use std::path::PathBuf;
122/// use wgpu::PipelineCacheDescriptor;
123/// # let adapter_info = todo!();
124/// # let device: wgpu::Device = todo!();
125/// let cache_dir: PathBuf = unimplemented!("Some reasonable platform-specific cache directory for your app.");
126/// let filename = wgpu::util::pipeline_cache_key(&adapter_info);
127/// let (pipeline_cache, cache_file) = if let Some(filename) = filename {
128///     let cache_path = cache_dir.join(&filename);
129///     // If we failed to read the cache, for whatever reason, treat the data as lost.
130///     // In a real app, we'd probably avoid caching entirely unless the error was "file not found".
131///     let cache_data = std::fs::read(&cache_path).ok();
132///     let pipeline_cache = unsafe {
133///         device.create_pipeline_cache(&PipelineCacheDescriptor {
134///             data: cache_data.as_deref(),
135///             label: None,
136///             fallback: true
137///         })
138///     };
139///     (Some(pipeline_cache), Some(cache_path))
140/// } else {
141///     (None, None)
142/// };
143///
144/// // Run pipeline initialisation, making sure to set the `cache`
145/// // fields of your `*PipelineDescriptor` to `pipeline_cache`
146///
147/// // And then save the resulting cache (probably off the main thread).
148/// if let (Some(pipeline_cache), Some(cache_file)) = (pipeline_cache, cache_file) {
149///     let data = pipeline_cache.get_data();
150///     if let Some(data) = data {
151///         let temp_file = cache_file.with_extension("temp");
152///         std::fs::write(&temp_file, &data)?;
153///         std::fs::rename(&temp_file, &cache_file)?;
154///     }
155/// }
156/// # Ok::<_, std::io::Error>(())
157/// ```
158///
159/// [`PipelineCache`]: super::PipelineCache
160pub fn pipeline_cache_key(adapter_info: &wgt::AdapterInfo) -> Option<String> {
161    match adapter_info.backend {
162        wgt::Backend::Vulkan => Some(format!(
163            // The vendor/device should uniquely define a driver
164            // We/the driver will also later validate that the vendor/device and driver
165            // version match, which may lead to clearing an outdated
166            // cache for the same device.
167            "wgpu_pipeline_cache_vulkan_{}_{}",
168            adapter_info.vendor, adapter_info.device
169        )),
170        _ => None,
171    }
172}
173
174/// Adds extra conversion functions to `TextureFormat`.
175pub trait TextureFormatExt {
176    /// Finds the [`TextureFormat`](wgt::TextureFormat) corresponding to the given
177    /// [`StorageFormat`](wgc::naga::StorageFormat).
178    ///
179    /// # Examples
180    /// ```
181    /// use wgpu::util::TextureFormatExt;
182    /// assert_eq!(wgpu::TextureFormat::from_storage_format(wgpu::naga::StorageFormat::Bgra8Unorm), wgpu::TextureFormat::Bgra8Unorm);
183    /// ```
184    #[cfg(wgpu_core)]
185    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self;
186
187    /// Finds the [`StorageFormat`](wgc::naga::StorageFormat) corresponding to the given [`TextureFormat`](wgt::TextureFormat).
188    /// Returns `None` if there is no matching storage format,
189    /// which typically indicates this format is not supported
190    /// for storage textures.
191    ///
192    /// # Examples
193    /// ```
194    /// use wgpu::util::TextureFormatExt;
195    /// assert_eq!(wgpu::TextureFormat::Bgra8Unorm.to_storage_format(), Some(wgpu::naga::StorageFormat::Bgra8Unorm));
196    /// ```
197    #[cfg(wgpu_core)]
198    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat>;
199}
200
201impl TextureFormatExt for wgt::TextureFormat {
202    #[cfg(wgpu_core)]
203    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self {
204        wgc::map_storage_format_from_naga(storage_format)
205    }
206
207    #[cfg(wgpu_core)]
208    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat> {
209        wgc::map_storage_format_to_naga(*self)
210    }
211}