Plumbing and a test for ACCELERATION_STRUCTURE_BINDING_ARRAY

This commit is contained in:
Dzmitry Malyshau authored and Jim Blandy committed 2026-03-11 08:18:38 -07:00
1 parent 43f48b43ee
commit e39b3aec8e
18 files changed
+393 -8

No files matched your search

+1
View File
@@ -122,6 +122,7 @@ depth_stencil: Some(wgpu::DepthStencilState::stencil(
#### General
- Added TLAS binding array support via `ACCELERATION_STRUCTURE_BINDING_ARRAY`. By @kvark in #8923.
- Added support for cooperative load/store operations in shaders. Currently only WGSL on the input and SPIR-V, METAL, and WGSL on the output are supported. By @kvark in [#8251](https://github.com/gfx-rs/wgpu/issues/8251).
- Added support for per-vertex attributes in fragment shaders. Currently only WGSL input is supported, and only SPIR-V or WGSL output is supported. By @atlv24 in [#8821](https://github.com/gfx-rs/wgpu/issues/8821).
- Added support for no-perspective barycentric coordinates. By @atlv24 in [#8852](https://github.com/gfx-rs/wgpu/issues/8852).
+8 -1
View File
@@ -962,7 +962,14 @@ impl super::Validator {
}
}
crate::TypeInner::AccelerationStructure { .. } => {
return Err(GlobalVariableError::InvalidBindingArray(base));
if !self
.capabilities
.contains(Capabilities::ACCELERATION_STRUCTURE_BINDING_ARRAY)
{
return Err(GlobalVariableError::UnsupportedCapability(
Capabilities::ACCELERATION_STRUCTURE_BINDING_ARRAY,
));
}
}
crate::TypeInner::RayQuery { .. } => {
// This should have been rejected in `validate_type`.
+2
View File
@@ -208,6 +208,8 @@ bitflags::bitflags! {
const RAY_TRACING_PIPELINE = 1 << 38;
/// Support for draw index builtin
const DRAW_INDEX = 1 << 39;
/// Support for binding arrays of acceleration structures.
const ACCELERATION_STRUCTURE_BINDING_ARRAY = 1 << 40;
}
}
+5 -3
View File
@@ -4685,7 +4685,7 @@ fn binding_array_requires_capability() {
Capabilities::TEXTURE_EXTERNAL
}
// Acceleration structures are not allowed in binding arrays
// Binding arrays of acceleration structures require a capability.
check_validation! {
r#"
enable wgpu_ray_query;
@@ -4693,10 +4693,12 @@ fn binding_array_requires_capability() {
var acc_struct_array: binding_array<acceleration_structure, 10>;
"#:
Err(naga::valid::ValidationError::GlobalVariable {
source: naga::valid::GlobalVariableError::InvalidBindingArray(_),
source: naga::valid::GlobalVariableError::UnsupportedCapability(
Capabilities::ACCELERATION_STRUCTURE_BINDING_ARRAY
),
..
}),
Capabilities::all()
Capabilities::RAY_QUERY
}
}
+10
View File
@@ -781,6 +781,16 @@ impl Player {
let tlas = self.resolve_tlas_id(tlas_id);
wgc::binding_model::ResolvedBindingResource::AccelerationStructure(tlas)
}
BindingResource::AccelerationStructureArray(tlas_ids) => {
let resolved_tlas: Vec<_> = tlas_ids
.to_vec()
.into_iter()
.map(|id| self.resolve_tlas_id(id))
.collect();
wgc::binding_model::ResolvedBindingResource::AccelerationStructureArray(
Cow::Owned(resolved_tlas),
)
}
BindingResource::ExternalTexture(external_texture_id) => {
let external_texture =
self.resolve_external_texture_id(external_texture_id);
@@ -2,10 +2,12 @@ mod buffers;
mod sampled_textures;
mod samplers;
mod storage_textures;
mod tlas;
pub fn all_tests(tests: &mut Vec<wgpu_test::GpuTestInitializer>) {
buffers::all_tests(tests);
sampled_textures::all_tests(tests);
samplers::all_tests(tests);
storage_textures::all_tests(tests);
tlas::all_tests(tests);
}
+235
View File
@@ -0,0 +1,235 @@
use std::{borrow::Cow, num::NonZeroU32};
use wgpu::util::DeviceExt;
use wgpu::*;
use wgpu_test::{
gpu_test, FailureCase, GpuTestConfiguration, GpuTestInitializer, TestParameters, TestingContext,
};
pub fn all_tests(tests: &mut Vec<GpuTestInitializer>) {
tests.push(BINDING_ARRAY_TLAS);
}
#[gpu_test]
static BINDING_ARRAY_TLAS: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.instance_flags(wgpu::InstanceFlags::GPU_BASED_VALIDATION)
// Ray queries + acceleration structure bindings are gated behind this experimental feature.
.features(
Features::EXPERIMENTAL_RAY_QUERY | Features::ACCELERATION_STRUCTURE_BINDING_ARRAY,
)
.limits({
let mut limits =
Limits::default().using_minimum_supported_acceleration_structure_values();
// Keep this small; we only need a couple of array elements.
limits.max_binding_array_elements_per_shader_stage = 8;
limits.max_acceleration_structures_per_shader_stage = 8;
limits
})
// As of writing, Metal's HAL does not implement binding acceleration structures.
.skip(FailureCase::backend(Backends::METAL)),
)
.run_async(|ctx| async move { binding_array_tlas(ctx).await });
async fn binding_array_tlas(ctx: TestingContext) {
// Minimal shader that consumes a TLAS binding array.
//
// We don't need to actually "trace" anything for this test. We only need:
// - Pipeline compilation to accept `binding_array<acceleration_structure>`
// - Bind group creation to accept `BindingResource::AccelerationStructureArray`
// - Encoder to successfully set the bind group and submit.
//
// Creating a `ray_query` and initializing it against element 0 forces the binding to be used.
let shader = r#"
enable wgpu_ray_query;
@group(0) @binding(0)
var tlas_array: binding_array<acceleration_structure>;
@compute
@workgroup_size(1, 1, 1)
fn main() {
var rq: ray_query;
rayQueryInitialize(
&rq,
tlas_array[0],
RayDesc(
0u,
0xffu,
0.001,
1000.0,
vec3f(0.0, 0.0, 0.0),
vec3f(0.0, 0.0, 1.0)
)
);
}
"#;
let module = ctx.device.create_shader_module(ShaderModuleDescriptor {
label: Some("Binding Array TLAS"),
source: ShaderSource::Wgsl(Cow::Borrowed(shader)),
});
// Build a minimal BLAS + two TLAS so we can bind an array of TLAS.
//
// This follows the shapes used in the ray tracing examples.
let vertex_data: [[f32; 3]; 3] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
let index_data: [u16; 3] = [0, 1, 2];
let vertex_buf = ctx
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("RT Vertex Buffer"),
contents: bytemuck::cast_slice(&vertex_data),
usage: BufferUsages::VERTEX | BufferUsages::BLAS_INPUT,
});
let index_buf = ctx
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("RT Index Buffer"),
contents: bytemuck::cast_slice(&index_data),
usage: BufferUsages::INDEX | BufferUsages::BLAS_INPUT,
});
let blas_geo_size_desc = wgpu::BlasTriangleGeometrySizeDescriptor {
vertex_format: wgpu::VertexFormat::Float32x3,
vertex_count: vertex_data.len() as u32,
index_format: Some(wgpu::IndexFormat::Uint16),
index_count: Some(index_data.len() as u32),
flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
};
let blas = ctx.device.create_blas(
&wgpu::CreateBlasDescriptor {
label: Some("BLAS"),
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
},
wgpu::BlasGeometrySizeDescriptors::Triangles {
descriptors: vec![blas_geo_size_desc.clone()],
},
);
let mut tlas_a = ctx.device.create_tlas(&wgpu::CreateTlasDescriptor {
label: Some("TLAS A"),
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
max_instances: 1,
});
let mut tlas_b = ctx.device.create_tlas(&wgpu::CreateTlasDescriptor {
label: Some("TLAS B"),
flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
update_mode: wgpu::AccelerationStructureUpdateMode::Build,
max_instances: 1,
});
// Put a single instance into each TLAS. Both reference the same BLAS.
//
// NOTE: This indexing API is how TLAS instances are populated in the examples.
tlas_a[0] = Some(wgpu::TlasInstance::new(
&blas,
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
0,
0xff,
));
tlas_b[0] = Some(wgpu::TlasInstance::new(
&blas,
[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
0,
0xff,
));
// Build BLAS and TLASes.
let mut encoder = ctx
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("RT Build"),
});
encoder.build_acceleration_structures(
std::iter::once(&wgpu::BlasBuildEntry {
blas: &blas,
geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
size: &blas_geo_size_desc,
vertex_buffer: &vertex_buf,
first_vertex: 0,
vertex_stride: std::mem::size_of::<[f32; 3]>() as u64,
index_buffer: Some(&index_buf),
first_index: Some(0),
transform_buffer: None,
transform_buffer_offset: None,
}]),
}),
std::iter::empty::<&wgpu::Tlas>()
.chain(std::iter::once(&tlas_a))
.chain(std::iter::once(&tlas_b)),
);
ctx.queue.submit(Some(encoder.finish()));
// Bind group layout with a TLAS array binding.
let bgl = ctx
.device
.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some("TLAS array BGL"),
entries: &[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: BindingType::AccelerationStructure {
vertex_return: false,
},
count: Some(NonZeroU32::new(2).unwrap()),
}],
});
let tlas_refs: [&Tlas; 2] = [&tlas_a, &tlas_b];
let bg = ctx.device.create_bind_group(&BindGroupDescriptor {
label: Some("TLAS array BG"),
layout: &bgl,
entries: &[BindGroupEntry {
binding: 0,
resource: BindingResource::AccelerationStructureArray(&tlas_refs),
}],
});
let pipeline_layout = ctx
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some("TLAS array pipeline layout"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipeline = ctx
.device
.create_compute_pipeline(&ComputePipelineDescriptor {
label: Some("TLAS array pipeline"),
layout: Some(&pipeline_layout),
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let mut encoder = ctx
.device
.create_command_encoder(&CommandEncoderDescriptor {
label: Some("Dispatch"),
});
{
let mut pass = encoder.begin_compute_pass(&ComputePassDescriptor {
label: Some("Compute pass"),
timestamp_writes: None,
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bg, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
ctx.queue.submit(Some(encoder.finish()));
}
+11
View File
@@ -600,9 +600,11 @@ pub struct BindGroupEntry<
[BufferBinding<B>]: ToOwned,
[S]: ToOwned,
[TV]: ToOwned,
[TLAS]: ToOwned,
<[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
<[S] as ToOwned>::Owned: fmt::Debug,
<[TV] as ToOwned>::Owned: fmt::Debug,
<[TLAS] as ToOwned>::Owned: fmt::Debug,
{
/// Slot for which binding provides resource. Corresponds to an entry of the same
/// binding index in the [`BindGroupLayoutDescriptor`].
@@ -640,9 +642,11 @@ pub struct BindGroupDescriptor<
[BufferBinding<B>]: ToOwned,
[S]: ToOwned,
[TV]: ToOwned,
[TLAS]: ToOwned,
<[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
<[S] as ToOwned>::Owned: fmt::Debug,
<[TV] as ToOwned>::Owned: fmt::Debug,
<[TLAS] as ToOwned>::Owned: fmt::Debug,
[BindGroupEntry<'a, B, S, TV, TLAS, ET>]: ToOwned,
<[BindGroupEntry<'a, B, S, TV, TLAS, ET>] as ToOwned>::Owned: fmt::Debug,
{
@@ -1007,9 +1011,11 @@ pub enum BindingResource<
[BufferBinding<B>]: ToOwned,
[S]: ToOwned,
[TV]: ToOwned,
[TLAS]: ToOwned,
<[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
<[S] as ToOwned>::Owned: fmt::Debug,
<[TV] as ToOwned>::Owned: fmt::Debug,
<[TLAS] as ToOwned>::Owned: fmt::Debug,
{
Buffer(BufferBinding<B>),
#[cfg_attr(
@@ -1030,6 +1036,11 @@ pub enum BindingResource<
)]
TextureViewArray(Cow<'a, [TV]>),
AccelerationStructure(TLAS),
#[cfg_attr(
feature = "serde",
serde(bound(deserialize = "<[TLAS] as ToOwned>::Owned: Deserialize<'de>"))
)]
AccelerationStructureArray(Cow<'a, [TLAS]>),
ExternalTexture(ET),
}
+7
View File
@@ -885,6 +885,13 @@ impl Global {
BindingResource::AccelerationStructure(ref tlas) => {
ResolvedBindingResource::AccelerationStructure(resolve_tlas(tlas)?)
}
BindingResource::AccelerationStructureArray(ref tlas_array) => {
let tlas_array = tlas_array
.iter()
.map(resolve_tlas)
.collect::<Result<Vec<_>, _>>()?;
ResolvedBindingResource::AccelerationStructureArray(Cow::Owned(tlas_array))
}
BindingResource::ExternalTexture(ref et) => {
ResolvedBindingResource::ExternalTexture(resolve_external_texture(et)?)
}
+4
View File
@@ -443,6 +443,10 @@ pub fn features_to_naga_capabilities(
features
.contains(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING),
);
caps.set(
Caps::ACCELERATION_STRUCTURE_BINDING_ARRAY,
features.contains(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
);
caps.set(
Caps::STORAGE_TEXTURE_16BIT_NORM_FORMATS,
features.contains(wgt::Features::TEXTURE_FORMAT_16BIT_NORM),
+24 -2
View File
@@ -2705,8 +2705,10 @@ impl Device {
error: e.into(),
})?;
}
(None, WritableStorage::No)
(
Some(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
WritableStorage::No,
)
}
Bt::ExternalTexture => {
self.require_features(wgt::Features::EXTERNAL_TEXTURE)
@@ -3348,6 +3350,26 @@ impl Device {
hal_tlas_s.push(tlas);
(res_index, 1)
}
Br::AccelerationStructureArray(ref tlas_array) => {
// Feature validation for TLAS binding arrays happens at bind group layout
// creation time (mirroring other binding-array resource types). By the time we
// get here, `decl.count` has already been validated against device features.
let num_bindings = tlas_array.len();
Self::check_array_binding(self.features, decl.count, num_bindings)?;
let res_index = hal_tlas_s.len();
for tlas in tlas_array.iter() {
let tlas = self.create_tlas_binding(
&mut used,
binding,
decl,
tlas,
&snatch_guard,
)?;
hal_tlas_s.push(tlas);
}
(res_index, num_bindings)
}
Br::ExternalTexture(ref et) => {
let et = self.create_external_texture_binding(
binding,
+5
View File
@@ -695,6 +695,11 @@ impl<'a> IntoTrace for &'_ crate::binding_model::ResolvedBindGroupDescriptor<'a>
ResolvedBindingResource::AccelerationStructure(tlas_id) => {
BindingResource::AccelerationStructure(tlas_id.to_trace())
}
ResolvedBindingResource::AccelerationStructureArray(tlas_ids) => {
let resolved: Vec<_> =
tlas_ids.iter().map(|id| id.to_trace()).collect();
BindingResource::AccelerationStructureArray(Cow::Owned(resolved))
}
ResolvedBindingResource::ExternalTexture(external_texture_id) => {
BindingResource::ExternalTexture(external_texture_id.to_trace())
}
+10
View File
@@ -615,12 +615,22 @@ impl super::Adapter {
>= Direct3D12::D3D12_RAYTRACING_TIER_1_1.0
&& shader_model >= naga::back::hlsl::ShaderModel::V6_5
&& has_features5;
features.set(
wgt::Features::EXPERIMENTAL_RAY_QUERY
| wgt::Features::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
supports_ray_tracing,
);
// Binding arrays of TLAS are supported on D3D12 when ray tracing is supported.
//
// This flag is used for shader-side `binding_array<acceleration_structure>` as well as
// allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`.
features.set(
wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY,
supports_ray_tracing,
);
// Check for Int64 atomic support on buffers. This is very convoluted, but is based on a conservative reading
// of https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_Int64_and_Float_Atomics.html#integer-64-bit-capabilities.
let atomic_int64_buffers;
+25 -2
View File
@@ -451,7 +451,11 @@ impl PhysicalDeviceFeatures {
{
Some(
vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()
.acceleration_structure(true),
.acceleration_structure(true)
.descriptor_binding_acceleration_structure_update_after_bind(
requested_features
.contains(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY),
),
)
} else {
None
@@ -913,12 +917,31 @@ impl PhysicalDeviceFeatures {
&& caps.supports_extension(khr::acceleration_structure::NAME)
&& caps.supports_extension(khr::buffer_device_address::NAME);
let supports_ray_query =
supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME);
let supports_acceleration_structure_binding_array = supports_ray_query
&& self
.acceleration_structure
.as_ref()
.is_some_and(|features| {
features.descriptor_binding_acceleration_structure_update_after_bind != 0
});
features.set(
F::EXPERIMENTAL_RAY_QUERY
// Although this doesn't really require ray queries, it does not make sense to be enabled if acceleration structures
// aren't enabled.
| F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS,
supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME),
supports_ray_query,
);
// Binding arrays of TLAS are supported on Vulkan when ray queries are supported.
//
// Note: this flag is used for shader-side `binding_array<acceleration_structure>` as well as
// allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`.
features.set(
F::ACCELERATION_STRUCTURE_BINDING_ARRAY,
supports_acceleration_structure_binding_array,
);
let rg11b10ufloat_renderable = supports_format(
+13
View File
@@ -1306,6 +1306,19 @@ bitflags_array! {
///
/// This is a native only feature.
const SHADER_DRAW_INDEX = 1 << 59;
/// Allows the user to create arrays of acceleration structures in shaders:
///
/// ex.
/// - `var tlas: binding_array<acceleration_structure, 10>` (WGSL)
///
/// This capability allows them to exist and to be indexed by dynamically uniform values.
///
/// Supported platforms:
/// - DX12
/// - Vulkan
///
/// This is a native only feature.
const ACCELERATION_STRUCTURE_BINDING_ARRAY = 1 << 60;
}
/// Features that are not guaranteed to be supported.
+9
View File
@@ -81,6 +81,15 @@ pub enum BindingResource<'a> {
/// built using `build_acceleration_structures` a validation error is generated otherwise this is a part of the
/// safety section of `build_acceleration_structures_unsafe_tlas` and so undefined behavior occurs.
AccelerationStructure(&'a Tlas),
/// Binding is backed by an array of top level acceleration structures.
///
/// Corresponds to [`wgt::BindingType::AccelerationStructure`] with [`BindGroupLayoutEntry::count`] set to Some.
///
/// # Validation
/// The same validation rules apply as for [`BindingResource::AccelerationStructure`], for each element.
///
/// Note: backend support may vary; this is primarily intended for native backends.
AccelerationStructureArray(&'a [&'a Tlas]),
/// Binding is backed by an external texture.
///
/// [`Features::EXTERNAL_TEXTURE`] must be supported to use this feature.
+3
View File
@@ -2102,6 +2102,9 @@ impl dispatch::DeviceInterface for WebDevice {
crate::BindingResource::AccelerationStructure(_) => {
unimplemented!("Raytracing not implemented for web")
}
crate::BindingResource::AccelerationStructureArray(_) => {
unimplemented!("Raytracing not implemented for web")
}
crate::BindingResource::ExternalTexture(_) => {
unimplemented!("ExternalTexture not implemented for web")
}
+19
View File
@@ -1193,6 +1193,19 @@ impl dispatch::DeviceInterface for CoreDevice {
}
let mut remaining_arrayed_buffer_bindings = &arrayed_buffer_bindings[..];
// Gather all the TLAS IDs used by TLAS arrays first (same pattern as other arrayed resources).
//
// Note: there isn't currently a dedicated feature flag for TLAS binding arrays at the wgpu API
// layer; validation happens in wgpu-core against `BindGroupLayoutEntry::count`.
let mut arrayed_acceleration_structures = Vec::new();
for entry in desc.entries.iter() {
if let BindingResource::AccelerationStructureArray(array) = entry.resource {
arrayed_acceleration_structures
.extend(array.iter().map(|tlas| tlas.inner.as_core().id));
}
}
let mut remaining_arrayed_acceleration_structures = &arrayed_acceleration_structures[..];
let entries = desc
.entries
.iter()
@@ -1236,6 +1249,12 @@ impl dispatch::DeviceInterface for CoreDevice {
acceleration_structure.inner.as_core().id,
)
}
BindingResource::AccelerationStructureArray(array) => {
let slice = &remaining_arrayed_acceleration_structures[..array.len()];
remaining_arrayed_acceleration_structures =
&remaining_arrayed_acceleration_structures[array.len()..];
bm::BindingResource::AccelerationStructureArray(Borrowed(slice))
}
BindingResource::ExternalTexture(external_texture) => {
bm::BindingResource::ExternalTexture(external_texture.inner.as_core().id)
}