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
100#[derive(Debug)]
101/// Definition for a triangle geometry for a Bottom Level Acceleration Structure (BLAS).
102///
103/// The size must match the rest of the structures fields, otherwise the build will fail.
104/// (e.g. if index count is present in the size, the index buffer must be present as well.)
105pub struct BlasTriangleGeometry<'a> {
106    /// Sub descriptor for the size defining attributes of a triangle geometry.
107    pub size: &'a BlasTriangleGeometrySizeDescriptor,
108    /// Vertex buffer.
109    pub vertex_buffer: &'a Buffer,
110    /// Offset into the vertex buffer as a factor of the vertex stride.
111    pub first_vertex: u32,
112    /// Vertex stride, must be greater than [`wgpu_types::VertexFormat::min_acceleration_structure_vertex_stride`]
113    /// of the format and must be a multiple of [`wgpu_types::VertexFormat::acceleration_structure_stride_alignment`].
114    pub vertex_stride: wgt::BufferAddress,
115    /// Index buffer (optional).
116    pub index_buffer: Option<&'a Buffer>,
117    /// Number of indexes to skip in the index buffer (optional, required if index buffer is present).
118    pub first_index: Option<u32>,
119    /// Transform buffer containing 3x4 (rows x columns, row major) affine transform matrices `[f32; 12]` (optional).
120    pub transform_buffer: Option<&'a Buffer>,
121    /// Transform buffer offset in bytes (optional, required if transform buffer is present).
122    pub transform_buffer_offset: Option<wgt::BufferAddress>,
123}
124static_assertions::assert_impl_all!(BlasTriangleGeometry<'_>: WasmNotSendSync);
125
126/// Definition for an axis-aligned bounding box geometry group for a bottom level acceleration structure.
127///
128/// Buffer data must contain `size.primitive_count` primitives at `primitive_offset`, each `size.stride` bytes,
129/// with `stride` at least [`AABB_GEOMETRY_MIN_STRIDE`] and a multiple of 8.
130pub struct BlasAabbGeometry<'a> {
131    /// Sub descriptor for the size defining attributes of this geometry.
132    pub size: &'a BlasAABBGeometrySizeDescriptor,
133    /// Stride in bytes between consecutive AABB primitives in the buffer (at least
134    /// [`AABB_GEOMETRY_MIN_STRIDE`], and must be a multiple of 8).
135    pub stride: wgt::BufferAddress,
136    /// Buffer containing packed AABB primitives (layout determined by `size.stride`).
137    pub aabb_buffer: &'a Buffer,
138    /// Byte offset to the first AABB primitive (must be a multiple of 8).
139    pub primitive_offset: u32,
140}
141static_assertions::assert_impl_all!(BlasAabbGeometry<'_>: WasmNotSendSync);
142
143/// Contains the sets of geometry that go into a [Blas].
144pub enum BlasGeometries<'a> {
145    /// Triangle geometry variant.
146    TriangleGeometries(Vec<BlasTriangleGeometry<'a>>),
147    /// Procedural AABB geometry variant.
148    AabbGeometries(Vec<BlasAabbGeometry<'a>>),
149}
150static_assertions::assert_impl_all!(BlasGeometries<'_>: WasmNotSendSync);
151
152/// Builds the given sets of geometry into the given [Blas].
153pub struct BlasBuildEntry<'a> {
154    /// Reference to the acceleration structure.
155    pub blas: &'a Blas,
156    /// Geometries.
157    pub geometry: BlasGeometries<'a>,
158}
159static_assertions::assert_impl_all!(BlasBuildEntry<'_>: WasmNotSendSync);
160
161#[derive(Debug, Clone)]
162/// Bottom Level Acceleration Structure (BLAS).
163///
164/// A BLAS is a device-specific raytracing acceleration structure that contains geometry data.
165///
166/// These BLASes are combined with transform in a [TlasInstance] to create a [Tlas].
167///
168/// [Tlas]: crate::Tlas
169pub struct Blas {
170    pub(crate) handle: Option<u64>,
171    pub(crate) inner: dispatch::DispatchBlas,
172}
173static_assertions::assert_impl_all!(Blas: WasmNotSendSync);
174
175crate::cmp::impl_eq_ord_hash_proxy!(Blas => .inner);
176
177impl Blas {
178    /// Raw handle to the acceleration structure, used inside raw instance buffers.
179    pub fn handle(&self) -> Option<u64> {
180        self.handle
181    }
182
183    /// Get the [`wgpu_hal`] acceleration structure from this `Blas`.
184    ///
185    /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
186    /// and pass that struct to the to the `A` type parameter.
187    ///
188    /// Returns a guard that dereferences to the type of the hal backend
189    /// which implements [`A::AccelerationStructure`].
190    ///
191    /// # Types
192    ///
193    /// The returned type depends on the backend:
194    ///
195    #[doc = crate::macros::hal_type_vulkan!("AccelerationStructure")]
196    #[doc = crate::macros::hal_type_metal!("AccelerationStructure")]
197    #[doc = crate::macros::hal_type_dx12!("AccelerationStructure")]
198    #[doc = crate::macros::hal_type_gles!("AccelerationStructure")]
199    ///
200    /// # Deadlocks
201    ///
202    /// - The returned guard holds a read-lock on a device-local "destruction"
203    ///   lock, which will cause all calls to `destroy` to block until the
204    ///   guard is released.
205    ///
206    /// # Errors
207    ///
208    /// This method will return None if:
209    /// - The acceleration structure is not from the backend specified by `A`.
210    /// - The acceleration structure is from the `webgpu` or `custom` backend.
211    ///
212    /// # Safety
213    ///
214    /// - The returned resource must not be destroyed unless the guard
215    ///   is the last reference to it and it is not in use by the GPU.
216    ///   The guard and handle may be dropped at any time however.
217    /// - All the safety requirements of wgpu-hal must be upheld.
218    ///
219    /// [`A::AccelerationStructure`]: hal::Api::AccelerationStructure
220    #[cfg(wgpu_core)]
221    pub unsafe fn as_hal<A: hal::Api>(
222        &mut self,
223    ) -> Option<impl Deref<Target = A::AccelerationStructure> + WasmNotSendSync> {
224        let blas = self.inner.as_core_opt()?;
225        unsafe { blas.context.blas_as_hal::<A>(blas) }
226    }
227
228    #[cfg(custom)]
229    /// Returns custom implementation of Blas (if custom backend and is internally T)
230    pub fn as_custom<T: crate::custom::BlasInterface>(&self) -> Option<&T> {
231        self.inner.as_custom()
232    }
233}
234
235/// Context version of [BlasTriangleGeometry].
236pub struct ContextBlasTriangleGeometry<'a> {
237    #[expect(dead_code)]
238    pub(crate) size: &'a BlasTriangleGeometrySizeDescriptor,
239    #[expect(dead_code)]
240    pub(crate) vertex_buffer: &'a dispatch::DispatchBuffer,
241    #[expect(dead_code)]
242    pub(crate) index_buffer: Option<&'a dispatch::DispatchBuffer>,
243    #[expect(dead_code)]
244    pub(crate) transform_buffer: Option<&'a dispatch::DispatchBuffer>,
245    #[expect(dead_code)]
246    pub(crate) first_vertex: u32,
247    #[expect(dead_code)]
248    pub(crate) vertex_stride: wgt::BufferAddress,
249    #[expect(dead_code)]
250    pub(crate) index_buffer_offset: Option<wgt::BufferAddress>,
251    #[expect(dead_code)]
252    pub(crate) transform_buffer_offset: Option<wgt::BufferAddress>,
253}
254
255/// Context version of [BlasGeometries].
256pub enum ContextBlasGeometries<'a> {
257    /// Triangle geometries.
258    TriangleGeometries(Box<dyn Iterator<Item = ContextBlasTriangleGeometry<'a>> + 'a>),
259    /// AABB geometries.
260    AabbGeometries(Box<dyn Iterator<Item = ContextBlasAabbGeometry<'a>> + 'a>),
261}
262
263/// Context version of [BlasAabbGeometry].
264pub struct ContextBlasAabbGeometry<'a> {
265    #[expect(dead_code)]
266    pub(crate) size: &'a BlasAABBGeometrySizeDescriptor,
267    #[expect(dead_code)]
268    pub(crate) stride: wgt::BufferAddress,
269    #[expect(dead_code)]
270    pub(crate) aabb_buffer: &'a dispatch::DispatchBuffer,
271    #[expect(dead_code)]
272    pub(crate) primitive_offset: u32,
273}
274
275/// Context version see [BlasBuildEntry].
276pub struct ContextBlasBuildEntry<'a> {
277    #[expect(dead_code)]
278    pub(crate) blas: &'a dispatch::DispatchBlas,
279    #[expect(dead_code)]
280    pub(crate) geometries: ContextBlasGeometries<'a>,
281}
282
283/// Error occurred when trying to asynchronously prepare a blas for compaction.
284#[derive(Clone, PartialEq, Eq, Debug)]
285pub struct BlasAsyncError;
286static_assertions::assert_impl_all!(BlasAsyncError: Send, Sync);
287
288impl core::fmt::Display for BlasAsyncError {
289    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
290        write!(
291            f,
292            "Error occurred when trying to asynchronously prepare a blas for compaction"
293        )
294    }
295}
296
297impl core::error::Error for BlasAsyncError {}
298
299impl Blas {
300    /// Asynchronously prepares this BLAS for compaction. The callback is called once all builds
301    /// using this BLAS are finished and the BLAS is compactable. This can be checked using
302    /// [`Blas::ready_for_compaction`]. Rebuilding this BLAS will reset its compacted state, and it
303    /// will need to be prepared again.
304    ///
305    /// ### Interaction with other functions
306    /// On native, `queue.submit(..)` and polling devices (that is calling `instance.poll_all` or
307    /// `device.poll`) with [`PollType::Poll`] may call the callback. On native, polling devices with
308    /// [`PollType::Wait`] (optionally with a submission index greater
309    /// than the last submit the BLAS was used in) will guarantee callback is called.
310    ///
311    /// [`PollType::Poll`]: wgpu_types::PollType::Poll
312    /// [`PollType::Wait`]: wgpu_types::PollType::Wait
313    pub fn prepare_compaction_async(
314        &self,
315        callback: impl FnOnce(Result<(), BlasAsyncError>) + WasmNotSend + 'static,
316    ) {
317        self.inner.prepare_compact_async(Box::new(callback));
318    }
319
320    /// Checks whether this BLAS is ready for compaction. The returned value is `true` if
321    /// [`Blas::prepare_compaction_async`]'s callback was called with a non-error value, otherwise
322    /// this is `false`.
323    pub fn ready_for_compaction(&self) -> bool {
324        self.inner.ready_for_compaction()
325    }
326}