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;
10mod texture_blitter;
11
12use std::sync::Arc;
13use std::{borrow::Cow, ptr::copy_nonoverlapping};
14
15pub use belt::StagingBelt;
16pub use device::{BufferInitDescriptor, DeviceExt};
17pub use encoder::RenderEncoder;
18pub use init::*;
19#[cfg(feature = "wgsl")]
20pub use texture_blitter::{TextureBlitter, TextureBlitterBuilder};
21pub use wgt::{
22 math::*, DispatchIndirectArgs, DrawIndexedIndirectArgs, DrawIndirectArgs, TextureDataOrder,
23};
24
25use crate::dispatch;
26
27/// Treat the given byte slice as a SPIR-V module.
28///
29/// # Panic
30///
31/// This function panics if:
32///
33/// - Input length isn't multiple of 4
34/// - Input is longer than [`usize::MAX`]
35/// - Input is empty
36/// - SPIR-V magic number is missing from beginning of stream
37#[cfg(feature = "spirv")]
38pub fn make_spirv(data: &[u8]) -> super::ShaderSource<'_> {
39 super::ShaderSource::SpirV(make_spirv_raw(data))
40}
41
42/// Version of make_spirv intended for use with [`Device::create_shader_module_spirv`].
43/// Returns raw slice instead of ShaderSource.
44///
45/// [`Device::create_shader_module_spirv`]: crate::Device::create_shader_module_spirv
46pub fn make_spirv_raw(data: &[u8]) -> Cow<'_, [u32]> {
47 const MAGIC_NUMBER: u32 = 0x0723_0203;
48 assert_eq!(
49 data.len() % size_of::<u32>(),
50 0,
51 "data size is not a multiple of 4"
52 );
53 assert_ne!(data.len(), 0, "data size must be larger than zero");
54
55 // If the data happens to be aligned, directly use the byte array,
56 // otherwise copy the byte array in an owned vector and use that instead.
57 let mut words = if data.as_ptr().align_offset(align_of::<u32>()) == 0 {
58 let (pre, words, post) = unsafe { data.align_to::<u32>() };
59 debug_assert!(pre.is_empty());
60 debug_assert!(post.is_empty());
61 Cow::from(words)
62 } else {
63 let mut words = vec![0u32; data.len() / size_of::<u32>()];
64 unsafe {
65 copy_nonoverlapping(data.as_ptr(), words.as_mut_ptr() as *mut u8, data.len());
66 }
67 Cow::from(words)
68 };
69
70 // Before checking if the data starts with the magic, check if it starts
71 // with the magic in non-native endianness, own & swap the data if so.
72 if words[0] == MAGIC_NUMBER.swap_bytes() {
73 for word in Cow::to_mut(&mut words) {
74 *word = word.swap_bytes();
75 }
76 }
77
78 assert_eq!(
79 words[0], MAGIC_NUMBER,
80 "wrong magic word {:x}. Make sure you are using a binary SPIRV file.",
81 words[0]
82 );
83
84 words
85}
86
87/// CPU accessible buffer used to download data back from the GPU.
88pub struct DownloadBuffer {
89 _gpu_buffer: Arc<super::Buffer>,
90 mapped_range: dispatch::DispatchBufferMappedRange,
91}
92
93impl DownloadBuffer {
94 /// Asynchronously read the contents of a buffer.
95 pub fn read_buffer(
96 device: &super::Device,
97 queue: &super::Queue,
98 buffer: &super::BufferSlice<'_>,
99 callback: impl FnOnce(Result<Self, super::BufferAsyncError>) + Send + 'static,
100 ) {
101 let size = match buffer.size {
102 Some(size) => size.into(),
103 None => buffer.buffer.map_context.lock().total_size - buffer.offset,
104 };
105
106 let download = Arc::new(device.create_buffer(&super::BufferDescriptor {
107 size,
108 usage: super::BufferUsages::COPY_DST | super::BufferUsages::MAP_READ,
109 mapped_at_creation: false,
110 label: None,
111 }));
112
113 let mut encoder =
114 device.create_command_encoder(&super::CommandEncoderDescriptor { label: None });
115 encoder.copy_buffer_to_buffer(buffer.buffer, buffer.offset, &download, 0, size);
116 let command_buffer: super::CommandBuffer = encoder.finish();
117 queue.submit(Some(command_buffer));
118
119 download
120 .clone()
121 .slice(..)
122 .map_async(super::MapMode::Read, move |result| {
123 if let Err(e) = result {
124 callback(Err(e));
125 return;
126 }
127
128 let mapped_range = download.inner.get_mapped_range(0..size);
129 callback(Ok(Self {
130 _gpu_buffer: download,
131 mapped_range,
132 }));
133 });
134 }
135}
136
137impl std::ops::Deref for DownloadBuffer {
138 type Target = [u8];
139 fn deref(&self) -> &[u8] {
140 self.mapped_range.slice()
141 }
142}
143
144/// A recommended key for storing [`PipelineCache`]s for the adapter
145/// associated with the given [`AdapterInfo`](wgt::AdapterInfo)
146/// This key will define a class of adapters for which the same cache
147/// might be valid.
148///
149/// If this returns `None`, the adapter doesn't support [`PipelineCache`].
150/// This may be because the API doesn't support application managed caches
151/// (such as browser WebGPU), or that `wgpu` hasn't implemented it for
152/// that API yet.
153///
154/// This key could be used as a filename, as seen in the example below.
155///
156/// # Examples
157///
158/// ``` no_run
159/// # use std::path::PathBuf;
160/// # let adapter_info = todo!();
161/// let cache_dir: PathBuf = PathBuf::new();
162/// let filename = wgpu::util::pipeline_cache_key(&adapter_info);
163/// if let Some(filename) = filename {
164/// let cache_file = cache_dir.join(&filename);
165/// let cache_data = std::fs::read(&cache_file);
166/// let pipeline_cache: wgpu::PipelineCache = todo!("Use data (if present) to create a pipeline cache");
167///
168/// let data = pipeline_cache.get_data();
169/// if let Some(data) = data {
170/// let temp_file = cache_file.with_extension("temp");
171/// std::fs::write(&temp_file, &data)?;
172/// std::fs::rename(&temp_file, &cache_file)?;
173/// }
174/// }
175/// # Ok::<(), std::io::Error>(())
176/// ```
177///
178/// [`PipelineCache`]: super::PipelineCache
179pub fn pipeline_cache_key(adapter_info: &wgt::AdapterInfo) -> Option<String> {
180 match adapter_info.backend {
181 wgt::Backend::Vulkan => Some(format!(
182 // The vendor/device should uniquely define a driver
183 // We/the driver will also later validate that the vendor/device and driver
184 // version match, which may lead to clearing an outdated
185 // cache for the same device.
186 "wgpu_pipeline_cache_vulkan_{}_{}",
187 adapter_info.vendor, adapter_info.device
188 )),
189 _ => None,
190 }
191}
192
193/// Adds extra conversion functions to `TextureFormat`.
194pub trait TextureFormatExt {
195 /// Finds the [`TextureFormat`](wgt::TextureFormat) corresponding to the given
196 /// [`StorageFormat`](wgc::naga::StorageFormat).
197 ///
198 /// # Examples
199 /// ```
200 /// use wgpu::util::TextureFormatExt;
201 /// assert_eq!(wgpu::TextureFormat::from_storage_format(wgpu::naga::StorageFormat::Bgra8Unorm), wgpu::TextureFormat::Bgra8Unorm);
202 /// ```
203 #[cfg_attr(docsrs, doc(cfg(any(wgpu_core, naga))))]
204 #[cfg(any(wgpu_core, naga))]
205 fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self;
206
207 /// Finds the [`StorageFormat`](wgc::naga::StorageFormat) corresponding to the given [`TextureFormat`](wgt::TextureFormat).
208 /// Returns `None` if there is no matching storage format,
209 /// which typically indicates this format is not supported
210 /// for storage textures.
211 ///
212 /// # Examples
213 /// ```
214 /// use wgpu::util::TextureFormatExt;
215 /// assert_eq!(wgpu::TextureFormat::Bgra8Unorm.to_storage_format(), Some(wgpu::naga::StorageFormat::Bgra8Unorm));
216 /// ```
217 #[cfg_attr(docsrs, doc(cfg(any(wgpu_core, naga))))]
218 #[cfg(any(wgpu_core, naga))]
219 fn to_storage_format(&self) -> Option<crate::naga::StorageFormat>;
220}
221
222impl TextureFormatExt for wgt::TextureFormat {
223 #[cfg_attr(docsrs, doc(cfg(any(wgpu_core, naga))))]
224 #[cfg(any(wgpu_core, naga))]
225 fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self {
226 wgc::map_storage_format_from_naga(storage_format)
227 }
228
229 #[cfg_attr(docsrs, doc(cfg(any(wgpu_core, naga))))]
230 #[cfg(any(wgpu_core, naga))]
231 fn to_storage_format(&self) -> Option<crate::naga::StorageFormat> {
232 wgc::map_storage_format_to_naga(*self)
233 }
234}