wgpu/api/blas.rs
1#[cfg(wgpu_core)]
2use core::ops::Deref;
3
4use alloc::{boxed::Box, vec::Vec};
5
6use wgt::{WasmNotSend, WasmNotSendSync};
7
8use crate::dispatch;
9use crate::{Buffer, Label};
10
11/// Descriptor for the size defining attributes of a triangle geometry, for a bottom level acceleration structure.
12pub type BlasTriangleGeometrySizeDescriptor = wgt::BlasTriangleGeometrySizeDescriptor;
13static_assertions::assert_impl_all!(BlasTriangleGeometrySizeDescriptor: Send, Sync);
14
15/// Descriptor for the size defining attributes of an AABB geometry group in a bottom level acceleration structure.
16pub type BlasAABBGeometrySizeDescriptor = wgt::BlasAABBGeometrySizeDescriptor;
17static_assertions::assert_impl_all!(BlasAABBGeometrySizeDescriptor: Send, Sync);
18
19/// Minimum stride for AABB geometry (24 bytes: two `vec3<f32>`).
20pub use wgt::AABB_GEOMETRY_MIN_STRIDE;
21
22/// Descriptor for the size defining attributes, for a bottom level acceleration structure.
23pub type BlasGeometrySizeDescriptors = wgt::BlasGeometrySizeDescriptors;
24static_assertions::assert_impl_all!(BlasGeometrySizeDescriptors: Send, Sync);
25
26/// Flags for an acceleration structure.
27pub type AccelerationStructureFlags = wgt::AccelerationStructureFlags;
28static_assertions::assert_impl_all!(AccelerationStructureFlags: Send, Sync);
29
30/// Flags for a geometry inside a bottom level acceleration structure.
31pub type AccelerationStructureGeometryFlags = wgt::AccelerationStructureGeometryFlags;
32static_assertions::assert_impl_all!(AccelerationStructureGeometryFlags: Send, Sync);
33
34/// Update mode for acceleration structure builds.
35pub type AccelerationStructureUpdateMode = wgt::AccelerationStructureUpdateMode;
36static_assertions::assert_impl_all!(AccelerationStructureUpdateMode: Send, Sync);
37
38/// Descriptor to create bottom level acceleration structures.
39pub type CreateBlasDescriptor<'a> = wgt::CreateBlasDescriptor<Label<'a>>;
40static_assertions::assert_impl_all!(CreateBlasDescriptor<'_>: Send, Sync);
41
42/// Safe instance for a [Tlas].
43///
44/// A TlasInstance may be made invalid, if a TlasInstance is invalid, any attempt to build a [Tlas] containing an
45/// invalid TlasInstance will generate a validation error
46///
47/// Each one contains:
48/// - A reference to a BLAS, this ***must*** be interacted with using [TlasInstance::new] or [TlasInstance::set_blas], a
49/// TlasInstance that references a BLAS keeps that BLAS from being dropped
50/// - A user accessible transformation matrix
51/// - A user accessible mask
52/// - A user accessible custom index
53///
54/// [Tlas]: crate::Tlas
55#[derive(Debug, Clone)]
56pub struct TlasInstance {
57 pub(crate) blas: dispatch::DispatchBlas,
58 /// Affine transform matrix 3x4 (rows x columns, row major order).
59 pub transform: [f32; 12],
60 /// Custom index for the instance used inside the shader.
61 ///
62 /// This must only use the lower 24 bits, if any bits are outside that range (byte 4 does not equal 0) the TlasInstance becomes
63 /// invalid and generates a validation error when built
64 pub custom_data: u32,
65 /// Mask for the instance used inside the shader to filter instances.
66 /// Reports hit only if `(shader_cull_mask & tlas_instance.mask) != 0u`.
67 pub mask: u8,
68}
69
70impl TlasInstance {
71 /// Construct TlasInstance.
72 /// - blas: Reference to the bottom level acceleration structure
73 /// - transform: Transform buffer offset in bytes (optional, required if transform buffer is present)
74 /// - custom_data: Custom index for the instance used inside the shader (max 24 bits)
75 /// - mask: Mask for the instance used inside the shader to filter instances
76 ///
77 /// Note: while one of these contains a reference to a BLAS that BLAS will not be dropped,
78 /// but it can still be destroyed. Destroying a BLAS that is referenced by one or more
79 /// TlasInstance(s) will immediately make them invalid. If one or more of those invalid
80 /// TlasInstances is inside a TlasPackage that is attempted to be built, the build will
81 /// generate a validation error.
82 pub fn new(blas: &Blas, transform: [f32; 12], custom_data: u32, mask: u8) -> Self {
83 Self {
84 blas: blas.inner.clone(),
85 transform,
86 custom_data,
87 mask,
88 }
89 }
90
91 /// Set the bottom level acceleration structure.
92 ///
93 /// See the note on [TlasInstance] about the
94 /// guarantees of keeping a BLAS alive.
95 pub fn set_blas(&mut self, blas: &Blas) {
96 self.blas = blas.inner.clone();
97 }
98
99 /// Returns custom implementation of the BLAS referenced by this instance
100 /// (if the custom backend is active and the BLAS is internally of type T).
101 #[cfg(custom)]
102 pub fn blas_as_custom<T: crate::custom::BlasInterface>(&self) -> Option<&T> {
103 self.blas.as_custom()
104 }
105}
106
107#[derive(Debug)]
108/// Definition for a triangle geometry for a Bottom Level Acceleration Structure (BLAS).
109///
110/// The size must match the rest of the structures fields, otherwise the build will fail.
111/// (e.g. if index count is present in the size, the index buffer must be present as well.)
112pub struct BlasTriangleGeometry<'a> {
113 /// Sub descriptor for the size defining attributes of a triangle geometry.
114 pub size: &'a BlasTriangleGeometrySizeDescriptor,
115 /// Vertex buffer.
116 pub vertex_buffer: &'a Buffer,
117 /// Offset into the vertex buffer as a factor of the vertex stride.
118 pub first_vertex: u32,
119 /// Vertex stride, must be greater than [`wgpu_types::VertexFormat::min_acceleration_structure_vertex_stride`]
120 /// of the format and must be a multiple of [`wgpu_types::VertexFormat::acceleration_structure_stride_alignment`].
121 pub vertex_stride: wgt::BufferAddress,
122 /// Index buffer (optional).
123 pub index_buffer: Option<&'a Buffer>,
124 /// Number of indexes to skip in the index buffer (optional, required if index buffer is present).
125 pub first_index: Option<u32>,
126 /// Transform buffer containing 3x4 (rows x columns, row major) affine transform matrices `[f32; 12]` (optional).
127 pub transform_buffer: Option<&'a Buffer>,
128 /// Transform buffer offset in bytes (optional, required if transform buffer is present).
129 pub transform_buffer_offset: Option<wgt::BufferAddress>,
130}
131static_assertions::assert_impl_all!(BlasTriangleGeometry<'_>: WasmNotSendSync);
132
133/// Definition for an axis-aligned bounding box geometry group for a bottom level acceleration structure.
134///
135/// Buffer data must contain `size.primitive_count` primitives at `primitive_offset`, each `size.stride` bytes,
136/// with `stride` at least [`AABB_GEOMETRY_MIN_STRIDE`] and a multiple of 8.
137pub struct BlasAabbGeometry<'a> {
138 /// Sub descriptor for the size defining attributes of this geometry.
139 pub size: &'a BlasAABBGeometrySizeDescriptor,
140 /// Stride in bytes between consecutive AABB primitives in the buffer (at least
141 /// [`AABB_GEOMETRY_MIN_STRIDE`], and must be a multiple of 8).
142 pub stride: wgt::BufferAddress,
143 /// Buffer containing packed AABB primitives (layout determined by `size.stride`).
144 pub aabb_buffer: &'a Buffer,
145 /// Byte offset to the first AABB primitive (must be a multiple of 8).
146 pub primitive_offset: u32,
147}
148static_assertions::assert_impl_all!(BlasAabbGeometry<'_>: WasmNotSendSync);
149
150/// Contains the sets of geometry that go into a [Blas].
151pub enum BlasGeometries<'a> {
152 /// Triangle geometry variant.
153 TriangleGeometries(Vec<BlasTriangleGeometry<'a>>),
154 /// Procedural AABB geometry variant.
155 AabbGeometries(Vec<BlasAabbGeometry<'a>>),
156}
157static_assertions::assert_impl_all!(BlasGeometries<'_>: WasmNotSendSync);
158
159/// Builds the given sets of geometry into the given [Blas].
160pub struct BlasBuildEntry<'a> {
161 /// Reference to the acceleration structure.
162 pub blas: &'a Blas,
163 /// Geometries.
164 pub geometry: BlasGeometries<'a>,
165}
166static_assertions::assert_impl_all!(BlasBuildEntry<'_>: WasmNotSendSync);
167
168#[derive(Debug, Clone)]
169/// Bottom Level Acceleration Structure (BLAS).
170///
171/// A BLAS is a device-specific raytracing acceleration structure that contains geometry data.
172///
173/// These BLASes are combined with transform in a [TlasInstance] to create a [Tlas].
174///
175/// [Tlas]: crate::Tlas
176pub struct Blas {
177 pub(crate) handle: Option<u64>,
178 pub(crate) inner: dispatch::DispatchBlas,
179}
180static_assertions::assert_impl_all!(Blas: WasmNotSendSync);
181
182crate::cmp::impl_eq_ord_hash_proxy!(Blas => .inner);
183
184impl Blas {
185 /// Raw handle to the acceleration structure, used inside raw instance buffers.
186 pub fn handle(&self) -> Option<u64> {
187 self.handle
188 }
189
190 /// Get the [`wgpu_hal`] acceleration structure from this `Blas`.
191 ///
192 /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
193 /// and pass that struct to the to the `A` type parameter.
194 ///
195 /// Returns a guard that dereferences to the type of the hal backend
196 /// which implements [`A::AccelerationStructure`].
197 ///
198 /// # Types
199 ///
200 /// The returned type depends on the backend:
201 ///
202 #[doc = crate::macros::hal_type_vulkan!("AccelerationStructure")]
203 #[doc = crate::macros::hal_type_metal!("AccelerationStructure")]
204 #[doc = crate::macros::hal_type_dx12!("AccelerationStructure")]
205 #[doc = crate::macros::hal_type_gles!("AccelerationStructure")]
206 ///
207 /// # Deadlocks
208 ///
209 /// - The returned guard holds a read-lock on a device-local "destruction"
210 /// lock, which will cause all calls to `destroy` to block until the
211 /// guard is released.
212 ///
213 /// # Errors
214 ///
215 /// This method will return None if:
216 /// - The acceleration structure is not from the backend specified by `A`.
217 /// - The acceleration structure is from the `webgpu` or `custom` backend.
218 ///
219 /// # Safety
220 ///
221 /// - The returned resource must not be destroyed unless the guard
222 /// is the last reference to it and it is not in use by the GPU.
223 /// The guard and handle may be dropped at any time however.
224 /// - All the safety requirements of wgpu-hal must be upheld.
225 ///
226 /// [`A::AccelerationStructure`]: hal::Api::AccelerationStructure
227 #[cfg(wgpu_core)]
228 pub unsafe fn as_hal<A: hal::Api>(
229 &mut self,
230 ) -> Option<impl Deref<Target = A::AccelerationStructure> + WasmNotSendSync> {
231 let blas = self.inner.as_core_opt()?;
232 unsafe { blas.context.blas_as_hal::<A>(blas) }
233 }
234
235 #[cfg(custom)]
236 /// Returns custom implementation of Blas (if custom backend and is internally T)
237 pub fn as_custom<T: crate::custom::BlasInterface>(&self) -> Option<&T> {
238 self.inner.as_custom()
239 }
240}
241
242/// Context version of [BlasTriangleGeometry].
243pub struct ContextBlasTriangleGeometry<'a> {
244 #[expect(dead_code)]
245 pub(crate) size: &'a BlasTriangleGeometrySizeDescriptor,
246 #[expect(dead_code)]
247 pub(crate) vertex_buffer: &'a dispatch::DispatchBuffer,
248 #[expect(dead_code)]
249 pub(crate) index_buffer: Option<&'a dispatch::DispatchBuffer>,
250 #[expect(dead_code)]
251 pub(crate) transform_buffer: Option<&'a dispatch::DispatchBuffer>,
252 #[expect(dead_code)]
253 pub(crate) first_vertex: u32,
254 #[expect(dead_code)]
255 pub(crate) vertex_stride: wgt::BufferAddress,
256 #[expect(dead_code)]
257 pub(crate) index_buffer_offset: Option<wgt::BufferAddress>,
258 #[expect(dead_code)]
259 pub(crate) transform_buffer_offset: Option<wgt::BufferAddress>,
260}
261
262/// Context version of [BlasGeometries].
263pub enum ContextBlasGeometries<'a> {
264 /// Triangle geometries.
265 TriangleGeometries(Box<dyn Iterator<Item = ContextBlasTriangleGeometry<'a>> + 'a>),
266 /// AABB geometries.
267 AabbGeometries(Box<dyn Iterator<Item = ContextBlasAabbGeometry<'a>> + 'a>),
268}
269
270/// Context version of [BlasAabbGeometry].
271pub struct ContextBlasAabbGeometry<'a> {
272 #[expect(dead_code)]
273 pub(crate) size: &'a BlasAABBGeometrySizeDescriptor,
274 #[expect(dead_code)]
275 pub(crate) stride: wgt::BufferAddress,
276 #[expect(dead_code)]
277 pub(crate) aabb_buffer: &'a dispatch::DispatchBuffer,
278 #[expect(dead_code)]
279 pub(crate) primitive_offset: u32,
280}
281
282/// Context version see [BlasBuildEntry].
283pub struct ContextBlasBuildEntry<'a> {
284 #[expect(dead_code)]
285 pub(crate) blas: &'a dispatch::DispatchBlas,
286 #[expect(dead_code)]
287 pub(crate) geometries: ContextBlasGeometries<'a>,
288}
289
290/// Error occurred when trying to asynchronously prepare a blas for compaction.
291#[derive(Clone, PartialEq, Eq, Debug)]
292pub struct BlasAsyncError;
293static_assertions::assert_impl_all!(BlasAsyncError: Send, Sync);
294
295impl core::fmt::Display for BlasAsyncError {
296 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
297 write!(
298 f,
299 "Error occurred when trying to asynchronously prepare a blas for compaction"
300 )
301 }
302}
303
304impl core::error::Error for BlasAsyncError {}
305
306impl Blas {
307 /// Asynchronously prepares this BLAS for compaction. The callback is called once all builds
308 /// using this BLAS are finished and the BLAS is compactable. This can be checked using
309 /// [`Blas::ready_for_compaction`]. Rebuilding this BLAS will reset its compacted state, and it
310 /// will need to be prepared again.
311 ///
312 /// ### Interaction with other functions
313 /// On native, `queue.submit(..)` and polling devices (that is calling `instance.poll_all` or
314 /// `device.poll`) with [`PollType::Poll`] may call the callback. On native, polling devices with
315 /// [`PollType::Wait`] (optionally with a submission index greater
316 /// than the last submit the BLAS was used in) will guarantee callback is called.
317 ///
318 /// [`PollType::Poll`]: wgpu_types::PollType::Poll
319 /// [`PollType::Wait`]: wgpu_types::PollType::Wait
320 pub fn prepare_compaction_async(
321 &self,
322 callback: impl FnOnce(Result<(), BlasAsyncError>) + WasmNotSend + 'static,
323 ) {
324 self.inner.prepare_compact_async(Box::new(callback));
325 }
326
327 /// Checks whether this BLAS is ready for compaction. The returned value is `true` if
328 /// [`Blas::prepare_compaction_async`]'s callback was called with a non-error value, otherwise
329 /// this is `false`.
330 pub fn ready_for_compaction(&self) -> bool {
331 self.inner.ready_for_compaction()
332 }
333}